From 6c23b7f62d92e0fabdd9db72bd38d2038caeb524 Mon Sep 17 00:00:00 2001 From: hallacy Date: Fri, 10 Mar 2023 19:48:42 -0800 Subject: [PATCH 001/816] Create wheels (#297) --- Makefile | 10 ++++++---- openai/version.py | 2 +- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/Makefile b/Makefile index f80c2b0a51..b3ef11eea1 100644 --- a/Makefile +++ b/Makefile @@ -1,9 +1,11 @@ .PHONY: build upload build: - python setup.py sdist + rm -rf dist/ build/ + python -m pip install build + python -m build . upload: - twine upload dist/openai-*.tar.gz - rm dist/openai-*.tar.gz - + python -m pip install twine + python -m twine upload dist/openai-* + rm -rf dist diff --git a/openai/version.py b/openai/version.py index e88778bd11..cba8d8927b 100644 --- a/openai/version.py +++ b/openai/version.py @@ -1 +1 @@ -VERSION = "0.27.1" +VERSION = "0.27.2" From 1d6142f376067e401492ca92ff88a08deb47d6ba Mon Sep 17 00:00:00 2001 From: Anthony Chiu Date: Tue, 14 Mar 2023 07:19:13 +0800 Subject: [PATCH 002/816] Update README.md (#301) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5dbd51a627..76f9e9b58e 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,7 @@ print(completion.choices[0].text) ### Params -All endpoints have a `.create` method that supports a `request_timeout` param. This param takes a `Union[float, Tuple[float, float]]` and will raise an `openai.error.TimeoutError` error if the request exceeds that time in seconds (See: https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts). +All endpoints have a `.create` method that supports a `request_timeout` param. This param takes a `Union[float, Tuple[float, float]]` and will raise an `openai.error.Timeout` error if the request exceeds that time in seconds (See: https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts). ### Microsoft Azure Endpoints From f3e06c05c59cd526ac446b0099f3d4195a8e67db Mon Sep 17 00:00:00 2001 From: Muluken Hakim <91600753+MuleHakim@users.noreply.github.com> Date: Wed, 22 Mar 2023 06:03:07 +0300 Subject: [PATCH 003/816] 'let us know at on our support page' to 'let us know on our support page' (#308) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 76f9e9b58e..49ae2efd22 100644 --- a/README.md +++ b/README.md @@ -287,7 +287,7 @@ See the [usage guide](https://platform.openai.com/docs/guides/images) for more d In general, we want to support the versions of Python that our customers are using. If you run into problems with any version -issues, please let us know at on our [support page](https://help.openai.com/en/). +issues, please let us know on our [support page](https://help.openai.com/en/). ## Credit From 62a208d93ad2e8ffdbd21c4adde5ad9e3b3daea5 Mon Sep 17 00:00:00 2001 From: Pinxi <52986595+FizzyAgent@users.noreply.github.com> Date: Wed, 22 Mar 2023 11:04:36 +0800 Subject: [PATCH 004/816] add cli version arg (#298) --- openai/_openai_scripts.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/openai/_openai_scripts.py b/openai/_openai_scripts.py index d234256c62..aaf23b0cad 100755 --- a/openai/_openai_scripts.py +++ b/openai/_openai_scripts.py @@ -4,6 +4,7 @@ import sys import openai +from openai import version from openai.cli import api_register, display_error, tools_register, wandb_register logger = logging.getLogger() @@ -15,6 +16,12 @@ def main(): parser = argparse.ArgumentParser(description=None) + parser.add_argument( + "-V", + "--version", + action="http://github.com/version", + version="%(prog)s " + version.VERSION, + ) parser.add_argument( "-v", "--verbose", From 2b0bb90712f48246a7dce5a755a7e93b169da6f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20M=C3=BCrtz?= <120655914+cmurtz-msft@users.noreply.github.com> Date: Sat, 25 Mar 2023 16:25:07 +0100 Subject: [PATCH 005/816] 2023-03-15-preview as default (#335) --- README.md | 6 +++--- openai/__init__.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 49ae2efd22..fb5a3e32f9 100644 --- a/README.md +++ b/README.md @@ -84,10 +84,10 @@ import openai openai.api_type = "azure" openai.api_key = "..." openai.api_base = "https://example-endpoint.openai.azure.com/" -openai.api_version = "2022-12-01" +openai.api_version = "2023-03-15-preview" # create a completion -completion = openai.Completion.create(engine="deployment-name", prompt="Hello world") +completion = openai.Completion.create(deployment_id="deployment-name", prompt="Hello world") # print the completion print(completion.choices[0].text) @@ -116,7 +116,7 @@ token = default_credential.get_token("https://cognitiveservices.azure.com/.defau%20openai.api_type%20="azure_ad" openai.api_key = token.token openai.api_base = "https://example-endpoint.openai.azure.com/" -openai.api_version = "2022-12-01" +openai.api_version = "2023-03-15-preview" # ... ``` diff --git a/openai/__init__.py b/openai/__init__.py index 2b184226df..f80085eada 100644 --- a/openai/__init__.py +++ b/openai/__init__.py @@ -37,7 +37,7 @@ api_base = os.environ.get("OPENAI_API_BASE", "https://api.openai.com/v1") api_type = os.environ.get("OPENAI_API_TYPE", "open_ai") api_version = ( - "2022-12-01" if api_type in ("azure", "azure_ad", "azuread") else None + "2023-03-15-preview" if api_type in ("azure", "azure_ad", "azuread") else None ) verify_ssl_certs = True # No effect. Certificates are always verified. proxy = None From 237448dc072a2c062698da3f9f512fae38300c1c Mon Sep 17 00:00:00 2001 From: liuliu <44393673+liuliuOD@users.noreply.github.com> Date: Sat, 25 Mar 2023 23:26:16 +0800 Subject: [PATCH 006/816] doc: add symbol comma into chatml.md (#329) --- chatml.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chatml.md b/chatml.md index 41f5bbdd9e..5fe9fe4c03 100644 --- a/chatml.md +++ b/chatml.md @@ -59,7 +59,7 @@ We do not currently allow autocompleting of partial messages, ``` [ {"token": "<|im_start|>"}, - "system\nPlease autocomplete the user's message." + "system\nPlease autocomplete the user's message.", {"token": "<|im_end|>"}, "\n", {"token": "<|im_start|>"}, "user\nThis morning I decided to eat a giant" ] @@ -87,7 +87,7 @@ Comment allez-vous? {{user input here}}<|im_end|> ``` If adding instructions in the `system` message doesn't work, you can -also try putting them into a `user` message. (In the near future, we +also try putting them into a `user` message. (In the near future, we will train our models to be much more steerable via the system message. But to date, we have trained only on a few system messages, so the models pay much more attention to user examples.) From 931b4d23c742349bf5f82a2a995dd46ae684cdd5 Mon Sep 17 00:00:00 2001 From: Lucas Pickup Date: Wed, 29 Mar 2023 14:27:12 -0700 Subject: [PATCH 007/816] Handle OpenAIErrors created with 'str' json_body (#356) `api_requestor.py` recently started respecting `text/plain` response `Content-Type`s. Azure OpenAI can sometimes return errors with that Content-Type that are still JSON strings with error info, which can break OpenAIErrors default behavior of checking for `error` being `in` the supplied `json_body`. Classic Python, `in` works for `dict` or `str` but `json_body["error"]` will only work if `json_body` is a `dict`. This is the minimal fix to now throw KeyError and let the unparsed json_body + message bubble up in the OpenAIError. --- openai/error.py | 1 + 1 file changed, 1 insertion(+) diff --git a/openai/error.py b/openai/error.py index d22e71c902..16692569da 100644 --- a/openai/error.py +++ b/openai/error.py @@ -58,6 +58,7 @@ def __repr__(self): def construct_error_object(self): if ( self.json_body is None + or not isinstance(self.json_body, dict) or "error" not in self.json_body or not isinstance(self.json_body["error"], dict) ): From 6db251894cbe0c0698307f58e5a46e3ee0d471f6 Mon Sep 17 00:00:00 2001 From: Jhen-Jie Hong Date: Thu, 30 Mar 2023 06:47:28 +0800 Subject: [PATCH 008/816] CLI: Fix missing max_tokens arg of chat_completions.create (#317) --- openai/cli.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openai/cli.py b/openai/cli.py index e9201b18b9..91daa1c5ff 100644 --- a/openai/cli.py +++ b/openai/cli.py @@ -126,7 +126,7 @@ def create(cls, args): messages=messages, # Optional n=args.n, - max_tokens=100, + max_tokens=args.max_tokens, temperature=args.temperature, top_p=args.top_p, stop=args.stop, From 15c6aebc6cda59e8d884e1fbc63fd1f6eddbc196 Mon Sep 17 00:00:00 2001 From: Owain Davies <116417456+OTheDev@users.noreply.github.com> Date: Thu, 30 Mar 2023 11:41:12 +0700 Subject: [PATCH 009/816] Fix a couple of grammar mistakes in chatml.md (#316) --- chatml.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chatml.md b/chatml.md index 5fe9fe4c03..783e91d996 100644 --- a/chatml.md +++ b/chatml.md @@ -28,8 +28,8 @@ follows: ] ``` You could also represent it in the classic "unsafe raw string" -format. Note this format inherently allows injections from user input -containing special-token syntax, similar to a SQL injections: +format. However, this format inherently allows injections from user +input containing special-token syntax, similar to SQL injections: ``` <|im_start|>system You are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible. From 47ce29542e7fc496c1cd0bb323293b7991f45bb0 Mon Sep 17 00:00:00 2001 From: Bojie Li Date: Thu, 30 Mar 2023 13:11:40 +0800 Subject: [PATCH 010/816] set openai.proxy explicitly to Requests lib to override environmental defaults (#339) By default, the Requests library use the proxy settings from the environment variable HTTPS_PROXY. It has higher priority than the "proxies" setting in the session, which may lead to confusing behaviors if both environment variables and the "openai.proxy" config are set. This patch explicitly informs the Requests library to use the "openai.proxy" config. --- openai/api_requestor.py | 1 + 1 file changed, 1 insertion(+) diff --git a/openai/api_requestor.py b/openai/api_requestor.py index 8a0e6cabc2..827b73b78e 100644 --- a/openai/api_requestor.py +++ b/openai/api_requestor.py @@ -521,6 +521,7 @@ def request_raw( files=files, stream=stream, timeout=request_timeout if request_timeout else TIMEOUT_SECS, + proxies=_thread_context.session.proxies, ) except requests.exceptions.Timeout as e: raise error.Timeout("Request timed out: {}".format(e)) from e From 39cdc662350cadd2e6a4a382454394d22908004d Mon Sep 17 00:00:00 2001 From: Michelle Pokrass Date: Mon, 3 Apr 2023 14:03:22 -0700 Subject: [PATCH 011/816] [audio] Use supplied api key (#170) (#369) --- openai/api_resources/audio.py | 80 +++++++++++++++++++++++++++++++---- openai/version.py | 2 +- 2 files changed, 73 insertions(+), 9 deletions(-) diff --git a/openai/api_resources/audio.py b/openai/api_resources/audio.py index 8ad6705680..33820c64a7 100644 --- a/openai/api_resources/audio.py +++ b/openai/api_resources/audio.py @@ -52,7 +52,15 @@ def transcribe( organization=None, **params, ): - requestor, files, data = cls._prepare_request(file, file.name, model, **params) + requestor, files, data = cls._prepare_request( + file=file, + filename=file.name, + model=model, + api_key=api_key, + api_base=api_base, + api_type=api_type, + **params, + ) url = cls._get_url("http://github.com/transcriptions") response, _, api_key = requestor.request("post", url, files=files, params=data) return util.convert_to_openai_object( @@ -71,7 +79,15 @@ def translate( organization=None, **params, ): - requestor, files, data = cls._prepare_request(file, file.name, model, **params) + requestor, files, data = cls._prepare_request( + file=file, + filename=file.name, + model=model, + api_key=api_key, + api_base=api_base, + api_type=api_type, + **params, + ) url = cls._get_url("http://github.com/translations") response, _, api_key = requestor.request("post", url, files=files, params=data) return util.convert_to_openai_object( @@ -91,7 +107,15 @@ def transcribe_raw( organization=None, **params, ): - requestor, files, data = cls._prepare_request(file, filename, model, **params) + requestor, files, data = cls._prepare_request( + file=file, + filename=filename, + model=model, + api_key=api_key, + api_base=api_base, + api_type=api_type, + **params, + ) url = cls._get_url("http://github.com/transcriptions") response, _, api_key = requestor.request("post", url, files=files, params=data) return util.convert_to_openai_object( @@ -111,7 +135,15 @@ def translate_raw( organization=None, **params, ): - requestor, files, data = cls._prepare_request(file, filename, model, **params) + requestor, files, data = cls._prepare_request( + file=file, + filename=filename, + model=model, + api_key=api_key, + api_base=api_base, + api_type=api_type, + **params, + ) url = cls._get_url("http://github.com/translations") response, _, api_key = requestor.request("post", url, files=files, params=data) return util.convert_to_openai_object( @@ -130,7 +162,15 @@ async def atranscribe( organization=None, **params, ): - requestor, files, data = cls._prepare_request(file, file.name, model, **params) + requestor, files, data = cls._prepare_request( + file=file, + filename=file.name, + model=model, + api_key=api_key, + api_base=api_base, + api_type=api_type, + **params, + ) url = cls._get_url("http://github.com/transcriptions") response, _, api_key = await requestor.arequest( "post", url, files=files, params=data @@ -151,7 +191,15 @@ async def atranslate( organization=None, **params, ): - requestor, files, data = cls._prepare_request(file, file.name, model, **params) + requestor, files, data = cls._prepare_request( + file=file, + filename=file.name, + model=model, + api_key=api_key, + api_base=api_base, + api_type=api_type, + **params, + ) url = cls._get_url("http://github.com/translations") response, _, api_key = await requestor.arequest( "post", url, files=files, params=data @@ -173,7 +221,15 @@ async def atranscribe_raw( organization=None, **params, ): - requestor, files, data = cls._prepare_request(file, filename, model, **params) + requestor, files, data = cls._prepare_request( + file=file, + filename=filename, + model=model, + api_key=api_key, + api_base=api_base, + api_type=api_type, + **params, + ) url = cls._get_url("http://github.com/transcriptions") response, _, api_key = await requestor.arequest( "post", url, files=files, params=data @@ -195,7 +251,15 @@ async def atranslate_raw( organization=None, **params, ): - requestor, files, data = cls._prepare_request(file, filename, model, **params) + requestor, files, data = cls._prepare_request( + file=file, + filename=filename, + model=model, + api_key=api_key, + api_base=api_base, + api_type=api_type, + **params, + ) url = cls._get_url("http://github.com/translations") response, _, api_key = await requestor.arequest( "post", url, files=files, params=data diff --git a/openai/version.py b/openai/version.py index cba8d8927b..cdf81e9c82 100644 --- a/openai/version.py +++ b/openai/version.py @@ -1 +1 @@ -VERSION = "0.27.2" +VERSION = "0.27.3" From ed821c85c35f57d8083afe8fd27502fe8a342a75 Mon Sep 17 00:00:00 2001 From: iaalm Date: Tue, 4 Apr 2023 14:34:08 +0800 Subject: [PATCH 012/816] add support for azure openai api (#359) --- openai/cli.py | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/openai/cli.py b/openai/cli.py index 91daa1c5ff..e1bf3eac06 100644 --- a/openai/cli.py +++ b/openai/cli.py @@ -123,6 +123,7 @@ def create(cls, args): resp = openai.ChatCompletion.create( # Required model=args.model, + engine=args.engine, messages=messages, # Optional n=args.n, @@ -714,12 +715,6 @@ def help(args): req = sub.add_argument_group("required arguments") opt = sub.add_argument_group("optional arguments") - req.add_argument( - "-m", - "--model", - help="The model to use.", - required=True, - ) req.add_argument( "-g", "--message", @@ -729,6 +724,19 @@ def help(args): help="A message in `{role} {content}` format. Use this argument multiple times to add multiple messages.", required=True, ) + + group = opt.add_mutually_exclusive_group() + group.add_argument( + "-e", + "--engine", + help="The engine to use. See https://learn.microsoft.com/en-us/azure/cognitive-services/openai/chatgpt-quickstart?pivots=programming-language-python for more about what engines are available.", + ) + group.add_argument( + "-m", + "--model", + help="The model to use.", + ) + opt.add_argument( "-n", "--n", From cf03fe16a92cd01f2a8867537399c12e183ba58e Mon Sep 17 00:00:00 2001 From: Atty Eleti Date: Tue, 4 Apr 2023 10:41:28 -0700 Subject: [PATCH 013/816] Bump version to v0.27.4 (#373) --- openai/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openai/version.py b/openai/version.py index cdf81e9c82..7fb4979dc6 100644 --- a/openai/version.py +++ b/openai/version.py @@ -1 +1 @@ -VERSION = "0.27.3" +VERSION = "0.27.4" From bd269ab91501f3c7a80bc67ddb0269a3e0e498fc Mon Sep 17 00:00:00 2001 From: hallacy Date: Fri, 7 Apr 2023 17:53:16 -0700 Subject: [PATCH 014/816] Speed up imports (#386) --- openai/__init__.py | 14 ++++++++++-- openai/api_resources/embedding.py | 4 ++-- openai/{datalib.py => datalib/common.py} | 24 -------------------- openai/datalib/numpy_helper.py | 15 ++++++++++++ openai/datalib/pandas_helper.py | 15 ++++++++++++ openai/embeddings_utils.py | 4 ++-- openai/tests/test_long_examples_validator.py | 10 +++----- openai/validators.py | 10 +++++--- openai/wandb_logger.py | 4 ++-- 9 files changed, 58 insertions(+), 42 deletions(-) rename openai/{datalib.py => datalib/common.py} (67%) create mode 100644 openai/datalib/numpy_helper.py create mode 100644 openai/datalib/pandas_helper.py diff --git a/openai/__init__.py b/openai/__init__.py index f80085eada..1a69e24485 100644 --- a/openai/__init__.py +++ b/openai/__init__.py @@ -3,16 +3,26 @@ # Originally forked from the MIT-licensed Stripe Python bindings. import os +import sys +from typing import TYPE_CHECKING, Optional + from contextvars import ContextVar -from typing import Optional, TYPE_CHECKING + +if "pkg_resources" not in sys.modules: + # workaround for the following: + # https://github.com/benoitc/gunicorn/pull/2539 + sys.modules["pkg_resources"] = object() # type: ignore[assignment] + import aiohttp + + del sys.modules["pkg_resources"] from openai.api_resources import ( Audio, ChatCompletion, Completion, Customer, - Edit, Deployment, + Edit, Embedding, Engine, ErrorObject, diff --git a/openai/api_resources/embedding.py b/openai/api_resources/embedding.py index 4eb97c68bf..e937636404 100644 --- a/openai/api_resources/embedding.py +++ b/openai/api_resources/embedding.py @@ -1,10 +1,10 @@ import base64 import time - from openai import util from openai.api_resources.abstract.engine_api_resource import EngineAPIResource -from openai.datalib import numpy as np, assert_has_numpy +from openai.datalib.numpy_helper import assert_has_numpy +from openai.datalib.numpy_helper import numpy as np from openai.error import TryAgain diff --git a/openai/datalib.py b/openai/datalib/common.py similarity index 67% rename from openai/datalib.py rename to openai/datalib/common.py index 2781cfc4db..678b3395fd 100644 --- a/openai/datalib.py +++ b/openai/datalib/common.py @@ -13,19 +13,6 @@ See also `setup.py`. """ -try: - import numpy -except ImportError: - numpy = None - -try: - import pandas -except ImportError: - pandas = None - -HAS_NUMPY = bool(numpy) -HAS_PANDAS = bool(pandas) - INSTRUCTIONS = """ OpenAI error: @@ -39,18 +26,7 @@ """ NUMPY_INSTRUCTIONS = INSTRUCTIONS.format(library="numpy") -PANDAS_INSTRUCTIONS = INSTRUCTIONS.format(library="pandas") class MissingDependencyError(Exception): pass - - -def assert_has_numpy(): - if not HAS_NUMPY: - raise MissingDependencyError(NUMPY_INSTRUCTIONS) - - -def assert_has_pandas(): - if not HAS_PANDAS: - raise MissingDependencyError(PANDAS_INSTRUCTIONS) diff --git a/openai/datalib/numpy_helper.py b/openai/datalib/numpy_helper.py new file mode 100644 index 0000000000..fb80f2ae54 --- /dev/null +++ b/openai/datalib/numpy_helper.py @@ -0,0 +1,15 @@ +from openai.datalib.common import INSTRUCTIONS, MissingDependencyError + +try: + import numpy +except ImportError: + numpy = None + +HAS_NUMPY = bool(numpy) + +NUMPY_INSTRUCTIONS = INSTRUCTIONS.format(library="numpy") + + +def assert_has_numpy(): + if not HAS_NUMPY: + raise MissingDependencyError(NUMPY_INSTRUCTIONS) diff --git a/openai/datalib/pandas_helper.py b/openai/datalib/pandas_helper.py new file mode 100644 index 0000000000..4e86d7b4f9 --- /dev/null +++ b/openai/datalib/pandas_helper.py @@ -0,0 +1,15 @@ +from openai.datalib.common import INSTRUCTIONS, MissingDependencyError + +try: + import pandas +except ImportError: + pandas = None + +HAS_PANDAS = bool(pandas) + +PANDAS_INSTRUCTIONS = INSTRUCTIONS.format(library="pandas") + + +def assert_has_pandas(): + if not HAS_PANDAS: + raise MissingDependencyError(PANDAS_INSTRUCTIONS) diff --git a/openai/embeddings_utils.py b/openai/embeddings_utils.py index 056c2065c1..08fa94c2ea 100644 --- a/openai/embeddings_utils.py +++ b/openai/embeddings_utils.py @@ -10,8 +10,8 @@ from tenacity import retry, stop_after_attempt, wait_random_exponential import openai -from openai.datalib import numpy as np -from openai.datalib import pandas as pd +from openai.datalib.numpy_helper import numpy as np +from openai.datalib.pandas_helper import pandas as pd @retry(wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6)) diff --git a/openai/tests/test_long_examples_validator.py b/openai/tests/test_long_examples_validator.py index 0cac1360cd..949a7cbbae 100644 --- a/openai/tests/test_long_examples_validator.py +++ b/openai/tests/test_long_examples_validator.py @@ -4,12 +4,8 @@ import pytest -from openai.datalib import ( - HAS_NUMPY, - HAS_PANDAS, - NUMPY_INSTRUCTIONS, - PANDAS_INSTRUCTIONS, -) +from openai.datalib.numpy_helper import HAS_NUMPY, NUMPY_INSTRUCTIONS +from openai.datalib.pandas_helper import HAS_PANDAS, PANDAS_INSTRUCTIONS @pytest.mark.skipif(not HAS_PANDAS, reason=PANDAS_INSTRUCTIONS) @@ -54,5 +50,5 @@ def test_long_examples_validator() -> None: assert prepared_data_cmd_output.stderr == "" # validate get_long_indexes() applied during optional_fn() call in long_examples_validator() assert "indices of the long examples has changed" in prepared_data_cmd_output.stdout - + return prepared_data_cmd_output.stdout diff --git a/openai/validators.py b/openai/validators.py index b15e59bee3..97083659df 100644 --- a/openai/validators.py +++ b/openai/validators.py @@ -2,7 +2,8 @@ import sys from typing import Any, Callable, NamedTuple, Optional -from openai.datalib import pandas as pd, assert_has_pandas +from openai.datalib.pandas_helper import assert_has_pandas +from openai.datalib.pandas_helper import pandas as pd class Remediation(NamedTuple): @@ -158,6 +159,7 @@ def long_examples_validator(df): ft_type = infer_task_type(df) if ft_type != "open-ended generation": + def get_long_indexes(d): long_examples = d.apply( lambda x: len(x.prompt) + len(x.completion) > 10000, axis=1 @@ -171,10 +173,12 @@ def get_long_indexes(d): optional_msg = f"Remove {len(long_indexes)} long examples" def optional_fn(x): - + long_indexes_to_drop = get_long_indexes(x) if long_indexes != long_indexes_to_drop: - sys.stdout.write(f"The indices of the long examples has changed as a result of a previously applied recommendation.\nThe {len(long_indexes_to_drop)} long examples to be dropped are now at the following indices: {long_indexes_to_drop}\n") + sys.stdout.write( + f"The indices of the long examples has changed as a result of a previously applied recommendation.\nThe {len(long_indexes_to_drop)} long examples to be dropped are now at the following indices: {long_indexes_to_drop}\n" + ) return x.drop(long_indexes_to_drop) return Remediation( diff --git a/openai/wandb_logger.py b/openai/wandb_logger.py index ba650d1fe4..fdd8c24adc 100644 --- a/openai/wandb_logger.py +++ b/openai/wandb_logger.py @@ -14,8 +14,8 @@ from pathlib import Path from openai import File, FineTune - from openai.datalib import numpy as np - from openai.datalib import pandas as pd + from openai.datalib.numpy_helper import numpy as np + from openai.datalib.pandas_helper import pandas as pd class WandbLogger: From 6572ef4f85371ec56397d9e125ae5f45ba231744 Mon Sep 17 00:00:00 2001 From: ZheNing Hu Date: Sat, 8 Apr 2023 09:09:55 +0800 Subject: [PATCH 015/816] Add proxy argument support for openai client (#313) Co-authored-by: huzhening.hzn --- README.md | 3 +++ openai/_openai_scripts.py | 8 ++++++++ 2 files changed, 11 insertions(+) diff --git a/README.md b/README.md index fb5a3e32f9..c0ca2724a6 100644 --- a/README.md +++ b/README.md @@ -138,6 +138,9 @@ openai api chat_completions.create -m gpt-3.5-turbo -g user "Hello world" # generate images via DALL·E API openai api image.create -p "two dogs playing chess, cartoon" -n 1 + +# using openai through a proxy +openai --proxy=http://proxy.com api models.list ``` ## Example code diff --git a/openai/_openai_scripts.py b/openai/_openai_scripts.py index aaf23b0cad..f2aa3ce2b9 100755 --- a/openai/_openai_scripts.py +++ b/openai/_openai_scripts.py @@ -32,6 +32,7 @@ def main(): ) parser.add_argument("-b", "--api-base", help="What API base url to use.") parser.add_argument("-k", "--api-key", help="What API key to use.") + parser.add_argument("-p", "--proxy", nargs='+', help="What proxy to use.") parser.add_argument( "-o", "--organization", @@ -65,6 +66,13 @@ def help(args): openai.api_base = args.api_base if args.organization is not None: openai.organization = args.organization + if args.proxy is not None: + openai.proxy = {} + for proxy in args.proxy: + if proxy.startswith('https'): + openai.proxy['https'] = proxy + elif proxy.startswith('http'): + openai.proxy['http'] = proxy try: args.func(args) From aa133ce3a883e2957aa1e0111ee27dfef986e787 Mon Sep 17 00:00:00 2001 From: Harutaka Kawamura Date: Sat, 8 Apr 2023 13:38:25 +0900 Subject: [PATCH 016/816] Update __init__.py (#382) --- openai/__init__.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/openai/__init__.py b/openai/__init__.py index 1a69e24485..3e2cb1e281 100644 --- a/openai/__init__.py +++ b/openai/__init__.py @@ -33,6 +33,7 @@ Moderation, ) from openai.error import APIError, InvalidRequestError, OpenAIError +from openai.version import VERSION if TYPE_CHECKING: from aiohttp import ClientSession @@ -62,6 +63,7 @@ ) # Acts as a global aiohttp ClientSession that reuses connections. # This is user-supplied; otherwise, a session is remade for each request. +__version__ = VERSION __all__ = [ "APIError", "Audio", From ff8d5cf1d4e696d7fcb6ff28857a2b5f8207e34c Mon Sep 17 00:00:00 2001 From: Luke Date: Mon, 10 Apr 2023 08:37:26 -0700 Subject: [PATCH 017/816] Fix grabbing value out of header (#388) --- openai/api_requestor.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openai/api_requestor.py b/openai/api_requestor.py index 827b73b78e..a56e16c417 100644 --- a/openai/api_requestor.py +++ b/openai/api_requestor.py @@ -667,7 +667,7 @@ def _interpret_response_line( headers=rheaders, ) try: - if 'text/plain' in rheaders.get('Content-Type'): + if 'text/plain' in rheaders.get('Content-Type', ''): data = rbody else: data = json.loads(rbody) From d6fa3bfaae69d639b0dd2e9251b375d7070bbef1 Mon Sep 17 00:00:00 2001 From: joe-at-openai <117690718+joe-at-openai@users.noreply.github.com> Date: Mon, 10 Apr 2023 08:41:17 -0700 Subject: [PATCH 018/816] add case to handle indented .json parsing (#175) (#389) --- openai/validators.py | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/openai/validators.py b/openai/validators.py index 97083659df..078179a44b 100644 --- a/openai/validators.py +++ b/openai/validators.py @@ -526,14 +526,21 @@ def read_any_format(fname, fields=["prompt", "completion"]): else: pass # this is what we expect for a .jsonl file elif fname.lower().endswith(".json"): - df = pd.read_json(fname, lines=True, dtype=str).fillna("") - if len(df) == 1: - # this is what we expect for a .json file + try: + # to handle case where .json file is actually a .jsonl file + df = pd.read_json(fname, lines=True, dtype=str).fillna("") + if len(df) == 1: + # this code path corresponds to a .json file that has one line + df = pd.read_json(fname, dtype=str).fillna("") + else: + # this is NOT what we expect for a .json file + immediate_msg = "\n- Your JSON file appears to be in a JSONL format. Your file will be converted to JSONL format" + necessary_msg = ( + "Your format `JSON` will be converted to `JSONL`" + ) + except ValueError: + # this code path corresponds to a .json file that has multiple lines (i.e. it is indented) df = pd.read_json(fname, dtype=str).fillna("") - else: - # this is NOT what we expect for a .json file - immediate_msg = "\n- Your JSON file appears to be in a JSONL format. Your file will be converted to JSONL format" - necessary_msg = "Your format `JSON` will be converted to `JSONL`" else: error_msg = "Your file must have one of the following extensions: .CSV, .TSV, .XLSX, .TXT, .JSON or .JSONL" if "." in fname: From c5f0cc41fb5480ecc2f7078be9749fe6a9b8f143 Mon Sep 17 00:00:00 2001 From: Harutaka Kawamura Date: Tue, 18 Apr 2023 02:59:15 +0900 Subject: [PATCH 019/816] Add openai/datalib/__init__.py (#404) Signed-off-by: harupy --- openai/datalib/__init__.py | 14 ++++++++++++++ openai/datalib/common.py | 19 ++----------------- 2 files changed, 16 insertions(+), 17 deletions(-) create mode 100644 openai/datalib/__init__.py diff --git a/openai/datalib/__init__.py b/openai/datalib/__init__.py new file mode 100644 index 0000000000..d02b49cfff --- /dev/null +++ b/openai/datalib/__init__.py @@ -0,0 +1,14 @@ +""" +This module helps make data libraries like `numpy` and `pandas` optional dependencies. + +The libraries add up to 130MB+, which makes it challenging to deploy applications +using this library in environments with code size constraints, like AWS Lambda. + +This module serves as an import proxy and provides a few utilities for dealing with the optionality. + +Since the primary use case of this library (talking to the OpenAI API) doesn't generally require data libraries, +it's safe to make them optional. The rare case when data libraries are needed in the client is handled through +assertions with instructive error messages. + +See also `setup.py`. +""" diff --git a/openai/datalib/common.py b/openai/datalib/common.py index 678b3395fd..96f9908a18 100644 --- a/openai/datalib/common.py +++ b/openai/datalib/common.py @@ -1,23 +1,8 @@ -""" -This module helps make data libraries like `numpy` and `pandas` optional dependencies. - -The libraries add up to 130MB+, which makes it challenging to deploy applications -using this library in environments with code size constraints, like AWS Lambda. - -This module serves as an import proxy and provides a few utilities for dealing with the optionality. - -Since the primary use case of this library (talking to the OpenAI API) doesn’t generally require data libraries, -it’s safe to make them optional. The rare case when data libraries are needed in the client is handled through -assertions with instructive error messages. - -See also `setup.py`. - -""" INSTRUCTIONS = """ -OpenAI error: +OpenAI error: - missing `{library}` + missing `{library}` This feature requires additional dependencies: From 794def37e51f9dbfd1fef7cd451a5d92d5323a43 Mon Sep 17 00:00:00 2001 From: Someet_Sahoo <32305867+Someet-Git@users.noreply.github.com> Date: Tue, 18 Apr 2023 01:40:12 +0530 Subject: [PATCH 020/816] updated the link for OpenAI API (#400) * just updated the url for OpenAi API * updated the docs --- openai/util.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openai/util.py b/openai/util.py index 56dfc2e677..f11dc08e8c 100644 --- a/openai/util.py +++ b/openai/util.py @@ -184,5 +184,5 @@ def default_api_key() -> str: return openai.api_key else: raise openai.error.AuthenticationError( - "No API key provided. You can set your API key in code using 'openai.api_key = ', or you can set the environment variable OPENAI_API_KEY=). If your API key is stored in a file, you can point the openai module at it with 'openai.api_key_path = '. You can generate API keys in the OpenAI web interface. See https://onboard.openai.com for details, or email support@openai.com if you have any questions." + "No API key provided. You can set your API key in code using 'openai.api_key = ', or you can set the environment variable OPENAI_API_KEY=). If your API key is stored in a file, you can point the openai module at it with 'openai.api_key_path = '. You can generate API keys in the OpenAI web interface. See https://platform.openai.com/account/api-keys for details, or email support@openai.com if you have any questions." ) From db3f3526f16ea518bcd16308508e035017f9259e Mon Sep 17 00:00:00 2001 From: Liren Tu Date: Wed, 19 Apr 2023 14:04:20 -0700 Subject: [PATCH 021/816] Pass in keyword arguments in embedding utility functions (#405) * Pass in kwargs in embedding util functions * Remove debug code --- openai/embeddings_utils.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/openai/embeddings_utils.py b/openai/embeddings_utils.py index 08fa94c2ea..1b65e7c8e9 100644 --- a/openai/embeddings_utils.py +++ b/openai/embeddings_utils.py @@ -15,51 +15,51 @@ @retry(wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6)) -def get_embedding(text: str, engine="text-similarity-davinci-001") -> List[float]: +def get_embedding(text: str, engine="text-similarity-davinci-001", **kwargs) -> List[float]: # replace newlines, which can negatively affect performance. text = text.replace("\n", " ") - return openai.Embedding.create(input=[text], engine=engine)["data"][0]["embedding"] + return openai.Embedding.create(input=[text], engine=engine, **kwargs)["data"][0]["embedding"] @retry(wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6)) async def aget_embedding( - text: str, engine="text-similarity-davinci-001" + text: str, engine="text-similarity-davinci-001", **kwargs ) -> List[float]: # replace newlines, which can negatively affect performance. text = text.replace("\n", " ") - return (await openai.Embedding.acreate(input=[text], engine=engine))["data"][0][ + return (await openai.Embedding.acreate(input=[text], engine=engine, **kwargs))["data"][0][ "embedding" ] @retry(wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6)) def get_embeddings( - list_of_text: List[str], engine="text-similarity-babbage-001" + list_of_text: List[str], engine="text-similarity-babbage-001", **kwargs ) -> List[List[float]]: assert len(list_of_text) <= 2048, "The batch size should not be larger than 2048." # replace newlines, which can negatively affect performance. list_of_text = [text.replace("\n", " ") for text in list_of_text] - data = openai.Embedding.create(input=list_of_text, engine=engine).data + data = openai.Embedding.create(input=list_of_text, engine=engine, **kwargs).data data = sorted(data, key=lambda x: x["index"]) # maintain the same order as input. return [d["embedding"] for d in data] @retry(wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6)) async def aget_embeddings( - list_of_text: List[str], engine="text-similarity-babbage-001" + list_of_text: List[str], engine="text-similarity-babbage-001", **kwargs ) -> List[List[float]]: assert len(list_of_text) <= 2048, "The batch size should not be larger than 2048." # replace newlines, which can negatively affect performance. list_of_text = [text.replace("\n", " ") for text in list_of_text] - data = (await openai.Embedding.acreate(input=list_of_text, engine=engine)).data + data = (await openai.Embedding.acreate(input=list_of_text, engine=engine, **kwargs)).data data = sorted(data, key=lambda x: x["index"]) # maintain the same order as input. return [d["embedding"] for d in data] From 96e7642a8e88260e33f486ea8aa38533602b984c Mon Sep 17 00:00:00 2001 From: hallacy Date: Thu, 27 Apr 2023 09:52:16 -0700 Subject: [PATCH 022/816] Bump to 0.27.5 (#417) --- openai/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openai/version.py b/openai/version.py index 7fb4979dc6..d1af62ba49 100644 --- a/openai/version.py +++ b/openai/version.py @@ -1 +1 @@ -VERSION = "0.27.4" +VERSION = "0.27.5" From c556584eff3b36c92278e6af62cfe02ebb68fb65 Mon Sep 17 00:00:00 2001 From: Krista Pratico Date: Thu, 27 Apr 2023 10:01:49 -0700 Subject: [PATCH 023/816] allow for user passed requests.Session (#390) --- openai/__init__.py | 7 ++++++- openai/api_requestor.py | 4 ++++ openai/tests/test_endpoints.py | 30 ++++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 1 deletion(-) diff --git a/openai/__init__.py b/openai/__init__.py index 3e2cb1e281..ecf663a3b0 100644 --- a/openai/__init__.py +++ b/openai/__init__.py @@ -4,7 +4,7 @@ import os import sys -from typing import TYPE_CHECKING, Optional +from typing import TYPE_CHECKING, Optional, Union, Callable from contextvars import ContextVar @@ -36,6 +36,7 @@ from openai.version import VERSION if TYPE_CHECKING: + import requests from aiohttp import ClientSession api_key = os.environ.get("OPENAI_API_KEY") @@ -58,6 +59,10 @@ debug = False log = None # Set to either 'debug' or 'info', controls console logging +requestssession: Optional[ + Union["requests.Session", Callable[[], "requests.Session"]] +] = None # Provide a requests.Session or Session factory. + aiosession: ContextVar[Optional["ClientSession"]] = ContextVar( "aiohttp-session", default=None ) # Acts as a global aiohttp ClientSession that reuses connections. diff --git a/openai/api_requestor.py b/openai/api_requestor.py index a56e16c417..a8a1fe331e 100644 --- a/openai/api_requestor.py +++ b/openai/api_requestor.py @@ -76,6 +76,10 @@ def _aiohttp_proxies_arg(proxy) -> Optional[str]: def _make_session() -> requests.Session: + if openai.requestssession: + if isinstance(openai.requestssession, requests.Session): + return openai.requestssession + return openai.requestssession() if not openai.verify_ssl_certs: warnings.warn("verify_ssl_certs is ignored; openai always verifies.") s = requests.Session() diff --git a/openai/tests/test_endpoints.py b/openai/tests/test_endpoints.py index c3fc1094bb..958e07f091 100644 --- a/openai/tests/test_endpoints.py +++ b/openai/tests/test_endpoints.py @@ -2,6 +2,7 @@ import json import pytest +import requests import openai from openai import error @@ -86,3 +87,32 @@ def test_timeout_does_not_error(): model="ada", request_timeout=10, ) + + +def test_user_session(): + with requests.Session() as session: + openai.requestssession = session + + completion = openai.Completion.create( + prompt="hello world", + model="ada", + ) + assert completion + + +def test_user_session_factory(): + def factory(): + session = requests.Session() + session.mount( + "https://", + requests.adapters.HTTPAdapter(max_retries=4), + ) + return session + + openai.requestssession = factory + + completion = openai.Completion.create( + prompt="hello world", + model="ada", + ) + assert completion From 6fb0efde6fa984f1b666e35814cc3e8e861bbca3 Mon Sep 17 00:00:00 2001 From: Michelle Pokrass Date: Mon, 1 May 2023 15:50:21 -0700 Subject: [PATCH 024/816] fix error messages mentioning support@ (#427) Co-authored-by: Shyamal H Anadkat --- openai/api_requestor.py | 2 +- openai/cli.py | 2 +- openai/error.py | 2 +- openai/util.py | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/openai/api_requestor.py b/openai/api_requestor.py index a8a1fe331e..964bbd84e7 100644 --- a/openai/api_requestor.py +++ b/openai/api_requestor.py @@ -487,7 +487,7 @@ def _prepare_request_raw( else: raise error.APIConnectionError( "Unrecognized HTTP method %r. This may indicate a bug in the " - "OpenAI bindings. Please contact support@openai.com for " + "OpenAI bindings. Please contact us through our help center at help.openai.com for " "assistance." % (method,) ) diff --git a/openai/cli.py b/openai/cli.py index e1bf3eac06..e924133d72 100644 --- a/openai/cli.py +++ b/openai/cli.py @@ -565,7 +565,7 @@ def signal_handler(sig, frame): ) elif status == "failed": sys.stdout.write( - "\nJob failed. Please contact support@openai.com if you need assistance." + "\nJob failed. Please contact us through our help center at help.openai.com if you need assistance." ) sys.stdout.write("\n") diff --git a/openai/error.py b/openai/error.py index 16692569da..2928ef6aa6 100644 --- a/openai/error.py +++ b/openai/error.py @@ -19,7 +19,7 @@ def __init__( except BaseException: http_body = ( "" + "Please contact us through our help center at help.openai.com.>" ) self._message = message diff --git a/openai/util.py b/openai/util.py index f11dc08e8c..5501d5b67e 100644 --- a/openai/util.py +++ b/openai/util.py @@ -184,5 +184,5 @@ def default_api_key() -> str: return openai.api_key else: raise openai.error.AuthenticationError( - "No API key provided. You can set your API key in code using 'openai.api_key = ', or you can set the environment variable OPENAI_API_KEY=). If your API key is stored in a file, you can point the openai module at it with 'openai.api_key_path = '. You can generate API keys in the OpenAI web interface. See https://platform.openai.com/account/api-keys for details, or email support@openai.com if you have any questions." + "No API key provided. You can set your API key in code using 'openai.api_key = ', or you can set the environment variable OPENAI_API_KEY=). If your API key is stored in a file, you can point the openai module at it with 'openai.api_key_path = '. You can generate API keys in the OpenAI web interface. See https://platform.openai.com/account/api-keys for details." ) From c975bce15e81f000a1c5130510928e92bfa04fa8 Mon Sep 17 00:00:00 2001 From: Michelle Pokrass Date: Mon, 1 May 2023 15:54:06 -0700 Subject: [PATCH 025/816] bump version (#428) --- openai/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openai/version.py b/openai/version.py index d1af62ba49..53d320d921 100644 --- a/openai/version.py +++ b/openai/version.py @@ -1 +1 @@ -VERSION = "0.27.5" +VERSION = "0.27.6" From f24d1931d3067234cf27319c6fa7250f133c8d90 Mon Sep 17 00:00:00 2001 From: Rafal Wojdyla Date: Wed, 3 May 2023 16:24:25 +0100 Subject: [PATCH 026/816] Embeddings util - remove unnecessary sort by index (#430) --- openai/embeddings_utils.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/openai/embeddings_utils.py b/openai/embeddings_utils.py index 1b65e7c8e9..f1d438c9c0 100644 --- a/openai/embeddings_utils.py +++ b/openai/embeddings_utils.py @@ -46,7 +46,6 @@ def get_embeddings( list_of_text = [text.replace("\n", " ") for text in list_of_text] data = openai.Embedding.create(input=list_of_text, engine=engine, **kwargs).data - data = sorted(data, key=lambda x: x["index"]) # maintain the same order as input. return [d["embedding"] for d in data] @@ -60,7 +59,6 @@ async def aget_embeddings( list_of_text = [text.replace("\n", " ") for text in list_of_text] data = (await openai.Embedding.acreate(input=list_of_text, engine=engine, **kwargs)).data - data = sorted(data, key=lambda x: x["index"]) # maintain the same order as input. return [d["embedding"] for d in data] From 03f848e3c91e1cb6e1a7860ea91e219f82cc97f4 Mon Sep 17 00:00:00 2001 From: Krista Pratico Date: Sat, 6 May 2023 09:26:23 -0700 Subject: [PATCH 027/816] allow api_version to be set by environment variable (#438) --- openai/__init__.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/openai/__init__.py b/openai/__init__.py index ecf663a3b0..3ff85c2662 100644 --- a/openai/__init__.py +++ b/openai/__init__.py @@ -48,8 +48,9 @@ organization = os.environ.get("OPENAI_ORGANIZATION") api_base = os.environ.get("OPENAI_API_BASE", "https://api.openai.com/v1") api_type = os.environ.get("OPENAI_API_TYPE", "open_ai") -api_version = ( - "2023-03-15-preview" if api_type in ("azure", "azure_ad", "azuread") else None +api_version = os.environ.get( + "OPENAI_API_VERSION", + ("2023-03-15-preview" if api_type in ("azure", "azure_ad", "azuread") else None), ) verify_ssl_certs = True # No effect. Certificates are always verified. proxy = None From 91a63f2ccd6468a2b32d66f4ee657ac1a3acf4c6 Mon Sep 17 00:00:00 2001 From: Mike Amy Date: Tue, 9 May 2023 01:27:54 +0700 Subject: [PATCH 028/816] Fixed CLI streamed chat completions. (#319) * Fixed streamed chat completions. Streamed chat completions use a different response structure per returned token, also they may have roles and empty tokens at the end. Handle this sensibly. * Only render content --------- Co-authored-by: Atty Eleti --- openai/cli.py | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/openai/cli.py b/openai/cli.py index e924133d72..ad08ac3e7b 100644 --- a/openai/cli.py +++ b/openai/cli.py @@ -141,9 +141,14 @@ def create(cls, args): for c_idx, c in enumerate(sorted(choices, key=lambda s: s["index"])): if len(choices) > 1: sys.stdout.write("===== Chat Completion {} =====\n".format(c_idx)) - sys.stdout.write(c["message"]["content"]) - if len(choices) > 1: - sys.stdout.write("\n") + if args.stream: + delta = c["delta"] + if "content" in delta: + sys.stdout.write(delta["content"]) + else: + sys.stdout.write(c["message"]["content"]) + if len(choices) > 1: # not in streams + sys.stdout.write("\n") sys.stdout.flush() @@ -203,7 +208,9 @@ def list(cls, args): @classmethod def create(cls, args): - models = openai.Deployment.create(model=args.model, scale_settings={"scale_type": args.scale_type}) + models = openai.Deployment.create( + model=args.model, scale_settings={"scale_type": args.scale_type} + ) print(models) @@ -833,10 +840,15 @@ def help(args): sub = subparsers.add_parser("deployments.delete") sub.add_argument("-i", "--id", required=True, help="The deployment ID") sub.set_defaults(func=Deployment.delete) - + sub = subparsers.add_parser("deployments.create") sub.add_argument("-m", "--model", required=True, help="The model ID") - sub.add_argument("-s", "--scale_type", required=True, help="The scale type. Either 'manual' or 'standard'") + sub.add_argument( + "-s", + "--scale_type", + required=True, + help="The scale type. Either 'manual' or 'standard'", + ) sub.set_defaults(func=Deployment.create) # Models From 2b21516ee87cae266160023da678a82deb791c9b Mon Sep 17 00:00:00 2001 From: Atty Eleti Date: Tue, 9 May 2023 21:37:02 +0530 Subject: [PATCH 029/816] Update README to use gpt-3.5-turbo by default (#441) --- README.md | 76 ++++++++++++++++++++++++++++++++----------------------- 1 file changed, 45 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index c0ca2724a6..4ce2921287 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ Data libraries like `numpy` and `pandas` are not installed by default due to the ```sh pip install openai[datalib] -```` +``` ## Usage @@ -63,16 +63,16 @@ models = openai.Model.list() # print the first model's id print(models.data[0].id) -# create a completion -completion = openai.Completion.create(model="ada", prompt="Hello world") +# create a chat completion +chat_completion = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello world"}]) -# print the completion -print(completion.choices[0].text) +# print the chat completion +print(chat_completion.choices[0].message.content) ``` - ### Params -All endpoints have a `.create` method that supports a `request_timeout` param. This param takes a `Union[float, Tuple[float, float]]` and will raise an `openai.error.Timeout` error if the request exceeds that time in seconds (See: https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts). + +All endpoints have a `.create` method that supports a `request_timeout` param. This param takes a `Union[float, Tuple[float, float]]` and will raise an `openai.error.Timeout` error if the request exceeds that time in seconds (See: https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts). ### Microsoft Azure Endpoints @@ -86,24 +86,24 @@ openai.api_key = "..." openai.api_base = "https://example-endpoint.openai.azure.com/" openai.api_version = "2023-03-15-preview" -# create a completion -completion = openai.Completion.create(deployment_id="deployment-name", prompt="Hello world") +# create a chat completion +chat_completion = openai.ChatCompletion.create(deployment_id="deployment-name", model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello world"}]) # print the completion -print(completion.choices[0].text) +print(completion.choices[0].message.content) ``` Please note that for the moment, the Microsoft Azure endpoints can only be used for completion, embedding, and fine-tuning operations. For a detailed example of how to use fine-tuning and other operations using Azure endpoints, please check out the following Jupyter notebooks: -* [Using Azure completions](https://github.com/openai/openai-cookbook/tree/main/examples/azure/completions.ipynb) -* [Using Azure fine-tuning](https://github.com/openai/openai-cookbook/tree/main/examples/azure/finetuning.ipynb) -* [Using Azure embeddings](https://github.com/openai/openai-cookbook/blob/main/examples/azure/embeddings.ipynb) + +- [Using Azure completions](https://github.com/openai/openai-cookbook/tree/main/examples/azure/completions.ipynb) +- [Using Azure fine-tuning](https://github.com/openai/openai-cookbook/tree/main/examples/azure/finetuning.ipynb) +- [Using Azure embeddings](https://github.com/openai/openai-cookbook/blob/main/examples/azure/embeddings.ipynb) ### Microsoft Azure Active Directory Authentication In order to use Microsoft Active Directory to authenticate to your Azure endpoint, you need to set the `api_type` to "azure_ad" and pass the acquired credential token to `api_key`. The rest of the parameters need to be set as specified in the previous section. - ```python from azure.identity import DefaultAzureCredential import openai @@ -120,6 +120,7 @@ openai.api_version = "2023-03-15-preview" # ... ``` + ### Command-line interface This library additionally provides an `openai` command-line utility @@ -130,12 +131,12 @@ which makes it easy to interact with the API from your terminal. Run # list models openai api models.list -# create a completion -openai api completions.create -m ada -p "Hello world" - -# create a chat completion +# create a chat completion (gpt-3.5-turbo, gpt-4, etc.) openai api chat_completions.create -m gpt-3.5-turbo -g user "Hello world" +# create a completion (text-davinci-003, text-davinci-002, ada, babbage, curie, davinci, etc.) +openai api completions.create -m ada -p "Hello world" + # generate images via DALL·E API openai api image.create -p "two dogs playing chess, cartoon" -n 1 @@ -147,18 +148,18 @@ openai --proxy=http://proxy.com api models.list Examples of how to use this Python library to accomplish various tasks can be found in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook/). It contains code examples for: -* Classification using fine-tuning -* Clustering -* Code search -* Customizing embeddings -* Question answering from a corpus of documents -* Recommendations -* Visualization of embeddings -* And more +- Classification using fine-tuning +- Clustering +- Code search +- Customizing embeddings +- Question answering from a corpus of documents +- Recommendations +- Visualization of embeddings +- And more Prior to July 2022, this OpenAI Python library hosted code examples in its examples folder, but since then all examples have been migrated to the [OpenAI Cookbook](https://github.com/openai/openai-cookbook/). -### Chat +### Chat Completions Conversational models such as `gpt-3.5-turbo` can be called using the chat completions endpoint. @@ -166,10 +167,22 @@ Conversational models such as `gpt-3.5-turbo` can be called using the chat compl import openai openai.api_key = "sk-..." # supply your API key however you choose -completion = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello world!"}]) +completion = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello world"}]) print(completion.choices[0].message.content) ``` +### Completions + +Text models such as `text-davinci-003`, `text-davinci-002` and earlier (`ada`, `babbage`, `curie`, `davinci`, etc.) can be called using the completions endpoint. + +```python +import openai +openai.api_key = "sk-..." # supply your API key however you choose + +completion = openai.Completion.create(model="text-davinci-003", prompt="Hello world") +print(completion.choices[0].text) +``` + ### Embeddings In the OpenAI Python library, an embedding represents a text string as a fixed-length vector of floating point numbers. Embeddings are designed to measure the similarity or relevance between text strings. @@ -248,6 +261,7 @@ image_resp = openai.Image.create(prompt="two dogs playing chess, oil painting", ``` ## Audio transcription (Whisper) + ```python import openai openai.api_key = "sk-..." # supply your API key however you choose @@ -264,13 +278,13 @@ Async support is available in the API by prepending `a` to a network-bound metho import openai openai.api_key = "sk-..." # supply your API key however you choose -async def create_completion(): - completion_resp = await openai.Completion.acreate(prompt="This is a test", model="davinci") +async def create_chat_completion(): + chat_completion_resp = await openai.ChatCompletion.acreate(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello world"}]) ``` To make async requests more efficient, you can pass in your own -``aiohttp.ClientSession``, but you must manually close the client session at the end +`aiohttp.ClientSession`, but you must manually close the client session at the end of your program/event loop: ```python From da828789387755c964c8816d1198d9a61df85b2e Mon Sep 17 00:00:00 2001 From: Gerardo Lecaros Date: Thu, 18 May 2023 15:26:57 -0700 Subject: [PATCH 030/816] Updating code and readme to reference the Azure's newest 2023-05-15 API version. (#452) --- README.md | 4 ++-- openai/__init__.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 4ce2921287..d61fdee644 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ import openai openai.api_type = "azure" openai.api_key = "..." openai.api_base = "https://example-endpoint.openai.azure.com/" -openai.api_version = "2023-03-15-preview" +openai.api_version = "2023-05-15" # create a chat completion chat_completion = openai.ChatCompletion.create(deployment_id="deployment-name", model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello world"}]) @@ -116,7 +116,7 @@ token = default_credential.get_token("https://cognitiveservices.azure.com/.defau%20openai.api_type%20="azure_ad" openai.api_key = token.token openai.api_base = "https://example-endpoint.openai.azure.com/" -openai.api_version = "2023-03-15-preview" +openai.api_version = "2023-05-15" # ... ``` diff --git a/openai/__init__.py b/openai/__init__.py index 3ff85c2662..537f12883e 100644 --- a/openai/__init__.py +++ b/openai/__init__.py @@ -50,7 +50,7 @@ api_type = os.environ.get("OPENAI_API_TYPE", "open_ai") api_version = os.environ.get( "OPENAI_API_VERSION", - ("2023-03-15-preview" if api_type in ("azure", "azure_ad", "azuread") else None), + ("2023-05-15" if api_type in ("azure", "azure_ad", "azuread") else None), ) verify_ssl_certs = True # No effect. Certificates are always verified. proxy = None From fe3abd16b582ae784d8a73fd249bcdfebd5752c9 Mon Sep 17 00:00:00 2001 From: hallacy Date: Fri, 19 May 2023 10:28:16 -0700 Subject: [PATCH 031/816] Update version.py (#458) Bump for release --- openai/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openai/version.py b/openai/version.py index 53d320d921..aa89e032d8 100644 --- a/openai/version.py +++ b/openai/version.py @@ -1 +1 @@ -VERSION = "0.27.6" +VERSION = "0.27.7" From 77e5cf97933235b5567a5c9af0eac39f470b1f94 Mon Sep 17 00:00:00 2001 From: John Allard Date: Mon, 5 Jun 2023 17:23:47 -0700 Subject: [PATCH 032/816] Periodically close open `request.Sessions` to avoid buggy interaction with Docker Desktop (#478) * Periodically refresh open `requests.Session`s to mitigate open filehandle issues (#179) As reported, we create a `requests.Session` object on first request to the servers and then reuse it indefinitely. This can leave some open file handles on the OS (not a big deal), but can interact poorly with a bug in Docker Desktop which causes the SDK to entierly break connections to the server. See https://github.com/openai/openai-python/issues/140 for more info. The order of items in the API responses is intentional, and this order is clobbered by the rendering of `OpenAIObject`. This change removes the alphabetic sort of response keys --- openai/api_requestor.py | 10 ++++++++++ openai/openai_object.py | 2 +- openai/tests/test_api_requestor.py | 32 ++++++++++++++++++++++++++++++ openai/tests/test_util.py | 25 +++++++++++++++++++++++ 4 files changed, 68 insertions(+), 1 deletion(-) diff --git a/openai/api_requestor.py b/openai/api_requestor.py index 964bbd84e7..cde4108bde 100644 --- a/openai/api_requestor.py +++ b/openai/api_requestor.py @@ -3,6 +3,7 @@ import platform import sys import threading +import time import warnings from contextlib import asynccontextmanager from json import JSONDecodeError @@ -32,6 +33,7 @@ from openai.util import ApiType TIMEOUT_SECS = 600 +MAX_SESSION_LIFETIME_SECS = 180 MAX_CONNECTION_RETRIES = 2 # Has one attribute per thread, 'session'. @@ -516,6 +518,14 @@ def request_raw( if not hasattr(_thread_context, "session"): _thread_context.session = _make_session() + _thread_context.session_create_time = time.time() + elif ( + time.time() - getattr(_thread_context, "session_create_time", 0) + >= MAX_SESSION_LIFETIME_SECS + ): + _thread_context.session.close() + _thread_context.session = _make_session() + _thread_context.session_create_time = time.time() try: result = _thread_context.session.request( method, diff --git a/openai/openai_object.py b/openai/openai_object.py index c0af6bbc2a..95f8829742 100644 --- a/openai/openai_object.py +++ b/openai/openai_object.py @@ -278,7 +278,7 @@ def __repr__(self): def __str__(self): obj = self.to_dict_recursive() - return json.dumps(obj, sort_keys=True, indent=2) + return json.dumps(obj, indent=2) def to_dict(self): return dict(self) diff --git a/openai/tests/test_api_requestor.py b/openai/tests/test_api_requestor.py index 4998a0ffb2..56e8ec89da 100644 --- a/openai/tests/test_api_requestor.py +++ b/openai/tests/test_api_requestor.py @@ -67,3 +67,35 @@ def test_requestor_azure_ad_headers() -> None: assert headers["Test_Header"] == "Unit_Test_Header" assert "Authorization" in headers assert headers["Authorization"] == "Bearer test_key" + + +@pytest.mark.requestor +def test_requestor_cycle_sessions(mocker: MockerFixture) -> None: + # HACK: we need to purge the _thread_context to not interfere + # with other tests + from openai.api_requestor import _thread_context + + delattr(_thread_context, "session") + + api_requestor = APIRequestor(key="test_key", api_type="azure_ad") + + mock_session = mocker.MagicMock() + mocker.patch("openai.api_requestor._make_session", lambda: mock_session) + + # We don't call `session.close()` if not enough time has elapsed + api_requestor.request_raw("get", "http://example.com/") + mock_session.request.assert_called() + api_requestor.request_raw("get", "http://example.com/") + mock_session.close.assert_not_called() + + mocker.patch("openai.api_requestor.MAX_SESSION_LIFETIME_SECS", 0) + + # Due to 0 lifetime, the original session will be closed before the next call + # and a new session will be created + mock_session_2 = mocker.MagicMock() + mocker.patch("openai.api_requestor._make_session", lambda: mock_session_2) + api_requestor.request_raw("get", "http://example.com/") + mock_session.close.assert_called() + mock_session_2.request.assert_called() + + delattr(_thread_context, "session") diff --git a/openai/tests/test_util.py b/openai/tests/test_util.py index d0ce0ac5c4..6220ccb7f4 100644 --- a/openai/tests/test_util.py +++ b/openai/tests/test_util.py @@ -1,3 +1,4 @@ +import json from tempfile import NamedTemporaryFile import pytest @@ -28,3 +29,27 @@ def test_openai_api_key_path_with_malformed_key(api_key_file) -> None: api_key_file.flush() with pytest.raises(ValueError, match="Malformed API key"): util.default_api_key() + + +def test_key_order_openai_object_rendering() -> None: + sample_response = { + "id": "chatcmpl-7NaPEA6sgX7LnNPyKPbRlsyqLbr5V", + "object": "chat.completion", + "created": 1685855844, + "model": "gpt-3.5-turbo-0301", + "usage": {"prompt_tokens": 57, "completion_tokens": 40, "total_tokens": 97}, + "choices": [ + { + "message": { + "role": "assistant", + "content": "The 2020 World Series was played at Globe Life Field in Arlington, Texas. It was the first time that the World Series was played at a neutral site because of the COVID-19 pandemic.", + }, + "finish_reason": "stop", + "index": 0, + } + ], + } + + oai_object = util.convert_to_openai_object(sample_response) + # The `__str__` method was sorting while dumping to json + assert list(json.loads(str(oai_object)).keys()) == list(sample_response.keys()) From 6e159bf0ba579b8feb2f24d02e4c4dab7afb3e57 Mon Sep 17 00:00:00 2001 From: Gerardo Lecaros Date: Tue, 6 Jun 2023 16:03:49 -0700 Subject: [PATCH 033/816] Support for Azure Dall-e (#439) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * This PR updates #337 with updates for it to work with the latest API preview --------- Co-authored-by: Christian Mürtz --- openai/api_requestor.py | 66 +++++++++++++++++++++++++++++++++++ openai/api_resources/image.py | 53 ++++++++++++++++++++++------ openai/openai_response.py | 11 ++++++ 3 files changed, 119 insertions(+), 11 deletions(-) diff --git a/openai/api_requestor.py b/openai/api_requestor.py index cde4108bde..a6565c0351 100644 --- a/openai/api_requestor.py +++ b/openai/api_requestor.py @@ -1,5 +1,6 @@ import asyncio import json +import time import platform import sys import threading @@ -10,6 +11,7 @@ from typing import ( AsyncGenerator, AsyncIterator, + Callable, Dict, Iterator, Optional, @@ -151,6 +153,70 @@ def format_app_info(cls, info): str += " (%s)" % (info["url"],) return str + def _check_polling_response(self, response: OpenAIResponse, predicate: Callable[[OpenAIResponse], bool]): + if not predicate(response): + return + error_data = response.data['error'] + message = error_data.get('message', 'Operation failed') + code = error_data.get('code') + raise error.OpenAIError(message=message, code=code) + + def _poll( + self, + method, + url, + until, + failed, + params = None, + headers = None, + interval = None, + delay = None + ) -> Tuple[Iterator[OpenAIResponse], bool, str]: + if delay: + time.sleep(delay) + + response, b, api_key = self.request(method, url, params, headers) + self._check_polling_response(response, failed) + start_time = time.time() + while not until(response): + if time.time() - start_time > TIMEOUT_SECS: + raise error.Timeout("Operation polling timed out.") + + time.sleep(interval or response.retry_after or 10) + response, b, api_key = self.request(method, url, params, headers) + self._check_polling_response(response, failed) + + response.data = response.data['result'] + return response, b, api_key + + async def _apoll( + self, + method, + url, + until, + failed, + params = None, + headers = None, + interval = None, + delay = None + ) -> Tuple[Iterator[OpenAIResponse], bool, str]: + if delay: + await asyncio.sleep(delay) + + response, b, api_key = await self.arequest(method, url, params, headers) + self._check_polling_response(response, failed) + start_time = time.time() + while not until(response): + if time.time() - start_time > TIMEOUT_SECS: + raise error.Timeout("Operation polling timed out.") + + await asyncio.sleep(interval or response.retry_after or 10) + response, b, api_key = await self.arequest(method, url, params, headers) + self._check_polling_response(response, failed) + + response.data = response.data['result'] + return response, b, api_key + @overload def request( self, diff --git a/openai/api_resources/image.py b/openai/api_resources/image.py index 39a5b6f616..1522923510 100644 --- a/openai/api_resources/image.py +++ b/openai/api_resources/image.py @@ -2,7 +2,7 @@ from typing import Any, List import openai -from openai import api_requestor, util +from openai import api_requestor, error, util from openai.api_resources.abstract import APIResource @@ -10,8 +10,11 @@ class Image(APIResource): OBJECT_NAME = "images" @classmethod - def _get_url(http://github.com/cls,%20action): - return cls.class_url() + f"/{action}" + def _get_url(http://github.com/cls,%20action,%20azure_action,%20api_type,%20api_version): + if api_type in (util.ApiType.AZURE, util.ApiType.AZURE_AD) and azure_action is not None: + return f"/{cls.azure_api_prefix}{cls.class_url()}/{action}:{azure_action}?api-version={api_version}" + else: + return f"{cls.class_url()}/{action}" @classmethod def create( @@ -31,12 +34,20 @@ def create( organization=organization, ) - _, api_version = cls._get_api_type_and_version(api_type, api_version) + api_type, api_version = cls._get_api_type_and_version(api_type, api_version) response, _, api_key = requestor.request( - "post", cls._get_url("http://github.com/generations"), params + "post", cls._get_url("http://github.com/generations%22,%20azure_action=%22/service/http://github.com/submit%22,%20api_type=api_type,%20api_version=api_version), params ) + if api_type in (util.ApiType.AZURE, util.ApiType.AZURE_AD): + requestor.api_base = "" # operation_location is a full url + response, _, api_key = requestor._poll( + "get", response.operation_location, + until=lambda response: response.data['status'] in [ 'succeeded' ], + failed=lambda response: response.data['status'] in [ 'failed' ] + ) + return util.convert_to_openai_object( response, api_key, api_version, organization ) @@ -60,12 +71,20 @@ async def acreate( organization=organization, ) - _, api_version = cls._get_api_type_and_version(api_type, api_version) + api_type, api_version = cls._get_api_type_and_version(api_type, api_version) response, _, api_key = await requestor.arequest( - "post", cls._get_url("http://github.com/generations"), params + "post", cls._get_url("http://github.com/generations%22,%20azure_action=%22/service/http://github.com/submit%22,%20api_type=api_type,%20api_version=api_version), params ) + if api_type in (util.ApiType.AZURE, util.ApiType.AZURE_AD): + requestor.api_base = "" # operation_location is a full url + response, _, api_key = await requestor._apoll( + "get", response.operation_location, + until=lambda response: response.data['status'] in [ 'succeeded' ], + failed=lambda response: response.data['status'] in [ 'failed' ] + ) + return util.convert_to_openai_object( response, api_key, api_version, organization ) @@ -88,9 +107,9 @@ def _prepare_create_variation( api_version=api_version, organization=organization, ) - _, api_version = cls._get_api_type_and_version(api_type, api_version) + api_type, api_version = cls._get_api_type_and_version(api_type, api_version) - url = cls._get_url("http://github.com/variations") + url = cls._get_url("http://github.com/variations%22,%20azure_action=None,%20api_type=api_type,%20api_version=api_version) files: List[Any] = [] for key, value in params.items(): @@ -109,6 +128,9 @@ def create_variation( organization=None, **params, ): + if api_type in (util.ApiType.AZURE, util.ApiType.AZURE_AD): + raise error.InvalidAPIType("Variations are not supported by the Azure OpenAI API yet.") + requestor, url, files = cls._prepare_create_variation( image, api_key, @@ -136,6 +158,9 @@ async def acreate_variation( organization=None, **params, ): + if api_type in (util.ApiType.AZURE, util.ApiType.AZURE_AD): + raise error.InvalidAPIType("Variations are not supported by the Azure OpenAI API yet.") + requestor, url, files = cls._prepare_create_variation( image, api_key, @@ -171,9 +196,9 @@ def _prepare_create_edit( api_version=api_version, organization=organization, ) - _, api_version = cls._get_api_type_and_version(api_type, api_version) + api_type, api_version = cls._get_api_type_and_version(api_type, api_version) - url = cls._get_url("http://github.com/edits") + url = cls._get_url("http://github.com/edits%22,%20azure_action=None,%20api_type=api_type,%20api_version=api_version) files: List[Any] = [] for key, value in params.items(): @@ -195,6 +220,9 @@ def create_edit( organization=None, **params, ): + if api_type in (util.ApiType.AZURE, util.ApiType.AZURE_AD): + raise error.InvalidAPIType("Edits are not supported by the Azure OpenAI API yet.") + requestor, url, files = cls._prepare_create_edit( image, mask, @@ -224,6 +252,9 @@ async def acreate_edit( organization=None, **params, ): + if api_type in (util.ApiType.AZURE, util.ApiType.AZURE_AD): + raise error.InvalidAPIType("Edits are not supported by the Azure OpenAI API yet.") + requestor, url, files = cls._prepare_create_edit( image, mask, diff --git a/openai/openai_response.py b/openai/openai_response.py index 9954247319..d2230b1540 100644 --- a/openai/openai_response.py +++ b/openai/openai_response.py @@ -10,6 +10,17 @@ def __init__(self, data, headers): def request_id(self) -> Optional[str]: return self._headers.get("request-id") + @property + def retry_after(self) -> Optional[int]: + try: + return int(self._headers.get("retry-after")) + except TypeError: + return None + + @property + def operation_location(self) -> Optional[str]: + return self._headers.get("operation-location") + @property def organization(self) -> Optional[str]: return self._headers.get("OpenAI-Organization") From 7610c5adfaebe3ffdb9927a551a741a3fab1b62e Mon Sep 17 00:00:00 2001 From: John Allard Date: Tue, 6 Jun 2023 16:39:03 -0700 Subject: [PATCH 034/816] Bump version to 0.27.8 (#480) --- openai/version.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openai/version.py b/openai/version.py index aa89e032d8..3b506fe925 100644 --- a/openai/version.py +++ b/openai/version.py @@ -1 +1 @@ -VERSION = "0.27.7" +VERSION = "0.27.8" From 041bf5a8ec54da19aad0169671793c2078bd6173 Mon Sep 17 00:00:00 2001 From: Vik Goel Date: Fri, 16 Jun 2023 09:53:37 -0700 Subject: [PATCH 035/816] catch asyncio.TimeoutError in _interpret_async_response (#180) (#489) --- openai/api_requestor.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/openai/api_requestor.py b/openai/api_requestor.py index a6565c0351..504f7c4411 100644 --- a/openai/api_requestor.py +++ b/openai/api_requestor.py @@ -720,6 +720,8 @@ async def _interpret_async_response( else: try: await result.read() + except (aiohttp.ServerTimeoutError, asyncio.TimeoutError) as e: + raise error.Timeout("Request timed out") from e except aiohttp.ClientError as e: util.log_warn(e, body=result.content) return ( From d1c36582e82cfa97568d7e9184454ee3b77975fc Mon Sep 17 00:00:00 2001 From: Yutian Liu <138078584+yutian-openai@users.noreply.github.com> Date: Wed, 5 Jul 2023 17:51:01 -0700 Subject: [PATCH 036/816] Add api_version and organization field in Audio API requests (#514) * Add api_version and organization field in Audio API requests * update version --- openai/api_resources/audio.py | 16 ++++++++++++++++ openai/version.py | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/openai/api_resources/audio.py b/openai/api_resources/audio.py index 33820c64a7..d5d906ed96 100644 --- a/openai/api_resources/audio.py +++ b/openai/api_resources/audio.py @@ -59,6 +59,8 @@ def transcribe( api_key=api_key, api_base=api_base, api_type=api_type, + api_version=api_version, + organization=organization, **params, ) url = cls._get_url("http://github.com/transcriptions") @@ -86,6 +88,8 @@ def translate( api_key=api_key, api_base=api_base, api_type=api_type, + api_version=api_version, + organization=organization, **params, ) url = cls._get_url("http://github.com/translations") @@ -114,6 +118,8 @@ def transcribe_raw( api_key=api_key, api_base=api_base, api_type=api_type, + api_version=api_version, + organization=organization, **params, ) url = cls._get_url("http://github.com/transcriptions") @@ -142,6 +148,8 @@ def translate_raw( api_key=api_key, api_base=api_base, api_type=api_type, + api_version=api_version, + organization=organization, **params, ) url = cls._get_url("http://github.com/translations") @@ -169,6 +177,8 @@ async def atranscribe( api_key=api_key, api_base=api_base, api_type=api_type, + api_version=api_version, + organization=organization, **params, ) url = cls._get_url("http://github.com/transcriptions") @@ -198,6 +208,8 @@ async def atranslate( api_key=api_key, api_base=api_base, api_type=api_type, + api_version=api_version, + organization=organization, **params, ) url = cls._get_url("http://github.com/translations") @@ -228,6 +240,8 @@ async def atranscribe_raw( api_key=api_key, api_base=api_base, api_type=api_type, + api_version=api_version, + organization=organization, **params, ) url = cls._get_url("http://github.com/transcriptions") @@ -258,6 +272,8 @@ async def atranslate_raw( api_key=api_key, api_base=api_base, api_type=api_type, + api_version=api_version, + organization=organization, **params, ) url = cls._get_url("http://github.com/translations") diff --git a/openai/version.py b/openai/version.py index 3b506fe925..51f3ce82ff 100644 --- a/openai/version.py +++ b/openai/version.py @@ -1 +1 @@ -VERSION = "0.27.8" +VERSION = "0.27.9" From b82a3f7e4c462a8a10fa445193301a3cefef9a4a Mon Sep 17 00:00:00 2001 From: Atty Eleti Date: Mon, 10 Jul 2023 15:38:09 -0700 Subject: [PATCH 037/816] Update docstring in chat_completion API resource (#527) Fixes a link to our docs. --- openai/api_resources/chat_completion.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/openai/api_resources/chat_completion.py b/openai/api_resources/chat_completion.py index 39fb58b33a..7e55f9e38f 100644 --- a/openai/api_resources/chat_completion.py +++ b/openai/api_resources/chat_completion.py @@ -14,7 +14,7 @@ def create(cls, *args, **kwargs): """ Creates a new chat completion for the provided messages and parameters. - See https://platform.openai.com/docs/api-reference/chat-completions/create + See https://platform.openai.com/docs/api-reference/chat/create for a list of valid parameters. """ start = time.time() @@ -34,7 +34,7 @@ async def acreate(cls, *args, **kwargs): """ Creates a new chat completion for the provided messages and parameters. - See https://platform.openai.com/docs/api-reference/chat-completions/create + See https://platform.openai.com/docs/api-reference/chat/create for a list of valid parameters. """ start = time.time() From 120d225b91a8453e15240a49fb1c6794d8119326 Mon Sep 17 00:00:00 2001 From: Logan Kilpatrick Date: Tue, 22 Aug 2023 09:04:10 -0700 Subject: [PATCH 038/816] Update chatml.md (#580) --- chatml.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/chatml.md b/chatml.md index 783e91d996..6689953adb 100644 --- a/chatml.md +++ b/chatml.md @@ -1,5 +1,8 @@ +> [!IMPORTANT] +> This page is not currently maintained and is intended to provide general insight into the ChatML format, not current up-to-date information. + (This document is a preview of the underlying format consumed by -ChatGPT models. As a developer, you can use our [higher-level +GPT models. As a developer, you can use our [higher-level API](https://platform.openai.com/docs/guides/chat) and won't need to interact directly with this format today — but expect to have the option in the future!) From fcec4dd0121472f60154932ab303b226c17dca38 Mon Sep 17 00:00:00 2001 From: Logan Kilpatrick Date: Tue, 22 Aug 2023 09:06:51 -0700 Subject: [PATCH 039/816] Update README.md to show newer completions models (#578) * Update README.md to show newer completions models * Update README.md * Update README.md --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index d61fdee644..fd537888f3 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ pre-defined set of classes for API resources that initialize themselves dynamically from API responses which makes it compatible with a wide range of versions of the OpenAI API. -You can find usage examples for the OpenAI Python library in our [API reference](https://beta.openai.com/docs/api-reference?lang=python) and the [OpenAI Cookbook](https://github.com/openai/openai-cookbook/). +You can find usage examples for the OpenAI Python library in our [API reference](https://platform.openai.com/docs/api-reference?lang=python) and the [OpenAI Cookbook](https://github.com/openai/openai-cookbook/). ## Installation @@ -173,13 +173,13 @@ print(completion.choices[0].message.content) ### Completions -Text models such as `text-davinci-003`, `text-davinci-002` and earlier (`ada`, `babbage`, `curie`, `davinci`, etc.) can be called using the completions endpoint. +Text models such as `babbage-002` or `davinci-002` (and our [legacy completions models](https://platform.openai.com/docs/deprecations/deprecation-history)) can be called using the completions endpoint. ```python import openai openai.api_key = "sk-..." # supply your API key however you choose -completion = openai.Completion.create(model="text-davinci-003", prompt="Hello world") +completion = openai.Completion.create(model="davinci-002", prompt="Hello world") print(completion.choices[0].text) ``` @@ -197,13 +197,13 @@ openai.api_key = "sk-..." # supply your API key however you choose text_string = "sample text" # choose an embedding -model_id = "text-similarity-davinci-001" +model_id = "text-embedding-ada-002" # compute the embedding of the text embedding = openai.Embedding.create(input=text_string, model=model_id)['data'][0]['embedding'] ``` -An example of how to call the embeddings method is shown in this [get embeddings notebook](https://github.com/openai/openai-cookbook/blob/main/examples/Get_embeddings.ipynb). +An example of how to call the embeddings method is shown in this [embeddings guide](https://platform.openai.com/docs/guides/embeddings/embeddings). Examples of how to use embeddings are shared in the following Jupyter notebooks: @@ -215,7 +215,7 @@ Examples of how to use embeddings are shared in the following Jupyter notebooks: - [Zero-shot classification using embeddings](https://github.com/openai/openai-cookbook/blob/main/examples/Zero-shot_classification_with_embeddings.ipynb) - [Recommendation using embeddings](https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb) -For more information on embeddings and the types of embeddings OpenAI offers, read the [embeddings guide](https://beta.openai.com/docs/guides/embeddings) in the OpenAI documentation. +For more information on embeddings and the types of embeddings OpenAI offers, read the [embeddings guide](https://platform.openai.com/docs/guides/embeddings) in the OpenAI documentation. ### Fine-tuning @@ -235,7 +235,7 @@ Sync your fine-tunes to [Weights & Biases](https://wandb.me/openai-docs) to trac openai wandb sync ``` -For more information on fine-tuning, read the [fine-tuning guide](https://beta.openai.com/docs/guides/fine-tuning) in the OpenAI documentation. +For more information on fine-tuning, read the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) in the OpenAI documentation. ### Moderation From b8dfa35e242de26e9a0371bc2c18bf8661cdc034 Mon Sep 17 00:00:00 2001 From: whysage <67018871+whysage@users.noreply.github.com> Date: Tue, 22 Aug 2023 19:13:03 +0300 Subject: [PATCH 040/816] doc: fix readme azure example code (#571) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fd537888f3..7dab22d5a8 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,7 @@ openai.api_version = "2023-05-15" chat_completion = openai.ChatCompletion.create(deployment_id="deployment-name", model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello world"}]) # print the completion -print(completion.choices[0].message.content) +print(chat_completion.choices[0].message.content) ``` Please note that for the moment, the Microsoft Azure endpoints can only be used for completion, embedding, and fine-tuning operations. From df8b0ba7853a2e7345d7506538ae0e57ec0d872b Mon Sep 17 00:00:00 2001 From: John Allard Date: Tue, 22 Aug 2023 09:19:06 -0700 Subject: [PATCH 041/816] Updates to the fine tuning SDK + addition of pagination primitives (#582) * Add support for new fine_tuning SDK + pagination primitives * typo --- openai/__init__.py | 2 + openai/api_resources/__init__.py | 1 + openai/api_resources/abstract/__init__.py | 3 + .../abstract/nested_resource_class_methods.py | 13 ++ .../abstract/paginatable_api_resource.py | 125 ++++++++++++++++++ openai/api_resources/fine_tuning.py | 88 ++++++++++++ openai/object_classes.py | 1 + 7 files changed, 233 insertions(+) create mode 100644 openai/api_resources/abstract/paginatable_api_resource.py create mode 100644 openai/api_resources/fine_tuning.py diff --git a/openai/__init__.py b/openai/__init__.py index 537f12883e..b44e50f97f 100644 --- a/openai/__init__.py +++ b/openai/__init__.py @@ -28,6 +28,7 @@ ErrorObject, File, FineTune, + FineTuningJob, Image, Model, Moderation, @@ -84,6 +85,7 @@ "ErrorObject", "File", "FineTune", + "FineTuningJob", "InvalidRequestError", "Model", "Moderation", diff --git a/openai/api_resources/__init__.py b/openai/api_resources/__init__.py index b06ebb4be9..78bad1a22a 100644 --- a/openai/api_resources/__init__.py +++ b/openai/api_resources/__init__.py @@ -9,6 +9,7 @@ from openai.api_resources.error_object import ErrorObject # noqa: F401 from openai.api_resources.file import File # noqa: F401 from openai.api_resources.fine_tune import FineTune # noqa: F401 +from openai.api_resources.fine_tuning import FineTuningJob # noqa: F401 from openai.api_resources.image import Image # noqa: F401 from openai.api_resources.model import Model # noqa: F401 from openai.api_resources.moderation import Moderation # noqa: F401 diff --git a/openai/api_resources/abstract/__init__.py b/openai/api_resources/abstract/__init__.py index 32830e273c..48482bd87a 100644 --- a/openai/api_resources/abstract/__init__.py +++ b/openai/api_resources/abstract/__init__.py @@ -7,4 +7,7 @@ from openai.api_resources.abstract.nested_resource_class_methods import ( nested_resource_class_methods, ) +from openai.api_resources.abstract.paginatable_api_resource import ( + PaginatableAPIResource, +) from openai.api_resources.abstract.updateable_api_resource import UpdateableAPIResource diff --git a/openai/api_resources/abstract/nested_resource_class_methods.py b/openai/api_resources/abstract/nested_resource_class_methods.py index bfa5bcd873..2f2dd45e40 100644 --- a/openai/api_resources/abstract/nested_resource_class_methods.py +++ b/openai/api_resources/abstract/nested_resource_class_methods.py @@ -124,6 +124,19 @@ def list_nested_resources(cls, id, **params): list_method = "list_%s" % resource_plural setattr(cls, list_method, classmethod(list_nested_resources)) + elif operation == "paginated_list": + + def paginated_list_nested_resources( + cls, id, limit=None, cursor=None, **params + ): + url = getattr(cls, resource_url_method)(id) + return getattr(cls, resource_request_method)( + "get", url, limit=limit, cursor=cursor, **params + ) + + list_method = "list_%s" % resource_plural + setattr(cls, list_method, classmethod(paginated_list_nested_resources)) + else: raise ValueError("Unknown operation: %s" % operation) diff --git a/openai/api_resources/abstract/paginatable_api_resource.py b/openai/api_resources/abstract/paginatable_api_resource.py new file mode 100644 index 0000000000..2d75744f23 --- /dev/null +++ b/openai/api_resources/abstract/paginatable_api_resource.py @@ -0,0 +1,125 @@ +from openai import api_requestor, error, util +from openai.api_resources.abstract.listable_api_resource import ListableAPIResource +from openai.util import ApiType + + +class PaginatableAPIResource(ListableAPIResource): + @classmethod + def auto_paging_iter(cls, *args, **params): + next_cursor = None + has_more = True + if not params.get("limit"): + params["limit"] = 20 + while has_more: + if next_cursor: + params["after"] = next_cursor + response = cls.list(*args, **params) + + for item in response.data: + yield item + + if response.data: + next_cursor = response.data[-1].id + has_more = response.has_more + + @classmethod + def __prepare_list_requestor( + cls, + api_key=None, + api_version=None, + organization=None, + api_base=None, + api_type=None, + ): + requestor = api_requestor.APIRequestor( + api_key, + api_base=api_base or cls.api_base(), + api_version=api_version, + api_type=api_type, + organization=organization, + ) + + typed_api_type, api_version = cls._get_api_type_and_version( + api_type, api_version + ) + + 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) + elif typed_api_type == ApiType.OPEN_AI: + url = cls.class_url() + else: + raise error.InvalidAPIType("Unsupported API type %s" % api_type) + return requestor, url + + @classmethod + def list( + cls, + limit=None, + starting_after=None, + api_key=None, + request_id=None, + api_version=None, + organization=None, + api_base=None, + api_type=None, + **params, + ): + requestor, url = cls.__prepare_list_requestor( + api_key, + api_version, + organization, + api_base, + api_type, + ) + + params = { + **params, + "limit": limit, + "starting_after": starting_after, + } + + response, _, api_key = requestor.request( + "get", url, params, request_id=request_id + ) + openai_object = util.convert_to_openai_object( + response, api_key, api_version, organization + ) + openai_object._retrieve_params = params + return openai_object + + @classmethod + async def alist( + cls, + limit=None, + starting_after=None, + api_key=None, + request_id=None, + api_version=None, + organization=None, + api_base=None, + api_type=None, + **params, + ): + requestor, url = cls.__prepare_list_requestor( + api_key, + api_version, + organization, + api_base, + api_type, + ) + + params = { + **params, + "limit": limit, + "starting_after": starting_after, + } + + response, _, api_key = await requestor.arequest( + "get", url, params, request_id=request_id + ) + openai_object = util.convert_to_openai_object( + response, api_key, api_version, organization + ) + openai_object._retrieve_params = params + return openai_object diff --git a/openai/api_resources/fine_tuning.py b/openai/api_resources/fine_tuning.py new file mode 100644 index 0000000000..f03be56ab7 --- /dev/null +++ b/openai/api_resources/fine_tuning.py @@ -0,0 +1,88 @@ +from urllib.parse import quote_plus + +from openai import error +from openai.api_resources.abstract import ( + CreateableAPIResource, + PaginatableAPIResource, + nested_resource_class_methods, +) +from openai.api_resources.abstract.deletable_api_resource import DeletableAPIResource +from openai.util import ApiType + + +@nested_resource_class_methods("event", operations=["paginated_list"]) +class FineTuningJob( + PaginatableAPIResource, CreateableAPIResource, DeletableAPIResource +): + OBJECT_NAME = "fine_tuning.jobs" + + @classmethod + def _prepare_cancel( + cls, + id, + api_key=None, + api_type=None, + request_id=None, + api_version=None, + **params, + ): + base = cls.class_url() + extn = quote_plus(id) + + typed_api_type, api_version = cls._get_api_type_and_version( + api_type, api_version + ) + if typed_api_type in (ApiType.AZURE, ApiType.AZURE_AD): + url = "/%s%s/%s/cancel?api-version=%s" % ( + cls.azure_api_prefix, + base, + extn, + api_version, + ) + elif typed_api_type == ApiType.OPEN_AI: + url = "%s/%s/cancel" % (base, extn) + else: + raise error.InvalidAPIType("Unsupported API type %s" % api_type) + + instance = cls(id, api_key, **params) + return instance, url + + @classmethod + def cancel( + cls, + id, + api_key=None, + api_type=None, + request_id=None, + api_version=None, + **params, + ): + instance, url = cls._prepare_cancel( + id, + api_key, + api_type, + request_id, + api_version, + **params, + ) + return instance.request("post", url, request_id=request_id) + + @classmethod + def acancel( + cls, + id, + api_key=None, + api_type=None, + request_id=None, + api_version=None, + **params, + ): + instance, url = cls._prepare_cancel( + id, + api_key, + api_type, + request_id, + api_version, + **params, + ) + return instance.arequest("post", url, request_id=request_id) diff --git a/openai/object_classes.py b/openai/object_classes.py index 5f72bd7cf8..08093650fd 100644 --- a/openai/object_classes.py +++ b/openai/object_classes.py @@ -8,4 +8,5 @@ "fine-tune": api_resources.FineTune, "model": api_resources.Model, "deployment": api_resources.Deployment, + "fine_tuning.job": api_resources.FineTuningJob, } From 2942bf4bb635b1e6722d6decb5e8619950fcddd1 Mon Sep 17 00:00:00 2001 From: Logan Kilpatrick Date: Tue, 22 Aug 2023 11:43:22 -0700 Subject: [PATCH 042/816] Update README.md with fine-tuning examples (#583) * Update README.md with fine-tuning examples * Update README.md --- README.md | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 7dab22d5a8..9b59ad5550 100644 --- a/README.md +++ b/README.md @@ -219,20 +219,26 @@ For more information on embeddings and the types of embeddings OpenAI offers, re ### Fine-tuning -Fine-tuning a model on training data can both improve the results (by giving the model more examples to learn from) and reduce the cost/latency of API calls (chiefly through reducing the need to include training examples in prompts). +Fine-tuning a model on training data can both improve the results (by giving the model more examples to learn from) and lower the cost/latency of API calls by reducing the need to include training examples in prompts. -Examples of fine-tuning are shared in the following Jupyter notebooks: +```python +# Create a fine-tuning job with an already uploaded file +openai.FineTuningJob.create(training_file="file-abc123", model="gpt-3.5-turbo") -- [Classification with fine-tuning](https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb) (a simple notebook that shows the steps required for fine-tuning) -- Fine-tuning a model that answers questions about the 2020 Olympics - - [Step 1: Collecting data](https://github.com/openai/openai-cookbook/blob/main/examples/fine-tuned_qa/olympics-1-collect-data.ipynb) - - [Step 2: Creating a synthetic Q&A dataset](https://github.com/openai/openai-cookbook/blob/main/examples/fine-tuned_qa/olympics-2-create-qa.ipynb) - - [Step 3: Train a fine-tuning model specialized for Q&A](https://github.com/openai/openai-cookbook/blob/main/examples/fine-tuned_qa/olympics-3-train-qa.ipynb) +# List 10 fine-tuning jobs +openai.FineTuningJob.list(limit=10) -Sync your fine-tunes to [Weights & Biases](https://wandb.me/openai-docs) to track experiments, models, and datasets in your central dashboard with: +# Retrieve the state of a fine-tune +openai.FineTuningJob.retrieve("ft-abc123") -```bash -openai wandb sync +# Cancel a job +openai.FineTuningJob.cancel("ft-abc123") + +# List up to 10 events from a fine-tuning job +openai.FineTuningJob.list_events(id="ft-abc123", limit=10) + +# Delete a fine-tuned model (must be an owner of the org the model was created in) +openai.Model.delete("ft-abc123") ``` For more information on fine-tuning, read the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) in the OpenAI documentation. From 9d559b064cda09d56c1ebf756be4a1f73d5a275a Mon Sep 17 00:00:00 2001 From: John Allard Date: Tue, 29 Aug 2023 17:19:23 -0700 Subject: [PATCH 043/816] [fine_tuning] Add CLI for fine_tuning.jobs (#592) --- openai/api_resources/file.py | 18 +++ openai/cli.py | 272 +++++++++++++++++++++++++++++++++++ 2 files changed, 290 insertions(+) diff --git a/openai/api_resources/file.py b/openai/api_resources/file.py index 394417245f..dba2ee92e1 100644 --- a/openai/api_resources/file.py +++ b/openai/api_resources/file.py @@ -1,6 +1,7 @@ import json import os from typing import cast +import time import openai from openai import api_requestor, util, error @@ -259,3 +260,20 @@ async def afind_matching_files( ) ).get("data", []) return cls.__find_matching_files(name, bytes, all_files, purpose) + + @classmethod + def wait_for_processing(cls, id, max_wait_seconds=30 * 60): + TERMINAL_STATES = ["processed", "error", "deleted"] + + start = time.time() + file = cls.retrieve(id=id) + while file.status not in TERMINAL_STATES: + file = cls.retrieve(id=id) + time.sleep(5.0) + if time.time() - start > max_wait_seconds: + raise openai.error.OpenAIError( + message="Giving up on waiting for file {id} to finish processing after {max_wait_seconds} seconds.".format( + id=id, max_wait_seconds=max_wait_seconds + ) + ) + return file.status diff --git a/openai/cli.py b/openai/cli.py index ad08ac3e7b..c272d0b8d8 100644 --- a/openai/cli.py +++ b/openai/cli.py @@ -606,6 +606,201 @@ def prepare_data(cls, args): ) +class FineTuningJob: + @classmethod + def list(cls, args): + has_ft_jobs = False + for fine_tune_job in openai.FineTuningJob.auto_paging_iter(): + has_ft_jobs = True + print(fine_tune_job) + if not has_ft_jobs: + print("No fine-tuning jobs found.") + + @classmethod + def _is_url(http://github.com/cls,%20file:%20str): + return file.lower().startswith("http") + + @classmethod + def _download_file_from_public_url(http://github.com/cls,%20url:%20str) -> Optional[bytes]: + resp = requests.get(url) + if resp.status_code == 200: + return resp.content + else: + return None + + @classmethod + def _maybe_upload_file( + cls, + file: Optional[str] = None, + content: Optional[bytes] = None, + user_provided_file: Optional[str] = None, + check_if_file_exists: bool = True, + ): + # Exactly one of `file` or `content` must be provided + if (file is None) == (content is None): + raise ValueError("Exactly one of `file` or `content` must be provided") + + if content is None: + assert file is not None + with open(file, "rb") as f: + content = f.read() + + if check_if_file_exists: + bytes = len(content) + matching_files = openai.File.find_matching_files( + name=user_provided_file or f.name, + bytes=bytes, + purpose="fine-tune", + ) + if len(matching_files) > 0: + file_ids = [f["id"] for f in matching_files] + sys.stdout.write( + "Found potentially duplicated files with name '{name}', purpose 'fine-tune', and size {size} bytes\n".format( + name=os.path.basename(matching_files[0]["filename"]), + size=matching_files[0]["bytes"] + if "bytes" in matching_files[0] + else matching_files[0]["size"], + ) + ) + sys.stdout.write("\n".join(file_ids)) + while True: + sys.stdout.write( + "\nEnter file ID to reuse an already uploaded file, or an empty string to upload this file anyway: " + ) + inp = sys.stdin.readline().strip() + if inp in file_ids: + sys.stdout.write( + "Reusing already uploaded file: {id}\n".format(id=inp) + ) + return inp + elif inp == "": + break + else: + sys.stdout.write( + "File id '{id}' is not among the IDs of the potentially duplicated files\n".format( + id=inp + ) + ) + + buffer_reader = BufferReader(content, desc="Upload progress") + resp = openai.File.create( + file=buffer_reader, + purpose="fine-tune", + user_provided_filename=user_provided_file or file, + ) + sys.stdout.write( + "Uploaded file from {file}: {id}\n".format( + file=user_provided_file or file, id=resp["id"] + ) + ) + sys.stdout.write("Waiting for file to finish processing before proceeding..\n") + sys.stdout.flush() + status = openai.File.wait_for_processing(resp["id"]) + if status != "processed": + raise openai.error.OpenAIError( + "File {id} failed to process, status={status}.".format( + id=resp["id"], status=status + ) + ) + + sys.stdout.write( + "File {id} finished processing and is ready for use in fine-tuning".format( + id=resp["id"] + ) + ) + sys.stdout.flush() + return resp["id"] + + @classmethod + def _get_or_upload(cls, file, check_if_file_exists=True): + try: + # 1. If it's a valid file, use it + openai.File.retrieve(file) + return file + except openai.error.InvalidRequestError: + pass + if os.path.isfile(file): + # 2. If it's a file on the filesystem, upload it + return cls._maybe_upload_file( + file=file, check_if_file_exists=check_if_file_exists + ) + if cls._is_url(http://github.com/file): + # 3. If it's a URL, download it temporarily + content = cls._download_file_from_public_url(http://github.com/file) + if content is not None: + return cls._maybe_upload_file( + content=content, + check_if_file_exists=check_if_file_exists, + user_provided_file=file, + ) + return file + + @classmethod + def create(cls, args): + create_args = { + "training_file": cls._get_or_upload( + args.training_file, args.check_if_files_exist + ), + } + if args.validation_file: + create_args["validation_file"] = cls._get_or_upload( + args.validation_file, args.check_if_files_exist + ) + + for param in ("model", "suffix"): + attr = getattr(args, param) + if attr is not None: + create_args[param] = attr + + if getattr(args, "n_epochs"): + create_args["hyperparameters"] = { + "n_epochs": args.n_epochs, + } + + resp = openai.FineTuningJob.create(**create_args) + print(resp) + return + + @classmethod + def get(cls, args): + resp = openai.FineTuningJob.retrieve(id=args.id) + print(resp) + + @classmethod + def results(cls, args): + fine_tune = openai.FineTuningJob.retrieve(id=args.id) + if "result_files" not in fine_tune or len(fine_tune["result_files"]) == 0: + raise openai.error.InvalidRequestError( + f"No results file available for fine-tune {args.id}", "id" + ) + result_file = openai.FineTuningJob.retrieve(id=args.id)["result_files"][0] + resp = openai.File.download(id=result_file) + print(resp.decode("utf-8")) + + @classmethod + def events(cls, args): + seen, has_more = 0, True + while has_more: + resp = openai.FineTuningJob.list_events(id=args.id) # type: ignore + for event in resp["data"]: + print(event) + seen += 1 + if args.limit is not None and seen >= args.limit: + return + has_more = resp["has_more"] + + @classmethod + def follow(cls, args): + raise openai.error.OpenAIError( + message="Event streaming is not yet supported for `fine_tuning.job` events" + ) + + @classmethod + def cancel(cls, args): + resp = openai.FineTuningJob.cancel(id=args.id) + print(resp) + + class WandbLogger: @classmethod def sync(cls, args): @@ -1098,6 +1293,83 @@ def help(args): sub.add_argument("--prompt", type=str) sub.set_defaults(func=Audio.translate) + # FineTuning Jobs + sub = subparsers.add_parser("fine_tuning.job.list") + sub.set_defaults(func=FineTuningJob.list) + + sub = subparsers.add_parser("fine_tuning.job.create") + sub.add_argument( + "-t", + "--training_file", + required=True, + help="JSONL file containing either chat-completion or prompt-completion examples for training. " + "This can be the ID of a file uploaded through the OpenAI API (e.g. file-abcde12345), " + 'a local file path, or a URL that starts with "http".', + ) + sub.add_argument( + "-v", + "--validation_file", + help="JSONL file containing either chat-completion or prompt-completion examples for validation. " + "This can be the ID of a file uploaded through the OpenAI API (e.g. file-abcde12345), " + 'a local file path, or a URL that starts with "http".', + ) + sub.add_argument( + "--no_check_if_files_exist", + dest="check_if_files_exist", + action="http://github.com/store_false", + help="If this argument is set and training_file or validation_file are file paths, immediately upload them. If this argument is not set, check if they may be duplicates of already uploaded files before uploading, based on file name and file size.", + ) + sub.add_argument( + "-m", + "--model", + help="The model to start fine-tuning from", + ) + sub.add_argument( + "--suffix", + help="If set, this argument can be used to customize the generated fine-tuned model name." + "All punctuation and whitespace in `suffix` will be replaced with a " + "single dash, and the string will be lower cased. The max " + "length of `suffix` is 18 chars. " + "The generated name will match the form `ft:{base_model}:{org-title}:{suffix}:{rstring}` where `rstring` " + "is a random string sortable as a timestamp. " + 'For example, `openai api fine_tuning.job.create -t test.jsonl -m gpt-3.5-turbo-0613 --suffix "first finetune!" ' + "could generate a model with the name " + "ft:gpt-3.5-turbo-0613:your-org:first-finetune:7p4PqAoY", + ) + sub.add_argument( + "--n_epochs", + type=int, + help="The number of epochs to train the model for. An epoch refers to one " + "full cycle through the training dataset.", + ) + sub.set_defaults(func=FineTuningJob.create) + + sub = subparsers.add_parser("fine_tuning.job.get") + sub.add_argument("-i", "--id", required=True, help="The id of the fine-tune job") + sub.set_defaults(func=FineTuningJob.get) + + sub = subparsers.add_parser("fine_tuning.job.results") + sub.add_argument("-i", "--id", required=True, help="The id of the fine-tune job") + sub.set_defaults(func=FineTuningJob.results) + + sub = subparsers.add_parser("fine_tuning.job.events") + sub.add_argument("-i", "--id", required=True, help="The id of the fine-tune job") + sub.add_argument( + "--limit", + type=int, + required=False, + help="The number of events to return, starting from most recent. If not specified, all events will be returned.", + ) + sub.set_defaults(func=FineTuningJob.events) + + sub = subparsers.add_parser("fine_tuning.job.follow") + sub.add_argument("-i", "--id", required=True, help="The id of the fine-tune job") + sub.set_defaults(func=FineTuningJob.follow) + + sub = subparsers.add_parser("fine_tuning.job.cancel") + sub.add_argument("-i", "--id", required=True, help="The id of the fine-tune job") + sub.set_defaults(func=FineTuningJob.cancel) + def wandb_register(parser): subparsers = parser.add_subparsers( From 1be14ee34a0f8e42d3f9aa5451aa4cb161f1781f Mon Sep 17 00:00:00 2001 From: John Allard Date: Thu, 31 Aug 2023 15:56:09 -0700 Subject: [PATCH 044/816] [fine_tuning] fix pagination for auto-generated list_events (#188) (#597) --- .../abstract/nested_resource_class_methods.py | 4 ++-- openai/cli.py | 8 +++++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/openai/api_resources/abstract/nested_resource_class_methods.py b/openai/api_resources/abstract/nested_resource_class_methods.py index 2f2dd45e40..f171737b17 100644 --- a/openai/api_resources/abstract/nested_resource_class_methods.py +++ b/openai/api_resources/abstract/nested_resource_class_methods.py @@ -127,11 +127,11 @@ def list_nested_resources(cls, id, **params): elif operation == "paginated_list": def paginated_list_nested_resources( - cls, id, limit=None, cursor=None, **params + cls, id, limit=None, after=None, **params ): url = getattr(cls, resource_url_method)(id) return getattr(cls, resource_request_method)( - "get", url, limit=limit, cursor=cursor, **params + "get", url, limit=limit, after=after, **params ) list_method = "list_%s" % resource_plural diff --git a/openai/cli.py b/openai/cli.py index c272d0b8d8..99d171a849 100644 --- a/openai/cli.py +++ b/openai/cli.py @@ -779,15 +779,17 @@ def results(cls, args): @classmethod def events(cls, args): - seen, has_more = 0, True + seen, has_more, after = 0, True, None while has_more: - resp = openai.FineTuningJob.list_events(id=args.id) # type: ignore + resp = openai.FineTuningJob.list_events(id=args.id, after=after) # type: ignore for event in resp["data"]: print(event) seen += 1 if args.limit is not None and seen >= args.limit: return - has_more = resp["has_more"] + has_more = resp.get("has_more", False) + if resp["data"]: + after = resp["data"][-1]["id"] @classmethod def follow(cls, args): From 52f571a70c1ffe9d1991adbde434e645d45dabad Mon Sep 17 00:00:00 2001 From: Logan Kilpatrick Date: Wed, 6 Sep 2023 17:33:34 -0500 Subject: [PATCH 045/816] Update README.md (#601) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9b59ad5550..9fa7651ec0 100644 --- a/README.md +++ b/README.md @@ -238,7 +238,7 @@ openai.FineTuningJob.cancel("ft-abc123") openai.FineTuningJob.list_events(id="ft-abc123", limit=10) # Delete a fine-tuned model (must be an owner of the org the model was created in) -openai.Model.delete("ft-abc123") +openai.Model.delete("ft:gpt-3.5-turbo:acemeco:suffix:abc123") ``` For more information on fine-tuning, read the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) in the OpenAI documentation. From 376dd19955aa34100045cc0e5b6e768e96677093 Mon Sep 17 00:00:00 2001 From: Logan Kilpatrick Date: Thu, 7 Sep 2023 09:26:55 -0500 Subject: [PATCH 046/816] Revamp README to make examples front and center (#603) * Revamp README * Add completions guides * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md --- README.md | 261 +++++++++++++++++++++--------------------------------- 1 file changed, 100 insertions(+), 161 deletions(-) diff --git a/README.md b/README.md index 9fa7651ec0..001b248e9c 100644 --- a/README.md +++ b/README.md @@ -10,14 +10,20 @@ You can find usage examples for the OpenAI Python library in our [API reference] ## Installation -You don't need this source code unless you want to modify the package. If you just -want to use the package, just run: +To start, ensure you have Python 3.7.1 or newer. If you just +want to use the package, run: ```sh pip install --upgrade openai ``` -Install from source with: +After you have installed the package, import it at the top of a file: + +```python +import openai +``` + +To install this package from source to make modifications to it, run the following command from the root of the repository: ```sh python setup.py install @@ -33,7 +39,7 @@ pip install openai[embeddings] Install support for [Weights & Biases](https://wandb.me/openai-docs): -``` +```sh pip install openai[wandb] ``` @@ -54,168 +60,48 @@ export OPENAI_API_KEY='sk-...' Or set `openai.api_key` to its value: ```python -import openai openai.api_key = "sk-..." - -# list models -models = openai.Model.list() - -# print the first model's id -print(models.data[0].id) - -# create a chat completion -chat_completion = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello world"}]) - -# print the chat completion -print(chat_completion.choices[0].message.content) -``` - -### Params - -All endpoints have a `.create` method that supports a `request_timeout` param. This param takes a `Union[float, Tuple[float, float]]` and will raise an `openai.error.Timeout` error if the request exceeds that time in seconds (See: https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts). - -### Microsoft Azure Endpoints - -In order to use the library with Microsoft Azure endpoints, you need to set the `api_type`, `api_base` and `api_version` in addition to the `api_key`. The `api_type` must be set to 'azure' and the others correspond to the properties of your endpoint. -In addition, the deployment name must be passed as the engine parameter. - -```python -import openai -openai.api_type = "azure" -openai.api_key = "..." -openai.api_base = "https://example-endpoint.openai.azure.com/" -openai.api_version = "2023-05-15" - -# create a chat completion -chat_completion = openai.ChatCompletion.create(deployment_id="deployment-name", model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello world"}]) - -# print the completion -print(chat_completion.choices[0].message.content) -``` - -Please note that for the moment, the Microsoft Azure endpoints can only be used for completion, embedding, and fine-tuning operations. -For a detailed example of how to use fine-tuning and other operations using Azure endpoints, please check out the following Jupyter notebooks: - -- [Using Azure completions](https://github.com/openai/openai-cookbook/tree/main/examples/azure/completions.ipynb) -- [Using Azure fine-tuning](https://github.com/openai/openai-cookbook/tree/main/examples/azure/finetuning.ipynb) -- [Using Azure embeddings](https://github.com/openai/openai-cookbook/blob/main/examples/azure/embeddings.ipynb) - -### Microsoft Azure Active Directory Authentication - -In order to use Microsoft Active Directory to authenticate to your Azure endpoint, you need to set the `api_type` to "azure_ad" and pass the acquired credential token to `api_key`. The rest of the parameters need to be set as specified in the previous section. - -```python -from azure.identity import DefaultAzureCredential -import openai - -# Request credential -default_credential = DefaultAzureCredential() -token = default_credential.get_token("https://cognitiveservices.azure.com/.default") - -# Setup parameters -openai.api_type = "azure_ad" -openai.api_key = token.token -openai.api_base = "https://example-endpoint.openai.azure.com/" -openai.api_version = "2023-05-15" - -# ... ``` -### Command-line interface +Examples of how to use this library to accomplish various tasks can be found in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook/). It contains code examples for: classification using fine-tuning, clustering, code search, customizing embeddings, question answering from a corpus of documents. recommendations, visualization of embeddings, and more. -This library additionally provides an `openai` command-line utility -which makes it easy to interact with the API from your terminal. Run -`openai api -h` for usage. +Most endpoints support a `request_timeout` param. This param takes a `Union[float, Tuple[float, float]]` and will raise an `openai.error.Timeout` error if the request exceeds that time in seconds (See: https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts). -```sh -# list models -openai api models.list - -# create a chat completion (gpt-3.5-turbo, gpt-4, etc.) -openai api chat_completions.create -m gpt-3.5-turbo -g user "Hello world" - -# create a completion (text-davinci-003, text-davinci-002, ada, babbage, curie, davinci, etc.) -openai api completions.create -m ada -p "Hello world" - -# generate images via DALL·E API -openai api image.create -p "two dogs playing chess, cartoon" -n 1 +### Chat completions -# using openai through a proxy -openai --proxy=http://proxy.com api models.list -``` - -## Example code - -Examples of how to use this Python library to accomplish various tasks can be found in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook/). It contains code examples for: - -- Classification using fine-tuning -- Clustering -- Code search -- Customizing embeddings -- Question answering from a corpus of documents -- Recommendations -- Visualization of embeddings -- And more - -Prior to July 2022, this OpenAI Python library hosted code examples in its examples folder, but since then all examples have been migrated to the [OpenAI Cookbook](https://github.com/openai/openai-cookbook/). - -### Chat Completions - -Conversational models such as `gpt-3.5-turbo` can be called using the chat completions endpoint. +Chat models such as `gpt-3.5-turbo` and `gpt-4` can be called using the [chat completions endpoint](https://platform.openai.com/docs/api-reference/chat/create). ```python -import openai -openai.api_key = "sk-..." # supply your API key however you choose - completion = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello world"}]) print(completion.choices[0].message.content) ``` +You can learn more in our [chat completions guide](https://platform.openai.com/docs/guides/gpt/chat-completions-api). + ### Completions Text models such as `babbage-002` or `davinci-002` (and our [legacy completions models](https://platform.openai.com/docs/deprecations/deprecation-history)) can be called using the completions endpoint. ```python -import openai -openai.api_key = "sk-..." # supply your API key however you choose - completion = openai.Completion.create(model="davinci-002", prompt="Hello world") print(completion.choices[0].text) ``` -### Embeddings +You can learn more in our [completions guide](https://platform.openai.com/docs/guides/gpt/completions-api). -In the OpenAI Python library, an embedding represents a text string as a fixed-length vector of floating point numbers. Embeddings are designed to measure the similarity or relevance between text strings. +### Embeddings -To get an embedding for a text string, you can use the embeddings method as follows in Python: +Embeddings are designed to measure the similarity or relevance between text strings. To get an embedding for a text string, you can use following: ```python -import openai -openai.api_key = "sk-..." # supply your API key however you choose - -# choose text to embed text_string = "sample text" -# choose an embedding model_id = "text-embedding-ada-002" -# compute the embedding of the text embedding = openai.Embedding.create(input=text_string, model=model_id)['data'][0]['embedding'] ``` -An example of how to call the embeddings method is shown in this [embeddings guide](https://platform.openai.com/docs/guides/embeddings/embeddings). - -Examples of how to use embeddings are shared in the following Jupyter notebooks: - -- [Classification using embeddings](https://github.com/openai/openai-cookbook/blob/main/examples/Classification_using_embeddings.ipynb) -- [Clustering using embeddings](https://github.com/openai/openai-cookbook/blob/main/examples/Clustering.ipynb) -- [Code search using embeddings](https://github.com/openai/openai-cookbook/blob/main/examples/Code_search.ipynb) -- [Semantic text search using embeddings](https://github.com/openai/openai-cookbook/blob/main/examples/Semantic_text_search_using_embeddings.ipynb) -- [User and product embeddings](https://github.com/openai/openai-cookbook/blob/main/examples/User_and_product_embeddings.ipynb) -- [Zero-shot classification using embeddings](https://github.com/openai/openai-cookbook/blob/main/examples/Zero-shot_classification_with_embeddings.ipynb) -- [Recommendation using embeddings](https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb) - -For more information on embeddings and the types of embeddings OpenAI offers, read the [embeddings guide](https://platform.openai.com/docs/guides/embeddings) in the OpenAI documentation. +You can learn more in our [embeddings guide](https://platform.openai.com/docs/guides/embeddings/embeddings). ### Fine-tuning @@ -241,52 +127,48 @@ openai.FineTuningJob.list_events(id="ft-abc123", limit=10) openai.Model.delete("ft:gpt-3.5-turbo:acemeco:suffix:abc123") ``` -For more information on fine-tuning, read the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) in the OpenAI documentation. +You can learn more in our [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning). ### Moderation -OpenAI provides a Moderation endpoint that can be used to check whether content complies with the OpenAI [content policy](https://platform.openai.com/docs/usage-policies) +OpenAI provides a free Moderation endpoint that can be used to check whether content complies with the OpenAI [content policy](https://platform.openai.com/docs/usage-policies). ```python -import openai -openai.api_key = "sk-..." # supply your API key however you choose - moderation_resp = openai.Moderation.create(input="Here is some perfectly innocuous text that follows all OpenAI content policies.") ``` -See the [moderation guide](https://platform.openai.com/docs/guides/moderation) for more details. +You can learn more in our [moderation guide](https://platform.openai.com/docs/guides/moderation). -## Image generation (DALL·E) +### Image generation (DALL·E) -```python -import openai -openai.api_key = "sk-..." # supply your API key however you choose +DALL·E is a generative image model that can create new images based on a prompt. +```python image_resp = openai.Image.create(prompt="two dogs playing chess, oil painting", n=4, size="512x512") - ``` -## Audio transcription (Whisper) +You can learn more in our [image generation guide](https://platform.openai.com/docs/guides/images). + +### Audio (Whisper) + +The speech to text API provides two endpoints, transcriptions and translations, based on our state-of-the-art [open source large-v2 Whisper model](https://github.com/openai/whisper). ```python -import openai -openai.api_key = "sk-..." # supply your API key however you choose f = open("path/to/file.mp3", "rb") transcript = openai.Audio.transcribe("whisper-1", f) +transcript = openai.Audio.translate("whisper-1", f) ``` -## Async API +You can learn more in our [speech to text guide](https://platform.openai.com/docs/guides/speech-to-text). + +### Async API Async support is available in the API by prepending `a` to a network-bound method: ```python -import openai -openai.api_key = "sk-..." # supply your API key however you choose - async def create_chat_completion(): chat_completion_resp = await openai.ChatCompletion.acreate(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello world"}]) - ``` To make async requests more efficient, you can pass in your own @@ -294,23 +176,80 @@ To make async requests more efficient, you can pass in your own of your program/event loop: ```python -import openai from aiohttp import ClientSession - openai.aiosession.set(ClientSession()) + # At the end of your program, close the http session await openai.aiosession.get().close() ``` -See the [usage guide](https://platform.openai.com/docs/guides/images) for more details. +### Command-line interface + +This library additionally provides an `openai` command-line utility +which makes it easy to interact with the API from your terminal. Run +`openai api -h` for usage. + +```sh +# list models +openai api models.list + +# create a chat completion (gpt-3.5-turbo, gpt-4, etc.) +openai api chat_completions.create -m gpt-3.5-turbo -g user "Hello world" + +# create a completion (text-davinci-003, text-davinci-002, ada, babbage, curie, davinci, etc.) +openai api completions.create -m ada -p "Hello world" + +# generate images via DALL·E API +openai api image.create -p "two dogs playing chess, cartoon" -n 1 + +# using openai through a proxy +openai --proxy=http://proxy.com api models.list +``` + +### Microsoft Azure Endpoints -## Requirements +In order to use the library with Microsoft Azure endpoints, you need to set the `api_type`, `api_base` and `api_version` in addition to the `api_key`. The `api_type` must be set to 'azure' and the others correspond to the properties of your endpoint. +In addition, the deployment name must be passed as the engine parameter. -- Python 3.7.1+ +```python +import openai +openai.api_type = "azure" +openai.api_key = "..." +openai.api_base = "https://example-endpoint.openai.azure.com/" +openai.api_version = "2023-05-15" + +# create a chat completion +chat_completion = openai.ChatCompletion.create(deployment_id="deployment-name", model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello world"}]) + +# print the completion +print(chat_completion.choices[0].message.content) +``` + +Please note that for the moment, the Microsoft Azure endpoints can only be used for completion, embedding, and fine-tuning operations. +For a detailed example of how to use fine-tuning and other operations using Azure endpoints, please check out the following Jupyter notebooks: -In general, we want to support the versions of Python that our -customers are using. If you run into problems with any version -issues, please let us know on our [support page](https://help.openai.com/en/). +- [Using Azure completions](https://github.com/openai/openai-cookbook/tree/main/examples/azure/completions.ipynb) +- [Using Azure fine-tuning](https://github.com/openai/openai-cookbook/tree/main/examples/azure/finetuning.ipynb) +- [Using Azure embeddings](https://github.com/openai/openai-cookbook/blob/main/examples/azure/embeddings.ipynb) + +### Microsoft Azure Active Directory Authentication + +In order to use Microsoft Active Directory to authenticate to your Azure endpoint, you need to set the `api_type` to "azure_ad" and pass the acquired credential token to `api_key`. The rest of the parameters need to be set as specified in the previous section. + +```python +from azure.identity import DefaultAzureCredential +import openai + +# Request credential +default_credential = DefaultAzureCredential() +token = default_credential.get_token("https://cognitiveservices.azure.com/.default") + +# Setup parameters +openai.api_type = "azure_ad" +openai.api_key = token.token +openai.api_base = "https://example-endpoint.openai.azure.com/" +openai.api_version = "2023-05-15" +``` ## Credit From 5d50e9e3b39540af782ca24e65c290343d86e1a9 Mon Sep 17 00:00:00 2001 From: Shapor Naghibzadeh Date: Thu, 7 Sep 2023 07:41:09 -0700 Subject: [PATCH 047/816] Update pointer to Jupyter notebooks as finetuning doesn't exist but chat does (#477) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 001b248e9c..a6c24bf18c 100644 --- a/README.md +++ b/README.md @@ -229,7 +229,7 @@ Please note that for the moment, the Microsoft Azure endpoints can only be used For a detailed example of how to use fine-tuning and other operations using Azure endpoints, please check out the following Jupyter notebooks: - [Using Azure completions](https://github.com/openai/openai-cookbook/tree/main/examples/azure/completions.ipynb) -- [Using Azure fine-tuning](https://github.com/openai/openai-cookbook/tree/main/examples/azure/finetuning.ipynb) +- [Using Azure chat](https://github.com/openai/openai-cookbook/tree/main/examples/azure/chat.ipynb) - [Using Azure embeddings](https://github.com/openai/openai-cookbook/blob/main/examples/azure/embeddings.ipynb) ### Microsoft Azure Active Directory Authentication From e389823ba013a24b4c32ce38fa0bd87e6bccae94 Mon Sep 17 00:00:00 2001 From: Morgan McGuire Date: Tue, 12 Sep 2023 19:54:15 +0200 Subject: [PATCH 048/816] Update the wandb logger (#590) * Update WandbLogger for new FineTuningJob api * remove prints * add docs link * remove pd * add pandas check * list all jobs * move pandas assert --------- Co-authored-by: Morgan McGuire Co-authored-by: Thomas Capelle Co-authored-by: John Allard --- README.md | 8 ++++++++ openai/_openai_scripts.py | 2 +- openai/cli.py | 14 ++++++++++---- openai/wandb_logger.py | 28 +++++++++++++++++++++------- 4 files changed, 40 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index a6c24bf18c..e65a5d45b6 100644 --- a/README.md +++ b/README.md @@ -129,6 +129,14 @@ openai.Model.delete("ft:gpt-3.5-turbo:acemeco:suffix:abc123") You can learn more in our [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning). +To log the training results from fine-tuning to Weights & Biases use: + +``` +openai wandb sync +``` + +For more information, read the [wandb documentation](https://docs.wandb.ai/guides/integrations/openai) on Weights & Biases. + ### Moderation OpenAI provides a free Moderation endpoint that can be used to check whether content complies with the OpenAI [content policy](https://platform.openai.com/docs/usage-policies). diff --git a/openai/_openai_scripts.py b/openai/_openai_scripts.py index f2aa3ce2b9..497de19fab 100755 --- a/openai/_openai_scripts.py +++ b/openai/_openai_scripts.py @@ -47,7 +47,7 @@ def help(args): subparsers = parser.add_subparsers() sub_api = subparsers.add_parser("api", help="Direct API calls") sub_tools = subparsers.add_parser("tools", help="Client side tools for convenience") - sub_wandb = subparsers.add_parser("wandb", help="Logging with Weights & Biases") + sub_wandb = subparsers.add_parser("wandb", help="Logging with Weights & Biases, see https://docs.wandb.ai/guides/integrations/openai for documentation") api_register(sub_api) tools_register(sub_tools) diff --git a/openai/cli.py b/openai/cli.py index 99d171a849..a6e99396ae 100644 --- a/openai/cli.py +++ b/openai/cli.py @@ -1375,7 +1375,7 @@ def help(args): def wandb_register(parser): subparsers = parser.add_subparsers( - title="wandb", help="Logging with Weights & Biases" + title="wandb", help="Logging with Weights & Biases, see https://docs.wandb.ai/guides/integrations/openai for documentation" ) def help(args): @@ -1394,17 +1394,23 @@ def help(args): ) sub.add_argument( "--project", - default="GPT-3", - help="""Name of the project where you're sending runs. By default, it is "GPT-3".""", + default="OpenAI-Fine-Tune", + help="""Name of the Weights & Biases project where you're sending runs. By default, it is "OpenAI-Fine-Tune".""", ) sub.add_argument( "--entity", - help="Username or team name where you're sending runs. By default, your default entity is used, which is usually your username.", + help="Weights & Biases username or team name where you're sending runs. By default, your default entity is used, which is usually your username.", ) sub.add_argument( "--force", action="http://github.com/store_true", help="Forces logging and overwrite existing wandb run of the same fine-tune.", ) + sub.add_argument( + "--legacy", + action="http://github.com/store_true", + help="Log results from legacy OpenAI /v1/fine-tunes api", + ) sub.set_defaults(force=False) + sub.set_defaults(legacy=False) sub.set_defaults(func=WandbLogger.sync) diff --git a/openai/wandb_logger.py b/openai/wandb_logger.py index fdd8c24adc..d8e060c41b 100644 --- a/openai/wandb_logger.py +++ b/openai/wandb_logger.py @@ -13,9 +13,9 @@ import re from pathlib import Path - from openai import File, FineTune + from openai import File, FineTune, FineTuningJob from openai.datalib.numpy_helper import numpy as np - from openai.datalib.pandas_helper import pandas as pd + from openai.datalib.pandas_helper import assert_has_pandas, pandas as pd class WandbLogger: @@ -34,9 +34,10 @@ def sync( cls, id=None, n_fine_tunes=None, - project="GPT-3", + project="OpenAI-Fine-Tune", entity=None, force=False, + legacy=False, **kwargs_wandb_init, ): """ @@ -47,18 +48,26 @@ def sync( :param entity: Username or team name where you're sending runs. By default, your default entity is used, which is usually your username. :param force: Forces logging and overwrite existing wandb run of the same fine-tune. """ + + assert_has_pandas() if not WANDB_AVAILABLE: return if id: - fine_tune = FineTune.retrieve(id=id) + print("Retrieving fine-tune job...") + if legacy: + fine_tune = FineTune.retrieve(id=id) + else: + fine_tune = FineTuningJob.retrieve(id=id) fine_tune.pop("events", None) fine_tunes = [fine_tune] - else: # get list of fine_tune to log - fine_tunes = FineTune.list() + if legacy: + fine_tunes = FineTune.list() + else: + fine_tunes = list(FineTuningJob.auto_paging_iter()) if not fine_tunes or fine_tunes.get("data") is None: print("No fine-tune has been retrieved") return @@ -76,6 +85,7 @@ def sync( project, entity, force, + legacy, show_individual_warnings, **kwargs_wandb_init, ) @@ -94,6 +104,7 @@ def _log_fine_tune( project, entity, force, + legacy, show_individual_warnings, **kwargs_wandb_init, ): @@ -110,7 +121,10 @@ def _log_fine_tune( # check results are present try: - results_id = fine_tune["result_files"][0]["id"] + if legacy: + results_id = fine_tune["result_files"][0]["id"] + else: + results_id = fine_tune["result_files"][0] results = File.download(id=results_id).decode("utf-8") except: if show_individual_warnings: From 3f6ef0604fb8ae2b705396e22be14fad0e80c1d2 Mon Sep 17 00:00:00 2001 From: Krista Pratico Date: Thu, 21 Sep 2023 14:49:55 -0700 Subject: [PATCH 049/816] [azure] enable audio/whisper support (#613) * enable azure for audio * reorder overloads * add additional tests * add helper function to utils * simplify - azure users will just need to pass model and deployment_id --- openai/api_resources/audio.py | 44 ++++++++++++++++++++++++++++------- 1 file changed, 35 insertions(+), 9 deletions(-) diff --git a/openai/api_resources/audio.py b/openai/api_resources/audio.py index d5d906ed96..cb316f07f1 100644 --- a/openai/api_resources/audio.py +++ b/openai/api_resources/audio.py @@ -9,7 +9,9 @@ class Audio(APIResource): OBJECT_NAME = "audio" @classmethod - def _get_url(http://github.com/cls,%20action): + def _get_url(http://github.com/cls,%20action,%20deployment_id=None,%20api_type=None,%20api_version=None): + if api_type in (util.ApiType.AZURE, util.ApiType.AZURE_AD): + return f"/{cls.azure_api_prefix}/deployments/{deployment_id}/audio/{action}?api-version={api_version}" return cls.class_url() + f"/{action}" @classmethod @@ -50,6 +52,8 @@ def transcribe( api_type=None, api_version=None, organization=None, + *, + deployment_id=None, **params, ): requestor, files, data = cls._prepare_request( @@ -63,7 +67,8 @@ def transcribe( organization=organization, **params, ) - url = cls._get_url("http://github.com/transcriptions") + api_type, api_version = cls._get_api_type_and_version(api_type, api_version) + url = cls._get_url("http://github.com/transcriptions%22,%20deployment_id=deployment_id,%20api_type=api_type,%20api_version=api_version) response, _, api_key = requestor.request("post", url, files=files, params=data) return util.convert_to_openai_object( response, api_key, api_version, organization @@ -79,6 +84,8 @@ def translate( api_type=None, api_version=None, organization=None, + *, + deployment_id=None, **params, ): requestor, files, data = cls._prepare_request( @@ -92,7 +99,8 @@ def translate( organization=organization, **params, ) - url = cls._get_url("http://github.com/translations") + api_type, api_version = cls._get_api_type_and_version(api_type, api_version) + url = cls._get_url("http://github.com/translations%22,%20deployment_id=deployment_id,%20api_type=api_type,%20api_version=api_version) response, _, api_key = requestor.request("post", url, files=files, params=data) return util.convert_to_openai_object( response, api_key, api_version, organization @@ -109,6 +117,8 @@ def transcribe_raw( api_type=None, api_version=None, organization=None, + *, + deployment_id=None, **params, ): requestor, files, data = cls._prepare_request( @@ -122,7 +132,8 @@ def transcribe_raw( organization=organization, **params, ) - url = cls._get_url("http://github.com/transcriptions") + api_type, api_version = cls._get_api_type_and_version(api_type, api_version) + url = cls._get_url("http://github.com/transcriptions%22,%20deployment_id=deployment_id,%20api_type=api_type,%20api_version=api_version) response, _, api_key = requestor.request("post", url, files=files, params=data) return util.convert_to_openai_object( response, api_key, api_version, organization @@ -139,6 +150,8 @@ def translate_raw( api_type=None, api_version=None, organization=None, + *, + deployment_id=None, **params, ): requestor, files, data = cls._prepare_request( @@ -152,7 +165,8 @@ def translate_raw( organization=organization, **params, ) - url = cls._get_url("http://github.com/translations") + api_type, api_version = cls._get_api_type_and_version(api_type, api_version) + url = cls._get_url("http://github.com/translations%22,%20deployment_id=deployment_id,%20api_type=api_type,%20api_version=api_version) response, _, api_key = requestor.request("post", url, files=files, params=data) return util.convert_to_openai_object( response, api_key, api_version, organization @@ -168,6 +182,8 @@ async def atranscribe( api_type=None, api_version=None, organization=None, + *, + deployment_id=None, **params, ): requestor, files, data = cls._prepare_request( @@ -181,7 +197,8 @@ async def atranscribe( organization=organization, **params, ) - url = cls._get_url("http://github.com/transcriptions") + api_type, api_version = cls._get_api_type_and_version(api_type, api_version) + url = cls._get_url("http://github.com/transcriptions%22,%20deployment_id=deployment_id,%20api_type=api_type,%20api_version=api_version) response, _, api_key = await requestor.arequest( "post", url, files=files, params=data ) @@ -199,6 +216,8 @@ async def atranslate( api_type=None, api_version=None, organization=None, + *, + deployment_id=None, **params, ): requestor, files, data = cls._prepare_request( @@ -212,7 +231,8 @@ async def atranslate( organization=organization, **params, ) - url = cls._get_url("http://github.com/translations") + api_type, api_version = cls._get_api_type_and_version(api_type, api_version) + url = cls._get_url("http://github.com/translations%22,%20deployment_id=deployment_id,%20api_type=api_type,%20api_version=api_version) response, _, api_key = await requestor.arequest( "post", url, files=files, params=data ) @@ -231,6 +251,8 @@ async def atranscribe_raw( api_type=None, api_version=None, organization=None, + *, + deployment_id=None, **params, ): requestor, files, data = cls._prepare_request( @@ -244,7 +266,8 @@ async def atranscribe_raw( organization=organization, **params, ) - url = cls._get_url("http://github.com/transcriptions") + api_type, api_version = cls._get_api_type_and_version(api_type, api_version) + url = cls._get_url("http://github.com/transcriptions%22,%20deployment_id=deployment_id,%20api_type=api_type,%20api_version=api_version) response, _, api_key = await requestor.arequest( "post", url, files=files, params=data ) @@ -263,6 +286,8 @@ async def atranslate_raw( api_type=None, api_version=None, organization=None, + *, + deployment_id=None, **params, ): requestor, files, data = cls._prepare_request( @@ -276,7 +301,8 @@ async def atranslate_raw( organization=organization, **params, ) - url = cls._get_url("http://github.com/translations") + api_type, api_version = cls._get_api_type_and_version(api_type, api_version) + url = cls._get_url("http://github.com/translations%22,%20deployment_id=deployment_id,%20api_type=api_type,%20api_version=api_version) response, _, api_key = await requestor.arequest( "post", url, files=files, params=data ) From 7fba4dce4b7e797e708aac7dc1c73a7c66f006d3 Mon Sep 17 00:00:00 2001 From: Arthur Date: Fri, 22 Sep 2023 21:04:44 +0800 Subject: [PATCH 050/816] Update nested_resource_class_methods.py (#612) support api-base in _nested_resource_class_methods --- .../abstract/nested_resource_class_methods.py | 38 ++++++++++--------- 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/openai/api_resources/abstract/nested_resource_class_methods.py b/openai/api_resources/abstract/nested_resource_class_methods.py index f171737b17..68197ab1fa 100644 --- a/openai/api_resources/abstract/nested_resource_class_methods.py +++ b/openai/api_resources/abstract/nested_resource_class_methods.py @@ -28,17 +28,18 @@ def nested_resource_url(http://github.com/cls,%20id,%20nested_id=None): setattr(cls, resource_url_method, classmethod(nested_resource_url)) def nested_resource_request( - cls, - method, - url, - api_key=None, - request_id=None, - api_version=None, - organization=None, - **params, + cls, + method, + url, + api_base=None, + api_key=None, + request_id=None, + api_version=None, + organization=None, + **params, ): requestor = api_requestor.APIRequestor( - api_key, api_version=api_version, organization=organization + api_key, api_base=api_base, api_version=api_version, organization=organization ) response, _, api_key = requestor.request( method, url, params, request_id=request_id @@ -48,17 +49,18 @@ def nested_resource_request( ) async def anested_resource_request( - cls, - method, - url, - api_key=None, - request_id=None, - api_version=None, - organization=None, - **params, + cls, + method, + url, + api_key=None, + api_base=None, + request_id=None, + api_version=None, + organization=None, + **params, ): requestor = api_requestor.APIRequestor( - api_key, api_version=api_version, organization=organization + api_key, api_base=api_base, api_version=api_version, organization=organization ) response, _, api_key = await requestor.arequest( method, url, params, request_id=request_id From 8944bd1609227d42e6283967a4eeb2ae800d6bb6 Mon Sep 17 00:00:00 2001 From: Michael Feil <63565275+michaelfeil@users.noreply.github.com> Date: Mon, 25 Sep 2023 02:12:24 +0200 Subject: [PATCH 051/816] Fix: SSE Stream parser expects additional space after colon "data:" (#559) * Update api_requestor.py * fix: SSE event for api_requestor.py --- openai/api_requestor.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/openai/api_requestor.py b/openai/api_requestor.py index 504f7c4411..0b44949839 100644 --- a/openai/api_requestor.py +++ b/openai/api_requestor.py @@ -98,16 +98,18 @@ def _make_session() -> requests.Session: def parse_stream_helper(line: bytes) -> Optional[str]: - if line: - if line.strip() == b"data: [DONE]": - # return here will cause GeneratorExit exception in urllib3 - # and it will close http connection with TCP Reset - return None + if line and line.startswith(b"data:"): if line.startswith(b"data: "): + # SSE event may be valid when it contain whitespace line = line[len(b"data: "):] - return line.decode("utf-8") else: + line = line[len(b"data:"):] + if line.strip() == b"[DONE]": + # return here will cause GeneratorExit exception in urllib3 + # and it will close http connection with TCP Reset return None + else: + return line.decode("utf-8") return None From 532d3df107e651deb95ca071a0ff7fb32588243f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hynek=20Kydl=C3=AD=C4=8Dek?= <39408646+hynky1999@users.noreply.github.com> Date: Tue, 26 Sep 2023 05:16:58 +0200 Subject: [PATCH 052/816] =?UTF-8?q?=F0=9F=90=9B=20fixed=20asyncio=20bugs?= =?UTF-8?q?=20(#584)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- openai/api_requestor.py | 41 ++++++++++++++++++++++++++++++----------- 1 file changed, 30 insertions(+), 11 deletions(-) diff --git a/openai/api_requestor.py b/openai/api_requestor.py index 0b44949839..c051bc64f2 100644 --- a/openai/api_requestor.py +++ b/openai/api_requestor.py @@ -6,11 +6,10 @@ import threading import time import warnings -from contextlib import asynccontextmanager from json import JSONDecodeError from typing import ( + AsyncContextManager, AsyncGenerator, - AsyncIterator, Callable, Dict, Iterator, @@ -368,8 +367,9 @@ async def arequest( request_id: Optional[str] = None, request_timeout: Optional[Union[float, Tuple[float, float]]] = None, ) -> Tuple[Union[OpenAIResponse, AsyncGenerator[OpenAIResponse, None]], bool, str]: - ctx = aiohttp_session() + ctx = AioHTTPSession() session = await ctx.__aenter__() + result = None try: result = await self.arequest_raw( method.lower(), @@ -383,6 +383,9 @@ async def arequest( ) resp, got_stream = await self._interpret_async_response(result, stream) except Exception: + # Close the request before exiting session context. + if result is not None: + result.release() await ctx.__aexit__(None, None, None) raise if got_stream: @@ -393,10 +396,15 @@ async def wrap_resp(): async for r in resp: yield r finally: + # Close the request before exiting session context. Important to do it here + # as if stream is not fully exhausted, we need to close the request nevertheless. + result.release() await ctx.__aexit__(None, None, None) return wrap_resp(), got_stream, self.api_key else: + # Close the request before exiting session context. + result.release() await ctx.__aexit__(None, None, None) return resp, got_stream, self.api_key @@ -770,11 +778,22 @@ def _interpret_response_line( return resp -@asynccontextmanager -async def aiohttp_session() -> AsyncIterator[aiohttp.ClientSession]: - user_set_session = openai.aiosession.get() - if user_set_session: - yield user_set_session - else: - async with aiohttp.ClientSession() as session: - yield session +class AioHTTPSession(AsyncContextManager): + def __init__(self): + self._session = None + self._should_close_session = False + + async def __aenter__(self): + self._session = openai.aiosession.get() + if self._session is None: + self._session = await aiohttp.ClientSession().__aenter__() + self._should_close_session = True + + return self._session + + async def __aexit__(self, exc_type, exc_value, traceback): + if self._session is None: + raise RuntimeError("Session is not initialized") + + if self._should_close_session: + await self._session.__aexit__(exc_type, exc_value, traceback) \ No newline at end of file From 19d2444a14b9d558361eb4d5342852ab94e7d54b Mon Sep 17 00:00:00 2001 From: William Horton Date: Mon, 25 Sep 2023 23:18:32 -0400 Subject: [PATCH 053/816] Bugfix: Add param positional arg to InvalidRequestError (#573) I was testing some code and I got this error: ``` File "/usr/local/lib/python3.10/site-packages/openai/api_resources/abstract/engine_api_resource.py", line 37, in class_url raise error.InvalidRequestError( TypeError: InvalidRequestError.__init__() missing 1 required positional argument: 'param' ``` So I checked this file and saw that in a few cases, InvalidRequestError was missing the second positional argument `param` --- openai/api_resources/abstract/engine_api_resource.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/openai/api_resources/abstract/engine_api_resource.py b/openai/api_resources/abstract/engine_api_resource.py index 1f172d8cbd..bbef90e23e 100644 --- a/openai/api_resources/abstract/engine_api_resource.py +++ b/openai/api_resources/abstract/engine_api_resource.py @@ -35,11 +35,13 @@ def class_url( if typed_api_type in (ApiType.AZURE, ApiType.AZURE_AD): if not api_version: raise error.InvalidRequestError( - "An API version is required for the Azure API type." + "An API version is required for the Azure API type.", + "api_version" ) if engine is None: raise error.InvalidRequestError( - "You must provide the deployment name in the 'engine' parameter to access the Azure OpenAI service" + "You must provide the deployment name in the 'engine' parameter to access the Azure OpenAI service", + "engine" ) extn = quote_plus(engine) return "/%s/%s/%s/%s?api-version=%s" % ( @@ -269,7 +271,8 @@ def instance_url(http://github.com/self): api_version = self.api_version or openai.api_version if not api_version: raise error.InvalidRequestError( - "An API version is required for the Azure API type." + "An API version is required for the Azure API type.", + "api_version" ) base = self.OBJECT_NAME.replace(".", "/") url = "/%s/%s/%s/%s/%s?api-version=%s" % ( From 2d711847c859e7c74da301701d0e0b1756d8af28 Mon Sep 17 00:00:00 2001 From: Pamela Fox Date: Tue, 26 Sep 2023 08:26:34 -0700 Subject: [PATCH 054/816] Replace engine with deployment_id in README (#614) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e65a5d45b6..a348a47b33 100644 --- a/README.md +++ b/README.md @@ -217,7 +217,7 @@ openai --proxy=http://proxy.com api models.list ### Microsoft Azure Endpoints In order to use the library with Microsoft Azure endpoints, you need to set the `api_type`, `api_base` and `api_version` in addition to the `api_key`. The `api_type` must be set to 'azure' and the others correspond to the properties of your endpoint. -In addition, the deployment name must be passed as the engine parameter. +In addition, the deployment name must be passed as the `deployment_id` parameter. ```python import openai From 870534d39cb4a37a696efc2507cc1e89e18e6a07 Mon Sep 17 00:00:00 2001 From: Logan Kilpatrick Date: Tue, 26 Sep 2023 10:34:18 -0500 Subject: [PATCH 055/816] Update embeddings_utils.py to set default model to text-embedding-ada-002 (#604) * Update embeddings_utils.py * Update max tokens for new embeddings model --- openai/embeddings_utils.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/openai/embeddings_utils.py b/openai/embeddings_utils.py index f1d438c9c0..dc26445c3c 100644 --- a/openai/embeddings_utils.py +++ b/openai/embeddings_utils.py @@ -15,7 +15,7 @@ @retry(wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6)) -def get_embedding(text: str, engine="text-similarity-davinci-001", **kwargs) -> List[float]: +def get_embedding(text: str, engine="text-embedding-ada-002", **kwargs) -> List[float]: # replace newlines, which can negatively affect performance. text = text.replace("\n", " ") @@ -25,7 +25,7 @@ def get_embedding(text: str, engine="text-similarity-davinci-001", **kwargs) -> @retry(wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6)) async def aget_embedding( - text: str, engine="text-similarity-davinci-001", **kwargs + text: str, engine="text-embedding-ada-002", **kwargs ) -> List[float]: # replace newlines, which can negatively affect performance. @@ -38,9 +38,9 @@ async def aget_embedding( @retry(wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6)) def get_embeddings( - list_of_text: List[str], engine="text-similarity-babbage-001", **kwargs + list_of_text: List[str], engine="text-embedding-ada-002", **kwargs ) -> List[List[float]]: - assert len(list_of_text) <= 2048, "The batch size should not be larger than 2048." + assert len(list_of_text) <= 8191, "The batch size should not be larger than 8191." # replace newlines, which can negatively affect performance. list_of_text = [text.replace("\n", " ") for text in list_of_text] @@ -51,9 +51,9 @@ def get_embeddings( @retry(wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6)) async def aget_embeddings( - list_of_text: List[str], engine="text-similarity-babbage-001", **kwargs + list_of_text: List[str], engine="text-embedding-ada-002", **kwargs ) -> List[List[float]]: - assert len(list_of_text) <= 2048, "The batch size should not be larger than 2048." + assert len(list_of_text) <= 8191, "The batch size should not be larger than 8191." # replace newlines, which can negatively affect performance. list_of_text = [text.replace("\n", " ") for text in list_of_text] From 5453a19efe6fa4395673782e5e3bd161572d383c Mon Sep 17 00:00:00 2001 From: Logan Kilpatrick Date: Tue, 26 Sep 2023 10:34:40 -0500 Subject: [PATCH 056/816] Update README.md (#625) --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a348a47b33..b2e0b1bf00 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ Install dependencies for [`openai.embeddings_utils`](openai/embeddings_utils.py) pip install openai[embeddings] ``` -Install support for [Weights & Biases](https://wandb.me/openai-docs): +Install support for [Weights & Biases](https://wandb.me/openai-docs) which can be used for fine-tuning: ```sh pip install openai[wandb] @@ -51,7 +51,7 @@ pip install openai[datalib] ## Usage -The library needs to be configured with your account's secret key which is available on the [website](https://platform.openai.com/account/api-keys). Either set it as the `OPENAI_API_KEY` environment variable before using the library: +The library needs to be configured with your OpenAI account's private API key which is available on our [developer platform](https://platform.openai.com/account/api-keys). Either set it as the `OPENAI_API_KEY` environment variable before using the library: ```bash export OPENAI_API_KEY='sk-...' From 96225bdb16a0fa5fd472c8f54ae74fcf7d3e433d Mon Sep 17 00:00:00 2001 From: hallacy <1945079+hallacy@users.noreply.github.com> Date: Tue, 3 Oct 2023 15:39:12 -0700 Subject: [PATCH 057/816] Add note to readme about new beta (#634) * Add note to readme about new beeta * Update README.md Co-authored-by: Logan Kilpatrick * Update README.md * Update README.md --------- Co-authored-by: Logan Kilpatrick --- README.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/README.md b/README.md index b2e0b1bf00..6ec4b6ae82 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,19 @@ with a wide range of versions of the OpenAI API. You can find usage examples for the OpenAI Python library in our [API reference](https://platform.openai.com/docs/api-reference?lang=python) and the [OpenAI Cookbook](https://github.com/openai/openai-cookbook/). +## Beta Release + +> [!IMPORTANT] +> We're is preparing to release version 1.0 of the OpenAI Python library. + +This new version will be a major release and will include breaking changes. We're releasing this beta version to give you a chance to try out the new features and provide feedback before the official release. You can install the beta version with: + +```sh +pip install --pre openai +``` +And follow along with the [beta release notes](https://github.com/openai/openai-python/discussions/631). + + ## Installation To start, ensure you have Python 3.7.1 or newer. If you just From 284c1799070c723c6a553337134148a7ab088dd8 Mon Sep 17 00:00:00 2001 From: hallacy <1945079+hallacy@users.noreply.github.com> Date: Tue, 3 Oct 2023 16:21:15 -0700 Subject: [PATCH 058/816] Update README.md (#635) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6ec4b6ae82..615160b3a4 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ You can find usage examples for the OpenAI Python library in our [API reference] ## Beta Release > [!IMPORTANT] -> We're is preparing to release version 1.0 of the OpenAI Python library. +> We're preparing to release version 1.0 of the OpenAI Python library. This new version will be a major release and will include breaking changes. We're releasing this beta version to give you a chance to try out the new features and provide feedback before the official release. You can install the beta version with: From 08b8179a6b3e46ca8eb117f819cc6563ae74e27d Mon Sep 17 00:00:00 2001 From: David Schnurr Date: Mon, 6 Nov 2023 08:19:00 -0800 Subject: [PATCH 059/816] V1 (#677) * cleanup * v1.0.0-beta.1 * docs: add basic manual azure example * docs: use chat completions instead of completions for demo example * test: rename `API_BASE_URL` to `TEST_API_BASE_URL` * feat(client): handle retry-after header with a date format * feat(api): remove `content_filter` stop_reason and update documentation * refactor(cli): rename internal types for improved auto complete * feat(client): add forwards-compatible pydantic methods * feat(api): move `n_epochs` under `hyperparameters` * feat(client): add support for passing in a httpx client * chore: update README * feat(cli): use http/2 if h2 is available * chore(docs): remove trailing spaces * feat(client): add logging setup * chore(internal): minor updates * v1.0.0-beta.2 * docs: use chat completions instead of completions for demo example * chore: add case insensitive get header function * fix(client): correctly handle errors during streaming * fix(streaming): add additional overload for ambiguous stream param * chore(internal): enable lint rule * chore(internal): cleanup some redundant code * fix(client): accept io.IOBase instances in file params * docs: improve error message for invalid file param type * 1.0.0-beta.3 * chore(internal): migrate from Poetry to Rye * feat(cli): add `tools fine_tunes.prepare_data` * feat(client): support passing httpx.URL instances to base_url * chore(internal): fix some latent type errors * feat(api): add embeddings encoding_format * feat: use numpy for faster embeddings decoding * chore(internal): bump pyright * chore(internal): bump deps * feat(client): improve file upload types * feat(client): adjust retry behavior to be exponential backoff * ci: add lint workflow * docs: improve to dictionary example * ci(lint): run ruff too * chore(internal): require explicit overrides * feat(client): support accessing raw response objects * test(qs): add an additional test case for array brackets * feat(client): add dedicated Azure client * feat(package): add classifiers * docs(readme): add Azure guide * 1.0.0-rc1 * docs: small cleanup * feat(github): include a devcontainer setup * chore: improve type names * feat(client): allow binary returns * feat(client): support passing BaseModels to request params at runtime * fix(binaries): don't synchronously block in astream_to_file * 1.0.0-rc2 * chore(internal): remove unused int/float conversion * docs(readme): improve example snippets * fix: prevent TypeError in Python 3.8 (ABC is not subscriptable) * 1.0.0-rc3 * docs: update streaming example * docs(readme): update opening * v1.0.0 --------- Co-authored-by: Robert Craigie Co-authored-by: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Co-authored-by: Stainless Bot Co-authored-by: Alex Rattray --- .devcontainer/Dockerfile | 27 + .devcontainer/devcontainer.json | 20 + .github/ISSUE_TEMPLATE/bug_report.yml | 56 - .github/ISSUE_TEMPLATE/config.yml | 7 - .github/ISSUE_TEMPLATE/feature_request.yml | 20 - .github/workflows/ci.yml | 41 + .gitignore | 24 +- .python-version | 1 + .stats.yml | 1 + LICENSE | 222 ++- Makefile | 11 - README.md | 534 +++-- api.md | 172 ++ bin/blacken-docs.py | 251 +++ bin/check-test-server | 50 + bin/test | 3 + chatml.md | 96 - examples/README.md | 7 - examples/async_demo.py | 22 + examples/azure.py | 43 + examples/azure/embeddings.ipynb | 38 - examples/azure/finetuning.ipynb | 38 - examples/azure_ad.py | 30 + examples/codex/backtranslation.py | 2 - examples/demo.py | 38 + examples/embeddings/Classification.ipynb | 38 - examples/embeddings/Clustering.ipynb | 38 - examples/embeddings/Code_search.ipynb | 38 - examples/embeddings/Get_embeddings.ipynb | 38 - examples/embeddings/Obtain_dataset.ipynb | 38 - examples/embeddings/Recommendation.ipynb | 36 - examples/embeddings/Regression.ipynb | 38 - ...emantic_text_search_using_embeddings.ipynb | 38 - .../User_and_product_embeddings.ipynb | 38 - examples/embeddings/Visualize_in_2d.ipynb | 38 - examples/embeddings/Visualize_in_3d.ipynb | 38 - .../embeddings/Zero-shot_classification.ipynb | 38 - examples/finetuning/answers_with_ft.py | 2 - .../finetuning-classification.ipynb | 38 - .../finetuning/olympics-1-collect-data.ipynb | 38 - .../finetuning/olympics-2-create-qa.ipynb | 38 - examples/finetuning/olympics-3-train-qa.ipynb | 38 - examples/module_client.py | 25 + examples/streaming.py | 56 + mypy.ini | 47 + noxfile.py | 9 + openai/__init__.py | 106 - openai/_openai_scripts.py | 89 - openai/api_requestor.py | 799 -------- openai/api_resources/__init__.py | 15 - openai/api_resources/abstract/__init__.py | 13 - openai/api_resources/abstract/api_resource.py | 172 -- .../abstract/createable_api_resource.py | 98 - .../abstract/deletable_api_resource.py | 48 - .../abstract/engine_api_resource.py | 328 --- .../abstract/listable_api_resource.py | 95 - .../abstract/nested_resource_class_methods.py | 169 -- .../abstract/paginatable_api_resource.py | 125 -- .../abstract/updateable_api_resource.py | 16 - openai/api_resources/audio.py | 311 --- openai/api_resources/chat_completion.py | 50 - openai/api_resources/completion.py | 50 - openai/api_resources/customer.py | 17 - openai/api_resources/deployment.py | 119 -- openai/api_resources/edit.py | 57 - openai/api_resources/embedding.py | 91 - openai/api_resources/engine.py | 50 - openai/api_resources/error_object.py | 28 - openai/api_resources/experimental/__init__.py | 3 - .../experimental/completion_config.py | 11 - openai/api_resources/file.py | 279 --- openai/api_resources/fine_tune.py | 204 -- openai/api_resources/fine_tuning.py | 88 - openai/api_resources/image.py | 273 --- openai/api_resources/model.py | 5 - openai/api_resources/moderation.py | 45 - openai/cli.py | 1416 ------------- openai/datalib/__init__.py | 14 - openai/datalib/common.py | 17 - openai/datalib/numpy_helper.py | 15 - openai/datalib/pandas_helper.py | 15 - openai/embeddings_utils.py | 252 --- openai/error.py | 169 -- openai/object_classes.py | 12 - openai/openai_object.py | 347 ---- openai/openai_response.py | 31 - openai/tests/__init__.py | 0 openai/tests/asyncio/__init__.py | 0 openai/tests/asyncio/test_endpoints.py | 90 - openai/tests/test_api_requestor.py | 101 - openai/tests/test_endpoints.py | 118 -- openai/tests/test_exceptions.py | 40 - openai/tests/test_file_cli.py | 39 - openai/tests/test_long_examples_validator.py | 54 - openai/tests/test_url_composition.py | 209 -- openai/tests/test_util.py | 55 - openai/upload_progress.py | 52 - openai/util.py | 188 -- openai/version.py | 1 - openai/wandb_logger.py | 314 --- public/Makefile | 7 - public/setup.py | 10 - pyproject.toml | 163 +- pytest.ini | 4 - requirements-dev.lock | 74 + requirements.lock | 32 + setup.cfg | 65 - setup.py | 3 - src/openai/__init__.py | 342 ++++ src/openai/__main__.py | 3 + src/openai/_base_client.py | 1768 +++++++++++++++++ src/openai/_client.py | 488 +++++ src/openai/_compat.py | 173 ++ src/openai/_constants.py | 10 + src/openai/_exceptions.py | 123 ++ src/openai/_extras/__init__.py | 3 + src/openai/_extras/_common.py | 21 + src/openai/_extras/numpy_proxy.py | 39 + src/openai/_extras/pandas_proxy.py | 30 + src/openai/_files.py | 122 ++ src/openai/_models.py | 460 +++++ src/openai/_module_client.py | 85 + src/openai/_qs.py | 150 ++ src/openai/_resource.py | 42 + src/openai/_response.py | 252 +++ src/openai/_streaming.py | 232 +++ src/openai/_types.py | 343 ++++ src/openai/_utils/__init__.py | 36 + src/openai/_utils/_logs.py | 25 + src/openai/_utils/_proxy.py | 61 + src/openai/_utils/_transform.py | 214 ++ src/openai/_utils/_utils.py | 408 ++++ src/openai/_version.py | 4 + src/openai/cli/__init__.py | 1 + src/openai/cli/_api/__init__.py | 1 + src/openai/cli/_api/_main.py | 16 + src/openai/cli/_api/audio.py | 94 + src/openai/cli/_api/chat/__init__.py | 13 + src/openai/cli/_api/chat/completions.py | 154 ++ src/openai/cli/_api/completions.py | 173 ++ src/openai/cli/_api/files.py | 75 + src/openai/cli/_api/image.py | 130 ++ src/openai/cli/_api/models.py | 45 + src/openai/cli/_cli.py | 234 +++ src/openai/cli/_errors.py | 23 + src/openai/cli/_models.py | 17 + src/openai/cli/_progress.py | 59 + src/openai/cli/_tools/__init__.py | 1 + src/openai/cli/_tools/_main.py | 17 + src/openai/cli/_tools/fine_tunes.py | 63 + src/openai/cli/_tools/migrate.py | 181 ++ src/openai/cli/_utils.py | 45 + .../openai/lib/_validators.py | 281 ++- src/openai/lib/azure.py | 439 ++++ src/openai/pagination.py | 95 + {openai => src/openai}/py.typed | 0 src/openai/resources/__init__.py | 95 + src/openai/resources/audio/__init__.py | 30 + src/openai/resources/audio/audio.py | 60 + src/openai/resources/audio/transcriptions.py | 206 ++ src/openai/resources/audio/translations.py | 192 ++ src/openai/resources/chat/__init__.py | 20 + src/openai/resources/chat/chat.py | 48 + src/openai/resources/chat/completions.py | 942 +++++++++ src/openai/resources/completions.py | 1117 +++++++++++ src/openai/resources/edits.py | 191 ++ src/openai/resources/embeddings.py | 221 +++ src/openai/resources/files.py | 471 +++++ src/openai/resources/fine_tunes.py | 820 ++++++++ src/openai/resources/fine_tuning/__init__.py | 20 + .../resources/fine_tuning/fine_tuning.py | 43 + src/openai/resources/fine_tuning/jobs.py | 567 ++++++ src/openai/resources/images.py | 479 +++++ src/openai/resources/models.py | 235 +++ src/openai/resources/moderations.py | 148 ++ src/openai/types/__init__.py | 42 + src/openai/types/audio/__init__.py | 12 + src/openai/types/audio/transcription.py | 9 + .../audio/transcription_create_params.py | 52 + src/openai/types/audio/translation.py | 9 + .../types/audio/translation_create_params.py | 44 + src/openai/types/chat/__init__.py | 12 + src/openai/types/chat/chat_completion.py | 50 + .../types/chat/chat_completion_chunk.py | 76 + .../types/chat/chat_completion_message.py | 35 + .../chat/chat_completion_message_param.py | 50 + src/openai/types/chat/chat_completion_role.py | 7 + .../types/chat/completion_create_params.py | 194 ++ src/openai/types/completion.py | 29 + src/openai/types/completion_choice.py | 35 + src/openai/types/completion_create_params.py | 184 ++ src/openai/types/completion_usage.py | 16 + src/openai/types/create_embedding_response.py | 30 + src/openai/types/edit.py | 40 + src/openai/types/edit_create_params.py | 44 + src/openai/types/embedding.py | 22 + src/openai/types/embedding_create_params.py | 43 + src/openai/types/file_content.py | 6 + src/openai/types/file_create_params.py | 26 + src/openai/types/file_deleted.py | 13 + src/openai/types/file_object.py | 40 + src/openai/types/fine_tune.py | 93 + src/openai/types/fine_tune_create_params.py | 140 ++ src/openai/types/fine_tune_event.py | 15 + .../types/fine_tune_events_list_response.py | 14 + .../types/fine_tune_list_events_params.py | 41 + src/openai/types/fine_tuning/__init__.py | 9 + .../types/fine_tuning/fine_tuning_job.py | 107 + .../fine_tuning/fine_tuning_job_event.py | 19 + .../types/fine_tuning/job_create_params.py | 65 + .../fine_tuning/job_list_events_params.py | 15 + .../types/fine_tuning/job_list_params.py | 15 + src/openai/types/image.py | 18 + .../types/image_create_variation_params.py | 40 + src/openai/types/image_edit_params.py | 54 + src/openai/types/image_generate_params.py | 38 + src/openai/types/images_response.py | 14 + src/openai/types/model.py | 19 + src/openai/types/model_deleted.py | 13 + src/openai/types/moderation.py | 120 ++ src/openai/types/moderation_create_params.py | 25 + .../types/moderation_create_response.py | 19 + src/openai/version.py | 3 + tests/__init__.py | 1 + tests/api_resources/__init__.py | 1 + tests/api_resources/audio/__init__.py | 1 + .../audio/test_transcriptions.py | 87 + .../api_resources/audio/test_translations.py | 85 + tests/api_resources/chat/__init__.py | 1 + tests/api_resources/chat/test_completions.py | 281 +++ tests/api_resources/fine_tuning/__init__.py | 1 + tests/api_resources/fine_tuning/test_jobs.py | 240 +++ tests/api_resources/test_completions.py | 185 ++ tests/api_resources/test_edits.py | 95 + tests/api_resources/test_embeddings.py | 83 + tests/api_resources/test_files.py | 184 ++ tests/api_resources/test_fine_tunes.py | 274 +++ tests/api_resources/test_images.py | 197 ++ tests/api_resources/test_models.py | 116 ++ tests/api_resources/test_moderations.py | 75 + tests/conftest.py | 16 + tests/lib/test_azure.py | 36 + tests/test_client.py | 1110 +++++++++++ tests/test_deepcopy.py | 59 + tests/test_extract_files.py | 64 + tests/test_files.py | 51 + tests/test_models.py | 573 ++++++ tests/test_module_client.py | 179 ++ tests/test_qs.py | 78 + tests/test_required_args.py | 111 ++ tests/test_streaming.py | 104 + tests/test_transform.py | 232 +++ tests/utils.py | 105 + 253 files changed, 21668 insertions(+), 8629 deletions(-) create mode 100644 .devcontainer/Dockerfile create mode 100644 .devcontainer/devcontainer.json delete mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml delete mode 100644 .github/ISSUE_TEMPLATE/config.yml delete mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml create mode 100644 .github/workflows/ci.yml create mode 100644 .python-version create mode 100644 .stats.yml delete mode 100644 Makefile create mode 100644 api.md create mode 100644 bin/blacken-docs.py create mode 100755 bin/check-test-server create mode 100755 bin/test delete mode 100644 chatml.md delete mode 100644 examples/README.md create mode 100644 examples/async_demo.py create mode 100644 examples/azure.py delete mode 100644 examples/azure/embeddings.ipynb delete mode 100644 examples/azure/finetuning.ipynb create mode 100644 examples/azure_ad.py delete mode 100644 examples/codex/backtranslation.py create mode 100644 examples/demo.py delete mode 100644 examples/embeddings/Classification.ipynb delete mode 100644 examples/embeddings/Clustering.ipynb delete mode 100644 examples/embeddings/Code_search.ipynb delete mode 100644 examples/embeddings/Get_embeddings.ipynb delete mode 100644 examples/embeddings/Obtain_dataset.ipynb delete mode 100644 examples/embeddings/Recommendation.ipynb delete mode 100644 examples/embeddings/Regression.ipynb delete mode 100644 examples/embeddings/Semantic_text_search_using_embeddings.ipynb delete mode 100644 examples/embeddings/User_and_product_embeddings.ipynb delete mode 100644 examples/embeddings/Visualize_in_2d.ipynb delete mode 100644 examples/embeddings/Visualize_in_3d.ipynb delete mode 100644 examples/embeddings/Zero-shot_classification.ipynb delete mode 100644 examples/finetuning/answers_with_ft.py delete mode 100644 examples/finetuning/finetuning-classification.ipynb delete mode 100644 examples/finetuning/olympics-1-collect-data.ipynb delete mode 100644 examples/finetuning/olympics-2-create-qa.ipynb delete mode 100644 examples/finetuning/olympics-3-train-qa.ipynb create mode 100644 examples/module_client.py create mode 100755 examples/streaming.py create mode 100644 mypy.ini create mode 100644 noxfile.py delete mode 100644 openai/__init__.py delete mode 100755 openai/_openai_scripts.py delete mode 100644 openai/api_requestor.py delete mode 100644 openai/api_resources/__init__.py delete mode 100644 openai/api_resources/abstract/__init__.py delete mode 100644 openai/api_resources/abstract/api_resource.py delete mode 100644 openai/api_resources/abstract/createable_api_resource.py delete mode 100644 openai/api_resources/abstract/deletable_api_resource.py delete mode 100644 openai/api_resources/abstract/engine_api_resource.py delete mode 100644 openai/api_resources/abstract/listable_api_resource.py delete mode 100644 openai/api_resources/abstract/nested_resource_class_methods.py delete mode 100644 openai/api_resources/abstract/paginatable_api_resource.py delete mode 100644 openai/api_resources/abstract/updateable_api_resource.py delete mode 100644 openai/api_resources/audio.py delete mode 100644 openai/api_resources/chat_completion.py delete mode 100644 openai/api_resources/completion.py delete mode 100644 openai/api_resources/customer.py delete mode 100644 openai/api_resources/deployment.py delete mode 100644 openai/api_resources/edit.py delete mode 100644 openai/api_resources/embedding.py delete mode 100644 openai/api_resources/engine.py delete mode 100644 openai/api_resources/error_object.py delete mode 100644 openai/api_resources/experimental/__init__.py delete mode 100644 openai/api_resources/experimental/completion_config.py delete mode 100644 openai/api_resources/file.py delete mode 100644 openai/api_resources/fine_tune.py delete mode 100644 openai/api_resources/fine_tuning.py delete mode 100644 openai/api_resources/image.py delete mode 100644 openai/api_resources/model.py delete mode 100644 openai/api_resources/moderation.py delete mode 100644 openai/cli.py delete mode 100644 openai/datalib/__init__.py delete mode 100644 openai/datalib/common.py delete mode 100644 openai/datalib/numpy_helper.py delete mode 100644 openai/datalib/pandas_helper.py delete mode 100644 openai/embeddings_utils.py delete mode 100644 openai/error.py delete mode 100644 openai/object_classes.py delete mode 100644 openai/openai_object.py delete mode 100644 openai/openai_response.py delete mode 100644 openai/tests/__init__.py delete mode 100644 openai/tests/asyncio/__init__.py delete mode 100644 openai/tests/asyncio/test_endpoints.py delete mode 100644 openai/tests/test_api_requestor.py delete mode 100644 openai/tests/test_endpoints.py delete mode 100644 openai/tests/test_exceptions.py delete mode 100644 openai/tests/test_file_cli.py delete mode 100644 openai/tests/test_long_examples_validator.py delete mode 100644 openai/tests/test_url_composition.py delete mode 100644 openai/tests/test_util.py delete mode 100644 openai/upload_progress.py delete mode 100644 openai/util.py delete mode 100644 openai/version.py delete mode 100644 openai/wandb_logger.py delete mode 100644 public/Makefile delete mode 100644 public/setup.py delete mode 100644 pytest.ini create mode 100644 requirements-dev.lock create mode 100644 requirements.lock delete mode 100644 setup.cfg delete mode 100644 setup.py create mode 100644 src/openai/__init__.py create mode 100644 src/openai/__main__.py create mode 100644 src/openai/_base_client.py create mode 100644 src/openai/_client.py create mode 100644 src/openai/_compat.py create mode 100644 src/openai/_constants.py create mode 100644 src/openai/_exceptions.py create mode 100644 src/openai/_extras/__init__.py create mode 100644 src/openai/_extras/_common.py create mode 100644 src/openai/_extras/numpy_proxy.py create mode 100644 src/openai/_extras/pandas_proxy.py create mode 100644 src/openai/_files.py create mode 100644 src/openai/_models.py create mode 100644 src/openai/_module_client.py create mode 100644 src/openai/_qs.py create mode 100644 src/openai/_resource.py create mode 100644 src/openai/_response.py create mode 100644 src/openai/_streaming.py create mode 100644 src/openai/_types.py create mode 100644 src/openai/_utils/__init__.py create mode 100644 src/openai/_utils/_logs.py create mode 100644 src/openai/_utils/_proxy.py create mode 100644 src/openai/_utils/_transform.py create mode 100644 src/openai/_utils/_utils.py create mode 100644 src/openai/_version.py create mode 100644 src/openai/cli/__init__.py create mode 100644 src/openai/cli/_api/__init__.py create mode 100644 src/openai/cli/_api/_main.py create mode 100644 src/openai/cli/_api/audio.py create mode 100644 src/openai/cli/_api/chat/__init__.py create mode 100644 src/openai/cli/_api/chat/completions.py create mode 100644 src/openai/cli/_api/completions.py create mode 100644 src/openai/cli/_api/files.py create mode 100644 src/openai/cli/_api/image.py create mode 100644 src/openai/cli/_api/models.py create mode 100644 src/openai/cli/_cli.py create mode 100644 src/openai/cli/_errors.py create mode 100644 src/openai/cli/_models.py create mode 100644 src/openai/cli/_progress.py create mode 100644 src/openai/cli/_tools/__init__.py create mode 100644 src/openai/cli/_tools/_main.py create mode 100644 src/openai/cli/_tools/fine_tunes.py create mode 100644 src/openai/cli/_tools/migrate.py create mode 100644 src/openai/cli/_utils.py rename openai/validators.py => src/openai/lib/_validators.py (80%) create mode 100644 src/openai/lib/azure.py create mode 100644 src/openai/pagination.py rename {openai => src/openai}/py.typed (100%) create mode 100644 src/openai/resources/__init__.py create mode 100644 src/openai/resources/audio/__init__.py create mode 100644 src/openai/resources/audio/audio.py create mode 100644 src/openai/resources/audio/transcriptions.py create mode 100644 src/openai/resources/audio/translations.py create mode 100644 src/openai/resources/chat/__init__.py create mode 100644 src/openai/resources/chat/chat.py create mode 100644 src/openai/resources/chat/completions.py create mode 100644 src/openai/resources/completions.py create mode 100644 src/openai/resources/edits.py create mode 100644 src/openai/resources/embeddings.py create mode 100644 src/openai/resources/files.py create mode 100644 src/openai/resources/fine_tunes.py create mode 100644 src/openai/resources/fine_tuning/__init__.py create mode 100644 src/openai/resources/fine_tuning/fine_tuning.py create mode 100644 src/openai/resources/fine_tuning/jobs.py create mode 100644 src/openai/resources/images.py create mode 100644 src/openai/resources/models.py create mode 100644 src/openai/resources/moderations.py create mode 100644 src/openai/types/__init__.py create mode 100644 src/openai/types/audio/__init__.py create mode 100644 src/openai/types/audio/transcription.py create mode 100644 src/openai/types/audio/transcription_create_params.py create mode 100644 src/openai/types/audio/translation.py create mode 100644 src/openai/types/audio/translation_create_params.py create mode 100644 src/openai/types/chat/__init__.py create mode 100644 src/openai/types/chat/chat_completion.py create mode 100644 src/openai/types/chat/chat_completion_chunk.py create mode 100644 src/openai/types/chat/chat_completion_message.py create mode 100644 src/openai/types/chat/chat_completion_message_param.py create mode 100644 src/openai/types/chat/chat_completion_role.py create mode 100644 src/openai/types/chat/completion_create_params.py create mode 100644 src/openai/types/completion.py create mode 100644 src/openai/types/completion_choice.py create mode 100644 src/openai/types/completion_create_params.py create mode 100644 src/openai/types/completion_usage.py create mode 100644 src/openai/types/create_embedding_response.py create mode 100644 src/openai/types/edit.py create mode 100644 src/openai/types/edit_create_params.py create mode 100644 src/openai/types/embedding.py create mode 100644 src/openai/types/embedding_create_params.py create mode 100644 src/openai/types/file_content.py create mode 100644 src/openai/types/file_create_params.py create mode 100644 src/openai/types/file_deleted.py create mode 100644 src/openai/types/file_object.py create mode 100644 src/openai/types/fine_tune.py create mode 100644 src/openai/types/fine_tune_create_params.py create mode 100644 src/openai/types/fine_tune_event.py create mode 100644 src/openai/types/fine_tune_events_list_response.py create mode 100644 src/openai/types/fine_tune_list_events_params.py create mode 100644 src/openai/types/fine_tuning/__init__.py create mode 100644 src/openai/types/fine_tuning/fine_tuning_job.py create mode 100644 src/openai/types/fine_tuning/fine_tuning_job_event.py create mode 100644 src/openai/types/fine_tuning/job_create_params.py create mode 100644 src/openai/types/fine_tuning/job_list_events_params.py create mode 100644 src/openai/types/fine_tuning/job_list_params.py create mode 100644 src/openai/types/image.py create mode 100644 src/openai/types/image_create_variation_params.py create mode 100644 src/openai/types/image_edit_params.py create mode 100644 src/openai/types/image_generate_params.py create mode 100644 src/openai/types/images_response.py create mode 100644 src/openai/types/model.py create mode 100644 src/openai/types/model_deleted.py create mode 100644 src/openai/types/moderation.py create mode 100644 src/openai/types/moderation_create_params.py create mode 100644 src/openai/types/moderation_create_response.py create mode 100644 src/openai/version.py create mode 100644 tests/__init__.py create mode 100644 tests/api_resources/__init__.py create mode 100644 tests/api_resources/audio/__init__.py create mode 100644 tests/api_resources/audio/test_transcriptions.py create mode 100644 tests/api_resources/audio/test_translations.py create mode 100644 tests/api_resources/chat/__init__.py create mode 100644 tests/api_resources/chat/test_completions.py create mode 100644 tests/api_resources/fine_tuning/__init__.py create mode 100644 tests/api_resources/fine_tuning/test_jobs.py create mode 100644 tests/api_resources/test_completions.py create mode 100644 tests/api_resources/test_edits.py create mode 100644 tests/api_resources/test_embeddings.py create mode 100644 tests/api_resources/test_files.py create mode 100644 tests/api_resources/test_fine_tunes.py create mode 100644 tests/api_resources/test_images.py create mode 100644 tests/api_resources/test_models.py create mode 100644 tests/api_resources/test_moderations.py create mode 100644 tests/conftest.py create mode 100644 tests/lib/test_azure.py create mode 100644 tests/test_client.py create mode 100644 tests/test_deepcopy.py create mode 100644 tests/test_extract_files.py create mode 100644 tests/test_files.py create mode 100644 tests/test_models.py create mode 100644 tests/test_module_client.py create mode 100644 tests/test_qs.py create mode 100644 tests/test_required_args.py create mode 100644 tests/test_streaming.py create mode 100644 tests/test_transform.py create mode 100644 tests/utils.py diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile new file mode 100644 index 0000000000..73f1b9f237 --- /dev/null +++ b/.devcontainer/Dockerfile @@ -0,0 +1,27 @@ +# syntax=docker/dockerfile:1 +FROM debian:bookworm-slim + +RUN apt-get update && apt-get install -y \ + libxkbcommon0 \ + ca-certificates \ + make \ + curl \ + git \ + unzip \ + libc++1 \ + vim \ + termcap \ + && apt-get clean autoclean + +RUN curl -sSf https://rye-up.com/get | RYE_VERSION="0.15.2" RYE_INSTALL_OPTION="--yes" bash +ENV PATH=/root/.rye/shims:$PATH + +WORKDIR /workspace + +COPY README.md .python-version pyproject.toml requirements.lock requirements-dev.lock /workspace/ + +RUN rye sync --all-features + +COPY . /workspace + +CMD ["rye", "shell"] diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..d55fc4d671 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,20 @@ +// For format details, see https://aka.ms/devcontainer.json. For config options, see the +// README at: https://github.com/devcontainers/templates/tree/main/src/debian +{ + "name": "Debian", + "build": { + "dockerfile": "Dockerfile" + } + + // Features to add to the dev container. More info: https://containers.dev/features. + // "features": {}, + + // Use 'forwardPorts' to make a list of ports inside the container available locally. + // "forwardPorts": [], + + // Configure tool-specific properties. + // "customizations": {}, + + // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. + // "remoteUser": "root" +} diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml deleted file mode 100644 index 300ad9f0ae..0000000000 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ /dev/null @@ -1,56 +0,0 @@ -name: Bug report -description: Create a report to help us improve -labels: ["bug"] -body: - - type: markdown - attributes: - value: | - Thanks for taking the time to fill out this bug report! If you have questions about using the OpenAI Python library, please post on our [Community forum](https://community.openai.com). - - type: textarea - id: what-happened - attributes: - label: Describe the bug - description: A clear and concise description of what the bug is, and any additional context. - placeholder: Tell us what you see! - validations: - required: true - - type: textarea - id: repro-steps - attributes: - label: To Reproduce - description: Steps to reproduce the behavior. - placeholder: | - 1. Fetch a '...' - 2. Update the '....' - 3. See error - validations: - required: true - - type: textarea - id: code-snippets - attributes: - label: Code snippets - description: If applicable, add code snippets to help explain your problem. - render: Python - validations: - required: false - - type: input - id: os - attributes: - label: OS - placeholder: macOS - validations: - required: true - - type: input - id: language-version - attributes: - label: Python version - placeholder: Python v3.7.1 - validations: - required: true - - type: input - id: lib-version - attributes: - label: Library version - placeholder: openai-python v0.26.4 - validations: - required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml deleted file mode 100644 index 5bedf975eb..0000000000 --- a/.github/ISSUE_TEMPLATE/config.yml +++ /dev/null @@ -1,7 +0,0 @@ -blank_issues_enabled: false -contact_links: - - name: OpenAI support - url: https://help.openai.com/ - about: | - Please only file issues here that you believe represent actual bugs or feature requests for the OpenAI Python library. - If you're having general trouble with the OpenAI API, ChatGPT, etc, please visit our help center to get support. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml deleted file mode 100644 index 2bd1c635ba..0000000000 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ /dev/null @@ -1,20 +0,0 @@ -name: Feature request -description: Suggest an idea for this library -labels: ["feature-request"] -body: - - type: markdown - attributes: - value: | - Thanks for taking the time to fill out this feature request! Please note, we are not able to accommodate all feature requests given limited bandwidth but we appreciate you taking the time to share with us how to improve the OpenAI Python library. - - type: textarea - id: feature - attributes: - label: Describe the feature or improvement you're requesting - description: A clear and concise description of what you want to happen. - validations: - required: true - - type: textarea - id: context - attributes: - label: Additional context - description: Add any other context about the feature request here. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000000..c031d9a1d1 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,41 @@ +name: CI +on: + push: + branches: + - main + pull_request: + branches: + - main + +jobs: + lint: + name: lint + runs-on: ubuntu-latest + if: github.repository == 'openai/openai-python' + + steps: + - uses: actions/checkout@v3 + + - name: Install Rye + run: | + curl -sSf https://rye-up.com/get | bash + echo "$HOME/.rye/shims" >> $GITHUB_PATH + env: + RYE_VERSION: 0.15.2 + RYE_INSTALL_OPTION: "--yes" + + - name: Install dependencies + run: | + rye sync --all-features + + - name: Run ruff + run: | + rye run check:ruff + + - name: Run type checking + run: | + rye run typecheck + + - name: Ensure importable + run: | + rye run python -c 'import openai' diff --git a/.gitignore b/.gitignore index 7ad641a0c8..a4b2f8c0bd 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +1,14 @@ -*.egg-info -.idea -.python-version -/public/dist +.vscode +_dev + __pycache__ -build -*.egg -.vscode/settings.json -.ipynb_checkpoints -.vscode/launch.json -examples/azure/training.jsonl -examples/azure/validation.jsonl +.mypy_cache + +dist + +.venv +.idea + +.env +.envrc +codegen.log diff --git a/.python-version b/.python-version new file mode 100644 index 0000000000..43077b2460 --- /dev/null +++ b/.python-version @@ -0,0 +1 @@ +3.9.18 diff --git a/.stats.yml b/.stats.yml new file mode 100644 index 0000000000..f21eb8fef0 --- /dev/null +++ b/.stats.yml @@ -0,0 +1 @@ +configured_endpoints: 28 diff --git a/LICENSE b/LICENSE index 4f14854c32..7b1b36a644 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,201 @@ -The MIT License - -Copyright (c) OpenAI (https://openai.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2023 OpenAI + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Makefile b/Makefile deleted file mode 100644 index b3ef11eea1..0000000000 --- a/Makefile +++ /dev/null @@ -1,11 +0,0 @@ -.PHONY: build upload - -build: - rm -rf dist/ build/ - python -m pip install build - python -m build . - -upload: - python -m pip install twine - python -m twine upload dist/openai-* - rm -rf dist diff --git a/README.md b/README.md index 615160b3a4..a27375d598 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,16 @@ -# OpenAI Python Library +# OpenAI Python API library -The OpenAI Python library provides convenient access to the OpenAI API -from applications written in the Python language. It includes a -pre-defined set of classes for API resources that initialize -themselves dynamically from API responses which makes it compatible -with a wide range of versions of the OpenAI API. +[![PyPI version](https://img.shields.io/pypi/v/openai.svg)](https://pypi.org/project/openai/) -You can find usage examples for the OpenAI Python library in our [API reference](https://platform.openai.com/docs/api-reference?lang=python) and the [OpenAI Cookbook](https://github.com/openai/openai-cookbook/). +The OpenAI Python library provides convenient access to the OpenAI REST API from any Python 3.7+ +application. The library includes type definitions for all request params and response fields, +and offers both synchronous and asynchronous clients powered by [httpx](https://github.com/encode/httpx). + +It is generated from our [OpenAPI specification](https://github.com/openai/openai-openapi) with [Stainless](https://stainlessapi.com/). + +## Documentation + +The API documentation can be found [here](https://platform.openai.com/docs). ## Beta Release @@ -23,255 +27,483 @@ And follow along with the [beta release notes](https://github.com/openai/openai- ## Installation -To start, ensure you have Python 3.7.1 or newer. If you just -want to use the package, run: - ```sh -pip install --upgrade openai +pip install --pre openai ``` -After you have installed the package, import it at the top of a file: +## Usage + +The full API of this library can be found in [api.md](https://www.github.com/openai/openai-python/blob/main/api.md). ```python -import openai +from openai import OpenAI + +client = OpenAI( + # defaults to os.environ.get("OPENAI_API_KEY") + api_key="My API Key", +) + +chat_completion = client.chat.completions.create( + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-3.5-turbo", +) ``` -To install this package from source to make modifications to it, run the following command from the root of the repository: +While you can provide an `api_key` keyword argument, +we recommend using [python-dotenv](https://pypi.org/project/python-dotenv/) +to add `OPENAI_API_KEY="My API Key"` to your `.env` file +so that your API Key is not stored in source control. -```sh -python setup.py install -``` +## Async usage -### Optional dependencies +Simply import `AsyncOpenAI` instead of `OpenAI` and use `await` with each API call: -Install dependencies for [`openai.embeddings_utils`](openai/embeddings_utils.py): +```python +import asyncio +from openai import AsyncOpenAI -```sh -pip install openai[embeddings] -``` +client = AsyncOpenAI( + # defaults to os.environ.get("OPENAI_API_KEY") + api_key="My API Key", +) -Install support for [Weights & Biases](https://wandb.me/openai-docs) which can be used for fine-tuning: -```sh -pip install openai[wandb] -``` +async def main() -> None: + chat_completion = await client.chat.completions.create( + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-3.5-turbo", + ) -Data libraries like `numpy` and `pandas` are not installed by default due to their size. They’re needed for some functionality of this library, but generally not for talking to the API. If you encounter a `MissingDependencyError`, install them with: -```sh -pip install openai[datalib] +asyncio.run(main()) ``` -## Usage +Functionality between the synchronous and asynchronous clients is otherwise identical. + +## Streaming Responses + +We provide support for streaming responses using Server Side Events (SSE). -The library needs to be configured with your OpenAI account's private API key which is available on our [developer platform](https://platform.openai.com/account/api-keys). Either set it as the `OPENAI_API_KEY` environment variable before using the library: +```python +from openai import OpenAI + +client = OpenAI() -```bash -export OPENAI_API_KEY='sk-...' +stream = client.chat.completions.create( + model="gpt-4", + messages=[{"role": "user", "content": "Say this is a test"}], + stream=True, +) +for part in stream: + print(part.choices[0].delta.content or "") ``` -Or set `openai.api_key` to its value: +The async client uses the exact same interface. ```python -openai.api_key = "sk-..." +from openai import AsyncOpenAI + +client = AsyncOpenAI() + +stream = await client.chat.completions.create( + prompt="Say this is a test", + messages=[{"role": "user", "content": "Say this is a test"}], + stream=True, +) +async for part in stream: + print(part.choices[0].delta.content or "") ``` -Examples of how to use this library to accomplish various tasks can be found in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook/). It contains code examples for: classification using fine-tuning, clustering, code search, customizing embeddings, question answering from a corpus of documents. recommendations, visualization of embeddings, and more. +## Module-level client -Most endpoints support a `request_timeout` param. This param takes a `Union[float, Tuple[float, float]]` and will raise an `openai.error.Timeout` error if the request exceeds that time in seconds (See: https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts). +> [!IMPORTANT] +> We highly recommend instantiating client instances instead of relying on the global client. -### Chat completions +We also expose a global client instance that is accessible in a similar fashion to versions prior to v1. -Chat models such as `gpt-3.5-turbo` and `gpt-4` can be called using the [chat completions endpoint](https://platform.openai.com/docs/api-reference/chat/create). +```py +import openai -```python -completion = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello world"}]) +# optional; defaults to `os.environ['OPENAI_API_KEY']` +openai.api_key = '...' + +# all client options can be configured just like the `OpenAI` instantiation counterpart +openai.base_url = "https://.../" +openai.default_headers = {"x-foo": "true"} + +completion = openai.chat.completions.create( + model="gpt-4", + messages=[ + { + "role": "user", + "content": "How do I output all files in a directory using Python?", + }, + ], +) print(completion.choices[0].message.content) ``` -You can learn more in our [chat completions guide](https://platform.openai.com/docs/guides/gpt/chat-completions-api). +The API is the exact same as the standard client instance based API. -### Completions +This is intended to be used within REPLs or notebooks for faster iteration, **not** in application code. -Text models such as `babbage-002` or `davinci-002` (and our [legacy completions models](https://platform.openai.com/docs/deprecations/deprecation-history)) can be called using the completions endpoint. +We recommend that you always instantiate a client (e.g., with `client = OpenAI()`) in application code because: -```python -completion = openai.Completion.create(model="davinci-002", prompt="Hello world") -print(completion.choices[0].text) -``` +- It can be difficult to reason about where client options are configured +- It's not possible to change certain client options without potentially causing race conditions +- It's harder to mock for testing purposes +- It's not possible to control cleanup of network connections + +## Using types + +Nested request parameters are [TypedDicts](https://docs.python.org/3/library/typing.html#typing.TypedDict). Responses are [Pydantic models](https://docs.pydantic.dev), which provide helper methods for things like serializing back into JSON ([v1](https://docs.pydantic.dev/1.10/usage/models/), [v2](https://docs.pydantic.dev/latest/usage/serialization/)). To get a dictionary, call `model.model_dump()`. -You can learn more in our [completions guide](https://platform.openai.com/docs/guides/gpt/completions-api). +Typed requests and responses provide autocomplete and documentation within your editor. If you would like to see type errors in VS Code to help catch bugs earlier, set `python.analysis.typeCheckingMode` to `basic`. -### Embeddings +## Pagination -Embeddings are designed to measure the similarity or relevance between text strings. To get an embedding for a text string, you can use following: +List methods in the OpenAI API are paginated. + +This library provides auto-paginating iterators with each list response, so you do not have to request successive pages manually: ```python -text_string = "sample text" +import openai -model_id = "text-embedding-ada-002" +client = OpenAI() -embedding = openai.Embedding.create(input=text_string, model=model_id)['data'][0]['embedding'] +all_jobs = [] +# Automatically fetches more pages as needed. +for job in client.fine_tuning.jobs.list( + limit=20, +): + # Do something with job here + all_jobs.append(job) +print(all_jobs) ``` -You can learn more in our [embeddings guide](https://platform.openai.com/docs/guides/embeddings/embeddings). +Or, asynchronously: -### Fine-tuning +```python +import asyncio +import openai -Fine-tuning a model on training data can both improve the results (by giving the model more examples to learn from) and lower the cost/latency of API calls by reducing the need to include training examples in prompts. +client = AsyncOpenAI() -```python -# Create a fine-tuning job with an already uploaded file -openai.FineTuningJob.create(training_file="file-abc123", model="gpt-3.5-turbo") -# List 10 fine-tuning jobs -openai.FineTuningJob.list(limit=10) +async def main() -> None: + all_jobs = [] + # Iterate through items across all pages, issuing requests as needed. + async for job in client.fine_tuning.jobs.list( + limit=20, + ): + all_jobs.append(job) + print(all_jobs) -# Retrieve the state of a fine-tune -openai.FineTuningJob.retrieve("ft-abc123") -# Cancel a job -openai.FineTuningJob.cancel("ft-abc123") +asyncio.run(main()) +``` -# List up to 10 events from a fine-tuning job -openai.FineTuningJob.list_events(id="ft-abc123", limit=10) +Alternatively, you can use the `.has_next_page()`, `.next_page_info()`, or `.get_next_page()` methods for more granular control working with pages: -# Delete a fine-tuned model (must be an owner of the org the model was created in) -openai.Model.delete("ft:gpt-3.5-turbo:acemeco:suffix:abc123") +```python +first_page = await client.fine_tuning.jobs.list( + limit=20, +) +if first_page.has_next_page(): + print(f"will fetch next page using these details: {first_page.next_page_info()}") + next_page = await first_page.get_next_page() + print(f"number of items we just fetched: {len(next_page.data)}") + +# Remove `await` for non-async usage. ``` -You can learn more in our [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning). +Or just work directly with the returned data: -To log the training results from fine-tuning to Weights & Biases use: +```python +first_page = await client.fine_tuning.jobs.list( + limit=20, +) -``` -openai wandb sync -``` +print(f"next page cursor: {first_page.after}") # => "next page cursor: ..." +for job in first_page.data: + print(job.id) -For more information, read the [wandb documentation](https://docs.wandb.ai/guides/integrations/openai) on Weights & Biases. +# Remove `await` for non-async usage. +``` -### Moderation +## Nested params -OpenAI provides a free Moderation endpoint that can be used to check whether content complies with the OpenAI [content policy](https://platform.openai.com/docs/usage-policies). +Nested parameters are dictionaries, typed using `TypedDict`, for example: ```python -moderation_resp = openai.Moderation.create(input="Here is some perfectly innocuous text that follows all OpenAI content policies.") -``` +from openai import OpenAI -You can learn more in our [moderation guide](https://platform.openai.com/docs/guides/moderation). +client = OpenAI() + +page = client.files.list() +``` -### Image generation (DALL·E) +## File Uploads -DALL·E is a generative image model that can create new images based on a prompt. +Request parameters that correspond to file uploads can be passed as `bytes`, a [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike) instance or a tuple of `(filename, contents, media type)`. ```python -image_resp = openai.Image.create(prompt="two dogs playing chess, oil painting", n=4, size="512x512") +from pathlib import Path +from openai import OpenAI + +client = OpenAI() + +client.files.create( + file=Path("input.jsonl"), + purpose="fine-tune", +) ``` -You can learn more in our [image generation guide](https://platform.openai.com/docs/guides/images). +The async client uses the exact same interface. If you pass a [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike) instance, the file contents will be read asynchronously automatically. -### Audio (Whisper) +## Handling errors -The speech to text API provides two endpoints, transcriptions and translations, based on our state-of-the-art [open source large-v2 Whisper model](https://github.com/openai/whisper). +When the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of `openai.APIConnectionError` is raised. -```python -f = open("path/to/file.mp3", "rb") -transcript = openai.Audio.transcribe("whisper-1", f) +When the API returns a non-success status code (that is, 4xx or 5xx +response), a subclass of `openai.APIStatusError` is raised, containing `status_code` and `response` properties. -transcript = openai.Audio.translate("whisper-1", f) +All errors inherit from `openai.APIError`. + +```python +import openai +from openai import OpenAI + +client = OpenAI() + +try: + client.fine_tunes.create( + training_file="file-XGinujblHPwGLSztz8cPS8XY", + ) +except openai.APIConnectionError as e: + print("The server could not be reached") + print(e.__cause__) # an underlying Exception, likely raised within httpx. +except openai.RateLimitError as e: + print("A 429 status code was received; we should back off a bit.") +except openai.APIStatusError as e: + print("Another non-200-range status code was received") + print(e.status_code) + print(e.response) ``` -You can learn more in our [speech to text guide](https://platform.openai.com/docs/guides/speech-to-text). +Error codes are as followed: + +| Status Code | Error Type | +| ----------- | -------------------------- | +| 400 | `BadRequestError` | +| 401 | `AuthenticationError` | +| 403 | `PermissionDeniedError` | +| 404 | `NotFoundError` | +| 422 | `UnprocessableEntityError` | +| 429 | `RateLimitError` | +| >=500 | `InternalServerError` | +| N/A | `APIConnectionError` | + +### Retries -### Async API +Certain errors are automatically retried 2 times by default, with a short exponential backoff. +Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, +429 Rate Limit, and >=500 Internal errors are all retried by default. -Async support is available in the API by prepending `a` to a network-bound method: +You can use the `max_retries` option to configure or disable retry settings: ```python -async def create_chat_completion(): - chat_completion_resp = await openai.ChatCompletion.acreate(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello world"}]) +from openai import OpenAI + +# Configure the default for all requests: +client = OpenAI( + # default is 2 + max_retries=0, +) + +# Or, configure per-request: +client.with_options(max_retries=5).chat.completions.create( + messages=[ + { + "role": "user", + "content": "How can I get the name of the current day in Node.js?", + } + ], + model="gpt-3.5-turbo", +) ``` -To make async requests more efficient, you can pass in your own -`aiohttp.ClientSession`, but you must manually close the client session at the end -of your program/event loop: +### Timeouts -```python -from aiohttp import ClientSession -openai.aiosession.set(ClientSession()) +By default requests time out after 10 minutes. You can configure this with a `timeout` option, +which accepts a float or an [`httpx.Timeout`](https://www.python-httpx.org/advanced/#fine-tuning-the-configuration) object: -# At the end of your program, close the http session -await openai.aiosession.get().close() +```python +from openai import OpenAI + +# Configure the default for all requests: +client = OpenAI( + # default is 60s + timeout=20.0, +) + +# More granular control: +client = OpenAI( + timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0), +) + +# Override per-request: +client.with_options(timeout=5 * 1000).chat.completions.create( + messages=[ + { + "role": "user", + "content": "How can I list all files in a directory using Python?", + } + ], + model="gpt-3.5-turbo", +) ``` -### Command-line interface +On timeout, an `APITimeoutError` is thrown. -This library additionally provides an `openai` command-line utility -which makes it easy to interact with the API from your terminal. Run -`openai api -h` for usage. +Note that requests that time out are [retried twice by default](#retries). -```sh -# list models -openai api models.list +## Advanced -# create a chat completion (gpt-3.5-turbo, gpt-4, etc.) -openai api chat_completions.create -m gpt-3.5-turbo -g user "Hello world" +### Logging -# create a completion (text-davinci-003, text-davinci-002, ada, babbage, curie, davinci, etc.) -openai api completions.create -m ada -p "Hello world" +We use the standard library [`logging`](https://docs.python.org/3/library/logging.html) module. -# generate images via DALL·E API -openai api image.create -p "two dogs playing chess, cartoon" -n 1 +You can enable logging by setting the environment variable `OPENAI_LOG` to `debug`. -# using openai through a proxy -openai --proxy=http://proxy.com api models.list +```shell +$ export OPENAI_LOG=debug ``` -### Microsoft Azure Endpoints +### How to tell whether `None` means `null` or missing -In order to use the library with Microsoft Azure endpoints, you need to set the `api_type`, `api_base` and `api_version` in addition to the `api_key`. The `api_type` must be set to 'azure' and the others correspond to the properties of your endpoint. -In addition, the deployment name must be passed as the `deployment_id` parameter. +In an API response, a field may be explicitly `null`, or missing entirely; in either case, its value is `None` in this library. You can differentiate the two cases with `.model_fields_set`: -```python -import openai -openai.api_type = "azure" -openai.api_key = "..." -openai.api_base = "https://example-endpoint.openai.azure.com/" -openai.api_version = "2023-05-15" +```py +if response.my_field is None: + if 'my_field' not in response.model_fields_set: + print('Got json like {}, without a "my_field" key present at all.') + else: + print('Got json like {"my_field": null}.') +``` -# create a chat completion -chat_completion = openai.ChatCompletion.create(deployment_id="deployment-name", model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello world"}]) +### Accessing raw response data (e.g. headers) -# print the completion -print(chat_completion.choices[0].message.content) +The "raw" Response object can be accessed by prefixing `.with_raw_response.` to any HTTP method call. + +```py +from openai import OpenAI + +client = OpenAI() +response = client.chat.completions.with_raw_response.create( + messages=[{ + "role": "user", + "content": "Say this is a test", + }], + model="gpt-3.5-turbo", +) +print(response.headers.get('X-My-Header')) + +completion = response.parse() # get the object that `chat.completions.create()` would have returned +print(completion) ``` -Please note that for the moment, the Microsoft Azure endpoints can only be used for completion, embedding, and fine-tuning operations. -For a detailed example of how to use fine-tuning and other operations using Azure endpoints, please check out the following Jupyter notebooks: +These methods return an [`APIResponse`](https://github.com/openai/openai-python/tree/v1/src/openai/_response.py) object. -- [Using Azure completions](https://github.com/openai/openai-cookbook/tree/main/examples/azure/completions.ipynb) -- [Using Azure chat](https://github.com/openai/openai-cookbook/tree/main/examples/azure/chat.ipynb) -- [Using Azure embeddings](https://github.com/openai/openai-cookbook/blob/main/examples/azure/embeddings.ipynb) +### Configuring the HTTP client -### Microsoft Azure Active Directory Authentication +You can directly override the [httpx client](https://www.python-httpx.org/api/#client) to customize it for your use case, including: -In order to use Microsoft Active Directory to authenticate to your Azure endpoint, you need to set the `api_type` to "azure_ad" and pass the acquired credential token to `api_key`. The rest of the parameters need to be set as specified in the previous section. +- Support for proxies +- Custom transports +- Additional [advanced](https://www.python-httpx.org/advanced/#client-instances) functionality ```python -from azure.identity import DefaultAzureCredential -import openai +import httpx +from openai import OpenAI + +client = OpenAI( + base_url="http://my.test.server.example.com:8083/", + http_client=httpx.Client( + proxies="http://my.test.proxy.example.com/", + transport=httpx.HTTPTransport(local_address="0.0.0.0"), + ), +) +``` + +### Managing HTTP resources + +By default the library closes underlying HTTP connections whenever the client is [garbage collected](https://docs.python.org/3/reference/datamodel.html#object.__del__). You can manually close the client using the `.close()` method if desired, or with a context manager that closes when exiting. + +## Microsoft Azure OpenAI + +To use this library with [Azure OpenAI](https://learn.microsoft.com/en-us/azure/ai-services/openai/overview), use the `AzureOpenAI` +class instead of the `OpenAI` class. + +> [!IMPORTANT] +> The Azure API shape differs from the core API shape which means that the static types for responses / params +> won't always be correct. -# Request credential -default_credential = DefaultAzureCredential() -token = default_credential.get_token("https://cognitiveservices.azure.com/.default") +```py +from openai import AzureOpenAI -# Setup parameters -openai.api_type = "azure_ad" -openai.api_key = token.token -openai.api_base = "https://example-endpoint.openai.azure.com/" -openai.api_version = "2023-05-15" +# gets the API Key from environment variable AZURE_OPENAI_API_KEY +client = AzureOpenAI( + # https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#rest-api-versioning + api_version="2023-07-01-preview" + # https://learn.microsoft.com/en-us/azure/cognitive-services/openai/how-to/create-resource?pivots=web-portal#create-a-resource + azure_endpoint="https://example-endpoint.openai.azure.com/", +) + +completion = client.chat.completions.create( + model="deployment-name", # e.g. gpt-35-instant + messages=[ + { + "role": "user", + "content": "How do I output all files in a directory using Python?", + }, + ], +) +print(completion.model_dump_json(indent=2)) ``` -## Credit +In addition to the options provided in the base `OpenAI` client, the following options are provided: + +- `azure_endpoint` +- `azure_deployment` +- `api_version` +- `azure_ad_token` +- `azure_ad_token_provider` + +An example of using the client with Azure Active Directory can be found [here](https://github.com/openai/openai-python/blob/v1/examples/azure_ad.py). + +## Versioning + +This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions: + +1. Changes that only affect static types, without breaking runtime behavior. +2. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals)_. +3. Changes that we do not expect to impact the vast majority of users in practice. + +We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience. + +We are keen for your feedback; please open an [issue](https://www.github.com/openai/openai-python/issues) with questions, bugs, or suggestions. + +## Requirements -This library is forked from the [Stripe Python Library](https://github.com/stripe/stripe-python). +Python 3.7 or higher. diff --git a/api.md b/api.md new file mode 100644 index 0000000000..915a05479a --- /dev/null +++ b/api.md @@ -0,0 +1,172 @@ +# Completions + +Types: + +```python +from openai.types import Completion, CompletionChoice, CompletionUsage +``` + +Methods: + +- client.completions.create(\*\*params) -> Completion + +# Chat + +## Completions + +Types: + +```python +from openai.types.chat import ( + ChatCompletion, + ChatCompletionChunk, + ChatCompletionMessage, + ChatCompletionMessageParam, + ChatCompletionRole, +) +``` + +Methods: + +- client.chat.completions.create(\*\*params) -> ChatCompletion + +# Edits + +Types: + +```python +from openai.types import Edit +``` + +Methods: + +- client.edits.create(\*\*params) -> Edit + +# Embeddings + +Types: + +```python +from openai.types import CreateEmbeddingResponse, Embedding +``` + +Methods: + +- client.embeddings.create(\*\*params) -> CreateEmbeddingResponse + +# Files + +Types: + +```python +from openai.types import FileContent, FileDeleted, FileObject +``` + +Methods: + +- client.files.create(\*\*params) -> FileObject +- client.files.retrieve(file_id) -> FileObject +- client.files.list() -> SyncPage[FileObject] +- client.files.delete(file_id) -> FileDeleted +- client.files.retrieve_content(file_id) -> str +- client.files.wait_for_processing(\*args) -> FileObject + +# Images + +Types: + +```python +from openai.types import Image, ImagesResponse +``` + +Methods: + +- client.images.create_variation(\*\*params) -> ImagesResponse +- client.images.edit(\*\*params) -> ImagesResponse +- client.images.generate(\*\*params) -> ImagesResponse + +# Audio + +## Transcriptions + +Types: + +```python +from openai.types.audio import Transcription +``` + +Methods: + +- client.audio.transcriptions.create(\*\*params) -> Transcription + +## Translations + +Types: + +```python +from openai.types.audio import Translation +``` + +Methods: + +- client.audio.translations.create(\*\*params) -> Translation + +# Moderations + +Types: + +```python +from openai.types import Moderation, ModerationCreateResponse +``` + +Methods: + +- client.moderations.create(\*\*params) -> ModerationCreateResponse + +# Models + +Types: + +```python +from openai.types import Model, ModelDeleted +``` + +Methods: + +- client.models.retrieve(model) -> Model +- client.models.list() -> SyncPage[Model] +- client.models.delete(model) -> ModelDeleted + +# FineTuning + +## Jobs + +Types: + +```python +from openai.types.fine_tuning import FineTuningJob, FineTuningJobEvent +``` + +Methods: + +- client.fine_tuning.jobs.create(\*\*params) -> FineTuningJob +- client.fine_tuning.jobs.retrieve(fine_tuning_job_id) -> FineTuningJob +- client.fine_tuning.jobs.list(\*\*params) -> SyncCursorPage[FineTuningJob] +- client.fine_tuning.jobs.cancel(fine_tuning_job_id) -> FineTuningJob +- client.fine_tuning.jobs.list_events(fine_tuning_job_id, \*\*params) -> SyncCursorPage[FineTuningJobEvent] + +# FineTunes + +Types: + +```python +from openai.types import FineTune, FineTuneEvent, FineTuneEventsListResponse +``` + +Methods: + +- client.fine_tunes.create(\*\*params) -> FineTune +- client.fine_tunes.retrieve(fine_tune_id) -> FineTune +- client.fine_tunes.list() -> SyncPage[FineTune] +- client.fine_tunes.cancel(fine_tune_id) -> FineTune +- client.fine_tunes.list_events(fine_tune_id, \*\*params) -> FineTuneEventsListResponse diff --git a/bin/blacken-docs.py b/bin/blacken-docs.py new file mode 100644 index 0000000000..45d0ad1225 --- /dev/null +++ b/bin/blacken-docs.py @@ -0,0 +1,251 @@ +# fork of https://github.com/asottile/blacken-docs implementing https://github.com/asottile/blacken-docs/issues/170 +from __future__ import annotations + +import re +import argparse +import textwrap +import contextlib +from typing import Match, Optional, Sequence, Generator, NamedTuple, cast + +import black +from black.mode import TargetVersion +from black.const import DEFAULT_LINE_LENGTH + +MD_RE = re.compile( + r"(?P^(?P *)```\s*python\n)" r"(?P.*?)" r"(?P^(?P=indent)```\s*$)", + re.DOTALL | re.MULTILINE, +) +MD_PYCON_RE = re.compile( + r"(?P^(?P *)```\s*pycon\n)" r"(?P.*?)" r"(?P^(?P=indent)```.*$)", + re.DOTALL | re.MULTILINE, +) +RST_PY_LANGS = frozenset(("python", "py", "sage", "python3", "py3", "numpy")) +BLOCK_TYPES = "(code|code-block|sourcecode|ipython)" +DOCTEST_TYPES = "(testsetup|testcleanup|testcode)" +RST_RE = re.compile( + rf"(?P" + rf"^(?P *)\.\. (" + rf"jupyter-execute::|" + rf"{BLOCK_TYPES}:: (?P\w+)|" + rf"{DOCTEST_TYPES}::.*" + rf")\n" + rf"((?P=indent) +:.*\n)*" + rf"\n*" + rf")" + rf"(?P(^((?P=indent) +.*)?\n)+)", + re.MULTILINE, +) +RST_PYCON_RE = re.compile( + r"(?P" + r"(?P *)\.\. ((code|code-block):: pycon|doctest::.*)\n" + r"((?P=indent) +:.*\n)*" + r"\n*" + r")" + r"(?P(^((?P=indent) +.*)?(\n|$))+)", + re.MULTILINE, +) +PYCON_PREFIX = ">>> " +PYCON_CONTINUATION_PREFIX = "..." +PYCON_CONTINUATION_RE = re.compile( + rf"^{re.escape(PYCON_CONTINUATION_PREFIX)}( |$)", +) +LATEX_RE = re.compile( + r"(?P^(?P *)\\begin{minted}{python}\n)" + r"(?P.*?)" + r"(?P^(?P=indent)\\end{minted}\s*$)", + re.DOTALL | re.MULTILINE, +) +LATEX_PYCON_RE = re.compile( + r"(?P^(?P *)\\begin{minted}{pycon}\n)" r"(?P.*?)" r"(?P^(?P=indent)\\end{minted}\s*$)", + re.DOTALL | re.MULTILINE, +) +PYTHONTEX_LANG = r"(?Ppyblock|pycode|pyconsole|pyverbatim)" +PYTHONTEX_RE = re.compile( + rf"(?P^(?P *)\\begin{{{PYTHONTEX_LANG}}}\n)" + rf"(?P.*?)" + rf"(?P^(?P=indent)\\end{{(?P=lang)}}\s*$)", + re.DOTALL | re.MULTILINE, +) +INDENT_RE = re.compile("^ +(?=[^ ])", re.MULTILINE) +TRAILING_NL_RE = re.compile(r"\n+\Z", re.MULTILINE) + + +class CodeBlockError(NamedTuple): + offset: int + exc: Exception + + +def format_str( + src: str, + black_mode: black.FileMode, +) -> tuple[str, Sequence[CodeBlockError]]: + errors: list[CodeBlockError] = [] + + @contextlib.contextmanager + def _collect_error(match: Match[str]) -> Generator[None, None, None]: + try: + yield + except Exception as e: + errors.append(CodeBlockError(match.start(), e)) + + def _md_match(match: Match[str]) -> str: + code = textwrap.dedent(match["code"]) + with _collect_error(match): + code = black.format_str(code, mode=black_mode) + code = textwrap.indent(code, match["indent"]) + return f'{match["before"]}{code}{match["after"]}' + + def _rst_match(match: Match[str]) -> str: + lang = match["lang"] + if lang is not None and lang not in RST_PY_LANGS: + return match[0] + min_indent = min(INDENT_RE.findall(match["code"])) + trailing_ws_match = TRAILING_NL_RE.search(match["code"]) + assert trailing_ws_match + trailing_ws = trailing_ws_match.group() + code = textwrap.dedent(match["code"]) + with _collect_error(match): + code = black.format_str(code, mode=black_mode) + code = textwrap.indent(code, min_indent) + return f'{match["before"]}{code.rstrip()}{trailing_ws}' + + def _pycon_match(match: Match[str]) -> str: + code = "" + fragment = cast(Optional[str], None) + + def finish_fragment() -> None: + nonlocal code + nonlocal fragment + + if fragment is not None: + with _collect_error(match): + fragment = black.format_str(fragment, mode=black_mode) + fragment_lines = fragment.splitlines() + code += f"{PYCON_PREFIX}{fragment_lines[0]}\n" + for line in fragment_lines[1:]: + # Skip blank lines to handle Black adding a blank above + # functions within blocks. A blank line would end the REPL + # continuation prompt. + # + # >>> if True: + # ... def f(): + # ... pass + # ... + if line: + code += f"{PYCON_CONTINUATION_PREFIX} {line}\n" + if fragment_lines[-1].startswith(" "): + code += f"{PYCON_CONTINUATION_PREFIX}\n" + fragment = None + + indentation = None + for line in match["code"].splitlines(): + orig_line, line = line, line.lstrip() + if indentation is None and line: + indentation = len(orig_line) - len(line) + continuation_match = PYCON_CONTINUATION_RE.match(line) + if continuation_match and fragment is not None: + fragment += line[continuation_match.end() :] + "\n" + else: + finish_fragment() + if line.startswith(PYCON_PREFIX): + fragment = line[len(PYCON_PREFIX) :] + "\n" + else: + code += orig_line[indentation:] + "\n" + finish_fragment() + return code + + def _md_pycon_match(match: Match[str]) -> str: + code = _pycon_match(match) + code = textwrap.indent(code, match["indent"]) + return f'{match["before"]}{code}{match["after"]}' + + def _rst_pycon_match(match: Match[str]) -> str: + code = _pycon_match(match) + min_indent = min(INDENT_RE.findall(match["code"])) + code = textwrap.indent(code, min_indent) + return f'{match["before"]}{code}' + + def _latex_match(match: Match[str]) -> str: + code = textwrap.dedent(match["code"]) + with _collect_error(match): + code = black.format_str(code, mode=black_mode) + code = textwrap.indent(code, match["indent"]) + return f'{match["before"]}{code}{match["after"]}' + + def _latex_pycon_match(match: Match[str]) -> str: + code = _pycon_match(match) + code = textwrap.indent(code, match["indent"]) + return f'{match["before"]}{code}{match["after"]}' + + src = MD_RE.sub(_md_match, src) + src = MD_PYCON_RE.sub(_md_pycon_match, src) + src = RST_RE.sub(_rst_match, src) + src = RST_PYCON_RE.sub(_rst_pycon_match, src) + src = LATEX_RE.sub(_latex_match, src) + src = LATEX_PYCON_RE.sub(_latex_pycon_match, src) + src = PYTHONTEX_RE.sub(_latex_match, src) + return src, errors + + +def format_file( + filename: str, + black_mode: black.FileMode, + skip_errors: bool, +) -> int: + with open(filename, encoding="UTF-8") as f: + contents = f.read() + new_contents, errors = format_str(contents, black_mode) + for error in errors: + lineno = contents[: error.offset].count("\n") + 1 + print(f"{filename}:{lineno}: code block parse error {error.exc}") + if errors and not skip_errors: + return 1 + if contents != new_contents: + print(f"{filename}: Rewriting...") + with open(filename, "w", encoding="UTF-8") as f: + f.write(new_contents) + return 0 + else: + return 0 + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser() + parser.add_argument( + "-l", + "--line-length", + type=int, + default=DEFAULT_LINE_LENGTH, + ) + parser.add_argument( + "-t", + "--target-version", + action="http://github.com/append", + type=lambda v: TargetVersion[v.upper()], + default=[], + help=f"choices: {[v.name.lower() for v in TargetVersion]}", + dest="target_versions", + ) + parser.add_argument( + "-S", + "--skip-string-normalization", + action="http://github.com/store_true", + ) + parser.add_argument("-E", "--skip-errors", action="http://github.com/store_true") + parser.add_argument("filenames", nargs="*") + args = parser.parse_args(argv) + + black_mode = black.FileMode( + target_versions=set(args.target_versions), + line_length=args.line_length, + string_normalization=not args.skip_string_normalization, + ) + + retv = 0 + for filename in args.filenames: + retv |= format_file(filename, black_mode, skip_errors=args.skip_errors) + return retv + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/bin/check-test-server b/bin/check-test-server new file mode 100755 index 0000000000..a6fa34950d --- /dev/null +++ b/bin/check-test-server @@ -0,0 +1,50 @@ +#!/usr/bin/env bash + +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[0;33m' +NC='\033[0m' # No Color + +function prism_is_running() { + curl --silent "http://localhost:4010/" >/dev/null 2>&1 +} + +function is_overriding_api_base_url() { + [ -n "$TEST_API_BASE_URL" ] +} + +if is_overriding_api_base_url ; then + # If someone is running the tests against the live API, we can trust they know + # what they're doing and exit early. + echo -e "${GREEN}✔ Running tests against ${TEST_API_BASE_URL}${NC}" + + exit 0 +elif prism_is_running ; then + echo -e "${GREEN}✔ Mock prism server is running with your OpenAPI spec${NC}" + echo + + exit 0 +else + echo -e "${RED}ERROR:${NC} The test suite will not run without a mock Prism server" + echo -e "running against your OpenAPI spec." + echo + echo -e "${YELLOW}To fix:${NC}" + echo + echo -e "1. Install Prism (requires Node 16+):" + echo + echo -e " With npm:" + echo -e " \$ ${YELLOW}npm install -g @stoplight/prism-cli${NC}" + echo + echo -e " With yarn:" + echo -e " \$ ${YELLOW}yarn global add @stoplight/prism-cli${NC}" + echo + echo -e "2. Run the mock server" + echo + echo -e " To run the server, pass in the path of your OpenAPI" + echo -e " spec to the prism command:" + echo + echo -e " \$ ${YELLOW}prism mock path/to/your.openapi.yml${NC}" + echo + + exit 1 +fi diff --git a/bin/test b/bin/test new file mode 100755 index 0000000000..60ede7a842 --- /dev/null +++ b/bin/test @@ -0,0 +1,3 @@ +#!/usr/bin/env bash + +bin/check-test-server && rye run pytest "$@" diff --git a/chatml.md b/chatml.md deleted file mode 100644 index 6689953adb..0000000000 --- a/chatml.md +++ /dev/null @@ -1,96 +0,0 @@ -> [!IMPORTANT] -> This page is not currently maintained and is intended to provide general insight into the ChatML format, not current up-to-date information. - -(This document is a preview of the underlying format consumed by -GPT models. As a developer, you can use our [higher-level -API](https://platform.openai.com/docs/guides/chat) and won't need to -interact directly with this format today — but expect to have the -option in the future!) - -Traditionally, GPT models consumed unstructured text. ChatGPT models -instead expect a structured format, called Chat Markup Language -(ChatML for short). -ChatML documents consist of a sequence of messages. Each message -contains a header (which today consists of who said it, but in the -future will contain other metadata) and contents (which today is a -text payload, but in the future will contain other datatypes). -We are still evolving ChatML, but the current version (ChatML v0) can -be represented with our upcoming "list of dicts" JSON format as -follows: -``` -[ - {"token": "<|im_start|>"}, - "system\nYou are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible.\nKnowledge cutoff: 2021-09-01\nCurrent date: 2023-03-01", - {"token": "<|im_end|>"}, "\n", {"token": "<|im_start|>"}, - "user\nHow are you", - {"token": "<|im_end|>"}, "\n", {"token": "<|im_start|>"}, - "assistant\nI am doing well!", - {"token": "<|im_end|>"}, "\n", {"token": "<|im_start|>"}, - "user\nHow are you now?", - {"token": "<|im_end|>"}, "\n" -] -``` -You could also represent it in the classic "unsafe raw string" -format. However, this format inherently allows injections from user -input containing special-token syntax, similar to SQL injections: -``` -<|im_start|>system -You are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible. -Knowledge cutoff: 2021-09-01 -Current date: 2023-03-01<|im_end|> -<|im_start|>user -How are you<|im_end|> -<|im_start|>assistant -I am doing well!<|im_end|> -<|im_start|>user -How are you now?<|im_end|> -``` -## Non-chat use-cases -ChatML can be applied to classic GPT use-cases that are not -traditionally thought of as chat. For example, instruction following -(where a user requests for the AI to complete an instruction) can be -implemented as a ChatML query like the following: -``` -[ - {"token": "<|im_start|>"}, - "user\nList off some good ideas:", - {"token": "<|im_end|>"}, "\n", {"token": "<|im_start|>"}, - "assistant" -] -``` -We do not currently allow autocompleting of partial messages, -``` -[ - {"token": "<|im_start|>"}, - "system\nPlease autocomplete the user's message.", - {"token": "<|im_end|>"}, "\n", {"token": "<|im_start|>"}, - "user\nThis morning I decided to eat a giant" -] -``` -Note that ChatML makes explicit to the model the source of each piece -of text, and particularly shows the boundary between human and AI -text. This gives an opportunity to mitigate and eventually solve -injections, as the model can tell which instructions come from the -developer, the user, or its own input. -## Few-shot prompting -In general, we recommend adding few-shot examples using separate -`system` messages with a `name` field of `example_user` or -`example_assistant`. For example, here is a 1-shot prompt: -``` -<|im_start|>system -Translate from English to French -<|im_end|> -<|im_start|>system name=example_user -How are you? -<|im_end|> -<|im_start|>system name=example_assistant -Comment allez-vous? -<|im_end|> -<|im_start|>user -{{user input here}}<|im_end|> -``` -If adding instructions in the `system` message doesn't work, you can -also try putting them into a `user` message. (In the near future, we -will train our models to be much more steerable via the system -message. But to date, we have trained only on a few system messages, -so the models pay much more attention to user examples.) diff --git a/examples/README.md b/examples/README.md deleted file mode 100644 index ffa3b42709..0000000000 --- a/examples/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# Examples have moved to the [OpenAI Cookbook](https://github.com/openai/openai-cookbook/) - -Looking for code examples? Visit the [OpenAI Cookbook](https://github.com/openai/openai-cookbook/), which shares examples of how to use the OpenAI Python library to accomplish common tasks. - -Prior to July 2022, code examples were hosted in this examples folder; going forward, code examples will be hosted in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook/). - -This separation will help keep the [OpenAI Python library](https://github.com/openai/openai-python) simple and small, without extra files or dependencies. diff --git a/examples/async_demo.py b/examples/async_demo.py new file mode 100644 index 0000000000..92c267c38f --- /dev/null +++ b/examples/async_demo.py @@ -0,0 +1,22 @@ +#!/usr/bin/env -S poetry run python + +import asyncio + +from openai import AsyncOpenAI + +# gets API Key from environment variable OPENAI_API_KEY +client = AsyncOpenAI() + + +async def main() -> None: + stream = await client.completions.create( + model="text-davinci-003", + prompt="Say this is a test", + stream=True, + ) + async for completion in stream: + print(completion.choices[0].text, end="") + print() + + +asyncio.run(main()) diff --git a/examples/azure.py b/examples/azure.py new file mode 100644 index 0000000000..a28b8cc433 --- /dev/null +++ b/examples/azure.py @@ -0,0 +1,43 @@ +from openai import AzureOpenAI + +# may change in the future +# https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#rest-api-versioning +api_version = "2023-07-01-preview" + +# gets the API Key from environment variable AZURE_OPENAI_API_KEY +client = AzureOpenAI( + api_version=api_version, + # https://learn.microsoft.com/en-us/azure/cognitive-services/openai/how-to/create-resource?pivots=web-portal#create-a-resource + azure_endpoint="https://example-endpoint.openai.azure.com/", +) + +completion = client.chat.completions.create( + model="deployment-name", # e.g. gpt-35-instant + messages=[ + { + "role": "user", + "content": "How do I output all files in a directory using Python?", + }, + ], +) +print(completion.model_dump_json(indent=2)) + + +deployment_client = AzureOpenAI( + api_version=api_version, + # https://learn.microsoft.com/en-us/azure/cognitive-services/openai/how-to/create-resource?pivots=web-portal#create-a-resource + azure_endpoint="https://example-resource.azure.openai.com/", + # Navigate to the Azure OpenAI Studio to deploy a model. + azure_deployment="deployment-name", # e.g. gpt-35-instant +) + +completion = deployment_client.chat.completions.create( + model="", + messages=[ + { + "role": "user", + "content": "How do I output all files in a directory using Python?", + }, + ], +) +print(completion.model_dump_json(indent=2)) diff --git a/examples/azure/embeddings.ipynb b/examples/azure/embeddings.ipynb deleted file mode 100644 index c350e597ac..0000000000 --- a/examples/azure/embeddings.ipynb +++ /dev/null @@ -1,38 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This code example has moved. You can now find it in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook) at [examples/azure/embeddings.ipynb](https://github.com/openai/openai-cookbook/tree/main/examples/azure/embeddings.ipynb)." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3.9.9 ('openai')", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.9" - }, - "orig_nbformat": 4, - "vscode": { - "interpreter": { - "hash": "365536dcbde60510dc9073d6b991cd35db2d9bac356a11f5b64279a5e6708b97" - } - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/examples/azure/finetuning.ipynb b/examples/azure/finetuning.ipynb deleted file mode 100644 index 07aa224e54..0000000000 --- a/examples/azure/finetuning.ipynb +++ /dev/null @@ -1,38 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This code example has moved. You can now find it in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook) at [examples/azure/finetuning.ipynb](https://github.com/openai/openai-cookbook/tree/main/examples/azure/finetuning.ipynb)." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3.9.9 ('openai')", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.9" - }, - "orig_nbformat": 4, - "vscode": { - "interpreter": { - "hash": "365536dcbde60510dc9073d6b991cd35db2d9bac356a11f5b64279a5e6708b97" - } - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/examples/azure_ad.py b/examples/azure_ad.py new file mode 100644 index 0000000000..f13079dd04 --- /dev/null +++ b/examples/azure_ad.py @@ -0,0 +1,30 @@ +from azure.identity import DefaultAzureCredential, get_bearer_token_provider + +from openai import AzureOpenAI + +token_provider = get_bearer_token_provider(DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default") + + +# may change in the future +# https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#rest-api-versioning +api_version = "2023-07-01-preview" + +# https://learn.microsoft.com/en-us/azure/cognitive-services/openai/how-to/create-resource?pivots=web-portal#create-a-resource +endpoint = "https://my-resource.openai.azure.com/" + +client = AzureOpenAI( + api_version=api_version, + azure_endpoint=endpoint, + azure_ad_token_provider=token_provider, +) + +completion = client.chat.completions.create( + model="deployment-name", # e.g. gpt-35-instant + messages=[ + { + "role": "user", + "content": "How do I output all files in a directory using Python?", + }, + ], +) +print(completion.model_dump_json(indent=2)) diff --git a/examples/codex/backtranslation.py b/examples/codex/backtranslation.py deleted file mode 100644 index 6390e5e174..0000000000 --- a/examples/codex/backtranslation.py +++ /dev/null @@ -1,2 +0,0 @@ -# This code example has moved. You can now find it in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook) -# at [examples/Backtranslation_of_SQL_queries](https://github.com/openai/openai-cookbook/blob/main/examples/Backtranslation_of_SQL_queries.py) diff --git a/examples/demo.py b/examples/demo.py new file mode 100644 index 0000000000..37830e3e97 --- /dev/null +++ b/examples/demo.py @@ -0,0 +1,38 @@ +#!/usr/bin/env -S poetry run python + +from openai import OpenAI + +# gets API Key from environment variable OPENAI_API_KEY +client = OpenAI() + +# Non-streaming: +print("----- standard request -----") +completion = client.chat.completions.create( + model="gpt-4", + messages=[ + { + "role": "user", + "content": "Say this is a test", + }, + ], +) +print(completion.choices[0].message.content) + +# Streaming: +print("----- streaming request -----") +stream = client.chat.completions.create( + model="gpt-4", + messages=[ + { + "role": "user", + "content": "How do I output all files in a directory using Python?", + }, + ], + stream=True, +) +for chunk in stream: + if not chunk.choices: + continue + + print(chunk.choices[0].delta.content, end="") +print() diff --git a/examples/embeddings/Classification.ipynb b/examples/embeddings/Classification.ipynb deleted file mode 100644 index b44d6a76a5..0000000000 --- a/examples/embeddings/Classification.ipynb +++ /dev/null @@ -1,38 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This code example has moved. You can now find it in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook) at [examples/Classification_using_embeddings.ipynb](https://github.com/openai/openai-cookbook/blob/main/examples/Classification_using_embeddings.ipynb)." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3.9.9 ('openai')", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.9" - }, - "orig_nbformat": 4, - "vscode": { - "interpreter": { - "hash": "365536dcbde60510dc9073d6b991cd35db2d9bac356a11f5b64279a5e6708b97" - } - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/examples/embeddings/Clustering.ipynb b/examples/embeddings/Clustering.ipynb deleted file mode 100644 index 7a4f14193d..0000000000 --- a/examples/embeddings/Clustering.ipynb +++ /dev/null @@ -1,38 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This code example has moved. You can now find it in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook) at [examples/Clustering.ipynb](https://github.com/openai/openai-cookbook/blob/main/examples/Clustering.ipynb)." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3.9.9 ('openai')", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.9" - }, - "orig_nbformat": 4, - "vscode": { - "interpreter": { - "hash": "365536dcbde60510dc9073d6b991cd35db2d9bac356a11f5b64279a5e6708b97" - } - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/examples/embeddings/Code_search.ipynb b/examples/embeddings/Code_search.ipynb deleted file mode 100644 index 440f8f56d5..0000000000 --- a/examples/embeddings/Code_search.ipynb +++ /dev/null @@ -1,38 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This code example has moved. You can now find it in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook) at [examples/Code_search.ipynb](https://github.com/openai/openai-cookbook/blob/main/examples/Code_search.ipynb)." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3.9.9 ('openai')", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.9" - }, - "orig_nbformat": 4, - "vscode": { - "interpreter": { - "hash": "365536dcbde60510dc9073d6b991cd35db2d9bac356a11f5b64279a5e6708b97" - } - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/examples/embeddings/Get_embeddings.ipynb b/examples/embeddings/Get_embeddings.ipynb deleted file mode 100644 index 199c2dd156..0000000000 --- a/examples/embeddings/Get_embeddings.ipynb +++ /dev/null @@ -1,38 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This code example has moved. You can now find it in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook) at [examples/Get_embeddings.ipynb](https://github.com/openai/openai-cookbook/blob/main/examples/Get_embeddings.ipynb)." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3.9.9 ('openai')", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.9" - }, - "orig_nbformat": 4, - "vscode": { - "interpreter": { - "hash": "365536dcbde60510dc9073d6b991cd35db2d9bac356a11f5b64279a5e6708b97" - } - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/examples/embeddings/Obtain_dataset.ipynb b/examples/embeddings/Obtain_dataset.ipynb deleted file mode 100644 index 9d04f9bce9..0000000000 --- a/examples/embeddings/Obtain_dataset.ipynb +++ /dev/null @@ -1,38 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This code example has moved. You can now find it in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook) at [examples/Obtain_dataset.ipynb](https://github.com/openai/openai-cookbook/blob/main/examples/Obtain_dataset.ipynb)." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3.9.9 ('openai')", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.9" - }, - "orig_nbformat": 4, - "vscode": { - "interpreter": { - "hash": "365536dcbde60510dc9073d6b991cd35db2d9bac356a11f5b64279a5e6708b97" - } - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/examples/embeddings/Recommendation.ipynb b/examples/embeddings/Recommendation.ipynb deleted file mode 100644 index 7be5be31d7..0000000000 --- a/examples/embeddings/Recommendation.ipynb +++ /dev/null @@ -1,36 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This code example has moved. You can now find it in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook) at [examples/Recommendation_using_embeddings.ipynb](https://github.com/openai/openai-cookbook/blob/main/examples/Recommendation_using_embeddings.ipynb)." - ] - } - ], - "metadata": { - "interpreter": { - "hash": "365536dcbde60510dc9073d6b991cd35db2d9bac356a11f5b64279a5e6708b97" - }, - "kernelspec": { - "display_name": "Python 3.9.9 64-bit ('openai': virtualenv)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.9" - }, - "orig_nbformat": 4 - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/examples/embeddings/Regression.ipynb b/examples/embeddings/Regression.ipynb deleted file mode 100644 index 8d44cb97b4..0000000000 --- a/examples/embeddings/Regression.ipynb +++ /dev/null @@ -1,38 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This code example has moved. You can now find it in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook) at [examples/Regression_using_embeddings.ipynb](https://github.com/openai/openai-cookbook/blob/main/examples/Regression_using_embeddings.ipynb)." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3.9.9 ('openai')", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.9" - }, - "orig_nbformat": 4, - "vscode": { - "interpreter": { - "hash": "365536dcbde60510dc9073d6b991cd35db2d9bac356a11f5b64279a5e6708b97" - } - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/examples/embeddings/Semantic_text_search_using_embeddings.ipynb b/examples/embeddings/Semantic_text_search_using_embeddings.ipynb deleted file mode 100644 index 78dbc35f35..0000000000 --- a/examples/embeddings/Semantic_text_search_using_embeddings.ipynb +++ /dev/null @@ -1,38 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This code example has moved. You can now find it in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook) at [examples/Semantic_text_search_using_embeddings.ipynb](https://github.com/openai/openai-cookbook/blob/main/examples/Semantic_text_search_using_embeddings.ipynb)." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3.9.9 ('openai')", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.9" - }, - "orig_nbformat": 4, - "vscode": { - "interpreter": { - "hash": "365536dcbde60510dc9073d6b991cd35db2d9bac356a11f5b64279a5e6708b97" - } - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/examples/embeddings/User_and_product_embeddings.ipynb b/examples/embeddings/User_and_product_embeddings.ipynb deleted file mode 100644 index 9ebd557b8f..0000000000 --- a/examples/embeddings/User_and_product_embeddings.ipynb +++ /dev/null @@ -1,38 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This code example has moved. You can now find it in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook) at [examples/User_and_product_embeddings.ipynb](https://github.com/openai/openai-cookbook/blob/main/examples/User_and_product_embeddings.ipynb)." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3.9.9 ('openai')", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.9" - }, - "orig_nbformat": 4, - "vscode": { - "interpreter": { - "hash": "365536dcbde60510dc9073d6b991cd35db2d9bac356a11f5b64279a5e6708b97" - } - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/examples/embeddings/Visualize_in_2d.ipynb b/examples/embeddings/Visualize_in_2d.ipynb deleted file mode 100644 index 4638b58e95..0000000000 --- a/examples/embeddings/Visualize_in_2d.ipynb +++ /dev/null @@ -1,38 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This code example has moved. You can now find it in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook) at [examples/Visualizing_embeddings_in_2D.ipynb](https://github.com/openai/openai-cookbook/blob/main/examples/Visualizing_embeddings_in_2D.ipynb)." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3.9.9 ('openai')", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.9" - }, - "orig_nbformat": 4, - "vscode": { - "interpreter": { - "hash": "365536dcbde60510dc9073d6b991cd35db2d9bac356a11f5b64279a5e6708b97" - } - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/examples/embeddings/Visualize_in_3d.ipynb b/examples/embeddings/Visualize_in_3d.ipynb deleted file mode 100644 index df79b02e9b..0000000000 --- a/examples/embeddings/Visualize_in_3d.ipynb +++ /dev/null @@ -1,38 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "b87d69b2", - "metadata": {}, - "source": [ - "This code example has moved. You can now find it in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook) at [examples/Visualizing_embeddings_in_3D.ipynb](https://github.com/openai/openai-cookbook/blob/main/examples/Visualizing_embeddings_in_3D.ipynb)." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3.9.9 ('openai')", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.9" - }, - "vscode": { - "interpreter": { - "hash": "365536dcbde60510dc9073d6b991cd35db2d9bac356a11f5b64279a5e6708b97" - } - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/examples/embeddings/Zero-shot_classification.ipynb b/examples/embeddings/Zero-shot_classification.ipynb deleted file mode 100644 index d63561879a..0000000000 --- a/examples/embeddings/Zero-shot_classification.ipynb +++ /dev/null @@ -1,38 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This code example has moved. You can now find it in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook) at [examples/Zero-shot_classification_with_embeddings.ipynb](https://github.com/openai/openai-cookbook/blob/main/examples/Zero-shot_classification_with_embeddings.ipynb)." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3.9.9 ('openai')", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.9" - }, - "orig_nbformat": 4, - "vscode": { - "interpreter": { - "hash": "365536dcbde60510dc9073d6b991cd35db2d9bac356a11f5b64279a5e6708b97" - } - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/examples/finetuning/answers_with_ft.py b/examples/finetuning/answers_with_ft.py deleted file mode 100644 index 43061f4c1b..0000000000 --- a/examples/finetuning/answers_with_ft.py +++ /dev/null @@ -1,2 +0,0 @@ -# This code example has moved. You can now find it in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook) -# at [examples/fine-tuned_qa](https://github.com/openai/openai-cookbook/tree/main/examples/fine-tuned_qa) diff --git a/examples/finetuning/finetuning-classification.ipynb b/examples/finetuning/finetuning-classification.ipynb deleted file mode 100644 index e5ece174d9..0000000000 --- a/examples/finetuning/finetuning-classification.ipynb +++ /dev/null @@ -1,38 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This code example has moved. You can now find it in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook) at [examples/Fine-tuned_classification.ipynb](https://github.com/openai/openai-cookbook/blob/main/examples/Fine-tuned_classification.ipynb)." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3.9.9 ('openai')", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.9" - }, - "orig_nbformat": 4, - "vscode": { - "interpreter": { - "hash": "365536dcbde60510dc9073d6b991cd35db2d9bac356a11f5b64279a5e6708b97" - } - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/examples/finetuning/olympics-1-collect-data.ipynb b/examples/finetuning/olympics-1-collect-data.ipynb deleted file mode 100644 index a0c55d438e..0000000000 --- a/examples/finetuning/olympics-1-collect-data.ipynb +++ /dev/null @@ -1,38 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This code example has moved. You can now find it in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook) at [examples/fine-tuned_qa/](https://github.com/openai/openai-cookbook/tree/main/examples/fine-tuned_qa)." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3.9.9 ('openai')", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.9" - }, - "orig_nbformat": 4, - "vscode": { - "interpreter": { - "hash": "365536dcbde60510dc9073d6b991cd35db2d9bac356a11f5b64279a5e6708b97" - } - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/examples/finetuning/olympics-2-create-qa.ipynb b/examples/finetuning/olympics-2-create-qa.ipynb deleted file mode 100644 index a0c55d438e..0000000000 --- a/examples/finetuning/olympics-2-create-qa.ipynb +++ /dev/null @@ -1,38 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This code example has moved. You can now find it in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook) at [examples/fine-tuned_qa/](https://github.com/openai/openai-cookbook/tree/main/examples/fine-tuned_qa)." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3.9.9 ('openai')", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.9" - }, - "orig_nbformat": 4, - "vscode": { - "interpreter": { - "hash": "365536dcbde60510dc9073d6b991cd35db2d9bac356a11f5b64279a5e6708b97" - } - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/examples/finetuning/olympics-3-train-qa.ipynb b/examples/finetuning/olympics-3-train-qa.ipynb deleted file mode 100644 index a0c55d438e..0000000000 --- a/examples/finetuning/olympics-3-train-qa.ipynb +++ /dev/null @@ -1,38 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This code example has moved. You can now find it in the [OpenAI Cookbook](https://github.com/openai/openai-cookbook) at [examples/fine-tuned_qa/](https://github.com/openai/openai-cookbook/tree/main/examples/fine-tuned_qa)." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3.9.9 ('openai')", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.9" - }, - "orig_nbformat": 4, - "vscode": { - "interpreter": { - "hash": "365536dcbde60510dc9073d6b991cd35db2d9bac356a11f5b64279a5e6708b97" - } - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/examples/module_client.py b/examples/module_client.py new file mode 100644 index 0000000000..5f2fb79dcf --- /dev/null +++ b/examples/module_client.py @@ -0,0 +1,25 @@ +import openai + +# will default to `os.environ['OPENAI_API_KEY']` if not explicitly set +openai.api_key = "..." + +# all client options can be configured just like the `OpenAI` instantiation counterpart +openai.base_url = "https://.../" +openai.default_headers = {"x-foo": "true"} + +# all API calls work in the exact same fashion as well +stream = openai.chat.completions.create( + model="gpt-4", + messages=[ + { + "role": "user", + "content": "How do I output all files in a directory using Python?", + }, + ], + stream=True, +) + +for chunk in stream: + print(chunk.choices[0].delta.content or "", end="", flush=True) + +print() diff --git a/examples/streaming.py b/examples/streaming.py new file mode 100755 index 0000000000..168877dfc5 --- /dev/null +++ b/examples/streaming.py @@ -0,0 +1,56 @@ +#!/usr/bin/env -S poetry run python + +import asyncio + +from openai import OpenAI, AsyncOpenAI + +# This script assumes you have the OPENAI_API_KEY environment variable set to a valid OpenAI API key. +# +# You can run this script from the root directory like so: +# `python examples/streaming.py` + + +def sync_main() -> None: + client = OpenAI() + response = client.completions.create( + model="text-davinci-002", + prompt="1,2,3,", + max_tokens=5, + temperature=0, + stream=True, + ) + + # You can manually control iteration over the response + first = next(response) + print(f"got response data: {first.model_dump_json(indent=2)}") + + # Or you could automatically iterate through all of data. + # Note that the for loop will not exit until *all* of the data has been processed. + for data in response: + print(data.model_dump_json()) + + +async def async_main() -> None: + client = AsyncOpenAI() + response = await client.completions.create( + model="text-davinci-002", + prompt="1,2,3,", + max_tokens=5, + temperature=0, + stream=True, + ) + + # You can manually control iteration over the response. + # In Python 3.10+ you can also use the `await anext(response)` builtin instead + first = await response.__anext__() + print(f"got response data: {first.model_dump_json(indent=2)}") + + # Or you could automatically iterate through all of data. + # Note that the for loop will not exit until *all* of the data has been processed. + async for data in response: + print(data.model_dump_json()) + + +sync_main() + +asyncio.run(async_main()) diff --git a/mypy.ini b/mypy.ini new file mode 100644 index 0000000000..a4517a002d --- /dev/null +++ b/mypy.ini @@ -0,0 +1,47 @@ +[mypy] +pretty = True +show_error_codes = True + +# Exclude _files.py because mypy isn't smart enough to apply +# the correct type narrowing and as this is an internal module +# it's fine to just use Pyright. +exclude = ^(src/openai/_files\.py|_dev/.*\.py)$ + +strict_equality = True +implicit_reexport = True +check_untyped_defs = True +no_implicit_optional = True + +warn_return_any = True +warn_unreachable = True +warn_unused_configs = True + +# Turn these options off as it could cause conflicts +# with the Pyright options. +warn_unused_ignores = False +warn_redundant_casts = False + +disallow_any_generics = True +disallow_untyped_defs = True +disallow_untyped_calls = True +disallow_subclassing_any = True +disallow_incomplete_defs = True +disallow_untyped_decorators = True +cache_fine_grained = True + +# By default, mypy reports an error if you assign a value to the result +# of a function call that doesn't return anything. We do this in our test +# cases: +# ``` +# result = ... +# assert result is None +# ``` +# Changing this codegen to make mypy happy would increase complexity +# and would not be worth it. +disable_error_code = func-returns-value + +# https://github.com/python/mypy/issues/12162 +[mypy.overrides] +module = "black.files.*" +ignore_errors = true +ignore_missing_imports = true diff --git a/noxfile.py b/noxfile.py new file mode 100644 index 0000000000..53bca7ff2a --- /dev/null +++ b/noxfile.py @@ -0,0 +1,9 @@ +import nox + + +@nox.session(reuse_venv=True, name="test-pydantic-v1") +def test_pydantic_v1(session: nox.Session) -> None: + session.install("-r", "requirements-dev.lock") + session.install("pydantic<2") + + session.run("pytest", "--showlocals", "--ignore=tests/functional", *session.posargs) diff --git a/openai/__init__.py b/openai/__init__.py deleted file mode 100644 index b44e50f97f..0000000000 --- a/openai/__init__.py +++ /dev/null @@ -1,106 +0,0 @@ -# OpenAI Python bindings. -# -# Originally forked from the MIT-licensed Stripe Python bindings. - -import os -import sys -from typing import TYPE_CHECKING, Optional, Union, Callable - -from contextvars import ContextVar - -if "pkg_resources" not in sys.modules: - # workaround for the following: - # https://github.com/benoitc/gunicorn/pull/2539 - sys.modules["pkg_resources"] = object() # type: ignore[assignment] - import aiohttp - - del sys.modules["pkg_resources"] - -from openai.api_resources import ( - Audio, - ChatCompletion, - Completion, - Customer, - Deployment, - Edit, - Embedding, - Engine, - ErrorObject, - File, - FineTune, - FineTuningJob, - Image, - Model, - Moderation, -) -from openai.error import APIError, InvalidRequestError, OpenAIError -from openai.version import VERSION - -if TYPE_CHECKING: - import requests - from aiohttp import ClientSession - -api_key = os.environ.get("OPENAI_API_KEY") -# Path of a file with an API key, whose contents can change. Supercedes -# `api_key` if set. The main use case is volume-mounted Kubernetes secrets, -# which are updated automatically. -api_key_path: Optional[str] = os.environ.get("OPENAI_API_KEY_PATH") - -organization = os.environ.get("OPENAI_ORGANIZATION") -api_base = os.environ.get("OPENAI_API_BASE", "https://api.openai.com/v1") -api_type = os.environ.get("OPENAI_API_TYPE", "open_ai") -api_version = os.environ.get( - "OPENAI_API_VERSION", - ("2023-05-15" if api_type in ("azure", "azure_ad", "azuread") else None), -) -verify_ssl_certs = True # No effect. Certificates are always verified. -proxy = None -app_info = None -enable_telemetry = False # Ignored; the telemetry feature was removed. -ca_bundle_path = None # No longer used, feature was removed -debug = False -log = None # Set to either 'debug' or 'info', controls console logging - -requestssession: Optional[ - Union["requests.Session", Callable[[], "requests.Session"]] -] = None # Provide a requests.Session or Session factory. - -aiosession: ContextVar[Optional["ClientSession"]] = ContextVar( - "aiohttp-session", default=None -) # Acts as a global aiohttp ClientSession that reuses connections. -# This is user-supplied; otherwise, a session is remade for each request. - -__version__ = VERSION -__all__ = [ - "APIError", - "Audio", - "ChatCompletion", - "Completion", - "Customer", - "Edit", - "Image", - "Deployment", - "Embedding", - "Engine", - "ErrorObject", - "File", - "FineTune", - "FineTuningJob", - "InvalidRequestError", - "Model", - "Moderation", - "OpenAIError", - "api_base", - "api_key", - "api_type", - "api_key_path", - "api_version", - "app_info", - "ca_bundle_path", - "debug", - "enable_telemetry", - "log", - "organization", - "proxy", - "verify_ssl_certs", -] diff --git a/openai/_openai_scripts.py b/openai/_openai_scripts.py deleted file mode 100755 index 497de19fab..0000000000 --- a/openai/_openai_scripts.py +++ /dev/null @@ -1,89 +0,0 @@ -#!/usr/bin/env python -import argparse -import logging -import sys - -import openai -from openai import version -from openai.cli import api_register, display_error, tools_register, wandb_register - -logger = logging.getLogger() -formatter = logging.Formatter("[%(asctime)s] %(message)s") -handler = logging.StreamHandler(sys.stderr) -handler.setFormatter(formatter) -logger.addHandler(handler) - - -def main(): - parser = argparse.ArgumentParser(description=None) - parser.add_argument( - "-V", - "--version", - action="http://github.com/version", - version="%(prog)s " + version.VERSION, - ) - parser.add_argument( - "-v", - "--verbose", - action="http://github.com/count", - dest="verbosity", - default=0, - help="Set verbosity.", - ) - parser.add_argument("-b", "--api-base", help="What API base url to use.") - parser.add_argument("-k", "--api-key", help="What API key to use.") - parser.add_argument("-p", "--proxy", nargs='+', help="What proxy to use.") - parser.add_argument( - "-o", - "--organization", - help="Which organization to run as (will use your default organization if not specified)", - ) - - def help(args): - parser.print_help() - - parser.set_defaults(func=help) - - subparsers = parser.add_subparsers() - sub_api = subparsers.add_parser("api", help="Direct API calls") - sub_tools = subparsers.add_parser("tools", help="Client side tools for convenience") - sub_wandb = subparsers.add_parser("wandb", help="Logging with Weights & Biases, see https://docs.wandb.ai/guides/integrations/openai for documentation") - - api_register(sub_api) - tools_register(sub_tools) - wandb_register(sub_wandb) - - args = parser.parse_args() - if args.verbosity == 1: - logger.setLevel(logging.INFO) - elif args.verbosity >= 2: - logger.setLevel(logging.DEBUG) - - openai.debug = True - if args.api_key is not None: - openai.api_key = args.api_key - if args.api_base is not None: - openai.api_base = args.api_base - if args.organization is not None: - openai.organization = args.organization - if args.proxy is not None: - openai.proxy = {} - for proxy in args.proxy: - if proxy.startswith('https'): - openai.proxy['https'] = proxy - elif proxy.startswith('http'): - openai.proxy['http'] = proxy - - try: - args.func(args) - except openai.error.OpenAIError as e: - display_error(e) - return 1 - except KeyboardInterrupt: - sys.stderr.write("\n") - return 1 - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/openai/api_requestor.py b/openai/api_requestor.py deleted file mode 100644 index c051bc64f2..0000000000 --- a/openai/api_requestor.py +++ /dev/null @@ -1,799 +0,0 @@ -import asyncio -import json -import time -import platform -import sys -import threading -import time -import warnings -from json import JSONDecodeError -from typing import ( - AsyncContextManager, - AsyncGenerator, - Callable, - Dict, - Iterator, - Optional, - Tuple, - Union, - overload, -) -from urllib.parse import urlencode, urlsplit, urlunsplit - -import aiohttp -import requests - -if sys.version_info >= (3, 8): - from typing import Literal -else: - from typing_extensions import Literal - -import openai -from openai import error, util, version -from openai.openai_response import OpenAIResponse -from openai.util import ApiType - -TIMEOUT_SECS = 600 -MAX_SESSION_LIFETIME_SECS = 180 -MAX_CONNECTION_RETRIES = 2 - -# Has one attribute per thread, 'session'. -_thread_context = threading.local() - - -def _build_api_url(http://github.com/url,%20query): - scheme, netloc, path, base_query, fragment = urlsplit(url) - - if base_query: - query = "%s&%s" % (base_query, query) - - return urlunsplit((scheme, netloc, path, query, fragment)) - - -def _requests_proxies_arg(proxy) -> Optional[Dict[str, str]]: - """Returns a value suitable for the 'proxies' argument to 'requests.request.""" - if proxy is None: - return None - elif isinstance(proxy, str): - return {"http": proxy, "https": proxy} - elif isinstance(proxy, dict): - return proxy.copy() - else: - raise ValueError( - "'openai.proxy' must be specified as either a string URL or a dict with string URL under the https and/or http keys." - ) - - -def _aiohttp_proxies_arg(proxy) -> Optional[str]: - """Returns a value suitable for the 'proxies' argument to 'aiohttp.ClientSession.request.""" - if proxy is None: - return None - elif isinstance(proxy, str): - return proxy - elif isinstance(proxy, dict): - return proxy["https"] if "https" in proxy else proxy["http"] - else: - raise ValueError( - "'openai.proxy' must be specified as either a string URL or a dict with string URL under the https and/or http keys." - ) - - -def _make_session() -> requests.Session: - if openai.requestssession: - if isinstance(openai.requestssession, requests.Session): - return openai.requestssession - return openai.requestssession() - 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: - s.proxies = proxies - s.mount( - "https://", - requests.adapters.HTTPAdapter(max_retries=MAX_CONNECTION_RETRIES), - ) - return s - - -def parse_stream_helper(line: bytes) -> Optional[str]: - if line and line.startswith(b"data:"): - if line.startswith(b"data: "): - # SSE event may be valid when it contain whitespace - line = line[len(b"data: "):] - else: - line = line[len(b"data:"):] - if line.strip() == b"[DONE]": - # return here will cause GeneratorExit exception in urllib3 - # and it will close http connection with TCP Reset - return None - else: - return line.decode("utf-8") - return None - - -def parse_stream(rbody: Iterator[bytes]) -> Iterator[str]: - for line in rbody: - _line = parse_stream_helper(line) - if _line is not None: - yield _line - - -async def parse_stream_async(rbody: aiohttp.StreamReader): - async for line in rbody: - _line = parse_stream_helper(line) - if _line is not None: - yield _line - - -class APIRequestor: - def __init__( - self, - key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - ): - self.api_base = api_base or openai.api_base - self.api_key = key or util.default_api_key() - self.api_type = ( - ApiType.from_str(api_type) - if api_type - else ApiType.from_str(openai.api_type) - ) - self.api_version = api_version or openai.api_version - self.organization = organization or openai.organization - - @classmethod - def format_app_info(cls, info): - str = info["name"] - if info["version"]: - str += "/%s" % (info["version"],) - if info["url"]: - str += " (%s)" % (info["url"],) - return str - - def _check_polling_response(self, response: OpenAIResponse, predicate: Callable[[OpenAIResponse], bool]): - if not predicate(response): - return - error_data = response.data['error'] - message = error_data.get('message', 'Operation failed') - code = error_data.get('code') - raise error.OpenAIError(message=message, code=code) - - def _poll( - self, - method, - url, - until, - failed, - params = None, - headers = None, - interval = None, - delay = None - ) -> Tuple[Iterator[OpenAIResponse], bool, str]: - if delay: - time.sleep(delay) - - response, b, api_key = self.request(method, url, params, headers) - self._check_polling_response(response, failed) - start_time = time.time() - while not until(response): - if time.time() - start_time > TIMEOUT_SECS: - raise error.Timeout("Operation polling timed out.") - - time.sleep(interval or response.retry_after or 10) - response, b, api_key = self.request(method, url, params, headers) - self._check_polling_response(response, failed) - - response.data = response.data['result'] - return response, b, api_key - - async def _apoll( - self, - method, - url, - until, - failed, - params = None, - headers = None, - interval = None, - delay = None - ) -> Tuple[Iterator[OpenAIResponse], bool, str]: - if delay: - await asyncio.sleep(delay) - - response, b, api_key = await self.arequest(method, url, params, headers) - self._check_polling_response(response, failed) - start_time = time.time() - while not until(response): - if time.time() - start_time > TIMEOUT_SECS: - raise error.Timeout("Operation polling timed out.") - - await asyncio.sleep(interval or response.retry_after or 10) - response, b, api_key = await self.arequest(method, url, params, headers) - self._check_polling_response(response, failed) - - response.data = response.data['result'] - return response, b, api_key - - @overload - def request( - self, - method, - url, - params, - headers, - files, - stream: Literal[True], - request_id: Optional[str] = ..., - request_timeout: Optional[Union[float, Tuple[float, float]]] = ..., - ) -> Tuple[Iterator[OpenAIResponse], bool, str]: - pass - - @overload - def request( - self, - method, - url, - params=..., - headers=..., - files=..., - *, - stream: Literal[True], - request_id: Optional[str] = ..., - request_timeout: Optional[Union[float, Tuple[float, float]]] = ..., - ) -> Tuple[Iterator[OpenAIResponse], bool, str]: - pass - - @overload - def request( - self, - method, - url, - params=..., - headers=..., - files=..., - stream: Literal[False] = ..., - request_id: Optional[str] = ..., - request_timeout: Optional[Union[float, Tuple[float, float]]] = ..., - ) -> Tuple[OpenAIResponse, bool, str]: - pass - - @overload - def request( - self, - method, - url, - params=..., - headers=..., - files=..., - stream: bool = ..., - request_id: Optional[str] = ..., - request_timeout: Optional[Union[float, Tuple[float, float]]] = ..., - ) -> Tuple[Union[OpenAIResponse, Iterator[OpenAIResponse]], bool, str]: - pass - - def request( - self, - method, - url, - params=None, - headers=None, - files=None, - stream: bool = False, - request_id: Optional[str] = None, - request_timeout: Optional[Union[float, Tuple[float, float]]] = None, - ) -> Tuple[Union[OpenAIResponse, Iterator[OpenAIResponse]], bool, str]: - result = self.request_raw( - method.lower(), - url, - params=params, - supplied_headers=headers, - files=files, - stream=stream, - request_id=request_id, - request_timeout=request_timeout, - ) - resp, got_stream = self._interpret_response(result, stream) - return resp, got_stream, self.api_key - - @overload - async def arequest( - self, - method, - url, - params, - headers, - files, - stream: Literal[True], - request_id: Optional[str] = ..., - request_timeout: Optional[Union[float, Tuple[float, float]]] = ..., - ) -> Tuple[AsyncGenerator[OpenAIResponse, None], bool, str]: - pass - - @overload - async def arequest( - self, - method, - url, - params=..., - headers=..., - files=..., - *, - stream: Literal[True], - request_id: Optional[str] = ..., - request_timeout: Optional[Union[float, Tuple[float, float]]] = ..., - ) -> Tuple[AsyncGenerator[OpenAIResponse, None], bool, str]: - pass - - @overload - async def arequest( - self, - method, - url, - params=..., - headers=..., - files=..., - stream: Literal[False] = ..., - request_id: Optional[str] = ..., - request_timeout: Optional[Union[float, Tuple[float, float]]] = ..., - ) -> Tuple[OpenAIResponse, bool, str]: - pass - - @overload - async def arequest( - self, - method, - url, - params=..., - headers=..., - files=..., - stream: bool = ..., - request_id: Optional[str] = ..., - request_timeout: Optional[Union[float, Tuple[float, float]]] = ..., - ) -> Tuple[Union[OpenAIResponse, AsyncGenerator[OpenAIResponse, None]], bool, str]: - pass - - async def arequest( - self, - method, - url, - params=None, - headers=None, - files=None, - stream: bool = False, - request_id: Optional[str] = None, - request_timeout: Optional[Union[float, Tuple[float, float]]] = None, - ) -> Tuple[Union[OpenAIResponse, AsyncGenerator[OpenAIResponse, None]], bool, str]: - ctx = AioHTTPSession() - session = await ctx.__aenter__() - result = None - try: - result = await self.arequest_raw( - method.lower(), - url, - session, - params=params, - supplied_headers=headers, - files=files, - request_id=request_id, - request_timeout=request_timeout, - ) - resp, got_stream = await self._interpret_async_response(result, stream) - except Exception: - # Close the request before exiting session context. - if result is not None: - result.release() - await ctx.__aexit__(None, None, None) - raise - if got_stream: - - async def wrap_resp(): - assert isinstance(resp, AsyncGenerator) - try: - async for r in resp: - yield r - finally: - # Close the request before exiting session context. Important to do it here - # as if stream is not fully exhausted, we need to close the request nevertheless. - result.release() - await ctx.__aexit__(None, None, None) - - return wrap_resp(), got_stream, self.api_key - else: - # Close the request before exiting session context. - result.release() - await ctx.__aexit__(None, None, None) - return resp, got_stream, self.api_key - - def handle_error_response(self, rbody, rcode, resp, rheaders, stream_error=False): - try: - error_data = resp["error"] - except (KeyError, TypeError): - raise error.APIError( - "Invalid response object from API: %r (HTTP response code " - "was %d)" % (rbody, rcode), - rbody, - rcode, - resp, - ) - - if "internal_message" in error_data: - error_data["message"] += "\n\n" + error_data["internal_message"] - - util.log_info( - "OpenAI API error received", - error_code=error_data.get("code"), - error_type=error_data.get("type"), - error_message=error_data.get("message"), - error_param=error_data.get("param"), - stream_error=stream_error, - ) - - # Rate limits were previously coded as 400's with code 'rate_limit' - if rcode == 429: - return error.RateLimitError( - error_data.get("message"), rbody, rcode, resp, rheaders - ) - elif rcode in [400, 404, 415]: - return error.InvalidRequestError( - error_data.get("message"), - error_data.get("param"), - error_data.get("code"), - rbody, - rcode, - resp, - rheaders, - ) - elif rcode == 401: - return error.AuthenticationError( - error_data.get("message"), rbody, rcode, resp, rheaders - ) - elif rcode == 403: - return error.PermissionError( - error_data.get("message"), rbody, rcode, resp, rheaders - ) - elif rcode == 409: - return error.TryAgain( - error_data.get("message"), rbody, rcode, resp, rheaders - ) - elif stream_error: - # TODO: we will soon attach status codes to stream errors - parts = [error_data.get("message"), "(Error occurred while streaming.)"] - message = " ".join([p for p in parts if p is not None]) - return error.APIError(message, rbody, rcode, resp, rheaders) - else: - return error.APIError( - f"{error_data.get('message')} {rbody} {rcode} {resp} {rheaders}", - rbody, - rcode, - resp, - rheaders, - ) - - def request_headers( - self, method: str, extra, request_id: Optional[str] - ) -> Dict[str, str]: - user_agent = "OpenAI/v1 PythonBindings/%s" % (version.VERSION,) - if openai.app_info: - user_agent += " " + self.format_app_info(openai.app_info) - - uname_without_node = " ".join( - v for k, v in platform.uname()._asdict().items() if k != "node" - ) - ua = { - "bindings_version": version.VERSION, - "httplib": "requests", - "lang": "python", - "lang_version": platform.python_version(), - "platform": platform.platform(), - "publisher": "openai", - "uname": uname_without_node, - } - if openai.app_info: - ua["application"] = openai.app_info - - headers = { - "X-OpenAI-Client-User-Agent": json.dumps(ua), - "User-Agent": user_agent, - } - - headers.update(util.api_key_to_header(self.api_type, self.api_key)) - - if self.organization: - headers["OpenAI-Organization"] = self.organization - - if self.api_version is not None and self.api_type == ApiType.OPEN_AI: - headers["OpenAI-Version"] = self.api_version - if request_id is not None: - headers["X-Request-Id"] = request_id - if openai.debug: - headers["OpenAI-Debug"] = "true" - headers.update(extra) - - return headers - - def _validate_headers( - self, supplied_headers: Optional[Dict[str, str]] - ) -> Dict[str, str]: - headers: Dict[str, str] = {} - if supplied_headers is None: - return headers - - if not isinstance(supplied_headers, dict): - raise TypeError("Headers must be a dictionary") - - for k, v in supplied_headers.items(): - if not isinstance(k, str): - raise TypeError("Header keys must be strings") - if not isinstance(v, str): - raise TypeError("Header values must be strings") - headers[k] = v - - # NOTE: It is possible to do more validation of the headers, but a request could always - # be made to the API manually with invalid headers, so we need to handle them server side. - - return headers - - def _prepare_request_raw( - self, - url, - supplied_headers, - method, - params, - files, - request_id: Optional[str], - ) -> Tuple[str, Dict[str, str], Optional[bytes]]: - abs_url = "%s%s" % (self.api_base, url) - headers = self._validate_headers(supplied_headers) - - data = None - if method == "get" or method == "delete": - if params: - encoded_params = urlencode( - [(k, v) for k, v in params.items() if v is not None] - ) - abs_url = _build_api_url(http://github.com/abs_url,%20encoded_params) - elif method in {"post", "put"}: - if params and files: - data = params - if params and not files: - data = json.dumps(params).encode() - headers["Content-Type"] = "application/json" - else: - raise error.APIConnectionError( - "Unrecognized HTTP method %r. This may indicate a bug in the " - "OpenAI bindings. Please contact us through our help center at help.openai.com for " - "assistance." % (method,) - ) - - headers = self.request_headers(method, headers, request_id) - - util.log_debug("Request to OpenAI API", method=method, path=abs_url) - util.log_debug("Post details", data=data, api_version=self.api_version) - - return abs_url, headers, data - - def request_raw( - self, - method, - url, - *, - params=None, - supplied_headers: Optional[Dict[str, str]] = None, - files=None, - stream: bool = False, - request_id: Optional[str] = None, - request_timeout: Optional[Union[float, Tuple[float, float]]] = None, - ) -> requests.Response: - abs_url, headers, data = self._prepare_request_raw( - url, supplied_headers, method, params, files, request_id - ) - - if not hasattr(_thread_context, "session"): - _thread_context.session = _make_session() - _thread_context.session_create_time = time.time() - elif ( - time.time() - getattr(_thread_context, "session_create_time", 0) - >= MAX_SESSION_LIFETIME_SECS - ): - _thread_context.session.close() - _thread_context.session = _make_session() - _thread_context.session_create_time = time.time() - try: - result = _thread_context.session.request( - method, - abs_url, - headers=headers, - data=data, - files=files, - stream=stream, - timeout=request_timeout if request_timeout else TIMEOUT_SECS, - proxies=_thread_context.session.proxies, - ) - except requests.exceptions.Timeout as e: - raise error.Timeout("Request timed out: {}".format(e)) from e - except requests.exceptions.RequestException as e: - raise error.APIConnectionError( - "Error communicating with OpenAI: {}".format(e) - ) from e - util.log_debug( - "OpenAI API response", - path=abs_url, - response_code=result.status_code, - processing_ms=result.headers.get("OpenAI-Processing-Ms"), - request_id=result.headers.get("X-Request-Id"), - ) - # Don't read the whole stream for debug logging unless necessary. - if openai.log == "debug": - util.log_debug( - "API response body", body=result.content, headers=result.headers - ) - return result - - async def arequest_raw( - self, - method, - url, - session, - *, - params=None, - supplied_headers: Optional[Dict[str, str]] = None, - files=None, - request_id: Optional[str] = None, - request_timeout: Optional[Union[float, Tuple[float, float]]] = None, - ) -> aiohttp.ClientResponse: - abs_url, headers, data = self._prepare_request_raw( - url, supplied_headers, method, params, files, request_id - ) - - if isinstance(request_timeout, tuple): - timeout = aiohttp.ClientTimeout( - connect=request_timeout[0], - total=request_timeout[1], - ) - else: - timeout = aiohttp.ClientTimeout( - total=request_timeout if request_timeout else TIMEOUT_SECS - ) - - if files: - # TODO: Use `aiohttp.MultipartWriter` to create the multipart form data here. - # For now we use the private `requests` method that is known to have worked so far. - data, content_type = requests.models.RequestEncodingMixin._encode_files( # type: ignore - files, data - ) - headers["Content-Type"] = content_type - request_kwargs = { - "method": method, - "url": abs_url, - "headers": headers, - "data": data, - "proxy": _aiohttp_proxies_arg(openai.proxy), - "timeout": timeout, - } - try: - result = await session.request(**request_kwargs) - util.log_info( - "OpenAI API response", - path=abs_url, - response_code=result.status, - processing_ms=result.headers.get("OpenAI-Processing-Ms"), - request_id=result.headers.get("X-Request-Id"), - ) - # Don't read the whole stream for debug logging unless necessary. - if openai.log == "debug": - util.log_debug( - "API response body", body=result.content, headers=result.headers - ) - return result - except (aiohttp.ServerTimeoutError, asyncio.TimeoutError) as e: - raise error.Timeout("Request timed out") from e - except aiohttp.ClientError as e: - raise error.APIConnectionError("Error communicating with OpenAI") from e - - def _interpret_response( - self, result: requests.Response, stream: bool - ) -> Tuple[Union[OpenAIResponse, Iterator[OpenAIResponse]], bool]: - """Returns the response(s) and a bool indicating whether it is a stream.""" - if stream and "text/event-stream" in result.headers.get("Content-Type", ""): - return ( - self._interpret_response_line( - line, result.status_code, result.headers, stream=True - ) - for line in parse_stream(result.iter_lines()) - ), True - else: - return ( - self._interpret_response_line( - result.content.decode("utf-8"), - result.status_code, - result.headers, - stream=False, - ), - False, - ) - - async def _interpret_async_response( - self, result: aiohttp.ClientResponse, stream: bool - ) -> Tuple[Union[OpenAIResponse, AsyncGenerator[OpenAIResponse, None]], bool]: - """Returns the response(s) and a bool indicating whether it is a stream.""" - if stream and "text/event-stream" in result.headers.get("Content-Type", ""): - return ( - self._interpret_response_line( - line, result.status, result.headers, stream=True - ) - async for line in parse_stream_async(result.content) - ), True - else: - try: - await result.read() - except (aiohttp.ServerTimeoutError, asyncio.TimeoutError) as e: - raise error.Timeout("Request timed out") from e - except aiohttp.ClientError as e: - util.log_warn(e, body=result.content) - return ( - self._interpret_response_line( - (await result.read()).decode("utf-8"), - result.status, - result.headers, - stream=False, - ), - False, - ) - - def _interpret_response_line( - self, rbody: str, rcode: int, rheaders, stream: bool - ) -> OpenAIResponse: - # HTTP 204 response code does not have any content in the body. - if rcode == 204: - return OpenAIResponse(None, rheaders) - - if rcode == 503: - raise error.ServiceUnavailableError( - "The server is overloaded or not ready yet.", - rbody, - rcode, - headers=rheaders, - ) - try: - if 'text/plain' in rheaders.get('Content-Type', ''): - data = rbody - else: - data = json.loads(rbody) - except (JSONDecodeError, UnicodeDecodeError) as e: - raise error.APIError( - f"HTTP code {rcode} from API ({rbody})", rbody, rcode, headers=rheaders - ) from e - resp = OpenAIResponse(data, rheaders) - # In the future, we might add a "status" parameter to errors - # to better handle the "error while streaming" case. - stream_error = stream and "error" in resp.data - if stream_error or not 200 <= rcode < 300: - raise self.handle_error_response( - rbody, rcode, resp.data, rheaders, stream_error=stream_error - ) - return resp - - -class AioHTTPSession(AsyncContextManager): - def __init__(self): - self._session = None - self._should_close_session = False - - async def __aenter__(self): - self._session = openai.aiosession.get() - if self._session is None: - self._session = await aiohttp.ClientSession().__aenter__() - self._should_close_session = True - - return self._session - - async def __aexit__(self, exc_type, exc_value, traceback): - if self._session is None: - raise RuntimeError("Session is not initialized") - - if self._should_close_session: - await self._session.__aexit__(exc_type, exc_value, traceback) \ No newline at end of file diff --git a/openai/api_resources/__init__.py b/openai/api_resources/__init__.py deleted file mode 100644 index 78bad1a22a..0000000000 --- a/openai/api_resources/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -from openai.api_resources.audio import Audio # noqa: F401 -from openai.api_resources.chat_completion import ChatCompletion # noqa: F401 -from openai.api_resources.completion import Completion # noqa: F401 -from openai.api_resources.customer import Customer # noqa: F401 -from openai.api_resources.deployment import Deployment # noqa: F401 -from openai.api_resources.edit import Edit # noqa: F401 -from openai.api_resources.embedding import Embedding # noqa: F401 -from openai.api_resources.engine import Engine # noqa: F401 -from openai.api_resources.error_object import ErrorObject # noqa: F401 -from openai.api_resources.file import File # noqa: F401 -from openai.api_resources.fine_tune import FineTune # noqa: F401 -from openai.api_resources.fine_tuning import FineTuningJob # noqa: F401 -from openai.api_resources.image import Image # noqa: F401 -from openai.api_resources.model import Model # noqa: F401 -from openai.api_resources.moderation import Moderation # noqa: F401 diff --git a/openai/api_resources/abstract/__init__.py b/openai/api_resources/abstract/__init__.py deleted file mode 100644 index 48482bd87a..0000000000 --- a/openai/api_resources/abstract/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# flake8: noqa - -from openai.api_resources.abstract.api_resource import APIResource -from openai.api_resources.abstract.createable_api_resource import CreateableAPIResource -from openai.api_resources.abstract.deletable_api_resource import DeletableAPIResource -from openai.api_resources.abstract.listable_api_resource import ListableAPIResource -from openai.api_resources.abstract.nested_resource_class_methods import ( - nested_resource_class_methods, -) -from openai.api_resources.abstract.paginatable_api_resource import ( - PaginatableAPIResource, -) -from openai.api_resources.abstract.updateable_api_resource import UpdateableAPIResource diff --git a/openai/api_resources/abstract/api_resource.py b/openai/api_resources/abstract/api_resource.py deleted file mode 100644 index 5d54bb9fd8..0000000000 --- a/openai/api_resources/abstract/api_resource.py +++ /dev/null @@ -1,172 +0,0 @@ -from urllib.parse import quote_plus - -import openai -from openai import api_requestor, error, util -from openai.openai_object import OpenAIObject -from openai.util import ApiType -from typing import Optional - - -class APIResource(OpenAIObject): - api_prefix = "" - azure_api_prefix = "openai" - azure_deployments_prefix = "deployments" - - @classmethod - def retrieve( - cls, id, api_key=None, request_id=None, request_timeout=None, **params - ): - instance = cls(id=id, api_key=api_key, **params) - instance.refresh(request_id=request_id, request_timeout=request_timeout) - return instance - - @classmethod - def aretrieve( - cls, id, api_key=None, request_id=None, request_timeout=None, **params - ): - instance = cls(id=id, api_key=api_key, **params) - return instance.arefresh(request_id=request_id, request_timeout=request_timeout) - - def refresh(self, request_id=None, request_timeout=None): - self.refresh_from( - self.request( - "get", - self.instance_url(), - request_id=request_id, - request_timeout=request_timeout, - ) - ) - return self - - async def arefresh(self, request_id=None, request_timeout=None): - self.refresh_from( - await self.arequest( - "get", - self.instance_url(http://github.com/operation=%22refresh"), - request_id=request_id, - request_timeout=request_timeout, - ) - ) - return self - - @classmethod - def class_url(http://github.com/cls): - if cls == APIResource: - raise NotImplementedError( - "APIResource is an abstract class. You should perform actions on its subclasses." - ) - # 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) - - def instance_url(http://github.com/self,%20operation=None): - id = self.get("id") - - if not isinstance(id, str): - raise error.InvalidRequestError( - "Could not determine which URL to request: %s instance " - "has invalid ID: %r, %s. ID should be of type `str` (or" - " `unicode`)" % (type(self).__name__, id, type(id)), - "id", - ) - api_version = self.api_version or openai.api_version - extn = quote_plus(id) - - if self.typed_api_type in (ApiType.AZURE, ApiType.AZURE_AD): - if not api_version: - raise error.InvalidRequestError( - "An API version is required for the Azure API type." - ) - - if not operation: - base = self.class_url() - return "/%s%s/%s?api-version=%s" % ( - self.azure_api_prefix, - base, - extn, - api_version, - ) - - return "/%s/%s/%s/%s?api-version=%s" % ( - self.azure_api_prefix, - self.azure_deployments_prefix, - extn, - operation, - api_version, - ) - - elif self.typed_api_type == ApiType.OPEN_AI: - base = self.class_url() - return "%s/%s" % (base, extn) - - else: - raise error.InvalidAPIType("Unsupported API type %s" % self.api_type) - - # The `method_` and `url_` arguments are suffixed with an underscore to - # avoid conflicting with actual request parameters in `params`. - @classmethod - def _static_request( - cls, - method_, - url_, - api_key=None, - api_base=None, - api_type=None, - request_id=None, - api_version=None, - organization=None, - **params, - ): - requestor = api_requestor.APIRequestor( - api_key, - api_version=api_version, - organization=organization, - api_base=api_base, - api_type=api_type, - ) - response, _, api_key = requestor.request( - method_, url_, params, request_id=request_id - ) - return util.convert_to_openai_object( - response, api_key, api_version, organization - ) - - @classmethod - async def _astatic_request( - cls, - method_, - url_, - api_key=None, - api_base=None, - api_type=None, - request_id=None, - api_version=None, - organization=None, - **params, - ): - requestor = api_requestor.APIRequestor( - api_key, - api_version=api_version, - organization=organization, - api_base=api_base, - api_type=api_type, - ) - response, _, api_key = await requestor.arequest( - method_, url_, params, request_id=request_id - ) - return response - - @classmethod - def _get_api_type_and_version( - cls, api_type: Optional[str] = None, api_version: Optional[str] = None - ): - typed_api_type = ( - ApiType.from_str(api_type) - if api_type - else ApiType.from_str(openai.api_type) - ) - typed_api_version = api_version or openai.api_version - return (typed_api_type, typed_api_version) diff --git a/openai/api_resources/abstract/createable_api_resource.py b/openai/api_resources/abstract/createable_api_resource.py deleted file mode 100644 index 1361c02627..0000000000 --- a/openai/api_resources/abstract/createable_api_resource.py +++ /dev/null @@ -1,98 +0,0 @@ -from openai import api_requestor, util, error -from openai.api_resources.abstract.api_resource import APIResource -from openai.util import ApiType - - -class CreateableAPIResource(APIResource): - plain_old_data = False - - @classmethod - def __prepare_create_requestor( - cls, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - ): - requestor = api_requestor.APIRequestor( - api_key, - api_base=api_base, - api_type=api_type, - api_version=api_version, - organization=organization, - ) - typed_api_type, api_version = cls._get_api_type_and_version( - api_type, api_version - ) - - 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) - elif typed_api_type == ApiType.OPEN_AI: - url = cls.class_url() - else: - raise error.InvalidAPIType("Unsupported API type %s" % api_type) - return requestor, url - - @classmethod - def create( - cls, - api_key=None, - api_base=None, - api_type=None, - request_id=None, - api_version=None, - organization=None, - **params, - ): - requestor, url = cls.__prepare_create_requestor( - api_key, - api_base, - api_type, - api_version, - organization, - ) - - response, _, api_key = requestor.request( - "post", url, params, request_id=request_id - ) - - return util.convert_to_openai_object( - response, - api_key, - api_version, - organization, - plain_old_data=cls.plain_old_data, - ) - - @classmethod - async def acreate( - cls, - api_key=None, - api_base=None, - api_type=None, - request_id=None, - api_version=None, - organization=None, - **params, - ): - requestor, url = cls.__prepare_create_requestor( - api_key, - api_base, - api_type, - api_version, - organization, - ) - - response, _, api_key = await requestor.arequest( - "post", url, params, request_id=request_id - ) - - return util.convert_to_openai_object( - response, - api_key, - api_version, - organization, - plain_old_data=cls.plain_old_data, - ) diff --git a/openai/api_resources/abstract/deletable_api_resource.py b/openai/api_resources/abstract/deletable_api_resource.py deleted file mode 100644 index a800ceb812..0000000000 --- a/openai/api_resources/abstract/deletable_api_resource.py +++ /dev/null @@ -1,48 +0,0 @@ -from urllib.parse import quote_plus -from typing import Awaitable - -from openai import error -from openai.api_resources.abstract.api_resource import APIResource -from openai.util import ApiType - - -class DeletableAPIResource(APIResource): - @classmethod - def __prepare_delete(cls, sid, api_type=None, api_version=None): - if isinstance(cls, APIResource): - raise ValueError(".delete may only be called as a class method now.") - - base = cls.class_url() - extn = quote_plus(sid) - - typed_api_type, api_version = cls._get_api_type_and_version( - 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, - ) - elif typed_api_type == ApiType.OPEN_AI: - url = "%s/%s" % (base, extn) - else: - raise error.InvalidAPIType("Unsupported API type %s" % api_type) - return url - - @classmethod - def delete(cls, sid, api_type=None, api_version=None, **params): - url = cls.__prepare_delete(sid, api_type, api_version) - - return cls._static_request( - "delete", url, api_type=api_type, api_version=api_version, **params - ) - - @classmethod - def adelete(cls, sid, api_type=None, api_version=None, **params) -> Awaitable: - url = cls.__prepare_delete(sid, api_type, api_version) - - return cls._astatic_request( - "delete", url, api_type=api_type, api_version=api_version, **params - ) diff --git a/openai/api_resources/abstract/engine_api_resource.py b/openai/api_resources/abstract/engine_api_resource.py deleted file mode 100644 index bbef90e23e..0000000000 --- a/openai/api_resources/abstract/engine_api_resource.py +++ /dev/null @@ -1,328 +0,0 @@ -import time -from pydoc import apropos -from typing import Optional -from urllib.parse import quote_plus - -import openai -from openai import api_requestor, error, util -from openai.api_resources.abstract.api_resource import APIResource -from openai.openai_response import OpenAIResponse -from openai.util import ApiType - -MAX_TIMEOUT = 20 - - -class EngineAPIResource(APIResource): - plain_old_data = False - - def __init__(self, engine: Optional[str] = None, **kwargs): - super().__init__(engine=engine, **kwargs) - - @classmethod - def class_url( - cls, - engine: Optional[str] = None, - api_type: Optional[str] = None, - api_version: Optional[str] = None, - ): - # 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 - typed_api_type, api_version = cls._get_api_type_and_version( - api_type, api_version - ) - - if typed_api_type in (ApiType.AZURE, ApiType.AZURE_AD): - if not api_version: - raise error.InvalidRequestError( - "An API version is required for the Azure API type.", - "api_version" - ) - if engine is None: - raise error.InvalidRequestError( - "You must provide the deployment name in the 'engine' parameter to access the Azure OpenAI service", - "engine" - ) - extn = quote_plus(engine) - return "/%s/%s/%s/%s?api-version=%s" % ( - cls.azure_api_prefix, - cls.azure_deployments_prefix, - extn, - base, - api_version, - ) - - elif typed_api_type == ApiType.OPEN_AI: - if engine is None: - return "/%s" % (base) - - extn = quote_plus(engine) - return "/engines/%s/%s" % (extn, base) - - else: - raise error.InvalidAPIType("Unsupported API type %s" % api_type) - - @classmethod - def __prepare_create_request( - cls, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - **params, - ): - deployment_id = params.pop("deployment_id", None) - engine = params.pop("engine", deployment_id) - model = params.get("model", None) - timeout = params.pop("timeout", None) - stream = params.get("stream", False) - headers = params.pop("headers", None) - request_timeout = params.pop("request_timeout", None) - typed_api_type = cls._get_api_type_and_version(api_type=api_type)[0] - 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, - "engine", - ) - - if timeout is None: - # No special timeout handling - pass - elif timeout > 0: - # API only supports timeouts up to MAX_TIMEOUT - params["timeout"] = min(timeout, MAX_TIMEOUT) - timeout = (timeout - params["timeout"]) or None - elif timeout == 0: - params["timeout"] = MAX_TIMEOUT - - requestor = api_requestor.APIRequestor( - api_key, - api_base=api_base, - api_type=api_type, - api_version=api_version, - organization=organization, - ) - url = cls.class_url(http://github.com/engine,%20api_type,%20api_version) - return ( - deployment_id, - engine, - timeout, - stream, - headers, - request_timeout, - typed_api_type, - requestor, - url, - params, - ) - - @classmethod - def create( - cls, - api_key=None, - api_base=None, - api_type=None, - request_id=None, - api_version=None, - organization=None, - **params, - ): - ( - deployment_id, - engine, - timeout, - stream, - headers, - request_timeout, - typed_api_type, - requestor, - url, - params, - ) = cls.__prepare_create_request( - api_key, api_base, api_type, api_version, organization, **params - ) - - response, _, api_key = requestor.request( - "post", - url, - params=params, - headers=headers, - stream=stream, - request_id=request_id, - request_timeout=request_timeout, - ) - - if stream: - # must be an iterator - assert not isinstance(response, OpenAIResponse) - return ( - util.convert_to_openai_object( - line, - api_key, - api_version, - organization, - engine=engine, - plain_old_data=cls.plain_old_data, - ) - for line in response - ) - else: - obj = util.convert_to_openai_object( - response, - api_key, - api_version, - organization, - engine=engine, - plain_old_data=cls.plain_old_data, - ) - - if timeout is not None: - obj.wait(timeout=timeout or None) - - return obj - - @classmethod - async def acreate( - cls, - api_key=None, - api_base=None, - api_type=None, - request_id=None, - api_version=None, - organization=None, - **params, - ): - ( - deployment_id, - engine, - timeout, - stream, - headers, - request_timeout, - typed_api_type, - requestor, - url, - params, - ) = cls.__prepare_create_request( - api_key, api_base, api_type, api_version, organization, **params - ) - response, _, api_key = await requestor.arequest( - "post", - url, - params=params, - headers=headers, - stream=stream, - request_id=request_id, - request_timeout=request_timeout, - ) - - if stream: - # must be an iterator - assert not isinstance(response, OpenAIResponse) - return ( - util.convert_to_openai_object( - line, - api_key, - api_version, - organization, - engine=engine, - plain_old_data=cls.plain_old_data, - ) - async for line in response - ) - else: - obj = util.convert_to_openai_object( - response, - api_key, - api_version, - organization, - engine=engine, - plain_old_data=cls.plain_old_data, - ) - - if timeout is not None: - await obj.await_(timeout=timeout or None) - - return obj - - def instance_url(http://github.com/self): - id = self.get("id") - - if not isinstance(id, str): - raise error.InvalidRequestError( - f"Could not determine which URL to request: {type(self).__name__} instance has invalid ID: {id}, {type(id)}. ID should be of type str.", - "id", - ) - - extn = quote_plus(id) - params_connector = "?" - - if self.typed_api_type in (ApiType.AZURE, ApiType.AZURE_AD): - api_version = self.api_version or openai.api_version - if not api_version: - raise error.InvalidRequestError( - "An API version is required for the Azure API type.", - "api_version" - ) - 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, - ) - params_connector = "&" - - elif self.typed_api_type == ApiType.OPEN_AI: - base = self.class_url(http://github.com/self.engine,%20self.api_type,%20self.api_version) - url = "%s/%s" % (base, extn) - - else: - raise error.InvalidAPIType("Unsupported API type %s" % self.api_type) - - timeout = self.get("timeout") - if timeout is not None: - timeout = quote_plus(str(timeout)) - url += params_connector + "timeout={}".format(timeout) - return url - - def wait(self, timeout=None): - start = time.time() - while self.status != "complete": - self.timeout = ( - min(timeout + start - time.time(), MAX_TIMEOUT) - if timeout is not None - else MAX_TIMEOUT - ) - if self.timeout < 0: - del self.timeout - break - self.refresh() - return self - - async def await_(self, timeout=None): - """Async version of `EngineApiResource.wait`""" - start = time.time() - while self.status != "complete": - self.timeout = ( - min(timeout + start - time.time(), MAX_TIMEOUT) - if timeout is not None - else MAX_TIMEOUT - ) - if self.timeout < 0: - del self.timeout - break - await self.arefresh() - return self diff --git a/openai/api_resources/abstract/listable_api_resource.py b/openai/api_resources/abstract/listable_api_resource.py deleted file mode 100644 index 3e59979f13..0000000000 --- a/openai/api_resources/abstract/listable_api_resource.py +++ /dev/null @@ -1,95 +0,0 @@ -from openai import api_requestor, util, error -from openai.api_resources.abstract.api_resource import APIResource -from openai.util import ApiType - - -class ListableAPIResource(APIResource): - @classmethod - def auto_paging_iter(cls, *args, **params): - return cls.list(*args, **params).auto_paging_iter() - - @classmethod - def __prepare_list_requestor( - cls, - api_key=None, - api_version=None, - organization=None, - api_base=None, - api_type=None, - ): - requestor = api_requestor.APIRequestor( - api_key, - api_base=api_base or cls.api_base(), - api_version=api_version, - api_type=api_type, - organization=organization, - ) - - typed_api_type, api_version = cls._get_api_type_and_version( - api_type, api_version - ) - - 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) - elif typed_api_type == ApiType.OPEN_AI: - url = cls.class_url() - else: - raise error.InvalidAPIType("Unsupported API type %s" % api_type) - return requestor, url - - @classmethod - def list( - cls, - api_key=None, - request_id=None, - api_version=None, - organization=None, - api_base=None, - api_type=None, - **params, - ): - requestor, url = cls.__prepare_list_requestor( - api_key, - api_version, - organization, - api_base, - api_type, - ) - - response, _, api_key = requestor.request( - "get", url, params, request_id=request_id - ) - openai_object = util.convert_to_openai_object( - response, api_key, api_version, organization - ) - openai_object._retrieve_params = params - return openai_object - - @classmethod - async def alist( - cls, - api_key=None, - request_id=None, - api_version=None, - organization=None, - api_base=None, - api_type=None, - **params, - ): - requestor, url = cls.__prepare_list_requestor( - api_key, - api_version, - organization, - api_base, - api_type, - ) - - response, _, api_key = await requestor.arequest( - "get", url, params, request_id=request_id - ) - openai_object = util.convert_to_openai_object( - response, api_key, api_version, organization - ) - openai_object._retrieve_params = params - return openai_object diff --git a/openai/api_resources/abstract/nested_resource_class_methods.py b/openai/api_resources/abstract/nested_resource_class_methods.py deleted file mode 100644 index 68197ab1fa..0000000000 --- a/openai/api_resources/abstract/nested_resource_class_methods.py +++ /dev/null @@ -1,169 +0,0 @@ -from urllib.parse import quote_plus - -from openai import api_requestor, util - - -def _nested_resource_class_methods( - resource, - path=None, - operations=None, - resource_plural=None, - async_=False, -): - if resource_plural is None: - resource_plural = "%ss" % resource - if path is None: - path = resource_plural - if operations is None: - raise ValueError("operations list required") - - def wrapper(cls): - def nested_resource_url(http://github.com/cls,%20id,%20nested_id=None): - url = "%s/%s/%s" % (cls.class_url(), quote_plus(id), quote_plus(path)) - if nested_id is not None: - url += "/%s" % quote_plus(nested_id) - return url - - resource_url_method = "%ss_url" % resource - setattr(cls, resource_url_method, classmethod(nested_resource_url)) - - def nested_resource_request( - cls, - method, - url, - api_base=None, - api_key=None, - request_id=None, - api_version=None, - organization=None, - **params, - ): - requestor = api_requestor.APIRequestor( - api_key, api_base=api_base, api_version=api_version, organization=organization - ) - response, _, api_key = requestor.request( - method, url, params, request_id=request_id - ) - return util.convert_to_openai_object( - response, api_key, api_version, organization - ) - - async def anested_resource_request( - cls, - method, - url, - api_key=None, - api_base=None, - request_id=None, - api_version=None, - organization=None, - **params, - ): - requestor = api_requestor.APIRequestor( - api_key, api_base=api_base, api_version=api_version, organization=organization - ) - response, _, api_key = await requestor.arequest( - method, url, params, request_id=request_id - ) - return util.convert_to_openai_object( - response, api_key, api_version, organization - ) - - resource_request_method = "%ss_request" % resource - setattr( - cls, - resource_request_method, - classmethod( - anested_resource_request if async_ else nested_resource_request - ), - ) - - for operation in operations: - if operation == "create": - - 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 - setattr(cls, create_method, classmethod(create_nested_resource)) - - elif operation == "retrieve": - - 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 - setattr(cls, retrieve_method, classmethod(retrieve_nested_resource)) - - elif operation == "update": - - 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 - setattr(cls, modify_method, classmethod(modify_nested_resource)) - - elif operation == "delete": - - def delete_nested_resource(cls, id, nested_id, **params): - url = getattr(cls, resource_url_method)(id, nested_id) - return getattr(cls, resource_request_method)( - "delete", url, **params - ) - - delete_method = "delete_%s" % resource - setattr(cls, delete_method, classmethod(delete_nested_resource)) - - elif operation == "list": - - 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 - setattr(cls, list_method, classmethod(list_nested_resources)) - - elif operation == "paginated_list": - - def paginated_list_nested_resources( - cls, id, limit=None, after=None, **params - ): - url = getattr(cls, resource_url_method)(id) - return getattr(cls, resource_request_method)( - "get", url, limit=limit, after=after, **params - ) - - list_method = "list_%s" % resource_plural - setattr(cls, list_method, classmethod(paginated_list_nested_resources)) - - else: - raise ValueError("Unknown operation: %s" % operation) - - return cls - - return wrapper - - -def nested_resource_class_methods( - resource, - path=None, - operations=None, - resource_plural=None, -): - return _nested_resource_class_methods( - resource, path, operations, resource_plural, async_=False - ) - - -def anested_resource_class_methods( - resource, - path=None, - operations=None, - resource_plural=None, -): - return _nested_resource_class_methods( - resource, path, operations, resource_plural, async_=True - ) diff --git a/openai/api_resources/abstract/paginatable_api_resource.py b/openai/api_resources/abstract/paginatable_api_resource.py deleted file mode 100644 index 2d75744f23..0000000000 --- a/openai/api_resources/abstract/paginatable_api_resource.py +++ /dev/null @@ -1,125 +0,0 @@ -from openai import api_requestor, error, util -from openai.api_resources.abstract.listable_api_resource import ListableAPIResource -from openai.util import ApiType - - -class PaginatableAPIResource(ListableAPIResource): - @classmethod - def auto_paging_iter(cls, *args, **params): - next_cursor = None - has_more = True - if not params.get("limit"): - params["limit"] = 20 - while has_more: - if next_cursor: - params["after"] = next_cursor - response = cls.list(*args, **params) - - for item in response.data: - yield item - - if response.data: - next_cursor = response.data[-1].id - has_more = response.has_more - - @classmethod - def __prepare_list_requestor( - cls, - api_key=None, - api_version=None, - organization=None, - api_base=None, - api_type=None, - ): - requestor = api_requestor.APIRequestor( - api_key, - api_base=api_base or cls.api_base(), - api_version=api_version, - api_type=api_type, - organization=organization, - ) - - typed_api_type, api_version = cls._get_api_type_and_version( - api_type, api_version - ) - - 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) - elif typed_api_type == ApiType.OPEN_AI: - url = cls.class_url() - else: - raise error.InvalidAPIType("Unsupported API type %s" % api_type) - return requestor, url - - @classmethod - def list( - cls, - limit=None, - starting_after=None, - api_key=None, - request_id=None, - api_version=None, - organization=None, - api_base=None, - api_type=None, - **params, - ): - requestor, url = cls.__prepare_list_requestor( - api_key, - api_version, - organization, - api_base, - api_type, - ) - - params = { - **params, - "limit": limit, - "starting_after": starting_after, - } - - response, _, api_key = requestor.request( - "get", url, params, request_id=request_id - ) - openai_object = util.convert_to_openai_object( - response, api_key, api_version, organization - ) - openai_object._retrieve_params = params - return openai_object - - @classmethod - async def alist( - cls, - limit=None, - starting_after=None, - api_key=None, - request_id=None, - api_version=None, - organization=None, - api_base=None, - api_type=None, - **params, - ): - requestor, url = cls.__prepare_list_requestor( - api_key, - api_version, - organization, - api_base, - api_type, - ) - - params = { - **params, - "limit": limit, - "starting_after": starting_after, - } - - response, _, api_key = await requestor.arequest( - "get", url, params, request_id=request_id - ) - openai_object = util.convert_to_openai_object( - response, api_key, api_version, organization - ) - openai_object._retrieve_params = params - return openai_object diff --git a/openai/api_resources/abstract/updateable_api_resource.py b/openai/api_resources/abstract/updateable_api_resource.py deleted file mode 100644 index 245f9b80b3..0000000000 --- a/openai/api_resources/abstract/updateable_api_resource.py +++ /dev/null @@ -1,16 +0,0 @@ -from urllib.parse import quote_plus -from typing import Awaitable - -from openai.api_resources.abstract.api_resource import APIResource - - -class UpdateableAPIResource(APIResource): - @classmethod - def modify(cls, sid, **params): - url = "%s/%s" % (cls.class_url(), quote_plus(sid)) - return cls._static_request("post", url, **params) - - @classmethod - def amodify(cls, sid, **params) -> Awaitable: - url = "%s/%s" % (cls.class_url(), quote_plus(sid)) - return cls._astatic_request("patch", url, **params) diff --git a/openai/api_resources/audio.py b/openai/api_resources/audio.py deleted file mode 100644 index cb316f07f1..0000000000 --- a/openai/api_resources/audio.py +++ /dev/null @@ -1,311 +0,0 @@ -from typing import Any, List - -import openai -from openai import api_requestor, util -from openai.api_resources.abstract import APIResource - - -class Audio(APIResource): - OBJECT_NAME = "audio" - - @classmethod - def _get_url(http://github.com/cls,%20action,%20deployment_id=None,%20api_type=None,%20api_version=None): - if api_type in (util.ApiType.AZURE, util.ApiType.AZURE_AD): - return f"/{cls.azure_api_prefix}/deployments/{deployment_id}/audio/{action}?api-version={api_version}" - return cls.class_url() + f"/{action}" - - @classmethod - def _prepare_request( - cls, - file, - filename, - model, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - **params, - ): - requestor = api_requestor.APIRequestor( - api_key, - api_base=api_base or openai.api_base, - api_type=api_type, - api_version=api_version, - organization=organization, - ) - files: List[Any] = [] - data = { - "model": model, - **params, - } - files.append(("file", (filename, file, "application/octet-stream"))) - return requestor, files, data - - @classmethod - def transcribe( - cls, - model, - file, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - *, - deployment_id=None, - **params, - ): - requestor, files, data = cls._prepare_request( - file=file, - filename=file.name, - model=model, - api_key=api_key, - api_base=api_base, - api_type=api_type, - api_version=api_version, - organization=organization, - **params, - ) - api_type, api_version = cls._get_api_type_and_version(api_type, api_version) - url = cls._get_url("http://github.com/transcriptions%22,%20deployment_id=deployment_id,%20api_type=api_type,%20api_version=api_version) - response, _, api_key = requestor.request("post", url, files=files, params=data) - return util.convert_to_openai_object( - response, api_key, api_version, organization - ) - - @classmethod - def translate( - cls, - model, - file, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - *, - deployment_id=None, - **params, - ): - requestor, files, data = cls._prepare_request( - file=file, - filename=file.name, - model=model, - api_key=api_key, - api_base=api_base, - api_type=api_type, - api_version=api_version, - organization=organization, - **params, - ) - api_type, api_version = cls._get_api_type_and_version(api_type, api_version) - url = cls._get_url("http://github.com/translations%22,%20deployment_id=deployment_id,%20api_type=api_type,%20api_version=api_version) - response, _, api_key = requestor.request("post", url, files=files, params=data) - return util.convert_to_openai_object( - response, api_key, api_version, organization - ) - - @classmethod - def transcribe_raw( - cls, - model, - file, - filename, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - *, - deployment_id=None, - **params, - ): - requestor, files, data = cls._prepare_request( - file=file, - filename=filename, - model=model, - api_key=api_key, - api_base=api_base, - api_type=api_type, - api_version=api_version, - organization=organization, - **params, - ) - api_type, api_version = cls._get_api_type_and_version(api_type, api_version) - url = cls._get_url("http://github.com/transcriptions%22,%20deployment_id=deployment_id,%20api_type=api_type,%20api_version=api_version) - response, _, api_key = requestor.request("post", url, files=files, params=data) - return util.convert_to_openai_object( - response, api_key, api_version, organization - ) - - @classmethod - def translate_raw( - cls, - model, - file, - filename, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - *, - deployment_id=None, - **params, - ): - requestor, files, data = cls._prepare_request( - file=file, - filename=filename, - model=model, - api_key=api_key, - api_base=api_base, - api_type=api_type, - api_version=api_version, - organization=organization, - **params, - ) - api_type, api_version = cls._get_api_type_and_version(api_type, api_version) - url = cls._get_url("http://github.com/translations%22,%20deployment_id=deployment_id,%20api_type=api_type,%20api_version=api_version) - response, _, api_key = requestor.request("post", url, files=files, params=data) - return util.convert_to_openai_object( - response, api_key, api_version, organization - ) - - @classmethod - async def atranscribe( - cls, - model, - file, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - *, - deployment_id=None, - **params, - ): - requestor, files, data = cls._prepare_request( - file=file, - filename=file.name, - model=model, - api_key=api_key, - api_base=api_base, - api_type=api_type, - api_version=api_version, - organization=organization, - **params, - ) - api_type, api_version = cls._get_api_type_and_version(api_type, api_version) - url = cls._get_url("http://github.com/transcriptions%22,%20deployment_id=deployment_id,%20api_type=api_type,%20api_version=api_version) - response, _, api_key = await requestor.arequest( - "post", url, files=files, params=data - ) - return util.convert_to_openai_object( - response, api_key, api_version, organization - ) - - @classmethod - async def atranslate( - cls, - model, - file, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - *, - deployment_id=None, - **params, - ): - requestor, files, data = cls._prepare_request( - file=file, - filename=file.name, - model=model, - api_key=api_key, - api_base=api_base, - api_type=api_type, - api_version=api_version, - organization=organization, - **params, - ) - api_type, api_version = cls._get_api_type_and_version(api_type, api_version) - url = cls._get_url("http://github.com/translations%22,%20deployment_id=deployment_id,%20api_type=api_type,%20api_version=api_version) - response, _, api_key = await requestor.arequest( - "post", url, files=files, params=data - ) - return util.convert_to_openai_object( - response, api_key, api_version, organization - ) - - @classmethod - async def atranscribe_raw( - cls, - model, - file, - filename, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - *, - deployment_id=None, - **params, - ): - requestor, files, data = cls._prepare_request( - file=file, - filename=filename, - model=model, - api_key=api_key, - api_base=api_base, - api_type=api_type, - api_version=api_version, - organization=organization, - **params, - ) - api_type, api_version = cls._get_api_type_and_version(api_type, api_version) - url = cls._get_url("http://github.com/transcriptions%22,%20deployment_id=deployment_id,%20api_type=api_type,%20api_version=api_version) - response, _, api_key = await requestor.arequest( - "post", url, files=files, params=data - ) - return util.convert_to_openai_object( - response, api_key, api_version, organization - ) - - @classmethod - async def atranslate_raw( - cls, - model, - file, - filename, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - *, - deployment_id=None, - **params, - ): - requestor, files, data = cls._prepare_request( - file=file, - filename=filename, - model=model, - api_key=api_key, - api_base=api_base, - api_type=api_type, - api_version=api_version, - organization=organization, - **params, - ) - api_type, api_version = cls._get_api_type_and_version(api_type, api_version) - url = cls._get_url("http://github.com/translations%22,%20deployment_id=deployment_id,%20api_type=api_type,%20api_version=api_version) - response, _, api_key = await requestor.arequest( - "post", url, files=files, params=data - ) - return util.convert_to_openai_object( - response, api_key, api_version, organization - ) diff --git a/openai/api_resources/chat_completion.py b/openai/api_resources/chat_completion.py deleted file mode 100644 index 7e55f9e38f..0000000000 --- a/openai/api_resources/chat_completion.py +++ /dev/null @@ -1,50 +0,0 @@ -import time - -from openai import util -from openai.api_resources.abstract.engine_api_resource import EngineAPIResource -from openai.error import TryAgain - - -class ChatCompletion(EngineAPIResource): - engine_required = False - OBJECT_NAME = "chat.completions" - - @classmethod - def create(cls, *args, **kwargs): - """ - Creates a new chat completion for the provided messages and parameters. - - See https://platform.openai.com/docs/api-reference/chat/create - for a list of valid parameters. - """ - start = time.time() - timeout = kwargs.pop("timeout", None) - - while True: - try: - return super().create(*args, **kwargs) - except TryAgain as e: - if timeout is not None and time.time() > start + timeout: - raise - - util.log_info("Waiting for model to warm up", error=e) - - @classmethod - async def acreate(cls, *args, **kwargs): - """ - Creates a new chat completion for the provided messages and parameters. - - See https://platform.openai.com/docs/api-reference/chat/create - for a list of valid parameters. - """ - start = time.time() - timeout = kwargs.pop("timeout", None) - - while True: - try: - return await super().acreate(*args, **kwargs) - except TryAgain as e: - if timeout is not None and time.time() > start + timeout: - raise - - util.log_info("Waiting for model to warm up", error=e) diff --git a/openai/api_resources/completion.py b/openai/api_resources/completion.py deleted file mode 100644 index 7b9c44bd08..0000000000 --- a/openai/api_resources/completion.py +++ /dev/null @@ -1,50 +0,0 @@ -import time - -from openai import util -from openai.api_resources.abstract import DeletableAPIResource, ListableAPIResource -from openai.api_resources.abstract.engine_api_resource import EngineAPIResource -from openai.error import TryAgain - - -class Completion(EngineAPIResource): - OBJECT_NAME = "completions" - - @classmethod - def create(cls, *args, **kwargs): - """ - Creates a new completion for the provided prompt and parameters. - - See https://platform.openai.com/docs/api-reference/completions/create for a list - of valid parameters. - """ - start = time.time() - timeout = kwargs.pop("timeout", None) - - while True: - try: - return super().create(*args, **kwargs) - except TryAgain as e: - if timeout is not None and time.time() > start + timeout: - raise - - util.log_info("Waiting for model to warm up", error=e) - - @classmethod - async def acreate(cls, *args, **kwargs): - """ - Creates a new completion for the provided prompt and parameters. - - See https://platform.openai.com/docs/api-reference/completions/create for a list - of valid parameters. - """ - start = time.time() - timeout = kwargs.pop("timeout", None) - - while True: - try: - return await super().acreate(*args, **kwargs) - except TryAgain as e: - if timeout is not None and time.time() > start + timeout: - raise - - util.log_info("Waiting for model to warm up", error=e) diff --git a/openai/api_resources/customer.py b/openai/api_resources/customer.py deleted file mode 100644 index 8690d07b38..0000000000 --- a/openai/api_resources/customer.py +++ /dev/null @@ -1,17 +0,0 @@ -from openai.openai_object import OpenAIObject - - -class Customer(OpenAIObject): - @classmethod - def get_url(http://github.com/cls,%20customer,%20endpoint): - return f"/customer/{customer}/{endpoint}" - - @classmethod - def create(cls, customer, endpoint, **params): - instance = cls() - return instance.request("post", cls.get_url(http://github.com/customer,%20endpoint), params) - - @classmethod - def acreate(cls, customer, endpoint, **params): - instance = cls() - return instance.arequest("post", cls.get_url(http://github.com/customer,%20endpoint), params) diff --git a/openai/api_resources/deployment.py b/openai/api_resources/deployment.py deleted file mode 100644 index 2f3fcd1307..0000000000 --- a/openai/api_resources/deployment.py +++ /dev/null @@ -1,119 +0,0 @@ -from openai import util -from openai.api_resources.abstract import ( - DeletableAPIResource, - ListableAPIResource, - CreateableAPIResource, -) -from openai.error import InvalidRequestError, APIError - - -class Deployment(CreateableAPIResource, ListableAPIResource, DeletableAPIResource): - OBJECT_NAME = "deployments" - - @classmethod - def _check_create(cls, *args, **kwargs): - typed_api_type, _ = cls._get_api_type_and_version( - kwargs.get("api_type", None), None - ) - if typed_api_type not in (util.ApiType.AZURE, util.ApiType.AZURE_AD): - raise APIError( - "Deployment operations are only available for the Azure API type." - ) - - if kwargs.get("model", None) is None: - raise InvalidRequestError( - "Must provide a 'model' parameter to create a Deployment.", - param="model", - ) - - scale_settings = kwargs.get("scale_settings", None) - if scale_settings is None: - raise InvalidRequestError( - "Must provide a 'scale_settings' parameter to create a Deployment.", - param="scale_settings", - ) - - if "scale_type" not in scale_settings or ( - scale_settings["scale_type"].lower() == "manual" - and "capacity" not in scale_settings - ): - raise InvalidRequestError( - "The 'scale_settings' parameter contains invalid or incomplete values.", - param="scale_settings", - ) - - @classmethod - def create(cls, *args, **kwargs): - """ - Creates a new deployment for the provided prompt and parameters. - """ - cls._check_create(*args, **kwargs) - return super().create(*args, **kwargs) - - @classmethod - def acreate(cls, *args, **kwargs): - """ - Creates a new deployment for the provided prompt and parameters. - """ - cls._check_create(*args, **kwargs) - return super().acreate(*args, **kwargs) - - @classmethod - def _check_list(cls, *args, **kwargs): - typed_api_type, _ = cls._get_api_type_and_version( - kwargs.get("api_type", None), None - ) - if typed_api_type not in (util.ApiType.AZURE, util.ApiType.AZURE_AD): - raise APIError( - "Deployment operations are only available for the Azure API type." - ) - - @classmethod - def list(cls, *args, **kwargs): - cls._check_list(*args, **kwargs) - return super().list(*args, **kwargs) - - @classmethod - def alist(cls, *args, **kwargs): - cls._check_list(*args, **kwargs) - return super().alist(*args, **kwargs) - - @classmethod - def _check_delete(cls, *args, **kwargs): - typed_api_type, _ = cls._get_api_type_and_version( - kwargs.get("api_type", None), None - ) - if typed_api_type not in (util.ApiType.AZURE, util.ApiType.AZURE_AD): - raise APIError( - "Deployment operations are only available for the Azure API type." - ) - - @classmethod - def delete(cls, *args, **kwargs): - cls._check_delete(*args, **kwargs) - return super().delete(*args, **kwargs) - - @classmethod - def adelete(cls, *args, **kwargs): - cls._check_delete(*args, **kwargs) - return super().adelete(*args, **kwargs) - - @classmethod - def _check_retrieve(cls, *args, **kwargs): - typed_api_type, _ = cls._get_api_type_and_version( - kwargs.get("api_type", None), None - ) - if typed_api_type not in (util.ApiType.AZURE, util.ApiType.AZURE_AD): - raise APIError( - "Deployment operations are only available for the Azure API type." - ) - - @classmethod - def retrieve(cls, *args, **kwargs): - cls._check_retrieve(*args, **kwargs) - return super().retrieve(*args, **kwargs) - - @classmethod - def aretrieve(cls, *args, **kwargs): - cls._check_retrieve(*args, **kwargs) - return super().aretrieve(*args, **kwargs) diff --git a/openai/api_resources/edit.py b/openai/api_resources/edit.py deleted file mode 100644 index 985f062ddb..0000000000 --- a/openai/api_resources/edit.py +++ /dev/null @@ -1,57 +0,0 @@ -import time - -from openai import util, error -from openai.api_resources.abstract.engine_api_resource import EngineAPIResource -from openai.error import TryAgain - - -class Edit(EngineAPIResource): - OBJECT_NAME = "edits" - - @classmethod - def create(cls, *args, **kwargs): - """ - Creates a new edit for the provided input, instruction, and parameters. - """ - start = time.time() - timeout = kwargs.pop("timeout", None) - - api_type = kwargs.pop("api_type", None) - typed_api_type = cls._get_api_type_and_version(api_type=api_type)[0] - if typed_api_type in (util.ApiType.AZURE, util.ApiType.AZURE_AD): - raise error.InvalidAPIType( - "This operation is not supported by the Azure OpenAI API yet." - ) - - while True: - try: - return super().create(*args, **kwargs) - except TryAgain as e: - if timeout is not None and time.time() > start + timeout: - raise - - util.log_info("Waiting for model to warm up", error=e) - - @classmethod - async def acreate(cls, *args, **kwargs): - """ - Creates a new edit for the provided input, instruction, and parameters. - """ - start = time.time() - timeout = kwargs.pop("timeout", None) - - api_type = kwargs.pop("api_type", None) - typed_api_type = cls._get_api_type_and_version(api_type=api_type)[0] - if typed_api_type in (util.ApiType.AZURE, util.ApiType.AZURE_AD): - raise error.InvalidAPIType( - "This operation is not supported by the Azure OpenAI API yet." - ) - - while True: - try: - return await super().acreate(*args, **kwargs) - except TryAgain as e: - if timeout is not None and time.time() > start + timeout: - raise - - util.log_info("Waiting for model to warm up", error=e) diff --git a/openai/api_resources/embedding.py b/openai/api_resources/embedding.py deleted file mode 100644 index e937636404..0000000000 --- a/openai/api_resources/embedding.py +++ /dev/null @@ -1,91 +0,0 @@ -import base64 -import time - -from openai import util -from openai.api_resources.abstract.engine_api_resource import EngineAPIResource -from openai.datalib.numpy_helper import assert_has_numpy -from openai.datalib.numpy_helper import numpy as np -from openai.error import TryAgain - - -class Embedding(EngineAPIResource): - OBJECT_NAME = "embeddings" - - @classmethod - def create(cls, *args, **kwargs): - """ - Creates a new embedding for the provided input and parameters. - - See https://platform.openai.com/docs/api-reference/embeddings for a list - of valid parameters. - """ - start = time.time() - timeout = kwargs.pop("timeout", None) - - user_provided_encoding_format = kwargs.get("encoding_format", None) - - # If encoding format was not explicitly specified, we opaquely use base64 for performance - if not user_provided_encoding_format: - kwargs["encoding_format"] = "base64" - - while True: - try: - response = super().create(*args, **kwargs) - - # If a user specifies base64, we'll just return the encoded string. - # This is only for the default case. - if not user_provided_encoding_format: - for data in response.data: - - # If an engine isn't using this optimization, don't do anything - if type(data["embedding"]) == str: - assert_has_numpy() - data["embedding"] = np.frombuffer( - base64.b64decode(data["embedding"]), dtype="float32" - ).tolist() - - return response - except TryAgain as e: - if timeout is not None and time.time() > start + timeout: - raise - - util.log_info("Waiting for model to warm up", error=e) - - @classmethod - async def acreate(cls, *args, **kwargs): - """ - Creates a new embedding for the provided input and parameters. - - See https://platform.openai.com/docs/api-reference/embeddings for a list - of valid parameters. - """ - start = time.time() - timeout = kwargs.pop("timeout", None) - - user_provided_encoding_format = kwargs.get("encoding_format", None) - - # If encoding format was not explicitly specified, we opaquely use base64 for performance - if not user_provided_encoding_format: - kwargs["encoding_format"] = "base64" - - while True: - try: - response = await super().acreate(*args, **kwargs) - - # If a user specifies base64, we'll just return the encoded string. - # This is only for the default case. - if not user_provided_encoding_format: - for data in response.data: - - # If an engine isn't using this optimization, don't do anything - if type(data["embedding"]) == str: - data["embedding"] = np.frombuffer( - base64.b64decode(data["embedding"]), dtype="float32" - ).tolist() - - return response - except TryAgain as e: - if timeout is not None and time.time() > start + timeout: - raise - - util.log_info("Waiting for model to warm up", error=e) diff --git a/openai/api_resources/engine.py b/openai/api_resources/engine.py deleted file mode 100644 index 5a0c467c2f..0000000000 --- a/openai/api_resources/engine.py +++ /dev/null @@ -1,50 +0,0 @@ -import time -import warnings - -from openai import util -from openai.api_resources.abstract import ListableAPIResource, UpdateableAPIResource -from openai.error import TryAgain - - -class Engine(ListableAPIResource, UpdateableAPIResource): - OBJECT_NAME = "engines" - - def generate(self, timeout=None, **params): - start = time.time() - while True: - try: - return self.request( - "post", - self.instance_url() + "/generate", - params, - stream=params.get("stream"), - plain_old_data=True, - ) - except TryAgain as e: - if timeout is not None and time.time() > start + timeout: - raise - - util.log_info("Waiting for model to warm up", error=e) - - async def agenerate(self, timeout=None, **params): - start = time.time() - while True: - try: - return await self.arequest( - "post", - self.instance_url() + "/generate", - params, - stream=params.get("stream"), - plain_old_data=True, - ) - except TryAgain as e: - if timeout is not None and time.time() > start + timeout: - raise - - util.log_info("Waiting for model to warm up", error=e) - - def embeddings(self, **params): - warnings.warn( - "Engine.embeddings is deprecated, use Embedding.create", DeprecationWarning - ) - return self.request("post", self.instance_url() + "/embeddings", params) diff --git a/openai/api_resources/error_object.py b/openai/api_resources/error_object.py deleted file mode 100644 index 555dc35237..0000000000 --- a/openai/api_resources/error_object.py +++ /dev/null @@ -1,28 +0,0 @@ -from typing import Optional - -from openai.openai_object import OpenAIObject -from openai.util import merge_dicts - - -class ErrorObject(OpenAIObject): - def refresh_from( - self, - values, - api_key=None, - api_version=None, - api_type=None, - organization=None, - response_ms: Optional[int] = None, - ): - # Unlike most other API resources, the API will omit attributes in - # error objects when they have a null value. We manually set default - # values here to facilitate generic error handling. - values = merge_dicts({"message": None, "type": None}, values) - return super(ErrorObject, self).refresh_from( - values=values, - api_key=api_key, - api_version=api_version, - api_type=api_type, - organization=organization, - response_ms=response_ms, - ) diff --git a/openai/api_resources/experimental/__init__.py b/openai/api_resources/experimental/__init__.py deleted file mode 100644 index d24c7b0cb5..0000000000 --- a/openai/api_resources/experimental/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from openai.api_resources.experimental.completion_config import ( # noqa: F401 - CompletionConfig, -) diff --git a/openai/api_resources/experimental/completion_config.py b/openai/api_resources/experimental/completion_config.py deleted file mode 100644 index 5d4feb40e1..0000000000 --- a/openai/api_resources/experimental/completion_config.py +++ /dev/null @@ -1,11 +0,0 @@ -from openai.api_resources.abstract import ( - CreateableAPIResource, - DeletableAPIResource, - ListableAPIResource, -) - - -class CompletionConfig( - CreateableAPIResource, ListableAPIResource, DeletableAPIResource -): - OBJECT_NAME = "experimental.completion_configs" diff --git a/openai/api_resources/file.py b/openai/api_resources/file.py deleted file mode 100644 index dba2ee92e1..0000000000 --- a/openai/api_resources/file.py +++ /dev/null @@ -1,279 +0,0 @@ -import json -import os -from typing import cast -import time - -import openai -from openai import api_requestor, util, error -from openai.api_resources.abstract import DeletableAPIResource, ListableAPIResource -from openai.util import ApiType - - -class File(ListableAPIResource, DeletableAPIResource): - OBJECT_NAME = "files" - - @classmethod - def __prepare_file_create( - cls, - file, - purpose, - model=None, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - user_provided_filename=None, - ): - requestor = api_requestor.APIRequestor( - api_key, - api_base=api_base or openai.api_base, - api_type=api_type, - api_version=api_version, - organization=organization, - ) - typed_api_type, api_version = cls._get_api_type_and_version( - api_type, api_version - ) - - 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) - elif typed_api_type == ApiType.OPEN_AI: - url = cls.class_url() - else: - raise error.InvalidAPIType("Unsupported API type %s" % api_type) - - # Set the filename on 'purpose' and 'model' to None so they are - # interpreted as form data. - files = [("purpose", (None, purpose))] - if model is not None: - files.append(("model", (None, model))) - if user_provided_filename is not None: - files.append( - ("file", (user_provided_filename, file, "application/octet-stream")) - ) - else: - files.append(("file", ("file", file, "application/octet-stream"))) - - return requestor, url, files - - @classmethod - def create( - cls, - file, - purpose, - model=None, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - user_provided_filename=None, - ): - requestor, url, files = cls.__prepare_file_create( - file, - purpose, - model, - api_key, - api_base, - api_type, - api_version, - organization, - user_provided_filename, - ) - response, _, api_key = requestor.request("post", url, files=files) - return util.convert_to_openai_object( - response, api_key, api_version, organization - ) - - @classmethod - async def acreate( - cls, - file, - purpose, - model=None, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - user_provided_filename=None, - ): - requestor, url, files = cls.__prepare_file_create( - file, - purpose, - model, - api_key, - api_base, - api_type, - api_version, - organization, - user_provided_filename, - ) - response, _, api_key = await requestor.arequest("post", url, files=files) - return util.convert_to_openai_object( - response, api_key, api_version, organization - ) - - @classmethod - def __prepare_file_download( - cls, - id, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - ): - requestor = api_requestor.APIRequestor( - api_key, - api_base=api_base or openai.api_base, - api_type=api_type, - api_version=api_version, - organization=organization, - ) - typed_api_type, api_version = cls._get_api_type_and_version( - api_type, api_version - ) - - if typed_api_type in (ApiType.AZURE, ApiType.AZURE_AD): - base = cls.class_url() - url = f"/{cls.azure_api_prefix}{base}/{id}/content?api-version={api_version}" - elif typed_api_type == ApiType.OPEN_AI: - url = f"{cls.class_url()}/{id}/content" - else: - raise error.InvalidAPIType("Unsupported API type %s" % api_type) - - return requestor, url - - @classmethod - def download( - cls, - id, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - ): - requestor, url = cls.__prepare_file_download( - id, api_key, api_base, api_type, api_version, organization - ) - - result = requestor.request_raw("get", url) - if not 200 <= result.status_code < 300: - raise requestor.handle_error_response( - result.content, - result.status_code, - json.loads(cast(bytes, result.content)), - result.headers, - stream_error=False, - ) - return result.content - - @classmethod - async def adownload( - cls, - id, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - ): - requestor, url = cls.__prepare_file_download( - id, api_key, api_base, api_type, api_version, organization - ) - - async with api_requestor.aiohttp_session() as session: - result = await requestor.arequest_raw("get", url, session) - if not 200 <= result.status < 300: - raise requestor.handle_error_response( - result.content, - result.status, - json.loads(cast(bytes, result.content)), - result.headers, - stream_error=False, - ) - return result.content - - @classmethod - def __find_matching_files(cls, name, bytes, all_files, purpose): - matching_files = [] - basename = os.path.basename(name) - for f in all_files: - if f["purpose"] != purpose: - continue - file_basename = os.path.basename(f["filename"]) - if file_basename != basename: - continue - if "bytes" in f and f["bytes"] != bytes: - continue - if "size" in f and int(f["size"]) != bytes: - continue - matching_files.append(f) - return matching_files - - @classmethod - def find_matching_files( - cls, - name, - bytes, - purpose, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - ): - """Find already uploaded files with the same name, size, and purpose.""" - all_files = cls.list( - api_key=api_key, - api_base=api_base or openai.api_base, - api_type=api_type, - api_version=api_version, - organization=organization, - ).get("data", []) - return cls.__find_matching_files(name, bytes, all_files, purpose) - - @classmethod - async def afind_matching_files( - cls, - name, - bytes, - purpose, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - ): - """Find already uploaded files with the same name, size, and purpose.""" - all_files = ( - await cls.alist( - api_key=api_key, - api_base=api_base or openai.api_base, - api_type=api_type, - api_version=api_version, - organization=organization, - ) - ).get("data", []) - return cls.__find_matching_files(name, bytes, all_files, purpose) - - @classmethod - def wait_for_processing(cls, id, max_wait_seconds=30 * 60): - TERMINAL_STATES = ["processed", "error", "deleted"] - - start = time.time() - file = cls.retrieve(id=id) - while file.status not in TERMINAL_STATES: - file = cls.retrieve(id=id) - time.sleep(5.0) - if time.time() - start > max_wait_seconds: - raise openai.error.OpenAIError( - message="Giving up on waiting for file {id} to finish processing after {max_wait_seconds} seconds.".format( - id=id, max_wait_seconds=max_wait_seconds - ) - ) - return file.status diff --git a/openai/api_resources/fine_tune.py b/openai/api_resources/fine_tune.py deleted file mode 100644 index 45e3cf2af3..0000000000 --- a/openai/api_resources/fine_tune.py +++ /dev/null @@ -1,204 +0,0 @@ -from urllib.parse import quote_plus - -from openai import api_requestor, util, error -from openai.api_resources.abstract import ( - CreateableAPIResource, - ListableAPIResource, - nested_resource_class_methods, -) -from openai.api_resources.abstract.deletable_api_resource import DeletableAPIResource -from openai.openai_response import OpenAIResponse -from openai.util import ApiType - - -@nested_resource_class_methods("event", operations=["list"]) -class FineTune(ListableAPIResource, CreateableAPIResource, DeletableAPIResource): - OBJECT_NAME = "fine-tunes" - - @classmethod - def _prepare_cancel( - cls, - id, - api_key=None, - api_type=None, - request_id=None, - api_version=None, - **params, - ): - base = cls.class_url() - extn = quote_plus(id) - - typed_api_type, api_version = cls._get_api_type_and_version( - api_type, api_version - ) - if typed_api_type in (ApiType.AZURE, ApiType.AZURE_AD): - url = "/%s%s/%s/cancel?api-version=%s" % ( - cls.azure_api_prefix, - base, - extn, - api_version, - ) - elif typed_api_type == ApiType.OPEN_AI: - url = "%s/%s/cancel" % (base, extn) - else: - raise error.InvalidAPIType("Unsupported API type %s" % api_type) - - instance = cls(id, api_key, **params) - return instance, url - - @classmethod - def cancel( - cls, - id, - api_key=None, - api_type=None, - request_id=None, - api_version=None, - **params, - ): - instance, url = cls._prepare_cancel( - id, - api_key, - api_type, - request_id, - api_version, - **params, - ) - return instance.request("post", url, request_id=request_id) - - @classmethod - def acancel( - cls, - id, - api_key=None, - api_type=None, - request_id=None, - api_version=None, - **params, - ): - instance, url = cls._prepare_cancel( - id, - api_key, - api_type, - request_id, - api_version, - **params, - ) - return instance.arequest("post", url, request_id=request_id) - - @classmethod - def _prepare_stream_events( - cls, - id, - api_key=None, - api_base=None, - api_type=None, - request_id=None, - api_version=None, - organization=None, - **params, - ): - base = cls.class_url() - extn = quote_plus(id) - - requestor = api_requestor.APIRequestor( - api_key, - api_base=api_base, - api_type=api_type, - api_version=api_version, - organization=organization, - ) - - typed_api_type, api_version = cls._get_api_type_and_version( - api_type, api_version - ) - - if typed_api_type in (ApiType.AZURE, ApiType.AZURE_AD): - url = "/%s%s/%s/events?stream=true&api-version=%s" % ( - cls.azure_api_prefix, - base, - extn, - api_version, - ) - elif typed_api_type == ApiType.OPEN_AI: - url = "%s/%s/events?stream=true" % (base, extn) - else: - raise error.InvalidAPIType("Unsupported API type %s" % api_type) - - return requestor, url - - @classmethod - def stream_events( - cls, - id, - api_key=None, - api_base=None, - api_type=None, - request_id=None, - api_version=None, - organization=None, - **params, - ): - requestor, url = cls._prepare_stream_events( - id, - api_key, - api_base, - api_type, - request_id, - api_version, - organization, - **params, - ) - - response, _, api_key = requestor.request( - "get", url, params, stream=True, request_id=request_id - ) - - assert not isinstance(response, OpenAIResponse) # must be an iterator - return ( - util.convert_to_openai_object( - line, - api_key, - api_version, - organization, - ) - for line in response - ) - - @classmethod - async def astream_events( - cls, - id, - api_key=None, - api_base=None, - api_type=None, - request_id=None, - api_version=None, - organization=None, - **params, - ): - requestor, url = cls._prepare_stream_events( - id, - api_key, - api_base, - api_type, - request_id, - api_version, - organization, - **params, - ) - - response, _, api_key = await requestor.arequest( - "get", url, params, stream=True, request_id=request_id - ) - - assert not isinstance(response, OpenAIResponse) # must be an iterator - return ( - util.convert_to_openai_object( - line, - api_key, - api_version, - organization, - ) - async for line in response - ) diff --git a/openai/api_resources/fine_tuning.py b/openai/api_resources/fine_tuning.py deleted file mode 100644 index f03be56ab7..0000000000 --- a/openai/api_resources/fine_tuning.py +++ /dev/null @@ -1,88 +0,0 @@ -from urllib.parse import quote_plus - -from openai import error -from openai.api_resources.abstract import ( - CreateableAPIResource, - PaginatableAPIResource, - nested_resource_class_methods, -) -from openai.api_resources.abstract.deletable_api_resource import DeletableAPIResource -from openai.util import ApiType - - -@nested_resource_class_methods("event", operations=["paginated_list"]) -class FineTuningJob( - PaginatableAPIResource, CreateableAPIResource, DeletableAPIResource -): - OBJECT_NAME = "fine_tuning.jobs" - - @classmethod - def _prepare_cancel( - cls, - id, - api_key=None, - api_type=None, - request_id=None, - api_version=None, - **params, - ): - base = cls.class_url() - extn = quote_plus(id) - - typed_api_type, api_version = cls._get_api_type_and_version( - api_type, api_version - ) - if typed_api_type in (ApiType.AZURE, ApiType.AZURE_AD): - url = "/%s%s/%s/cancel?api-version=%s" % ( - cls.azure_api_prefix, - base, - extn, - api_version, - ) - elif typed_api_type == ApiType.OPEN_AI: - url = "%s/%s/cancel" % (base, extn) - else: - raise error.InvalidAPIType("Unsupported API type %s" % api_type) - - instance = cls(id, api_key, **params) - return instance, url - - @classmethod - def cancel( - cls, - id, - api_key=None, - api_type=None, - request_id=None, - api_version=None, - **params, - ): - instance, url = cls._prepare_cancel( - id, - api_key, - api_type, - request_id, - api_version, - **params, - ) - return instance.request("post", url, request_id=request_id) - - @classmethod - def acancel( - cls, - id, - api_key=None, - api_type=None, - request_id=None, - api_version=None, - **params, - ): - instance, url = cls._prepare_cancel( - id, - api_key, - api_type, - request_id, - api_version, - **params, - ) - return instance.arequest("post", url, request_id=request_id) diff --git a/openai/api_resources/image.py b/openai/api_resources/image.py deleted file mode 100644 index 1522923510..0000000000 --- a/openai/api_resources/image.py +++ /dev/null @@ -1,273 +0,0 @@ -# WARNING: This interface is considered experimental and may changed in the future without warning. -from typing import Any, List - -import openai -from openai import api_requestor, error, util -from openai.api_resources.abstract import APIResource - - -class Image(APIResource): - OBJECT_NAME = "images" - - @classmethod - def _get_url(http://github.com/cls,%20action,%20azure_action,%20api_type,%20api_version): - if api_type in (util.ApiType.AZURE, util.ApiType.AZURE_AD) and azure_action is not None: - return f"/{cls.azure_api_prefix}{cls.class_url()}/{action}:{azure_action}?api-version={api_version}" - else: - return f"{cls.class_url()}/{action}" - - @classmethod - def create( - cls, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - **params, - ): - requestor = api_requestor.APIRequestor( - api_key, - api_base=api_base or openai.api_base, - api_type=api_type, - api_version=api_version, - organization=organization, - ) - - api_type, api_version = cls._get_api_type_and_version(api_type, api_version) - - response, _, api_key = requestor.request( - "post", cls._get_url("http://github.com/generations%22,%20azure_action=%22/service/http://github.com/submit%22,%20api_type=api_type,%20api_version=api_version), params - ) - - if api_type in (util.ApiType.AZURE, util.ApiType.AZURE_AD): - requestor.api_base = "" # operation_location is a full url - response, _, api_key = requestor._poll( - "get", response.operation_location, - until=lambda response: response.data['status'] in [ 'succeeded' ], - failed=lambda response: response.data['status'] in [ 'failed' ] - ) - - return util.convert_to_openai_object( - response, api_key, api_version, organization - ) - - @classmethod - async def acreate( - cls, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - **params, - ): - - requestor = api_requestor.APIRequestor( - api_key, - api_base=api_base or openai.api_base, - api_type=api_type, - api_version=api_version, - organization=organization, - ) - - api_type, api_version = cls._get_api_type_and_version(api_type, api_version) - - response, _, api_key = await requestor.arequest( - "post", cls._get_url("http://github.com/generations%22,%20azure_action=%22/service/http://github.com/submit%22,%20api_type=api_type,%20api_version=api_version), params - ) - - if api_type in (util.ApiType.AZURE, util.ApiType.AZURE_AD): - requestor.api_base = "" # operation_location is a full url - response, _, api_key = await requestor._apoll( - "get", response.operation_location, - until=lambda response: response.data['status'] in [ 'succeeded' ], - failed=lambda response: response.data['status'] in [ 'failed' ] - ) - - return util.convert_to_openai_object( - response, api_key, api_version, organization - ) - - @classmethod - def _prepare_create_variation( - cls, - image, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - **params, - ): - requestor = api_requestor.APIRequestor( - api_key, - api_base=api_base or openai.api_base, - api_type=api_type, - api_version=api_version, - organization=organization, - ) - api_type, api_version = cls._get_api_type_and_version(api_type, api_version) - - url = cls._get_url("http://github.com/variations%22,%20azure_action=None,%20api_type=api_type,%20api_version=api_version) - - files: List[Any] = [] - for key, value in params.items(): - files.append((key, (None, value))) - files.append(("image", ("image", image, "application/octet-stream"))) - return requestor, url, files - - @classmethod - def create_variation( - cls, - image, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - **params, - ): - if api_type in (util.ApiType.AZURE, util.ApiType.AZURE_AD): - raise error.InvalidAPIType("Variations are not supported by the Azure OpenAI API yet.") - - requestor, url, files = cls._prepare_create_variation( - image, - api_key, - api_base, - api_type, - api_version, - organization, - **params, - ) - - response, _, api_key = requestor.request("post", url, files=files) - - return util.convert_to_openai_object( - response, api_key, api_version, organization - ) - - @classmethod - async def acreate_variation( - cls, - image, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - **params, - ): - if api_type in (util.ApiType.AZURE, util.ApiType.AZURE_AD): - raise error.InvalidAPIType("Variations are not supported by the Azure OpenAI API yet.") - - requestor, url, files = cls._prepare_create_variation( - image, - api_key, - api_base, - api_type, - api_version, - organization, - **params, - ) - - response, _, api_key = await requestor.arequest("post", url, files=files) - - return util.convert_to_openai_object( - response, api_key, api_version, organization - ) - - @classmethod - def _prepare_create_edit( - cls, - image, - mask=None, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - **params, - ): - requestor = api_requestor.APIRequestor( - api_key, - api_base=api_base or openai.api_base, - api_type=api_type, - api_version=api_version, - organization=organization, - ) - api_type, api_version = cls._get_api_type_and_version(api_type, api_version) - - url = cls._get_url("http://github.com/edits%22,%20azure_action=None,%20api_type=api_type,%20api_version=api_version) - - files: List[Any] = [] - for key, value in params.items(): - files.append((key, (None, value))) - files.append(("image", ("image", image, "application/octet-stream"))) - if mask is not None: - files.append(("mask", ("mask", mask, "application/octet-stream"))) - return requestor, url, files - - @classmethod - def create_edit( - cls, - image, - mask=None, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - **params, - ): - if api_type in (util.ApiType.AZURE, util.ApiType.AZURE_AD): - raise error.InvalidAPIType("Edits are not supported by the Azure OpenAI API yet.") - - requestor, url, files = cls._prepare_create_edit( - image, - mask, - api_key, - api_base, - api_type, - api_version, - organization, - **params, - ) - - response, _, api_key = requestor.request("post", url, files=files) - - return util.convert_to_openai_object( - response, api_key, api_version, organization - ) - - @classmethod - async def acreate_edit( - cls, - image, - mask=None, - api_key=None, - api_base=None, - api_type=None, - api_version=None, - organization=None, - **params, - ): - if api_type in (util.ApiType.AZURE, util.ApiType.AZURE_AD): - raise error.InvalidAPIType("Edits are not supported by the Azure OpenAI API yet.") - - requestor, url, files = cls._prepare_create_edit( - image, - mask, - api_key, - api_base, - api_type, - api_version, - organization, - **params, - ) - - response, _, api_key = await requestor.arequest("post", url, files=files) - - return util.convert_to_openai_object( - response, api_key, api_version, organization - ) diff --git a/openai/api_resources/model.py b/openai/api_resources/model.py deleted file mode 100644 index 9785e17fe1..0000000000 --- a/openai/api_resources/model.py +++ /dev/null @@ -1,5 +0,0 @@ -from openai.api_resources.abstract import DeletableAPIResource, ListableAPIResource - - -class Model(ListableAPIResource, DeletableAPIResource): - OBJECT_NAME = "models" diff --git a/openai/api_resources/moderation.py b/openai/api_resources/moderation.py deleted file mode 100644 index bd19646b49..0000000000 --- a/openai/api_resources/moderation.py +++ /dev/null @@ -1,45 +0,0 @@ -from typing import List, Optional, Union - -from openai.openai_object import OpenAIObject - - -class Moderation(OpenAIObject): - VALID_MODEL_NAMES: List[str] = ["text-moderation-stable", "text-moderation-latest"] - - @classmethod - def get_url(http://github.com/cls): - return "/moderations" - - @classmethod - def _prepare_create(cls, input, model, api_key): - if model is not None and model not in cls.VALID_MODEL_NAMES: - raise ValueError( - f"The parameter model should be chosen from {cls.VALID_MODEL_NAMES} " - f"and it is default to be None." - ) - - instance = cls(api_key=api_key) - params = {"input": input} - if model is not None: - params["model"] = model - return instance, params - - @classmethod - def create( - cls, - input: Union[str, List[str]], - model: Optional[str] = None, - api_key: Optional[str] = None, - ): - instance, params = cls._prepare_create(input, model, api_key) - return instance.request("post", cls.get_url(), params) - - @classmethod - def acreate( - cls, - input: Union[str, List[str]], - model: Optional[str] = None, - api_key: Optional[str] = None, - ): - instance, params = cls._prepare_create(input, model, api_key) - return instance.arequest("post", cls.get_url(), params) diff --git a/openai/cli.py b/openai/cli.py deleted file mode 100644 index a6e99396ae..0000000000 --- a/openai/cli.py +++ /dev/null @@ -1,1416 +0,0 @@ -import datetime -import os -import signal -import sys -import warnings -from typing import Optional - -import requests - -import openai -from openai.upload_progress import BufferReader -from openai.validators import ( - apply_necessary_remediation, - apply_validators, - get_validators, - read_any_format, - write_out_file, -) - - -class bcolors: - HEADER = "\033[95m" - OKBLUE = "\033[94m" - OKGREEN = "\033[92m" - WARNING = "\033[93m" - FAIL = "\033[91m" - ENDC = "\033[0m" - BOLD = "\033[1m" - UNDERLINE = "\033[4m" - - -def organization_info(obj): - organization = getattr(obj, "organization", None) - if organization is not None: - return "[organization={}] ".format(organization) - else: - return "" - - -def display(obj): - sys.stderr.write(organization_info(obj)) - sys.stderr.flush() - print(obj) - - -def display_error(e): - extra = ( - " (HTTP status code: {})".format(e.http_status) - if e.http_status is not None - else "" - ) - sys.stderr.write( - "{}{}Error:{} {}{}\n".format( - organization_info(e), bcolors.FAIL, bcolors.ENDC, e, extra - ) - ) - - -class Engine: - @classmethod - def get(cls, args): - engine = openai.Engine.retrieve(id=args.id) - display(engine) - - @classmethod - def update(cls, args): - engine = openai.Engine.modify(args.id, replicas=args.replicas) - display(engine) - - @classmethod - def generate(cls, args): - warnings.warn( - "Engine.generate is deprecated, use Completion.create", DeprecationWarning - ) - if args.completions and args.completions > 1 and args.stream: - raise ValueError("Can't stream multiple completions with openai CLI") - - kwargs = {} - if args.model is not None: - kwargs["model"] = args.model - resp = openai.Engine(id=args.id).generate( - completions=args.completions, - context=args.context, - length=args.length, - stream=args.stream, - temperature=args.temperature, - top_p=args.top_p, - logprobs=args.logprobs, - stop=args.stop, - **kwargs, - ) - if not args.stream: - resp = [resp] - - for part in resp: - completions = len(part["data"]) - for c_idx, c in enumerate(part["data"]): - if completions > 1: - sys.stdout.write("===== Completion {} =====\n".format(c_idx)) - sys.stdout.write("".join(c["text"])) - if completions > 1: - sys.stdout.write("\n") - sys.stdout.flush() - - @classmethod - def list(cls, args): - engines = openai.Engine.list() - display(engines) - - -class ChatCompletion: - @classmethod - def create(cls, args): - if args.n is not None and args.n > 1 and args.stream: - raise ValueError( - "Can't stream chat completions with n>1 with the current CLI" - ) - - messages = [ - {"role": role, "content": content} for role, content in args.message - ] - - resp = openai.ChatCompletion.create( - # Required - model=args.model, - engine=args.engine, - messages=messages, - # Optional - n=args.n, - max_tokens=args.max_tokens, - temperature=args.temperature, - top_p=args.top_p, - stop=args.stop, - stream=args.stream, - ) - if not args.stream: - resp = [resp] - - for part in resp: - choices = part["choices"] - for c_idx, c in enumerate(sorted(choices, key=lambda s: s["index"])): - if len(choices) > 1: - sys.stdout.write("===== Chat Completion {} =====\n".format(c_idx)) - if args.stream: - delta = c["delta"] - if "content" in delta: - sys.stdout.write(delta["content"]) - else: - sys.stdout.write(c["message"]["content"]) - if len(choices) > 1: # not in streams - sys.stdout.write("\n") - sys.stdout.flush() - - -class Completion: - @classmethod - def create(cls, args): - if args.n is not None and args.n > 1 and args.stream: - raise ValueError("Can't stream completions with n>1 with the current CLI") - - if args.engine and args.model: - warnings.warn( - "In most cases, you should not be specifying both engine and model." - ) - - resp = openai.Completion.create( - engine=args.engine, - model=args.model, - n=args.n, - max_tokens=args.max_tokens, - logprobs=args.logprobs, - prompt=args.prompt, - stream=args.stream, - temperature=args.temperature, - top_p=args.top_p, - stop=args.stop, - echo=True, - ) - if not args.stream: - resp = [resp] - - for part in resp: - choices = part["choices"] - for c_idx, c in enumerate(sorted(choices, key=lambda s: s["index"])): - if len(choices) > 1: - sys.stdout.write("===== Completion {} =====\n".format(c_idx)) - sys.stdout.write(c["text"]) - if len(choices) > 1: - sys.stdout.write("\n") - sys.stdout.flush() - - -class Deployment: - @classmethod - def get(cls, args): - resp = openai.Deployment.retrieve(id=args.id) - print(resp) - - @classmethod - def delete(cls, args): - model = openai.Deployment.delete(args.id) - print(model) - - @classmethod - def list(cls, args): - models = openai.Deployment.list() - print(models) - - @classmethod - def create(cls, args): - models = openai.Deployment.create( - model=args.model, scale_settings={"scale_type": args.scale_type} - ) - print(models) - - -class Model: - @classmethod - def get(cls, args): - resp = openai.Model.retrieve(id=args.id) - print(resp) - - @classmethod - def delete(cls, args): - model = openai.Model.delete(args.id) - print(model) - - @classmethod - def list(cls, args): - models = openai.Model.list() - print(models) - - -class File: - @classmethod - def create(cls, args): - with open(args.file, "rb") as file_reader: - buffer_reader = BufferReader(file_reader.read(), desc="Upload progress") - resp = openai.File.create( - file=buffer_reader, - purpose=args.purpose, - user_provided_filename=args.file, - ) - print(resp) - - @classmethod - def get(cls, args): - resp = openai.File.retrieve(id=args.id) - print(resp) - - @classmethod - def delete(cls, args): - file = openai.File.delete(args.id) - print(file) - - @classmethod - def list(cls, args): - file = openai.File.list() - print(file) - - -class Image: - @classmethod - def create(cls, args): - resp = openai.Image.create( - prompt=args.prompt, - size=args.size, - n=args.num_images, - response_format=args.response_format, - ) - print(resp) - - @classmethod - def create_variation(cls, args): - with open(args.image, "rb") as file_reader: - buffer_reader = BufferReader(file_reader.read(), desc="Upload progress") - resp = openai.Image.create_variation( - image=buffer_reader, - size=args.size, - n=args.num_images, - response_format=args.response_format, - ) - print(resp) - - @classmethod - def create_edit(cls, args): - with open(args.image, "rb") as file_reader: - image_reader = BufferReader(file_reader.read(), desc="Upload progress") - mask_reader = None - if args.mask is not None: - with open(args.mask, "rb") as file_reader: - mask_reader = BufferReader(file_reader.read(), desc="Upload progress") - resp = openai.Image.create_edit( - image=image_reader, - mask=mask_reader, - prompt=args.prompt, - size=args.size, - n=args.num_images, - response_format=args.response_format, - ) - print(resp) - - -class Audio: - @classmethod - def transcribe(cls, args): - with open(args.file, "rb") as r: - file_reader = BufferReader(r.read(), desc="Upload progress") - - resp = openai.Audio.transcribe_raw( - # Required - model=args.model, - file=file_reader, - filename=args.file, - # Optional - response_format=args.response_format, - language=args.language, - temperature=args.temperature, - prompt=args.prompt, - ) - print(resp) - - @classmethod - def translate(cls, args): - with open(args.file, "rb") as r: - file_reader = BufferReader(r.read(), desc="Upload progress") - resp = openai.Audio.translate_raw( - # Required - model=args.model, - file=file_reader, - filename=args.file, - # Optional - response_format=args.response_format, - language=args.language, - temperature=args.temperature, - prompt=args.prompt, - ) - print(resp) - - -class FineTune: - @classmethod - def list(cls, args): - resp = openai.FineTune.list() - print(resp) - - @classmethod - def _is_url(http://github.com/cls,%20file:%20str): - return file.lower().startswith("http") - - @classmethod - def _download_file_from_public_url(http://github.com/cls,%20url:%20str) -> Optional[bytes]: - resp = requests.get(url) - if resp.status_code == 200: - return resp.content - else: - return None - - @classmethod - def _maybe_upload_file( - cls, - file: Optional[str] = None, - content: Optional[bytes] = None, - user_provided_file: Optional[str] = None, - check_if_file_exists: bool = True, - ): - # Exactly one of `file` or `content` must be provided - if (file is None) == (content is None): - raise ValueError("Exactly one of `file` or `content` must be provided") - - if content is None: - assert file is not None - with open(file, "rb") as f: - content = f.read() - - if check_if_file_exists: - bytes = len(content) - matching_files = openai.File.find_matching_files( - name=user_provided_file or f.name, bytes=bytes, purpose="fine-tune" - ) - if len(matching_files) > 0: - file_ids = [f["id"] for f in matching_files] - sys.stdout.write( - "Found potentially duplicated files with name '{name}', purpose 'fine-tune' and size {size} bytes\n".format( - name=os.path.basename(matching_files[0]["filename"]), - size=matching_files[0]["bytes"] - if "bytes" in matching_files[0] - else matching_files[0]["size"], - ) - ) - sys.stdout.write("\n".join(file_ids)) - while True: - sys.stdout.write( - "\nEnter file ID to reuse an already uploaded file, or an empty string to upload this file anyway: " - ) - inp = sys.stdin.readline().strip() - if inp in file_ids: - sys.stdout.write( - "Reusing already uploaded file: {id}\n".format(id=inp) - ) - return inp - elif inp == "": - break - else: - sys.stdout.write( - "File id '{id}' is not among the IDs of the potentially duplicated files\n".format( - id=inp - ) - ) - - buffer_reader = BufferReader(content, desc="Upload progress") - resp = openai.File.create( - file=buffer_reader, - purpose="fine-tune", - user_provided_filename=user_provided_file or file, - ) - sys.stdout.write( - "Uploaded file from {file}: {id}\n".format( - file=user_provided_file or file, id=resp["id"] - ) - ) - return resp["id"] - - @classmethod - def _get_or_upload(cls, file, check_if_file_exists=True): - try: - # 1. If it's a valid file, use it - openai.File.retrieve(file) - return file - except openai.error.InvalidRequestError: - pass - if os.path.isfile(file): - # 2. If it's a file on the filesystem, upload it - return cls._maybe_upload_file( - file=file, check_if_file_exists=check_if_file_exists - ) - if cls._is_url(http://github.com/file): - # 3. If it's a URL, download it temporarily - content = cls._download_file_from_public_url(http://github.com/file) - if content is not None: - return cls._maybe_upload_file( - content=content, - check_if_file_exists=check_if_file_exists, - user_provided_file=file, - ) - return file - - @classmethod - def create(cls, args): - create_args = { - "training_file": cls._get_or_upload( - args.training_file, args.check_if_files_exist - ), - } - if args.validation_file: - create_args["validation_file"] = cls._get_or_upload( - args.validation_file, args.check_if_files_exist - ) - - for hparam in ( - "model", - "suffix", - "n_epochs", - "batch_size", - "learning_rate_multiplier", - "prompt_loss_weight", - "compute_classification_metrics", - "classification_n_classes", - "classification_positive_class", - "classification_betas", - ): - attr = getattr(args, hparam) - if attr is not None: - create_args[hparam] = attr - - resp = openai.FineTune.create(**create_args) - - if args.no_follow: - print(resp) - return - - sys.stdout.write( - "Created fine-tune: {job_id}\n" - "Streaming events until fine-tuning is complete...\n\n" - "(Ctrl-C will interrupt the stream, but not cancel the fine-tune)\n".format( - job_id=resp["id"] - ) - ) - cls._stream_events(resp["id"]) - - @classmethod - def get(cls, args): - resp = openai.FineTune.retrieve(id=args.id) - print(resp) - - @classmethod - def results(cls, args): - fine_tune = openai.FineTune.retrieve(id=args.id) - if "result_files" not in fine_tune or len(fine_tune["result_files"]) == 0: - raise openai.error.InvalidRequestError( - f"No results file available for fine-tune {args.id}", "id" - ) - result_file = openai.FineTune.retrieve(id=args.id)["result_files"][0] - resp = openai.File.download(id=result_file["id"]) - print(resp.decode("utf-8")) - - @classmethod - def events(cls, args): - if args.stream: - raise openai.error.OpenAIError( - message=( - "The --stream parameter is deprecated, use fine_tunes.follow " - "instead:\n\n" - " openai api fine_tunes.follow -i {id}\n".format(id=args.id) - ), - ) - - resp = openai.FineTune.list_events(id=args.id) # type: ignore - print(resp) - - @classmethod - def follow(cls, args): - cls._stream_events(args.id) - - @classmethod - def _stream_events(cls, job_id): - def signal_handler(sig, frame): - status = openai.FineTune.retrieve(job_id).status - sys.stdout.write( - "\nStream interrupted. Job is still {status}.\n" - "To resume the stream, run:\n\n" - " openai api fine_tunes.follow -i {job_id}\n\n" - "To cancel your job, run:\n\n" - " openai api fine_tunes.cancel -i {job_id}\n\n".format( - status=status, job_id=job_id - ) - ) - sys.exit(0) - - signal.signal(signal.SIGINT, signal_handler) - - events = openai.FineTune.stream_events(job_id) - # TODO(rachel): Add a nifty spinner here. - try: - for event in events: - sys.stdout.write( - "[%s] %s" - % ( - datetime.datetime.fromtimestamp(event["created_at"]), - event["message"], - ) - ) - sys.stdout.write("\n") - sys.stdout.flush() - except Exception: - sys.stdout.write( - "\nStream interrupted (client disconnected).\n" - "To resume the stream, run:\n\n" - " openai api fine_tunes.follow -i {job_id}\n\n".format(job_id=job_id) - ) - return - - resp = openai.FineTune.retrieve(id=job_id) - status = resp["status"] - if status == "succeeded": - sys.stdout.write("\nJob complete! Status: succeeded 🎉") - sys.stdout.write( - "\nTry out your fine-tuned model:\n\n" - "openai api completions.create -m {model} -p ".format( - model=resp["fine_tuned_model"] - ) - ) - elif status == "failed": - sys.stdout.write( - "\nJob failed. Please contact us through our help center at help.openai.com if you need assistance." - ) - sys.stdout.write("\n") - - @classmethod - def cancel(cls, args): - resp = openai.FineTune.cancel(id=args.id) - print(resp) - - @classmethod - def delete(cls, args): - resp = openai.FineTune.delete(sid=args.id) - print(resp) - - @classmethod - def prepare_data(cls, args): - sys.stdout.write("Analyzing...\n") - fname = args.file - auto_accept = args.quiet - df, remediation = read_any_format(fname) - apply_necessary_remediation(None, remediation) - - validators = get_validators() - - apply_validators( - df, - fname, - remediation, - validators, - auto_accept, - write_out_file_func=write_out_file, - ) - - -class FineTuningJob: - @classmethod - def list(cls, args): - has_ft_jobs = False - for fine_tune_job in openai.FineTuningJob.auto_paging_iter(): - has_ft_jobs = True - print(fine_tune_job) - if not has_ft_jobs: - print("No fine-tuning jobs found.") - - @classmethod - def _is_url(http://github.com/cls,%20file:%20str): - return file.lower().startswith("http") - - @classmethod - def _download_file_from_public_url(http://github.com/cls,%20url:%20str) -> Optional[bytes]: - resp = requests.get(url) - if resp.status_code == 200: - return resp.content - else: - return None - - @classmethod - def _maybe_upload_file( - cls, - file: Optional[str] = None, - content: Optional[bytes] = None, - user_provided_file: Optional[str] = None, - check_if_file_exists: bool = True, - ): - # Exactly one of `file` or `content` must be provided - if (file is None) == (content is None): - raise ValueError("Exactly one of `file` or `content` must be provided") - - if content is None: - assert file is not None - with open(file, "rb") as f: - content = f.read() - - if check_if_file_exists: - bytes = len(content) - matching_files = openai.File.find_matching_files( - name=user_provided_file or f.name, - bytes=bytes, - purpose="fine-tune", - ) - if len(matching_files) > 0: - file_ids = [f["id"] for f in matching_files] - sys.stdout.write( - "Found potentially duplicated files with name '{name}', purpose 'fine-tune', and size {size} bytes\n".format( - name=os.path.basename(matching_files[0]["filename"]), - size=matching_files[0]["bytes"] - if "bytes" in matching_files[0] - else matching_files[0]["size"], - ) - ) - sys.stdout.write("\n".join(file_ids)) - while True: - sys.stdout.write( - "\nEnter file ID to reuse an already uploaded file, or an empty string to upload this file anyway: " - ) - inp = sys.stdin.readline().strip() - if inp in file_ids: - sys.stdout.write( - "Reusing already uploaded file: {id}\n".format(id=inp) - ) - return inp - elif inp == "": - break - else: - sys.stdout.write( - "File id '{id}' is not among the IDs of the potentially duplicated files\n".format( - id=inp - ) - ) - - buffer_reader = BufferReader(content, desc="Upload progress") - resp = openai.File.create( - file=buffer_reader, - purpose="fine-tune", - user_provided_filename=user_provided_file or file, - ) - sys.stdout.write( - "Uploaded file from {file}: {id}\n".format( - file=user_provided_file or file, id=resp["id"] - ) - ) - sys.stdout.write("Waiting for file to finish processing before proceeding..\n") - sys.stdout.flush() - status = openai.File.wait_for_processing(resp["id"]) - if status != "processed": - raise openai.error.OpenAIError( - "File {id} failed to process, status={status}.".format( - id=resp["id"], status=status - ) - ) - - sys.stdout.write( - "File {id} finished processing and is ready for use in fine-tuning".format( - id=resp["id"] - ) - ) - sys.stdout.flush() - return resp["id"] - - @classmethod - def _get_or_upload(cls, file, check_if_file_exists=True): - try: - # 1. If it's a valid file, use it - openai.File.retrieve(file) - return file - except openai.error.InvalidRequestError: - pass - if os.path.isfile(file): - # 2. If it's a file on the filesystem, upload it - return cls._maybe_upload_file( - file=file, check_if_file_exists=check_if_file_exists - ) - if cls._is_url(http://github.com/file): - # 3. If it's a URL, download it temporarily - content = cls._download_file_from_public_url(http://github.com/file) - if content is not None: - return cls._maybe_upload_file( - content=content, - check_if_file_exists=check_if_file_exists, - user_provided_file=file, - ) - return file - - @classmethod - def create(cls, args): - create_args = { - "training_file": cls._get_or_upload( - args.training_file, args.check_if_files_exist - ), - } - if args.validation_file: - create_args["validation_file"] = cls._get_or_upload( - args.validation_file, args.check_if_files_exist - ) - - for param in ("model", "suffix"): - attr = getattr(args, param) - if attr is not None: - create_args[param] = attr - - if getattr(args, "n_epochs"): - create_args["hyperparameters"] = { - "n_epochs": args.n_epochs, - } - - resp = openai.FineTuningJob.create(**create_args) - print(resp) - return - - @classmethod - def get(cls, args): - resp = openai.FineTuningJob.retrieve(id=args.id) - print(resp) - - @classmethod - def results(cls, args): - fine_tune = openai.FineTuningJob.retrieve(id=args.id) - if "result_files" not in fine_tune or len(fine_tune["result_files"]) == 0: - raise openai.error.InvalidRequestError( - f"No results file available for fine-tune {args.id}", "id" - ) - result_file = openai.FineTuningJob.retrieve(id=args.id)["result_files"][0] - resp = openai.File.download(id=result_file) - print(resp.decode("utf-8")) - - @classmethod - def events(cls, args): - seen, has_more, after = 0, True, None - while has_more: - resp = openai.FineTuningJob.list_events(id=args.id, after=after) # type: ignore - for event in resp["data"]: - print(event) - seen += 1 - if args.limit is not None and seen >= args.limit: - return - has_more = resp.get("has_more", False) - if resp["data"]: - after = resp["data"][-1]["id"] - - @classmethod - def follow(cls, args): - raise openai.error.OpenAIError( - message="Event streaming is not yet supported for `fine_tuning.job` events" - ) - - @classmethod - def cancel(cls, args): - resp = openai.FineTuningJob.cancel(id=args.id) - print(resp) - - -class WandbLogger: - @classmethod - def sync(cls, args): - import openai.wandb_logger - - resp = openai.wandb_logger.WandbLogger.sync( - id=args.id, - n_fine_tunes=args.n_fine_tunes, - project=args.project, - entity=args.entity, - force=args.force, - ) - print(resp) - - -def tools_register(parser): - subparsers = parser.add_subparsers( - title="Tools", help="Convenience client side tools" - ) - - def help(args): - parser.print_help() - - parser.set_defaults(func=help) - - sub = subparsers.add_parser("fine_tunes.prepare_data") - sub.add_argument( - "-f", - "--file", - required=True, - help="JSONL, JSON, CSV, TSV, TXT or XLSX file containing prompt-completion examples to be analyzed." - "This should be the local file path.", - ) - sub.add_argument( - "-q", - "--quiet", - required=False, - action="http://github.com/store_true", - help="Auto accepts all suggestions, without asking for user input. To be used within scripts.", - ) - sub.set_defaults(func=FineTune.prepare_data) - - -def api_register(parser): - # Engine management - subparsers = parser.add_subparsers(help="All API subcommands") - - def help(args): - parser.print_help() - - parser.set_defaults(func=help) - - sub = subparsers.add_parser("engines.list") - sub.set_defaults(func=Engine.list) - - sub = subparsers.add_parser("engines.get") - sub.add_argument("-i", "--id", required=True) - sub.set_defaults(func=Engine.get) - - sub = subparsers.add_parser("engines.update") - sub.add_argument("-i", "--id", required=True) - sub.add_argument("-r", "--replicas", type=int) - sub.set_defaults(func=Engine.update) - - sub = subparsers.add_parser("engines.generate") - sub.add_argument("-i", "--id", required=True) - sub.add_argument( - "--stream", help="Stream tokens as they're ready.", action="http://github.com/store_true" - ) - sub.add_argument("-c", "--context", help="An optional context to generate from") - sub.add_argument("-l", "--length", help="How many tokens to generate", type=int) - sub.add_argument( - "-t", - "--temperature", - help="""What sampling temperature to use. Higher values means the model will take more risks. Try 0.9 for more creative applications, and 0 (argmax sampling) for ones with a well-defined answer. - -Mutually exclusive with `top_p`.""", - type=float, - ) - sub.add_argument( - "-p", - "--top_p", - help="""An alternative to sampling with temperature, called nucleus sampling, where the considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10%% probability mass are considered. - - Mutually exclusive with `temperature`.""", - type=float, - ) - sub.add_argument( - "-n", - "--completions", - help="How many parallel completions to run on this context", - type=int, - ) - sub.add_argument( - "--logprobs", - help="Include the log probabilites on the `logprobs` most likely tokens. So for example, if `logprobs` is 10, the API will return a list of the 10 most likely tokens. If `logprobs` is supplied, the API will always return the logprob of the generated token, so there may be up to `logprobs+1` elements in the response.", - type=int, - ) - sub.add_argument( - "--stop", help="A stop sequence at which to stop generating tokens." - ) - sub.add_argument( - "-m", - "--model", - required=False, - help="A model (most commonly a model ID) to generate from. Defaults to the engine's default model.", - ) - sub.set_defaults(func=Engine.generate) - - # Chat Completions - sub = subparsers.add_parser("chat_completions.create") - - sub._action_groups.pop() - req = sub.add_argument_group("required arguments") - opt = sub.add_argument_group("optional arguments") - - req.add_argument( - "-g", - "--message", - action="http://github.com/append", - nargs=2, - metavar=("ROLE", "CONTENT"), - help="A message in `{role} {content}` format. Use this argument multiple times to add multiple messages.", - required=True, - ) - - group = opt.add_mutually_exclusive_group() - group.add_argument( - "-e", - "--engine", - help="The engine to use. See https://learn.microsoft.com/en-us/azure/cognitive-services/openai/chatgpt-quickstart?pivots=programming-language-python for more about what engines are available.", - ) - group.add_argument( - "-m", - "--model", - help="The model to use.", - ) - - opt.add_argument( - "-n", - "--n", - help="How many completions to generate for the conversation.", - type=int, - ) - opt.add_argument( - "-M", "--max-tokens", help="The maximum number of tokens to generate.", type=int - ) - opt.add_argument( - "-t", - "--temperature", - help="""What sampling temperature to use. Higher values means the model will take more risks. Try 0.9 for more creative applications, and 0 (argmax sampling) for ones with a well-defined answer. - -Mutually exclusive with `top_p`.""", - type=float, - ) - opt.add_argument( - "-P", - "--top_p", - help="""An alternative to sampling with temperature, called nucleus sampling, where the considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10%% probability mass are considered. - - Mutually exclusive with `temperature`.""", - type=float, - ) - opt.add_argument( - "--stop", - help="A stop sequence at which to stop generating tokens for the message.", - ) - opt.add_argument( - "--stream", help="Stream messages as they're ready.", action="http://github.com/store_true" - ) - sub.set_defaults(func=ChatCompletion.create) - - # Completions - sub = subparsers.add_parser("completions.create") - sub.add_argument( - "-e", - "--engine", - help="The engine to use. See https://platform.openai.com/docs/engines for more about what engines are available.", - ) - sub.add_argument( - "-m", - "--model", - help="The model to use. At most one of `engine` or `model` should be specified.", - ) - sub.add_argument( - "--stream", help="Stream tokens as they're ready.", action="http://github.com/store_true" - ) - sub.add_argument("-p", "--prompt", help="An optional prompt to complete from") - sub.add_argument( - "-M", "--max-tokens", help="The maximum number of tokens to generate", type=int - ) - sub.add_argument( - "-t", - "--temperature", - help="""What sampling temperature to use. Higher values means the model will take more risks. Try 0.9 for more creative applications, and 0 (argmax sampling) for ones with a well-defined answer. - -Mutually exclusive with `top_p`.""", - type=float, - ) - sub.add_argument( - "-P", - "--top_p", - help="""An alternative to sampling with temperature, called nucleus sampling, where the considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10%% probability mass are considered. - - Mutually exclusive with `temperature`.""", - type=float, - ) - sub.add_argument( - "-n", - "--n", - help="How many sub-completions to generate for each prompt.", - type=int, - ) - sub.add_argument( - "--logprobs", - help="Include the log probabilites on the `logprobs` most likely tokens, as well the chosen tokens. So for example, if `logprobs` is 10, the API will return a list of the 10 most likely tokens. If `logprobs` is 0, only the chosen tokens will have logprobs returned.", - type=int, - ) - sub.add_argument( - "--stop", help="A stop sequence at which to stop generating tokens." - ) - sub.set_defaults(func=Completion.create) - - # Deployments - sub = subparsers.add_parser("deployments.list") - sub.set_defaults(func=Deployment.list) - - sub = subparsers.add_parser("deployments.get") - sub.add_argument("-i", "--id", required=True, help="The deployment ID") - sub.set_defaults(func=Deployment.get) - - sub = subparsers.add_parser("deployments.delete") - sub.add_argument("-i", "--id", required=True, help="The deployment ID") - sub.set_defaults(func=Deployment.delete) - - sub = subparsers.add_parser("deployments.create") - sub.add_argument("-m", "--model", required=True, help="The model ID") - sub.add_argument( - "-s", - "--scale_type", - required=True, - help="The scale type. Either 'manual' or 'standard'", - ) - sub.set_defaults(func=Deployment.create) - - # Models - sub = subparsers.add_parser("models.list") - sub.set_defaults(func=Model.list) - - sub = subparsers.add_parser("models.get") - sub.add_argument("-i", "--id", required=True, help="The model ID") - sub.set_defaults(func=Model.get) - - sub = subparsers.add_parser("models.delete") - sub.add_argument("-i", "--id", required=True, help="The model ID") - sub.set_defaults(func=Model.delete) - - # Files - sub = subparsers.add_parser("files.create") - - sub.add_argument( - "-f", - "--file", - required=True, - help="File to upload", - ) - sub.add_argument( - "-p", - "--purpose", - help="Why are you uploading this file? (see https://platform.openai.com/docs/api-reference/ for purposes)", - required=True, - ) - sub.set_defaults(func=File.create) - - sub = subparsers.add_parser("files.get") - sub.add_argument("-i", "--id", required=True, help="The files ID") - sub.set_defaults(func=File.get) - - sub = subparsers.add_parser("files.delete") - sub.add_argument("-i", "--id", required=True, help="The files ID") - sub.set_defaults(func=File.delete) - - sub = subparsers.add_parser("files.list") - sub.set_defaults(func=File.list) - - # Finetune - sub = subparsers.add_parser("fine_tunes.list") - sub.set_defaults(func=FineTune.list) - - sub = subparsers.add_parser("fine_tunes.create") - sub.add_argument( - "-t", - "--training_file", - required=True, - help="JSONL file containing prompt-completion examples for training. This can " - "be the ID of a file uploaded through the OpenAI API (e.g. file-abcde12345), " - 'a local file path, or a URL that starts with "http".', - ) - sub.add_argument( - "-v", - "--validation_file", - help="JSONL file containing prompt-completion examples for validation. This can " - "be the ID of a file uploaded through the OpenAI API (e.g. file-abcde12345), " - 'a local file path, or a URL that starts with "http".', - ) - sub.add_argument( - "--no_check_if_files_exist", - dest="check_if_files_exist", - action="http://github.com/store_false", - help="If this argument is set and training_file or validation_file are file paths, immediately upload them. If this argument is not set, check if they may be duplicates of already uploaded files before uploading, based on file name and file size.", - ) - sub.add_argument( - "-m", - "--model", - help="The model to start fine-tuning from", - ) - sub.add_argument( - "--suffix", - help="If set, this argument can be used to customize the generated fine-tuned model name." - "All punctuation and whitespace in `suffix` will be replaced with a " - "single dash, and the string will be lower cased. The max " - "length of `suffix` is 40 chars. " - "The generated name will match the form `{base_model}:ft-{org-title}:{suffix}-{timestamp}`. " - 'For example, `openai api fine_tunes.create -t test.jsonl -m ada --suffix "custom model name" ' - "could generate a model with the name " - "ada:ft-your-org:custom-model-name-2022-02-15-04-21-04", - ) - sub.add_argument( - "--no_follow", - action="http://github.com/store_true", - help="If set, returns immediately after creating the job. Otherwise, streams events and waits for the job to complete.", - ) - sub.add_argument( - "--n_epochs", - type=int, - help="The number of epochs to train the model for. An epoch refers to one " - "full cycle through the training dataset.", - ) - sub.add_argument( - "--batch_size", - type=int, - help="The batch size to use for training. The batch size is the number of " - "training examples used to train a single forward and backward pass.", - ) - sub.add_argument( - "--learning_rate_multiplier", - type=float, - help="The learning rate multiplier to use for training. The fine-tuning " - "learning rate is determined by the original learning rate used for " - "pretraining multiplied by this value.", - ) - sub.add_argument( - "--prompt_loss_weight", - type=float, - help="The weight to use for the prompt loss. The optimum value here depends " - "depends on your use case. This determines how much the model prioritizes " - "learning from prompt tokens vs learning from completion tokens.", - ) - sub.add_argument( - "--compute_classification_metrics", - action="http://github.com/store_true", - help="If set, we calculate classification-specific metrics such as accuracy " - "and F-1 score using the validation set at the end of every epoch.", - ) - sub.set_defaults(compute_classification_metrics=None) - sub.add_argument( - "--classification_n_classes", - type=int, - help="The number of classes in a classification task. This parameter is " - "required for multiclass classification.", - ) - sub.add_argument( - "--classification_positive_class", - help="The positive class in binary classification. This parameter is needed " - "to generate precision, recall and F-1 metrics when doing binary " - "classification.", - ) - sub.add_argument( - "--classification_betas", - type=float, - nargs="+", - help="If this is provided, we calculate F-beta scores at the specified beta " - "values. The F-beta score is a generalization of F-1 score. This is only " - "used for binary classification.", - ) - sub.set_defaults(func=FineTune.create) - - sub = subparsers.add_parser("fine_tunes.get") - sub.add_argument("-i", "--id", required=True, help="The id of the fine-tune job") - sub.set_defaults(func=FineTune.get) - - sub = subparsers.add_parser("fine_tunes.results") - sub.add_argument("-i", "--id", required=True, help="The id of the fine-tune job") - sub.set_defaults(func=FineTune.results) - - sub = subparsers.add_parser("fine_tunes.events") - sub.add_argument("-i", "--id", required=True, help="The id of the fine-tune job") - - # TODO(rachel): Remove this in 1.0 - sub.add_argument( - "-s", - "--stream", - action="http://github.com/store_true", - help="[DEPRECATED] If set, events will be streamed until the job is done. Otherwise, " - "displays the event history to date.", - ) - sub.set_defaults(func=FineTune.events) - - sub = subparsers.add_parser("fine_tunes.follow") - sub.add_argument("-i", "--id", required=True, help="The id of the fine-tune job") - sub.set_defaults(func=FineTune.follow) - - sub = subparsers.add_parser("fine_tunes.cancel") - sub.add_argument("-i", "--id", required=True, help="The id of the fine-tune job") - sub.set_defaults(func=FineTune.cancel) - - sub = subparsers.add_parser("fine_tunes.delete") - sub.add_argument("-i", "--id", required=True, help="The id of the fine-tune job") - sub.set_defaults(func=FineTune.delete) - - # Image - sub = subparsers.add_parser("image.create") - sub.add_argument("-p", "--prompt", type=str, required=True) - sub.add_argument("-n", "--num-images", type=int, default=1) - sub.add_argument( - "-s", "--size", type=str, default="1024x1024", help="Size of the output image" - ) - sub.add_argument("--response-format", type=str, default="url") - sub.set_defaults(func=Image.create) - - sub = subparsers.add_parser("image.create_edit") - sub.add_argument("-p", "--prompt", type=str, required=True) - sub.add_argument("-n", "--num-images", type=int, default=1) - sub.add_argument( - "-I", - "--image", - type=str, - required=True, - help="Image to modify. Should be a local path and a PNG encoded image.", - ) - sub.add_argument( - "-s", "--size", type=str, default="1024x1024", help="Size of the output image" - ) - sub.add_argument("--response-format", type=str, default="url") - sub.add_argument( - "-M", - "--mask", - type=str, - required=False, - help="Path to a mask image. It should be the same size as the image you're editing and a RGBA PNG image. The Alpha channel acts as the mask.", - ) - sub.set_defaults(func=Image.create_edit) - - sub = subparsers.add_parser("image.create_variation") - sub.add_argument("-n", "--num-images", type=int, default=1) - sub.add_argument( - "-I", - "--image", - type=str, - required=True, - help="Image to modify. Should be a local path and a PNG encoded image.", - ) - sub.add_argument( - "-s", "--size", type=str, default="1024x1024", help="Size of the output image" - ) - sub.add_argument("--response-format", type=str, default="url") - sub.set_defaults(func=Image.create_variation) - - # Audio - # transcriptions - sub = subparsers.add_parser("audio.transcribe") - # Required - sub.add_argument("-m", "--model", type=str, default="whisper-1") - sub.add_argument("-f", "--file", type=str, required=True) - # Optional - sub.add_argument("--response-format", type=str) - sub.add_argument("--language", type=str) - sub.add_argument("-t", "--temperature", type=float) - sub.add_argument("--prompt", type=str) - sub.set_defaults(func=Audio.transcribe) - # translations - sub = subparsers.add_parser("audio.translate") - # Required - sub.add_argument("-m", "--model", type=str, default="whisper-1") - sub.add_argument("-f", "--file", type=str, required=True) - # Optional - sub.add_argument("--response-format", type=str) - sub.add_argument("--language", type=str) - sub.add_argument("-t", "--temperature", type=float) - sub.add_argument("--prompt", type=str) - sub.set_defaults(func=Audio.translate) - - # FineTuning Jobs - sub = subparsers.add_parser("fine_tuning.job.list") - sub.set_defaults(func=FineTuningJob.list) - - sub = subparsers.add_parser("fine_tuning.job.create") - sub.add_argument( - "-t", - "--training_file", - required=True, - help="JSONL file containing either chat-completion or prompt-completion examples for training. " - "This can be the ID of a file uploaded through the OpenAI API (e.g. file-abcde12345), " - 'a local file path, or a URL that starts with "http".', - ) - sub.add_argument( - "-v", - "--validation_file", - help="JSONL file containing either chat-completion or prompt-completion examples for validation. " - "This can be the ID of a file uploaded through the OpenAI API (e.g. file-abcde12345), " - 'a local file path, or a URL that starts with "http".', - ) - sub.add_argument( - "--no_check_if_files_exist", - dest="check_if_files_exist", - action="http://github.com/store_false", - help="If this argument is set and training_file or validation_file are file paths, immediately upload them. If this argument is not set, check if they may be duplicates of already uploaded files before uploading, based on file name and file size.", - ) - sub.add_argument( - "-m", - "--model", - help="The model to start fine-tuning from", - ) - sub.add_argument( - "--suffix", - help="If set, this argument can be used to customize the generated fine-tuned model name." - "All punctuation and whitespace in `suffix` will be replaced with a " - "single dash, and the string will be lower cased. The max " - "length of `suffix` is 18 chars. " - "The generated name will match the form `ft:{base_model}:{org-title}:{suffix}:{rstring}` where `rstring` " - "is a random string sortable as a timestamp. " - 'For example, `openai api fine_tuning.job.create -t test.jsonl -m gpt-3.5-turbo-0613 --suffix "first finetune!" ' - "could generate a model with the name " - "ft:gpt-3.5-turbo-0613:your-org:first-finetune:7p4PqAoY", - ) - sub.add_argument( - "--n_epochs", - type=int, - help="The number of epochs to train the model for. An epoch refers to one " - "full cycle through the training dataset.", - ) - sub.set_defaults(func=FineTuningJob.create) - - sub = subparsers.add_parser("fine_tuning.job.get") - sub.add_argument("-i", "--id", required=True, help="The id of the fine-tune job") - sub.set_defaults(func=FineTuningJob.get) - - sub = subparsers.add_parser("fine_tuning.job.results") - sub.add_argument("-i", "--id", required=True, help="The id of the fine-tune job") - sub.set_defaults(func=FineTuningJob.results) - - sub = subparsers.add_parser("fine_tuning.job.events") - sub.add_argument("-i", "--id", required=True, help="The id of the fine-tune job") - sub.add_argument( - "--limit", - type=int, - required=False, - help="The number of events to return, starting from most recent. If not specified, all events will be returned.", - ) - sub.set_defaults(func=FineTuningJob.events) - - sub = subparsers.add_parser("fine_tuning.job.follow") - sub.add_argument("-i", "--id", required=True, help="The id of the fine-tune job") - sub.set_defaults(func=FineTuningJob.follow) - - sub = subparsers.add_parser("fine_tuning.job.cancel") - sub.add_argument("-i", "--id", required=True, help="The id of the fine-tune job") - sub.set_defaults(func=FineTuningJob.cancel) - - -def wandb_register(parser): - subparsers = parser.add_subparsers( - title="wandb", help="Logging with Weights & Biases, see https://docs.wandb.ai/guides/integrations/openai for documentation" - ) - - def help(args): - parser.print_help() - - parser.set_defaults(func=help) - - sub = subparsers.add_parser("sync") - sub.add_argument("-i", "--id", help="The id of the fine-tune job (optional)") - sub.add_argument( - "-n", - "--n_fine_tunes", - type=int, - default=None, - help="Number of most recent fine-tunes to log when an id is not provided. By default, every fine-tune is synced.", - ) - sub.add_argument( - "--project", - default="OpenAI-Fine-Tune", - help="""Name of the Weights & Biases project where you're sending runs. By default, it is "OpenAI-Fine-Tune".""", - ) - sub.add_argument( - "--entity", - help="Weights & Biases username or team name where you're sending runs. By default, your default entity is used, which is usually your username.", - ) - sub.add_argument( - "--force", - action="http://github.com/store_true", - help="Forces logging and overwrite existing wandb run of the same fine-tune.", - ) - sub.add_argument( - "--legacy", - action="http://github.com/store_true", - help="Log results from legacy OpenAI /v1/fine-tunes api", - ) - sub.set_defaults(force=False) - sub.set_defaults(legacy=False) - sub.set_defaults(func=WandbLogger.sync) diff --git a/openai/datalib/__init__.py b/openai/datalib/__init__.py deleted file mode 100644 index d02b49cfff..0000000000 --- a/openai/datalib/__init__.py +++ /dev/null @@ -1,14 +0,0 @@ -""" -This module helps make data libraries like `numpy` and `pandas` optional dependencies. - -The libraries add up to 130MB+, which makes it challenging to deploy applications -using this library in environments with code size constraints, like AWS Lambda. - -This module serves as an import proxy and provides a few utilities for dealing with the optionality. - -Since the primary use case of this library (talking to the OpenAI API) doesn't generally require data libraries, -it's safe to make them optional. The rare case when data libraries are needed in the client is handled through -assertions with instructive error messages. - -See also `setup.py`. -""" diff --git a/openai/datalib/common.py b/openai/datalib/common.py deleted file mode 100644 index 96f9908a18..0000000000 --- a/openai/datalib/common.py +++ /dev/null @@ -1,17 +0,0 @@ -INSTRUCTIONS = """ - -OpenAI error: - - missing `{library}` - -This feature requires additional dependencies: - - $ pip install openai[datalib] - -""" - -NUMPY_INSTRUCTIONS = INSTRUCTIONS.format(library="numpy") - - -class MissingDependencyError(Exception): - pass diff --git a/openai/datalib/numpy_helper.py b/openai/datalib/numpy_helper.py deleted file mode 100644 index fb80f2ae54..0000000000 --- a/openai/datalib/numpy_helper.py +++ /dev/null @@ -1,15 +0,0 @@ -from openai.datalib.common import INSTRUCTIONS, MissingDependencyError - -try: - import numpy -except ImportError: - numpy = None - -HAS_NUMPY = bool(numpy) - -NUMPY_INSTRUCTIONS = INSTRUCTIONS.format(library="numpy") - - -def assert_has_numpy(): - if not HAS_NUMPY: - raise MissingDependencyError(NUMPY_INSTRUCTIONS) diff --git a/openai/datalib/pandas_helper.py b/openai/datalib/pandas_helper.py deleted file mode 100644 index 4e86d7b4f9..0000000000 --- a/openai/datalib/pandas_helper.py +++ /dev/null @@ -1,15 +0,0 @@ -from openai.datalib.common import INSTRUCTIONS, MissingDependencyError - -try: - import pandas -except ImportError: - pandas = None - -HAS_PANDAS = bool(pandas) - -PANDAS_INSTRUCTIONS = INSTRUCTIONS.format(library="pandas") - - -def assert_has_pandas(): - if not HAS_PANDAS: - raise MissingDependencyError(PANDAS_INSTRUCTIONS) diff --git a/openai/embeddings_utils.py b/openai/embeddings_utils.py deleted file mode 100644 index dc26445c3c..0000000000 --- a/openai/embeddings_utils.py +++ /dev/null @@ -1,252 +0,0 @@ -import textwrap as tr -from typing import List, Optional - -import matplotlib.pyplot as plt -import plotly.express as px -from scipy import spatial -from sklearn.decomposition import PCA -from sklearn.manifold import TSNE -from sklearn.metrics import average_precision_score, precision_recall_curve -from tenacity import retry, stop_after_attempt, wait_random_exponential - -import openai -from openai.datalib.numpy_helper import numpy as np -from openai.datalib.pandas_helper import pandas as pd - - -@retry(wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6)) -def get_embedding(text: str, engine="text-embedding-ada-002", **kwargs) -> List[float]: - - # replace newlines, which can negatively affect performance. - text = text.replace("\n", " ") - - return openai.Embedding.create(input=[text], engine=engine, **kwargs)["data"][0]["embedding"] - - -@retry(wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6)) -async def aget_embedding( - text: str, engine="text-embedding-ada-002", **kwargs -) -> List[float]: - - # replace newlines, which can negatively affect performance. - text = text.replace("\n", " ") - - return (await openai.Embedding.acreate(input=[text], engine=engine, **kwargs))["data"][0][ - "embedding" - ] - - -@retry(wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6)) -def get_embeddings( - list_of_text: List[str], engine="text-embedding-ada-002", **kwargs -) -> List[List[float]]: - assert len(list_of_text) <= 8191, "The batch size should not be larger than 8191." - - # replace newlines, which can negatively affect performance. - list_of_text = [text.replace("\n", " ") for text in list_of_text] - - data = openai.Embedding.create(input=list_of_text, engine=engine, **kwargs).data - return [d["embedding"] for d in data] - - -@retry(wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6)) -async def aget_embeddings( - list_of_text: List[str], engine="text-embedding-ada-002", **kwargs -) -> List[List[float]]: - assert len(list_of_text) <= 8191, "The batch size should not be larger than 8191." - - # replace newlines, which can negatively affect performance. - list_of_text = [text.replace("\n", " ") for text in list_of_text] - - data = (await openai.Embedding.acreate(input=list_of_text, engine=engine, **kwargs)).data - return [d["embedding"] for d in data] - - -def cosine_similarity(a, b): - return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)) - - -def plot_multiclass_precision_recall( - y_score, y_true_untransformed, class_list, classifier_name -): - """ - Precision-Recall plotting for a multiclass problem. It plots average precision-recall, per class precision recall and reference f1 contours. - - Code slightly modified, but heavily based on https://scikit-learn.org/stable/auto_examples/model_selection/plot_precision_recall.html - """ - n_classes = len(class_list) - y_true = pd.concat( - [(y_true_untransformed == class_list[i]) for i in range(n_classes)], axis=1 - ).values - - # For each class - precision = dict() - recall = dict() - average_precision = dict() - for i in range(n_classes): - precision[i], recall[i], _ = precision_recall_curve(y_true[:, i], y_score[:, i]) - average_precision[i] = average_precision_score(y_true[:, i], y_score[:, i]) - - # A "micro-average": quantifying score on all classes jointly - precision_micro, recall_micro, _ = precision_recall_curve( - y_true.ravel(), y_score.ravel() - ) - average_precision_micro = average_precision_score(y_true, y_score, average="micro") - print( - str(classifier_name) - + " - Average precision score over all classes: {0:0.2f}".format( - average_precision_micro - ) - ) - - # setup plot details - plt.figure(figsize=(9, 10)) - f_scores = np.linspace(0.2, 0.8, num=4) - lines = [] - labels = [] - for f_score in f_scores: - x = np.linspace(0.01, 1) - y = f_score * x / (2 * x - f_score) - (l,) = plt.plot(x[y >= 0], y[y >= 0], color="gray", alpha=0.2) - plt.annotate("f1={0:0.1f}".format(f_score), xy=(0.9, y[45] + 0.02)) - - lines.append(l) - labels.append("iso-f1 curves") - (l,) = plt.plot(recall_micro, precision_micro, color="gold", lw=2) - lines.append(l) - labels.append( - "average Precision-recall (auprc = {0:0.2f})" "".format(average_precision_micro) - ) - - for i in range(n_classes): - (l,) = plt.plot(recall[i], precision[i], lw=2) - lines.append(l) - labels.append( - "Precision-recall for class `{0}` (auprc = {1:0.2f})" - "".format(class_list[i], average_precision[i]) - ) - - fig = plt.gcf() - fig.subplots_adjust(bottom=0.25) - plt.xlim([0.0, 1.0]) - plt.ylim([0.0, 1.05]) - plt.xlabel("Recall") - plt.ylabel("Precision") - plt.title(f"{classifier_name}: Precision-Recall curve for each class") - plt.legend(lines, labels) - - -def distances_from_embeddings( - query_embedding: List[float], - embeddings: List[List[float]], - distance_metric="cosine", -) -> List[List]: - """Return the distances between a query embedding and a list of embeddings.""" - distance_metrics = { - "cosine": spatial.distance.cosine, - "L1": spatial.distance.cityblock, - "L2": spatial.distance.euclidean, - "Linf": spatial.distance.chebyshev, - } - distances = [ - distance_metrics[distance_metric](query_embedding, embedding) - for embedding in embeddings - ] - return distances - - -def indices_of_nearest_neighbors_from_distances(distances) -> np.ndarray: - """Return a list of indices of nearest neighbors from a list of distances.""" - return np.argsort(distances) - - -def pca_components_from_embeddings( - embeddings: List[List[float]], n_components=2 -) -> np.ndarray: - """Return the PCA components of a list of embeddings.""" - pca = PCA(n_components=n_components) - array_of_embeddings = np.array(embeddings) - return pca.fit_transform(array_of_embeddings) - - -def tsne_components_from_embeddings( - embeddings: List[List[float]], n_components=2, **kwargs -) -> np.ndarray: - """Returns t-SNE components of a list of embeddings.""" - # use better defaults if not specified - if "init" not in kwargs.keys(): - kwargs["init"] = "pca" - if "learning_rate" not in kwargs.keys(): - kwargs["learning_rate"] = "auto" - tsne = TSNE(n_components=n_components, **kwargs) - array_of_embeddings = np.array(embeddings) - return tsne.fit_transform(array_of_embeddings) - - -def chart_from_components( - components: np.ndarray, - labels: Optional[List[str]] = None, - strings: Optional[List[str]] = None, - x_title="Component 0", - y_title="Component 1", - mark_size=5, - **kwargs, -): - """Return an interactive 2D chart of embedding components.""" - empty_list = ["" for _ in components] - data = pd.DataFrame( - { - x_title: components[:, 0], - y_title: components[:, 1], - "label": labels if labels else empty_list, - "string": ["
".join(tr.wrap(string, width=30)) for string in strings] - if strings - else empty_list, - } - ) - chart = px.scatter( - data, - x=x_title, - y=y_title, - color="label" if labels else None, - symbol="label" if labels else None, - hover_data=["string"] if strings else None, - **kwargs, - ).update_traces(marker=dict(size=mark_size)) - return chart - - -def chart_from_components_3D( - components: np.ndarray, - labels: Optional[List[str]] = None, - strings: Optional[List[str]] = None, - x_title: str = "Component 0", - y_title: str = "Component 1", - z_title: str = "Compontent 2", - mark_size: int = 5, - **kwargs, -): - """Return an interactive 3D chart of embedding components.""" - empty_list = ["" for _ in components] - data = pd.DataFrame( - { - x_title: components[:, 0], - y_title: components[:, 1], - z_title: components[:, 2], - "label": labels if labels else empty_list, - "string": ["
".join(tr.wrap(string, width=30)) for string in strings] - if strings - else empty_list, - } - ) - chart = px.scatter_3d( - data, - x=x_title, - y=y_title, - z=z_title, - color="label" if labels else None, - symbol="label" if labels else None, - hover_data=["string"] if strings else None, - **kwargs, - ).update_traces(marker=dict(size=mark_size)) - return chart diff --git a/openai/error.py b/openai/error.py deleted file mode 100644 index 2928ef6aa6..0000000000 --- a/openai/error.py +++ /dev/null @@ -1,169 +0,0 @@ -import openai - - -class OpenAIError(Exception): - def __init__( - self, - message=None, - http_body=None, - http_status=None, - json_body=None, - headers=None, - code=None, - ): - super(OpenAIError, self).__init__(message) - - if http_body and hasattr(http_body, "decode"): - try: - http_body = http_body.decode("utf-8") - except BaseException: - http_body = ( - "" - ) - - self._message = message - self.http_body = http_body - self.http_status = http_status - self.json_body = json_body - self.headers = headers or {} - self.code = code - self.request_id = self.headers.get("request-id", None) - self.error = self.construct_error_object() - self.organization = self.headers.get("openai-organization", None) - - def __str__(self): - msg = self._message or "" - if self.request_id is not None: - return "Request {0}: {1}".format(self.request_id, msg) - else: - return msg - - # Returns the underlying `Exception` (base class) message, which is usually - # the raw message returned by OpenAI's API. This was previously available - # in python2 via `error.message`. Unlike `str(error)`, it omits "Request - # req_..." from the beginning of the string. - @property - def user_message(self): - return self._message - - def __repr__(self): - return "%s(message=%r, http_status=%r, request_id=%r)" % ( - self.__class__.__name__, - self._message, - self.http_status, - self.request_id, - ) - - def construct_error_object(self): - if ( - self.json_body is None - or not isinstance(self.json_body, dict) - or "error" not in self.json_body - or not isinstance(self.json_body["error"], dict) - ): - return None - - return openai.api_resources.error_object.ErrorObject.construct_from( - self.json_body["error"] - ) - - -class APIError(OpenAIError): - pass - - -class TryAgain(OpenAIError): - pass - - -class Timeout(OpenAIError): - pass - - -class APIConnectionError(OpenAIError): - def __init__( - self, - message, - http_body=None, - http_status=None, - json_body=None, - headers=None, - code=None, - should_retry=False, - ): - super(APIConnectionError, self).__init__( - message, http_body, http_status, json_body, headers, code - ) - self.should_retry = should_retry - - -class InvalidRequestError(OpenAIError): - def __init__( - self, - message, - param, - code=None, - http_body=None, - http_status=None, - json_body=None, - headers=None, - ): - super(InvalidRequestError, self).__init__( - message, http_body, http_status, json_body, headers, code - ) - self.param = param - - def __repr__(self): - return "%s(message=%r, param=%r, code=%r, http_status=%r, " "request_id=%r)" % ( - self.__class__.__name__, - self._message, - self.param, - self.code, - self.http_status, - self.request_id, - ) - - def __reduce__(self): - return type(self), ( - self._message, - self.param, - self.code, - self.http_body, - self.http_status, - self.json_body, - self.headers, - ) - - -class AuthenticationError(OpenAIError): - pass - - -class PermissionError(OpenAIError): - pass - - -class RateLimitError(OpenAIError): - pass - - -class ServiceUnavailableError(OpenAIError): - pass - - -class InvalidAPIType(OpenAIError): - pass - - -class SignatureVerificationError(OpenAIError): - def __init__(self, message, sig_header, http_body=None): - super(SignatureVerificationError, self).__init__(message, http_body) - self.sig_header = sig_header - - def __reduce__(self): - return type(self), ( - self._message, - self.sig_header, - self.http_body, - ) diff --git a/openai/object_classes.py b/openai/object_classes.py deleted file mode 100644 index 08093650fd..0000000000 --- a/openai/object_classes.py +++ /dev/null @@ -1,12 +0,0 @@ -from openai import api_resources -from openai.api_resources.experimental.completion_config import CompletionConfig - -OBJECT_CLASSES = { - "engine": api_resources.Engine, - "experimental.completion_config": CompletionConfig, - "file": api_resources.File, - "fine-tune": api_resources.FineTune, - "model": api_resources.Model, - "deployment": api_resources.Deployment, - "fine_tuning.job": api_resources.FineTuningJob, -} diff --git a/openai/openai_object.py b/openai/openai_object.py deleted file mode 100644 index 95f8829742..0000000000 --- a/openai/openai_object.py +++ /dev/null @@ -1,347 +0,0 @@ -import json -from copy import deepcopy -from typing import Optional, Tuple, Union - -import openai -from openai import api_requestor, util -from openai.openai_response import OpenAIResponse -from openai.util import ApiType - - -class OpenAIObject(dict): - api_base_override = None - - def __init__( - self, - id=None, - api_key=None, - api_version=None, - api_type=None, - organization=None, - response_ms: Optional[int] = None, - api_base=None, - engine=None, - **params, - ): - super(OpenAIObject, self).__init__() - - if response_ms is not None and not isinstance(response_ms, int): - raise TypeError(f"response_ms is a {type(response_ms).__name__}.") - self._response_ms = response_ms - - self._retrieve_params = params - - object.__setattr__(self, "api_key", api_key) - object.__setattr__(self, "api_version", api_version) - object.__setattr__(self, "api_type", api_type) - object.__setattr__(self, "organization", organization) - object.__setattr__(self, "api_base_override", api_base) - object.__setattr__(self, "engine", engine) - - if id: - self["id"] = id - - @property - def response_ms(self) -> Optional[int]: - return self._response_ms - - def __setattr__(self, k, v): - if k[0] == "_" or k in self.__dict__: - return super(OpenAIObject, self).__setattr__(k, v) - - self[k] = v - return None - - def __getattr__(self, k): - if k[0] == "_": - raise AttributeError(k) - try: - return self[k] - except KeyError as err: - raise AttributeError(*err.args) - - def __delattr__(self, k): - if k[0] == "_" or k in self.__dict__: - return super(OpenAIObject, self).__delattr__(k) - else: - del self[k] - - def __setitem__(self, k, v): - if v == "": - raise ValueError( - "You cannot set %s to an empty string. " - "We interpret empty strings as None in requests." - "You may set %s.%s = None to delete the property" % (k, str(self), k) - ) - super(OpenAIObject, self).__setitem__(k, v) - - def __delitem__(self, k): - raise NotImplementedError("del is not supported") - - # Custom unpickling method that uses `update` to update the dictionary - # without calling __setitem__, which would fail if any value is an empty - # string - def __setstate__(self, state): - self.update(state) - - # Custom pickling method to ensure the instance is pickled as a custom - # class and not as a dict, otherwise __setstate__ would not be called when - # unpickling. - def __reduce__(self): - reduce_value = ( - type(self), # callable - ( # args - self.get("id", None), - self.api_key, - self.api_version, - self.api_type, - self.organization, - ), - dict(self), # state - ) - return reduce_value - - @classmethod - def construct_from( - cls, - values, - api_key: Optional[str] = None, - api_version=None, - organization=None, - engine=None, - response_ms: Optional[int] = None, - ): - instance = cls( - values.get("id"), - api_key=api_key, - api_version=api_version, - organization=organization, - engine=engine, - response_ms=response_ms, - ) - instance.refresh_from( - values, - api_key=api_key, - api_version=api_version, - organization=organization, - response_ms=response_ms, - ) - return instance - - def refresh_from( - self, - values, - api_key=None, - api_version=None, - api_type=None, - organization=None, - response_ms: Optional[int] = None, - ): - self.api_key = api_key or getattr(values, "api_key", None) - self.api_version = api_version or getattr(values, "api_version", None) - self.api_type = api_type or getattr(values, "api_type", None) - self.organization = organization or getattr(values, "organization", None) - self._response_ms = response_ms or getattr(values, "_response_ms", None) - - # Wipe old state before setting new. - self.clear() - for k, v in values.items(): - super(OpenAIObject, self).__setitem__( - k, util.convert_to_openai_object(v, api_key, api_version, organization) - ) - - self._previous = values - - @classmethod - def api_base(cls): - return None - - def request( - self, - method, - url, - params=None, - headers=None, - stream=False, - plain_old_data=False, - request_id: Optional[str] = None, - request_timeout: Optional[Union[float, Tuple[float, float]]] = None, - ): - if params is None: - params = self._retrieve_params - requestor = api_requestor.APIRequestor( - key=self.api_key, - api_base=self.api_base_override or self.api_base(), - api_type=self.api_type, - api_version=self.api_version, - organization=self.organization, - ) - response, stream, api_key = requestor.request( - method, - url, - params=params, - stream=stream, - headers=headers, - request_id=request_id, - request_timeout=request_timeout, - ) - - if stream: - assert not isinstance(response, OpenAIResponse) # must be an iterator - return ( - util.convert_to_openai_object( - line, - api_key, - self.api_version, - self.organization, - plain_old_data=plain_old_data, - ) - for line in response - ) - else: - return util.convert_to_openai_object( - response, - api_key, - self.api_version, - self.organization, - plain_old_data=plain_old_data, - ) - - async def arequest( - self, - method, - url, - params=None, - headers=None, - stream=False, - plain_old_data=False, - request_id: Optional[str] = None, - request_timeout: Optional[Union[float, Tuple[float, float]]] = None, - ): - if params is None: - params = self._retrieve_params - requestor = api_requestor.APIRequestor( - key=self.api_key, - api_base=self.api_base_override or self.api_base(), - api_type=self.api_type, - api_version=self.api_version, - organization=self.organization, - ) - response, stream, api_key = await requestor.arequest( - method, - url, - params=params, - stream=stream, - headers=headers, - request_id=request_id, - request_timeout=request_timeout, - ) - - if stream: - assert not isinstance(response, OpenAIResponse) # must be an iterator - return ( - util.convert_to_openai_object( - line, - api_key, - self.api_version, - self.organization, - plain_old_data=plain_old_data, - ) - for line in response - ) - else: - return util.convert_to_openai_object( - response, - api_key, - self.api_version, - self.organization, - plain_old_data=plain_old_data, - ) - - def __repr__(self): - ident_parts = [type(self).__name__] - - obj = self.get("object") - if isinstance(obj, str): - ident_parts.append(obj) - - if isinstance(self.get("id"), str): - ident_parts.append("id=%s" % (self.get("id"),)) - - unicode_repr = "<%s at %s> JSON: %s" % ( - " ".join(ident_parts), - hex(id(self)), - str(self), - ) - - return unicode_repr - - def __str__(self): - obj = self.to_dict_recursive() - return json.dumps(obj, indent=2) - - def to_dict(self): - return dict(self) - - def to_dict_recursive(self): - d = dict(self) - for k, v in d.items(): - if isinstance(v, OpenAIObject): - d[k] = v.to_dict_recursive() - elif isinstance(v, list): - d[k] = [ - e.to_dict_recursive() if isinstance(e, OpenAIObject) else e - for e in v - ] - return d - - @property - def openai_id(self): - return self.id - - @property - def typed_api_type(self): - return ( - ApiType.from_str(self.api_type) - if self.api_type - else ApiType.from_str(openai.api_type) - ) - - # This class overrides __setitem__ to throw exceptions on inputs that it - # doesn't like. This can cause problems when we try to copy an object - # wholesale because some data that's returned from the API may not be valid - # if it was set to be set manually. Here we override the class' copy - # arguments so that we can bypass these possible exceptions on __setitem__. - def __copy__(self): - copied = OpenAIObject( - self.get("id"), - self.api_key, - api_version=self.api_version, - api_type=self.api_type, - organization=self.organization, - ) - - copied._retrieve_params = self._retrieve_params - - for k, v in self.items(): - # Call parent's __setitem__ to avoid checks that we've added in the - # overridden version that can throw exceptions. - super(OpenAIObject, copied).__setitem__(k, v) - - return copied - - # This class overrides __setitem__ to throw exceptions on inputs that it - # doesn't like. This can cause problems when we try to copy an object - # wholesale because some data that's returned from the API may not be valid - # if it was set to be set manually. Here we override the class' copy - # arguments so that we can bypass these possible exceptions on __setitem__. - def __deepcopy__(self, memo): - copied = self.__copy__() - memo[id(self)] = copied - - for k, v in self.items(): - # Call parent's __setitem__ to avoid checks that we've added in the - # overridden version that can throw exceptions. - super(OpenAIObject, copied).__setitem__(k, deepcopy(v, memo)) - - return copied diff --git a/openai/openai_response.py b/openai/openai_response.py deleted file mode 100644 index d2230b1540..0000000000 --- a/openai/openai_response.py +++ /dev/null @@ -1,31 +0,0 @@ -from typing import Optional - - -class OpenAIResponse: - def __init__(self, data, headers): - self._headers = headers - self.data = data - - @property - def request_id(self) -> Optional[str]: - return self._headers.get("request-id") - - @property - def retry_after(self) -> Optional[int]: - try: - return int(self._headers.get("retry-after")) - except TypeError: - return None - - @property - def operation_location(self) -> Optional[str]: - return self._headers.get("operation-location") - - @property - def organization(self) -> Optional[str]: - return self._headers.get("OpenAI-Organization") - - @property - def response_ms(self) -> Optional[int]: - h = self._headers.get("Openai-Processing-Ms") - return None if h is None else round(float(h)) diff --git a/openai/tests/__init__.py b/openai/tests/__init__.py deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/openai/tests/asyncio/__init__.py b/openai/tests/asyncio/__init__.py deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/openai/tests/asyncio/test_endpoints.py b/openai/tests/asyncio/test_endpoints.py deleted file mode 100644 index 1b146e6749..0000000000 --- a/openai/tests/asyncio/test_endpoints.py +++ /dev/null @@ -1,90 +0,0 @@ -import io -import json - -import pytest -from aiohttp import ClientSession - -import openai -from openai import error - -pytestmark = [pytest.mark.asyncio] - - -# FILE TESTS -async def test_file_upload(): - result = await openai.File.acreate( - file=io.StringIO( - json.dumps({"prompt": "test file data", "completion": "tada"}) - ), - purpose="fine-tune", - ) - assert result.purpose == "fine-tune" - assert "id" in result - - result = await openai.File.aretrieve(id=result.id) - assert result.status == "uploaded" - - -# COMPLETION TESTS -async def test_completions(): - result = await openai.Completion.acreate( - prompt="This was a test", n=5, engine="ada" - ) - assert len(result.choices) == 5 - - -async def test_completions_multiple_prompts(): - result = await openai.Completion.acreate( - prompt=["This was a test", "This was another test"], n=5, engine="ada" - ) - assert len(result.choices) == 10 - - -async def test_completions_model(): - result = await openai.Completion.acreate(prompt="This was a test", n=5, model="ada") - assert len(result.choices) == 5 - assert result.model.startswith("ada") - - -async def test_timeout_raises_error(): - # A query that should take awhile to return - with pytest.raises(error.Timeout): - await openai.Completion.acreate( - prompt="test" * 1000, - n=10, - model="ada", - max_tokens=100, - request_timeout=0.01, - ) - - -async def test_timeout_does_not_error(): - # A query that should be fast - await openai.Completion.acreate( - prompt="test", - model="ada", - request_timeout=10, - ) - - -async def test_completions_stream_finishes_global_session(): - async with ClientSession() as session: - openai.aiosession.set(session) - - # A query that should be fast - parts = [] - async for part in await openai.Completion.acreate( - prompt="test", model="ada", request_timeout=3, stream=True - ): - parts.append(part) - assert len(parts) > 1 - - -async def test_completions_stream_finishes_local_session(): - # A query that should be fast - parts = [] - async for part in await openai.Completion.acreate( - prompt="test", model="ada", request_timeout=3, stream=True - ): - parts.append(part) - assert len(parts) > 1 diff --git a/openai/tests/test_api_requestor.py b/openai/tests/test_api_requestor.py deleted file mode 100644 index 56e8ec89da..0000000000 --- a/openai/tests/test_api_requestor.py +++ /dev/null @@ -1,101 +0,0 @@ -import json - -import pytest -import requests -from pytest_mock import MockerFixture - -from openai import Model -from openai.api_requestor import APIRequestor - - -@pytest.mark.requestor -def test_requestor_sets_request_id(mocker: MockerFixture) -> None: - # Fake out 'requests' and confirm that the X-Request-Id header is set. - - got_headers = {} - - def fake_request(self, *args, **kwargs): - nonlocal got_headers - got_headers = kwargs["headers"] - r = requests.Response() - r.status_code = 200 - r.headers["content-type"] = "application/json" - r._content = json.dumps({}).encode("utf-8") - return r - - mocker.patch("requests.sessions.Session.request", fake_request) - fake_request_id = "1234" - Model.retrieve("xxx", request_id=fake_request_id) # arbitrary API resource - got_request_id = got_headers.get("X-Request-Id") - assert got_request_id == fake_request_id - - -@pytest.mark.requestor -def test_requestor_open_ai_headers() -> None: - api_requestor = APIRequestor(key="test_key", api_type="open_ai") - headers = {"Test_Header": "Unit_Test_Header"} - headers = api_requestor.request_headers( - method="get", extra=headers, request_id="test_id" - ) - assert "Test_Header" in headers - assert headers["Test_Header"] == "Unit_Test_Header" - assert "Authorization" in headers - assert headers["Authorization"] == "Bearer test_key" - - -@pytest.mark.requestor -def test_requestor_azure_headers() -> None: - api_requestor = APIRequestor(key="test_key", api_type="azure") - headers = {"Test_Header": "Unit_Test_Header"} - headers = api_requestor.request_headers( - method="get", extra=headers, request_id="test_id" - ) - assert "Test_Header" in headers - assert headers["Test_Header"] == "Unit_Test_Header" - assert "api-key" in headers - assert headers["api-key"] == "test_key" - - -@pytest.mark.requestor -def test_requestor_azure_ad_headers() -> None: - api_requestor = APIRequestor(key="test_key", api_type="azure_ad") - headers = {"Test_Header": "Unit_Test_Header"} - headers = api_requestor.request_headers( - method="get", extra=headers, request_id="test_id" - ) - assert "Test_Header" in headers - assert headers["Test_Header"] == "Unit_Test_Header" - assert "Authorization" in headers - assert headers["Authorization"] == "Bearer test_key" - - -@pytest.mark.requestor -def test_requestor_cycle_sessions(mocker: MockerFixture) -> None: - # HACK: we need to purge the _thread_context to not interfere - # with other tests - from openai.api_requestor import _thread_context - - delattr(_thread_context, "session") - - api_requestor = APIRequestor(key="test_key", api_type="azure_ad") - - mock_session = mocker.MagicMock() - mocker.patch("openai.api_requestor._make_session", lambda: mock_session) - - # We don't call `session.close()` if not enough time has elapsed - api_requestor.request_raw("get", "http://example.com/") - mock_session.request.assert_called() - api_requestor.request_raw("get", "http://example.com/") - mock_session.close.assert_not_called() - - mocker.patch("openai.api_requestor.MAX_SESSION_LIFETIME_SECS", 0) - - # Due to 0 lifetime, the original session will be closed before the next call - # and a new session will be created - mock_session_2 = mocker.MagicMock() - mocker.patch("openai.api_requestor._make_session", lambda: mock_session_2) - api_requestor.request_raw("get", "http://example.com/") - mock_session.close.assert_called() - mock_session_2.request.assert_called() - - delattr(_thread_context, "session") diff --git a/openai/tests/test_endpoints.py b/openai/tests/test_endpoints.py deleted file mode 100644 index 958e07f091..0000000000 --- a/openai/tests/test_endpoints.py +++ /dev/null @@ -1,118 +0,0 @@ -import io -import json - -import pytest -import requests - -import openai -from openai import error - - -# FILE TESTS -def test_file_upload(): - result = openai.File.create( - file=io.StringIO( - json.dumps({"prompt": "test file data", "completion": "tada"}) - ), - purpose="fine-tune", - ) - assert result.purpose == "fine-tune" - assert "id" in result - - result = openai.File.retrieve(id=result.id) - assert result.status == "uploaded" - - -# CHAT COMPLETION TESTS -def test_chat_completions(): - result = openai.ChatCompletion.create( - model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello!"}] - ) - assert len(result.choices) == 1 - - -def test_chat_completions_multiple(): - result = openai.ChatCompletion.create( - model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello!"}], n=5 - ) - assert len(result.choices) == 5 - - -def test_chat_completions_streaming(): - result = None - events = openai.ChatCompletion.create( - model="gpt-3.5-turbo", - messages=[{"role": "user", "content": "Hello!"}], - stream=True, - ) - for result in events: - assert len(result.choices) == 1 - - -# COMPLETION TESTS -def test_completions(): - result = openai.Completion.create(prompt="This was a test", n=5, engine="ada") - assert len(result.choices) == 5 - - -def test_completions_multiple_prompts(): - result = openai.Completion.create( - prompt=["This was a test", "This was another test"], n=5, engine="ada" - ) - assert len(result.choices) == 10 - - -def test_completions_model(): - result = openai.Completion.create(prompt="This was a test", n=5, model="ada") - assert len(result.choices) == 5 - assert result.model.startswith("ada") - - -def test_timeout_raises_error(): - # A query that should take awhile to return - with pytest.raises(error.Timeout): - openai.Completion.create( - prompt="test" * 1000, - n=10, - model="ada", - max_tokens=100, - request_timeout=0.01, - ) - - -def test_timeout_does_not_error(): - # A query that should be fast - openai.Completion.create( - prompt="test", - model="ada", - request_timeout=10, - ) - - -def test_user_session(): - with requests.Session() as session: - openai.requestssession = session - - completion = openai.Completion.create( - prompt="hello world", - model="ada", - ) - assert completion - - -def test_user_session_factory(): - def factory(): - session = requests.Session() - session.mount( - "https://", - requests.adapters.HTTPAdapter(max_retries=4), - ) - return session - - openai.requestssession = factory - - completion = openai.Completion.create( - prompt="hello world", - model="ada", - ) - assert completion diff --git a/openai/tests/test_exceptions.py b/openai/tests/test_exceptions.py deleted file mode 100644 index 7760cdc5f6..0000000000 --- a/openai/tests/test_exceptions.py +++ /dev/null @@ -1,40 +0,0 @@ -import pickle - -import pytest - -import openai - -EXCEPTION_TEST_CASES = [ - openai.InvalidRequestError( - "message", - "param", - code=400, - http_body={"test": "test1"}, - http_status="fail", - json_body={"text": "iono some text"}, - headers={"request-id": "asasd"}, - ), - openai.error.AuthenticationError(), - openai.error.PermissionError(), - openai.error.RateLimitError(), - openai.error.ServiceUnavailableError(), - openai.error.SignatureVerificationError("message", "sig_header?"), - openai.error.APIConnectionError("message!", should_retry=True), - openai.error.TryAgain(), - openai.error.Timeout(), - openai.error.APIError( - message="message", - code=400, - http_body={"test": "test1"}, - http_status="fail", - json_body={"text": "iono some text"}, - headers={"request-id": "asasd"}, - ), - openai.error.OpenAIError(), -] - - -class TestExceptions: - @pytest.mark.parametrize("error", EXCEPTION_TEST_CASES) - def test_exceptions_are_pickleable(self, error) -> None: - assert error.__repr__() == pickle.loads(pickle.dumps(error)).__repr__() diff --git a/openai/tests/test_file_cli.py b/openai/tests/test_file_cli.py deleted file mode 100644 index 69ea29e2a0..0000000000 --- a/openai/tests/test_file_cli.py +++ /dev/null @@ -1,39 +0,0 @@ -import json -import subprocess -import time -from tempfile import NamedTemporaryFile - -STILL_PROCESSING = "File is still processing. Check back later." - - -def test_file_cli() -> None: - contents = json.dumps({"prompt": "1 + 3 =", "completion": "4"}) + "\n" - with NamedTemporaryFile(suffix=".jsonl", mode="wb") as train_file: - train_file.write(contents.encode("utf-8")) - train_file.flush() - create_output = subprocess.check_output( - ["openai", "api", "files.create", "-f", train_file.name, "-p", "fine-tune"] - ) - file_obj = json.loads(create_output) - assert file_obj["bytes"] == len(contents) - file_id: str = file_obj["id"] - assert file_id.startswith("file-") - start_time = time.time() - while True: - delete_result = subprocess.run( - ["openai", "api", "files.delete", "-i", file_id], - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - encoding="utf-8", - ) - if delete_result.returncode == 0: - break - elif STILL_PROCESSING in delete_result.stderr: - time.sleep(0.5) - if start_time + 60 < time.time(): - raise RuntimeError("timed out waiting for file to become available") - continue - else: - raise RuntimeError( - f"delete failed: stdout={delete_result.stdout} stderr={delete_result.stderr}" - ) diff --git a/openai/tests/test_long_examples_validator.py b/openai/tests/test_long_examples_validator.py deleted file mode 100644 index 949a7cbbae..0000000000 --- a/openai/tests/test_long_examples_validator.py +++ /dev/null @@ -1,54 +0,0 @@ -import json -import subprocess -from tempfile import NamedTemporaryFile - -import pytest - -from openai.datalib.numpy_helper import HAS_NUMPY, NUMPY_INSTRUCTIONS -from openai.datalib.pandas_helper import HAS_PANDAS, PANDAS_INSTRUCTIONS - - -@pytest.mark.skipif(not HAS_PANDAS, reason=PANDAS_INSTRUCTIONS) -@pytest.mark.skipif(not HAS_NUMPY, reason=NUMPY_INSTRUCTIONS) -def test_long_examples_validator() -> None: - """ - Ensures that long_examples_validator() handles previously applied recommendations, - namely dropped duplicates, without resulting in a KeyError. - """ - - # data - short_prompt = "a prompt " - long_prompt = short_prompt * 500 - - short_completion = "a completion " - long_completion = short_completion * 500 - - # the order of these matters - unprepared_training_data = [ - {"prompt": long_prompt, "completion": long_completion}, # 1 of 2 duplicates - {"prompt": short_prompt, "completion": short_completion}, - {"prompt": long_prompt, "completion": long_completion}, # 2 of 2 duplicates - ] - - with NamedTemporaryFile(suffix=".jsonl", mode="w") as training_data: - print(training_data.name) - for prompt_completion_row in unprepared_training_data: - training_data.write(json.dumps(prompt_completion_row) + "\n") - training_data.flush() - - prepared_data_cmd_output = subprocess.run( - [f"openai tools fine_tunes.prepare_data -f {training_data.name}"], - stdout=subprocess.PIPE, - text=True, - input="y\ny\ny\ny\ny", # apply all recommendations, one at a time - stderr=subprocess.PIPE, - encoding="utf-8", - shell=True, - ) - - # validate data was prepared successfully - assert prepared_data_cmd_output.stderr == "" - # validate get_long_indexes() applied during optional_fn() call in long_examples_validator() - assert "indices of the long examples has changed" in prepared_data_cmd_output.stdout - - return prepared_data_cmd_output.stdout diff --git a/openai/tests/test_url_composition.py b/openai/tests/test_url_composition.py deleted file mode 100644 index 5034354a05..0000000000 --- a/openai/tests/test_url_composition.py +++ /dev/null @@ -1,209 +0,0 @@ -from sys import api_version - -import pytest - -from openai import Completion, Engine -from openai.util import ApiType - - -@pytest.mark.url -def test_completions_url_composition_azure() -> None: - url = Completion.class_url("http://github.com/test_engine%22,%20%22azure%22,%20%222021-11-01-preview") - assert ( - url - == "/openai/deployments/test_engine/completions?api-version=2021-11-01-preview" - ) - - -@pytest.mark.url -def test_completions_url_composition_azure_ad() -> None: - url = Completion.class_url("http://github.com/test_engine%22,%20%22azure_ad%22,%20%222021-11-01-preview") - assert ( - url - == "/openai/deployments/test_engine/completions?api-version=2021-11-01-preview" - ) - - -@pytest.mark.url -def test_completions_url_composition_default() -> None: - url = Completion.class_url("http://github.com/test_engine") - assert url == "/engines/test_engine/completions" - - -@pytest.mark.url -def test_completions_url_composition_open_ai() -> None: - url = Completion.class_url("http://github.com/test_engine%22,%20%22open_ai") - assert url == "/engines/test_engine/completions" - - -@pytest.mark.url -def test_completions_url_composition_invalid_type() -> None: - with pytest.raises(Exception): - url = Completion.class_url("http://github.com/test_engine%22,%20%22invalid") - - -@pytest.mark.url -def test_completions_url_composition_instance_url_azure() -> None: - completion = Completion( - id="test_id", - engine="test_engine", - api_type="azure", - api_version="2021-11-01-preview", - ) - url = completion.instance_url() - assert ( - url - == "/openai/deployments/test_engine/completions/test_id?api-version=2021-11-01-preview" - ) - - -@pytest.mark.url -def test_completions_url_composition_instance_url_azure_ad() -> None: - completion = Completion( - id="test_id", - engine="test_engine", - api_type="azure_ad", - api_version="2021-11-01-preview", - ) - url = completion.instance_url() - assert ( - url - == "/openai/deployments/test_engine/completions/test_id?api-version=2021-11-01-preview" - ) - - -@pytest.mark.url -def test_completions_url_composition_instance_url_azure_no_version() -> None: - completion = Completion( - id="test_id", engine="test_engine", api_type="azure", api_version=None - ) - with pytest.raises(Exception): - completion.instance_url() - - -@pytest.mark.url -def test_completions_url_composition_instance_url_default() -> None: - completion = Completion(id="test_id", engine="test_engine") - url = completion.instance_url() - assert url == "/engines/test_engine/completions/test_id" - - -@pytest.mark.url -def test_completions_url_composition_instance_url_open_ai() -> None: - completion = Completion( - id="test_id", - engine="test_engine", - api_type="open_ai", - api_version="2021-11-01-preview", - ) - url = completion.instance_url() - assert url == "/engines/test_engine/completions/test_id" - - -@pytest.mark.url -def test_completions_url_composition_instance_url_invalid() -> None: - completion = Completion(id="test_id", engine="test_engine", api_type="invalid") - with pytest.raises(Exception): - url = completion.instance_url() - - -@pytest.mark.url -def test_completions_url_composition_instance_url_timeout_azure() -> None: - completion = Completion( - id="test_id", - engine="test_engine", - api_type="azure", - api_version="2021-11-01-preview", - ) - completion["timeout"] = 12 - url = completion.instance_url() - assert ( - url - == "/openai/deployments/test_engine/completions/test_id?api-version=2021-11-01-preview&timeout=12" - ) - - -@pytest.mark.url -def test_completions_url_composition_instance_url_timeout_openai() -> None: - completion = Completion(id="test_id", engine="test_engine", api_type="open_ai") - completion["timeout"] = 12 - url = completion.instance_url() - assert url == "/engines/test_engine/completions/test_id?timeout=12" - - -@pytest.mark.url -def test_engine_search_url_composition_azure() -> None: - engine = Engine(id="test_id", api_type="azure", api_version="2021-11-01-preview") - assert engine.api_type == "azure" - assert engine.typed_api_type == ApiType.AZURE - url = engine.instance_url("http://github.com/test_operation") - assert ( - url - == "/openai/deployments/test_id/test_operation?api-version=2021-11-01-preview" - ) - - -@pytest.mark.url -def test_engine_search_url_composition_azure_ad() -> None: - engine = Engine(id="test_id", api_type="azure_ad", api_version="2021-11-01-preview") - assert engine.api_type == "azure_ad" - assert engine.typed_api_type == ApiType.AZURE_AD - url = engine.instance_url("http://github.com/test_operation") - assert ( - url - == "/openai/deployments/test_id/test_operation?api-version=2021-11-01-preview" - ) - - -@pytest.mark.url -def test_engine_search_url_composition_azure_no_version() -> None: - engine = Engine(id="test_id", api_type="azure", api_version=None) - assert engine.api_type == "azure" - assert engine.typed_api_type == ApiType.AZURE - with pytest.raises(Exception): - engine.instance_url("http://github.com/test_operation") - - -@pytest.mark.url -def test_engine_search_url_composition_azure_no_operation() -> None: - engine = Engine(id="test_id", api_type="azure", api_version="2021-11-01-preview") - assert engine.api_type == "azure" - assert engine.typed_api_type == ApiType.AZURE - assert ( - engine.instance_url() - == "/openai/engines/test_id?api-version=2021-11-01-preview" - ) - - -@pytest.mark.url -def test_engine_search_url_composition_default() -> None: - engine = Engine(id="test_id") - assert engine.api_type == None - assert engine.typed_api_type == ApiType.OPEN_AI - url = engine.instance_url() - assert url == "/engines/test_id" - - -@pytest.mark.url -def test_engine_search_url_composition_open_ai() -> None: - engine = Engine(id="test_id", api_type="open_ai") - assert engine.api_type == "open_ai" - assert engine.typed_api_type == ApiType.OPEN_AI - url = engine.instance_url() - assert url == "/engines/test_id" - - -@pytest.mark.url -def test_engine_search_url_composition_invalid_type() -> None: - engine = Engine(id="test_id", api_type="invalid") - assert engine.api_type == "invalid" - with pytest.raises(Exception): - assert engine.typed_api_type == ApiType.OPEN_AI - - -@pytest.mark.url -def test_engine_search_url_composition_invalid_search() -> None: - engine = Engine(id="test_id", api_type="invalid") - assert engine.api_type == "invalid" - with pytest.raises(Exception): - engine.search() diff --git a/openai/tests/test_util.py b/openai/tests/test_util.py deleted file mode 100644 index 6220ccb7f4..0000000000 --- a/openai/tests/test_util.py +++ /dev/null @@ -1,55 +0,0 @@ -import json -from tempfile import NamedTemporaryFile - -import pytest - -import openai -from openai import util - - -@pytest.fixture(scope="function") -def api_key_file(): - saved_path = openai.api_key_path - try: - with NamedTemporaryFile(prefix="openai-api-key", mode="wt") as tmp: - openai.api_key_path = tmp.name - yield tmp - finally: - openai.api_key_path = saved_path - - -def test_openai_api_key_path(api_key_file) -> None: - print("sk-foo", file=api_key_file) - api_key_file.flush() - assert util.default_api_key() == "sk-foo" - - -def test_openai_api_key_path_with_malformed_key(api_key_file) -> None: - print("malformed-api-key", file=api_key_file) - api_key_file.flush() - with pytest.raises(ValueError, match="Malformed API key"): - util.default_api_key() - - -def test_key_order_openai_object_rendering() -> None: - sample_response = { - "id": "chatcmpl-7NaPEA6sgX7LnNPyKPbRlsyqLbr5V", - "object": "chat.completion", - "created": 1685855844, - "model": "gpt-3.5-turbo-0301", - "usage": {"prompt_tokens": 57, "completion_tokens": 40, "total_tokens": 97}, - "choices": [ - { - "message": { - "role": "assistant", - "content": "The 2020 World Series was played at Globe Life Field in Arlington, Texas. It was the first time that the World Series was played at a neutral site because of the COVID-19 pandemic.", - }, - "finish_reason": "stop", - "index": 0, - } - ], - } - - oai_object = util.convert_to_openai_object(sample_response) - # The `__str__` method was sorting while dumping to json - assert list(json.loads(str(oai_object)).keys()) == list(sample_response.keys()) diff --git a/openai/upload_progress.py b/openai/upload_progress.py deleted file mode 100644 index e4da62a4e0..0000000000 --- a/openai/upload_progress.py +++ /dev/null @@ -1,52 +0,0 @@ -import io - - -class CancelledError(Exception): - def __init__(self, msg): - self.msg = msg - Exception.__init__(self, msg) - - def __str__(self): - return self.msg - - __repr__ = __str__ - - -class BufferReader(io.BytesIO): - def __init__(self, buf=b"", desc=None): - self._len = len(buf) - io.BytesIO.__init__(self, buf) - self._progress = 0 - self._callback = progress(len(buf), desc=desc) - - def __len__(self): - return self._len - - def read(self, n=-1): - chunk = io.BytesIO.read(self, n) - self._progress += len(chunk) - if self._callback: - try: - self._callback(self._progress) - except Exception as e: # catches exception from the callback - raise CancelledError("The upload was cancelled: {}".format(e)) - return chunk - - -def progress(total, desc): - import tqdm # type: ignore - - meter = tqdm.tqdm(total=total, unit_scale=True, desc=desc) - - def incr(progress): - meter.n = progress - if progress == total: - meter.close() - else: - meter.refresh() - - return incr - - -def MB(i): - return int(i // 1024**2) diff --git a/openai/util.py b/openai/util.py deleted file mode 100644 index 5501d5b67e..0000000000 --- a/openai/util.py +++ /dev/null @@ -1,188 +0,0 @@ -import logging -import os -import re -import sys -from enum import Enum -from typing import Optional - -import openai - -OPENAI_LOG = os.environ.get("OPENAI_LOG") - -logger = logging.getLogger("openai") - -__all__ = [ - "log_info", - "log_debug", - "log_warn", - "logfmt", -] - -api_key_to_header = ( - lambda api, key: {"Authorization": f"Bearer {key}"} - if api in (ApiType.OPEN_AI, ApiType.AZURE_AD) - else {"api-key": f"{key}"} -) - - -class ApiType(Enum): - AZURE = 1 - OPEN_AI = 2 - AZURE_AD = 3 - - @staticmethod - def from_str(label): - if label.lower() == "azure": - return ApiType.AZURE - elif label.lower() in ("azure_ad", "azuread"): - return ApiType.AZURE_AD - elif label.lower() in ("open_ai", "openai"): - return ApiType.OPEN_AI - else: - raise openai.error.InvalidAPIType( - "The API type provided in invalid. Please select one of the supported API types: 'azure', 'azure_ad', 'open_ai'" - ) - - -def _console_log_level(): - if openai.log in ["debug", "info"]: - return openai.log - elif OPENAI_LOG in ["debug", "info"]: - return OPENAI_LOG - else: - return None - - -def log_debug(message, **params): - msg = logfmt(dict(message=message, **params)) - if _console_log_level() == "debug": - print(msg, file=sys.stderr) - logger.debug(msg) - - -def log_info(message, **params): - msg = logfmt(dict(message=message, **params)) - if _console_log_level() in ["debug", "info"]: - print(msg, file=sys.stderr) - logger.info(msg) - - -def log_warn(message, **params): - msg = logfmt(dict(message=message, **params)) - print(msg, file=sys.stderr) - logger.warn(msg) - - -def logfmt(props): - def fmt(key, val): - # Handle case where val is a bytes or bytesarray - if hasattr(val, "decode"): - val = val.decode("utf-8") - # Check if val is already a string to avoid re-encoding into ascii. - if not isinstance(val, str): - val = str(val) - if re.search(r"\s", val): - val = repr(val) - # key should already be a string - if re.search(r"\s", key): - key = repr(key) - return "{key}={val}".format(key=key, val=val) - - return " ".join([fmt(key, val) for key, val in sorted(props.items())]) - - -def get_object_classes(): - # This is here to avoid a circular dependency - from openai.object_classes import OBJECT_CLASSES - - return OBJECT_CLASSES - - -def convert_to_openai_object( - resp, - api_key=None, - api_version=None, - organization=None, - engine=None, - plain_old_data=False, -): - # If we get a OpenAIResponse, we'll want to return a OpenAIObject. - - response_ms: Optional[int] = None - if isinstance(resp, openai.openai_response.OpenAIResponse): - organization = resp.organization - response_ms = resp.response_ms - resp = resp.data - - if plain_old_data: - return resp - elif isinstance(resp, list): - return [ - convert_to_openai_object( - i, api_key, api_version, organization, engine=engine - ) - for i in resp - ] - elif isinstance(resp, dict) and not isinstance( - resp, openai.openai_object.OpenAIObject - ): - resp = resp.copy() - klass_name = resp.get("object") - if isinstance(klass_name, str): - klass = get_object_classes().get( - klass_name, openai.openai_object.OpenAIObject - ) - else: - klass = openai.openai_object.OpenAIObject - - return klass.construct_from( - resp, - api_key=api_key, - api_version=api_version, - organization=organization, - response_ms=response_ms, - engine=engine, - ) - else: - return resp - - -def convert_to_dict(obj): - """Converts a OpenAIObject back to a regular dict. - - Nested OpenAIObjects are also converted back to regular dicts. - - :param obj: The OpenAIObject to convert. - - :returns: The OpenAIObject as a dict. - """ - if isinstance(obj, list): - return [convert_to_dict(i) for i in obj] - # This works by virtue of the fact that OpenAIObjects _are_ dicts. The dict - # comprehension returns a regular dict and recursively applies the - # conversion to each value. - elif isinstance(obj, dict): - return {k: convert_to_dict(v) for k, v in obj.items()} - else: - return obj - - -def merge_dicts(x, y): - z = x.copy() - z.update(y) - return z - - -def default_api_key() -> str: - if openai.api_key_path: - with open(openai.api_key_path, "rt") as k: - api_key = k.read().strip() - if not api_key.startswith("sk-"): - raise ValueError(f"Malformed API key in {openai.api_key_path}.") - return api_key - elif openai.api_key is not None: - return openai.api_key - else: - raise openai.error.AuthenticationError( - "No API key provided. You can set your API key in code using 'openai.api_key = ', or you can set the environment variable OPENAI_API_KEY=). If your API key is stored in a file, you can point the openai module at it with 'openai.api_key_path = '. You can generate API keys in the OpenAI web interface. See https://platform.openai.com/account/api-keys for details." - ) diff --git a/openai/version.py b/openai/version.py deleted file mode 100644 index 51f3ce82ff..0000000000 --- a/openai/version.py +++ /dev/null @@ -1 +0,0 @@ -VERSION = "0.27.9" diff --git a/openai/wandb_logger.py b/openai/wandb_logger.py deleted file mode 100644 index d8e060c41b..0000000000 --- a/openai/wandb_logger.py +++ /dev/null @@ -1,314 +0,0 @@ -try: - import wandb - - WANDB_AVAILABLE = True -except: - WANDB_AVAILABLE = False - - -if WANDB_AVAILABLE: - import datetime - import io - import json - import re - from pathlib import Path - - from openai import File, FineTune, FineTuningJob - from openai.datalib.numpy_helper import numpy as np - from openai.datalib.pandas_helper import assert_has_pandas, pandas as pd - - -class WandbLogger: - """ - Log fine-tunes to [Weights & Biases](https://wandb.me/openai-docs) - """ - - if not WANDB_AVAILABLE: - print("Logging requires wandb to be installed. Run `pip install wandb`.") - else: - _wandb_api = None - _logged_in = False - - @classmethod - def sync( - cls, - id=None, - n_fine_tunes=None, - project="OpenAI-Fine-Tune", - entity=None, - force=False, - legacy=False, - **kwargs_wandb_init, - ): - """ - Sync fine-tunes to Weights & Biases. - :param id: The id of the fine-tune (optional) - :param n_fine_tunes: Number of most recent fine-tunes to log when an id is not provided. By default, every fine-tune is synced. - :param project: Name of the project where you're sending runs. By default, it is "GPT-3". - :param entity: Username or team name where you're sending runs. By default, your default entity is used, which is usually your username. - :param force: Forces logging and overwrite existing wandb run of the same fine-tune. - """ - - assert_has_pandas() - - if not WANDB_AVAILABLE: - return - - if id: - print("Retrieving fine-tune job...") - if legacy: - fine_tune = FineTune.retrieve(id=id) - else: - fine_tune = FineTuningJob.retrieve(id=id) - fine_tune.pop("events", None) - fine_tunes = [fine_tune] - else: - # get list of fine_tune to log - if legacy: - fine_tunes = FineTune.list() - else: - fine_tunes = list(FineTuningJob.auto_paging_iter()) - if not fine_tunes or fine_tunes.get("data") is None: - print("No fine-tune has been retrieved") - return - fine_tunes = fine_tunes["data"][ - -n_fine_tunes if n_fine_tunes is not None else None : - ] - - # log starting from oldest fine_tune - show_individual_warnings = ( - False if id is None and n_fine_tunes is None else True - ) - fine_tune_logged = [ - cls._log_fine_tune( - fine_tune, - project, - entity, - force, - legacy, - show_individual_warnings, - **kwargs_wandb_init, - ) - for fine_tune in fine_tunes - ] - - if not show_individual_warnings and not any(fine_tune_logged): - print("No new successful fine-tunes were found") - - return "🎉 wandb sync completed successfully" - - @classmethod - def _log_fine_tune( - cls, - fine_tune, - project, - entity, - force, - legacy, - show_individual_warnings, - **kwargs_wandb_init, - ): - fine_tune_id = fine_tune.get("id") - status = fine_tune.get("status") - - # check run completed successfully - if status != "succeeded": - if show_individual_warnings: - print( - f'Fine-tune {fine_tune_id} has the status "{status}" and will not be logged' - ) - return - - # check results are present - try: - if legacy: - results_id = fine_tune["result_files"][0]["id"] - else: - results_id = fine_tune["result_files"][0] - results = File.download(id=results_id).decode("utf-8") - except: - if show_individual_warnings: - print(f"Fine-tune {fine_tune_id} has no results and will not be logged") - return - - # check run has not been logged already - run_path = f"{project}/{fine_tune_id}" - if entity is not None: - run_path = f"{entity}/{run_path}" - wandb_run = cls._get_wandb_run(run_path) - if wandb_run: - wandb_status = wandb_run.summary.get("status") - if show_individual_warnings: - if wandb_status == "succeeded": - print( - f"Fine-tune {fine_tune_id} has already been logged successfully at {wandb_run.url}" - ) - if not force: - print( - 'Use "--force" in the CLI or "force=True" in python if you want to overwrite previous run' - ) - else: - print( - f"A run for fine-tune {fine_tune_id} was previously created but didn't end successfully" - ) - if wandb_status != "succeeded" or force: - print( - f"A new wandb run will be created for fine-tune {fine_tune_id} and previous run will be overwritten" - ) - if wandb_status == "succeeded" and not force: - return - - # start a wandb run - wandb.init( - job_type="fine-tune", - config=cls._get_config(fine_tune), - project=project, - entity=entity, - name=fine_tune_id, - id=fine_tune_id, - **kwargs_wandb_init, - ) - - # log results - df_results = pd.read_csv(io.StringIO(results)) - for _, row in df_results.iterrows(): - metrics = {k: v for k, v in row.items() if not np.isnan(v)} - step = metrics.pop("step") - if step is not None: - step = int(step) - wandb.log(metrics, step=step) - fine_tuned_model = fine_tune.get("fine_tuned_model") - if fine_tuned_model is not None: - wandb.summary["fine_tuned_model"] = fine_tuned_model - - # training/validation files and fine-tune details - cls._log_artifacts(fine_tune, project, entity) - - # mark run as complete - wandb.summary["status"] = "succeeded" - - wandb.finish() - return True - - @classmethod - def _ensure_logged_in(cls): - if not cls._logged_in: - if wandb.login(): - cls._logged_in = True - else: - raise Exception("You need to log in to wandb") - - @classmethod - def _get_wandb_run(cls, run_path): - cls._ensure_logged_in() - try: - if cls._wandb_api is None: - cls._wandb_api = wandb.Api() - return cls._wandb_api.run(run_path) - except Exception: - return None - - @classmethod - def _get_wandb_artifact(cls, artifact_path): - cls._ensure_logged_in() - try: - if cls._wandb_api is None: - cls._wandb_api = wandb.Api() - return cls._wandb_api.artifact(artifact_path) - except Exception: - return None - - @classmethod - def _get_config(cls, fine_tune): - config = dict(fine_tune) - for key in ("training_files", "validation_files", "result_files"): - if config.get(key) and len(config[key]): - config[key] = config[key][0] - if config.get("created_at"): - config["created_at"] = datetime.datetime.fromtimestamp(config["created_at"]) - return config - - @classmethod - def _log_artifacts(cls, fine_tune, project, entity): - # training/validation files - training_file = ( - fine_tune["training_files"][0] - if fine_tune.get("training_files") and len(fine_tune["training_files"]) - else None - ) - validation_file = ( - fine_tune["validation_files"][0] - if fine_tune.get("validation_files") and len(fine_tune["validation_files"]) - else None - ) - for file, prefix, artifact_type in ( - (training_file, "train", "training_files"), - (validation_file, "valid", "validation_files"), - ): - if file is not None: - cls._log_artifact_inputs(file, prefix, artifact_type, project, entity) - - # fine-tune details - fine_tune_id = fine_tune.get("id") - artifact = wandb.Artifact( - "fine_tune_details", - type="fine_tune_details", - metadata=fine_tune, - ) - with artifact.new_file( - "fine_tune_details.json", mode="w", encoding="utf-8" - ) as f: - json.dump(fine_tune, f, indent=2) - wandb.run.log_artifact( - artifact, - aliases=["latest", fine_tune_id], - ) - - @classmethod - def _log_artifact_inputs(cls, file, prefix, artifact_type, project, entity): - file_id = file["id"] - filename = Path(file["filename"]).name - stem = Path(file["filename"]).stem - - # get input artifact - artifact_name = f"{prefix}-{filename}" - # sanitize name to valid wandb artifact name - artifact_name = re.sub(r"[^a-zA-Z0-9_\-.]", "_", artifact_name) - artifact_alias = file_id - artifact_path = f"{project}/{artifact_name}:{artifact_alias}" - if entity is not None: - artifact_path = f"{entity}/{artifact_path}" - artifact = cls._get_wandb_artifact(artifact_path) - - # create artifact if file not already logged previously - if artifact is None: - # get file content - try: - file_content = File.download(id=file_id).decode("utf-8") - except: - print( - f"File {file_id} could not be retrieved. Make sure you are allowed to download training/validation files" - ) - return - artifact = wandb.Artifact(artifact_name, type=artifact_type, metadata=file) - with artifact.new_file(filename, mode="w", encoding="utf-8") as f: - f.write(file_content) - - # create a Table - try: - table, n_items = cls._make_table(file_content) - artifact.add(table, stem) - wandb.config.update({f"n_{prefix}": n_items}) - artifact.metadata["items"] = n_items - except: - print(f"File {file_id} could not be read as a valid JSON file") - else: - # log number of items - wandb.config.update({f"n_{prefix}": artifact.metadata.get("items")}) - - wandb.run.use_artifact(artifact, aliases=["latest", artifact_alias]) - - @classmethod - def _make_table(cls, file_content): - df = pd.read_json(io.StringIO(file_content), orient="records", lines=True) - return wandb.Table(dataframe=df), len(df) diff --git a/public/Makefile b/public/Makefile deleted file mode 100644 index 2862fd4261..0000000000 --- a/public/Makefile +++ /dev/null @@ -1,7 +0,0 @@ -.PHONY: build upload - -build: - OPENAI_UPLOAD=y python setup.py sdist - -upload: - OPENAI_UPLOAD=y twine upload dist/* diff --git a/public/setup.py b/public/setup.py deleted file mode 100644 index 0198a53361..0000000000 --- a/public/setup.py +++ /dev/null @@ -1,10 +0,0 @@ -import os - -from setuptools import setup - -if os.getenv("OPENAI_UPLOAD") != "y": - raise RuntimeError( - "This package is a placeholder package on the public PyPI instance, and is not the correct version to install. If you are having trouble figuring out the correct package to install, please contact us." - ) - -setup(name="openai", description="Placeholder package", version="0.0.1") diff --git a/pyproject.toml b/pyproject.toml index 6116c7fa2f..7f6e3123d4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,13 +1,160 @@ +[project] +name = "openai" +version = "1.0.0" +description = "Client library for the openai API" +readme = "README.md" +license = "Apache-2.0" +authors = [ +{ name = "OpenAI", email = "support@openai.com" }, +] +dependencies = [ + "httpx>=0.23.0, <1", + "pydantic>=1.9.0, <3", + "typing-extensions>=4.5, <5", + "anyio>=3.5.0, <4", + "distro>=1.7.0, <2", + "tqdm > 4" +] +requires-python = ">= 3.7.1" +classifiers = [ + "Typing :: Typed", + "Intended Audience :: Developers", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Operating System :: OS Independent", + "Operating System :: POSIX", + "Operating System :: MacOS", + "Operating System :: POSIX :: Linux", + "Operating System :: Microsoft :: Windows", + "Topic :: Software Development :: Libraries :: Python Modules", +] + +[project.optional-dependencies] +datalib = ["numpy >= 1", "pandas >= 1.2.3", "pandas-stubs >= 1.1.0.11"] + +[project.urls] +Homepage = "https://github.com/openai/openai-python" +Repository = "https://github.com/openai/openai-python" + +[project.scripts] +openai = "openai.cli:main" + +[tool.rye] +managed = true +dev-dependencies = [ + "pyright==1.1.332", + "mypy==1.6.1", + "black==23.3.0", + "respx==0.19.2", + "pytest==7.1.1", + "pytest-asyncio==0.21.1", + "ruff==0.0.282", + "isort==5.10.1", + "time-machine==2.9.0", + "nox==2023.4.22", + "dirty-equals>=0.6.0", + "azure-identity >=1.14.1", + "types-tqdm > 4" +] + +[tool.rye.scripts] +format = { chain = [ + "format:black", + "format:docs", + "format:ruff", + "format:isort", +]} +"format:black" = "black ." +"format:docs" = "python bin/blacken-docs.py README.md api.md" +"format:ruff" = "ruff --fix ." +"format:isort" = "isort ." + +"check:ruff" = "ruff ." + +typecheck = { chain = [ + "typecheck:pyright", + "typecheck:mypy" +]} +"typecheck:pyright" = "pyright" +"typecheck:verify-types" = "pyright --verifytypes openai --ignoreexternal" +"typecheck:mypy" = "mypy --enable-incomplete-feature=Unpack ." + [build-system] -requires = ["setuptools"] -build-backend = "setuptools.build_meta" +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.hatch.build] +include = [ + "src/*" +] + +[tool.hatch.build.targets.wheel] +packages = ["src/openai"] [tool.black] -target-version = ['py36'] -exclude = '.*\.ipynb' +line-length = 120 +target-version = ["py37"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +addopts = "--tb=short" +xfail_strict = true +asyncio_mode = "auto" +filterwarnings = [ + "error" +] + +[tool.pyright] +# this enables practically every flag given by pyright. +# there are a couple of flags that are still disabled by +# default in strict mode as they are experimental and niche. +typeCheckingMode = "strict" +pythonVersion = "3.7" + +exclude = [ + "_dev", + ".venv", + ".nox", +] + +reportImplicitOverride = true + +reportImportCycles = false +reportPrivateUsage = false [tool.isort] -py_version = 36 -include_trailing_comma = "true" -line_length = 88 -multi_line_output = 3 +profile = "black" +length_sort = true +extra_standard_library = ["typing_extensions"] + +[tool.ruff] +line-length = 120 +format = "grouped" +target-version = "py37" +select = [ + # remove unused imports + "F401", + # bare except statements + "E722", + # unused arguments + "ARG", + # print statements + "T201", + "T203", +] +unfixable = [ + # disable auto fix for print statements + "T201", + "T203", +] +ignore-init-module-imports = true + + +[tool.ruff.per-file-ignores] +"bin/**.py" = ["T201", "T203"] +"tests/**.py" = ["T201", "T203"] +"examples/**.py" = ["T201", "T203"] diff --git a/pytest.ini b/pytest.ini deleted file mode 100644 index 5b78d87c16..0000000000 --- a/pytest.ini +++ /dev/null @@ -1,4 +0,0 @@ -[pytest] -markers = - url: mark a test as part of the url composition tests. - requestor: mark test as part of the api_requestor tests. diff --git a/requirements-dev.lock b/requirements-dev.lock new file mode 100644 index 0000000000..0747babdc5 --- /dev/null +++ b/requirements-dev.lock @@ -0,0 +1,74 @@ +# generated by rye +# use `rye lock` or `rye sync` to update this lockfile +# +# last locked with the following flags: +# pre: false +# features: [] +# all-features: true + +-e file:. +annotated-types==0.6.0 +anyio==3.7.1 +argcomplete==3.1.2 +attrs==23.1.0 +azure-core==1.29.5 +azure-identity==1.15.0 +black==23.3.0 +certifi==2023.7.22 +cffi==1.16.0 +charset-normalizer==3.3.1 +click==8.1.7 +colorlog==6.7.0 +cryptography==41.0.5 +dirty-equals==0.6.0 +distlib==0.3.7 +distro==1.8.0 +exceptiongroup==1.1.3 +filelock==3.12.4 +h11==0.12.0 +httpcore==0.15.0 +httpx==0.23.0 +idna==3.4 +iniconfig==2.0.0 +isort==5.10.1 +msal==1.24.1 +msal-extensions==1.0.0 +mypy==1.6.1 +mypy-extensions==1.0.0 +nodeenv==1.8.0 +nox==2023.4.22 +numpy==1.26.1 +packaging==23.2 +pandas==2.1.1 +pandas-stubs==2.1.1.230928 +pathspec==0.11.2 +platformdirs==3.11.0 +pluggy==1.3.0 +portalocker==2.8.2 +py==1.11.0 +pycparser==2.21 +pydantic==2.4.2 +pydantic-core==2.10.1 +pyjwt==2.8.0 +pyright==1.1.332 +pytest==7.1.1 +pytest-asyncio==0.21.1 +python-dateutil==2.8.2 +pytz==2023.3.post1 +requests==2.31.0 +respx==0.19.2 +rfc3986==1.5.0 +ruff==0.0.282 +six==1.16.0 +sniffio==1.3.0 +time-machine==2.9.0 +tomli==2.0.1 +tqdm==4.66.1 +types-pytz==2023.3.1.1 +types-tqdm==4.66.0.2 +typing-extensions==4.8.0 +tzdata==2023.3 +urllib3==2.0.7 +virtualenv==20.24.5 +# The following packages are considered to be unsafe in a requirements file: +setuptools==68.2.2 diff --git a/requirements.lock b/requirements.lock new file mode 100644 index 0000000000..be9606fc3c --- /dev/null +++ b/requirements.lock @@ -0,0 +1,32 @@ +# generated by rye +# use `rye lock` or `rye sync` to update this lockfile +# +# last locked with the following flags: +# pre: false +# features: [] +# all-features: true + +-e file:. +annotated-types==0.6.0 +anyio==3.7.1 +certifi==2023.7.22 +distro==1.8.0 +exceptiongroup==1.1.3 +h11==0.12.0 +httpcore==0.15.0 +httpx==0.23.0 +idna==3.4 +numpy==1.26.1 +pandas==2.1.1 +pandas-stubs==2.1.1.230928 +pydantic==2.4.2 +pydantic-core==2.10.1 +python-dateutil==2.8.2 +pytz==2023.3.post1 +rfc3986==1.5.0 +six==1.16.0 +sniffio==1.3.0 +tqdm==4.66.1 +types-pytz==2023.3.1.1 +typing-extensions==4.8.0 +tzdata==2023.3 diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 3729647b8d..0000000000 --- a/setup.cfg +++ /dev/null @@ -1,65 +0,0 @@ -[metadata] -name = openai -version = attr: openai.version.VERSION -description = Python client library for the OpenAI API -long_description = file: README.md -long_description_content_type = text/markdown -author = OpenAI -author_email = support@openai.com -url = https://github.com/openai/openai-python -license_files = LICENSE -classifiers = - Programming Language :: Python :: 3 - License :: OSI Approved :: MIT License - Operating System :: OS Independent - -[options] -packages = find: -python_requires = >=3.7.1 -zip_safe = True -include_package_data = True -install_requires = - requests >= 2.20 # to get the patch for CVE-2018-18074 - tqdm # Needed for progress bars - typing_extensions; python_version<"3.8" # Needed for type hints for mypy - aiohttp # Needed for async support - -[options.extras_require] -dev = - black ~= 21.6b0 - pytest == 6.* - pytest-asyncio - pytest-mock -datalib = - numpy - pandas >= 1.2.3 # Needed for CLI fine-tuning data preparation tool - pandas-stubs >= 1.1.0.11 # Needed for type hints for mypy - openpyxl >= 3.0.7 # Needed for CLI fine-tuning data preparation tool xlsx format -wandb = - wandb - numpy - pandas >= 1.2.3 # Needed for CLI fine-tuning data preparation tool - pandas-stubs >= 1.1.0.11 # Needed for type hints for mypy - openpyxl >= 3.0.7 # Needed for CLI fine-tuning data preparation tool xlsx format -embeddings = - scikit-learn >= 1.0.2 # Needed for embedding utils, versions >= 1.1 require python 3.8 - tenacity >= 8.0.1 - matplotlib - plotly - numpy - scipy - pandas >= 1.2.3 # Needed for CLI fine-tuning data preparation tool - pandas-stubs >= 1.1.0.11 # Needed for type hints for mypy - openpyxl >= 3.0.7 # Needed for CLI fine-tuning data preparation tool xlsx format - -[options.entry_points] -console_scripts = - openai = openai._openai_scripts:main - -[options.package_data] - openai = py.typed - -[options.packages.find] -exclude = - tests - tests.* diff --git a/setup.py b/setup.py deleted file mode 100644 index 606849326a..0000000000 --- a/setup.py +++ /dev/null @@ -1,3 +0,0 @@ -from setuptools import setup - -setup() diff --git a/src/openai/__init__.py b/src/openai/__init__.py new file mode 100644 index 0000000000..f033d8f26c --- /dev/null +++ b/src/openai/__init__.py @@ -0,0 +1,342 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import os as _os +from typing_extensions import override + +from . import types +from ._types import NoneType, Transport, ProxiesTypes +from ._utils import file_from_path +from ._client import ( + Client, + OpenAI, + Stream, + Timeout, + Transport, + AsyncClient, + AsyncOpenAI, + AsyncStream, + RequestOptions, +) +from ._version import __title__, __version__ +from ._exceptions import ( + APIError, + OpenAIError, + ConflictError, + NotFoundError, + APIStatusError, + RateLimitError, + APITimeoutError, + BadRequestError, + APIConnectionError, + AuthenticationError, + InternalServerError, + PermissionDeniedError, + UnprocessableEntityError, + APIResponseValidationError, +) +from ._utils._logs import setup_logging as _setup_logging + +__all__ = [ + "types", + "__version__", + "__title__", + "NoneType", + "Transport", + "ProxiesTypes", + "OpenAIError", + "APIError", + "APIStatusError", + "APITimeoutError", + "APIConnectionError", + "APIResponseValidationError", + "BadRequestError", + "AuthenticationError", + "PermissionDeniedError", + "NotFoundError", + "ConflictError", + "UnprocessableEntityError", + "RateLimitError", + "InternalServerError", + "Timeout", + "RequestOptions", + "Client", + "AsyncClient", + "Stream", + "AsyncStream", + "OpenAI", + "AsyncOpenAI", + "file_from_path", +] + +from .lib import azure as _azure +from .version import VERSION as VERSION +from .lib.azure import AzureOpenAI as AzureOpenAI +from .lib.azure import AsyncAzureOpenAI as AsyncAzureOpenAI + +_setup_logging() + +# Update the __module__ attribute for exported symbols so that +# error messages point to this module instead of the module +# it was originally defined in, e.g. +# openai._exceptions.NotFoundError -> openai.NotFoundError +__locals = locals() +for __name in __all__: + if not __name.startswith("__"): + try: + setattr(__locals[__name], "__module__", "openai") + except (TypeError, AttributeError): + # Some of our exported symbols are builtins which we can't set attributes for. + pass + +# ------ Module level client ------ +import typing as _t +import typing_extensions as _te + +import httpx as _httpx + +from ._base_client import DEFAULT_TIMEOUT, DEFAULT_MAX_RETRIES + +api_key: str | None = None + +organization: str | None = None + +base_url: str | _httpx.URL | None = None + +timeout: float | Timeout | None = DEFAULT_TIMEOUT + +max_retries: int = DEFAULT_MAX_RETRIES + +default_headers: _t.Mapping[str, str] | None = None + +default_query: _t.Mapping[str, object] | None = None + +http_client: _httpx.Client | None = None + +_ApiType = _te.Literal["openai", "azure"] + +api_type: _ApiType | None = _t.cast(_ApiType, _os.environ.get("OPENAI_API_TYPE")) + +api_version: str | None = _os.environ.get("OPENAI_API_VERSION") + +azure_endpoint: str | None = _os.environ.get("AZURE_OPENAI_ENDPOINT") + +azure_ad_token: str | None = _os.environ.get("AZURE_OPENAI_AD_TOKEN") + +azure_ad_token_provider: _azure.AzureADTokenProvider | None = None + + +class _ModuleClient(OpenAI): + # Note: we have to use type: ignores here as overriding class members + # with properties is technically unsafe but it is fine for our use case + + @property # type: ignore + @override + def api_key(self) -> str | None: + return api_key + + @api_key.setter # type: ignore + def api_key(self, value: str | None) -> None: # type: ignore + global api_key + + api_key = value + + @property # type: ignore + @override + def organization(self) -> str | None: + return organization + + @organization.setter # type: ignore + def organization(self, value: str | None) -> None: # type: ignore + global organization + + organization = value + + @property + @override + def base_url(http://github.com/self) -> _httpx.URL: + if base_url is not None: + return _httpx.URL(base_url) + + return super().base_url + + @base_url.setter + def base_url(http://github.com/self,%20url:%20_httpx.URL%20|%20str) -> None: + super().base_url = url # type: ignore[misc] + + @property # type: ignore + @override + def timeout(self) -> float | Timeout | None: + return timeout + + @timeout.setter # type: ignore + def timeout(self, value: float | Timeout | None) -> None: # type: ignore + global timeout + + timeout = value + + @property # type: ignore + @override + def max_retries(self) -> int: + return max_retries + + @max_retries.setter # type: ignore + def max_retries(self, value: int) -> None: # type: ignore + global max_retries + + max_retries = value + + @property # type: ignore + @override + def _custom_headers(self) -> _t.Mapping[str, str] | None: + return default_headers + + @_custom_headers.setter # type: ignore + def _custom_headers(self, value: _t.Mapping[str, str] | None) -> None: # type: ignore + global default_headers + + default_headers = value + + @property # type: ignore + @override + def _custom_query(self) -> _t.Mapping[str, object] | None: + return default_query + + @_custom_query.setter # type: ignore + def _custom_query(self, value: _t.Mapping[str, object] | None) -> None: # type: ignore + global default_query + + default_query = value + + @property # type: ignore + @override + def _client(self) -> _httpx.Client: + return http_client or super()._client + + @_client.setter # type: ignore + def _client(self, value: _httpx.Client) -> None: # type: ignore + global http_client + + http_client = value + + @override + def __del__(self) -> None: + try: + super().__del__() + except Exception: + pass + + +class _AzureModuleClient(_ModuleClient, AzureOpenAI): # type: ignore + ... + + +class _AmbiguousModuleClientUsageError(OpenAIError): + def __init__(self) -> None: + super().__init__( + "Ambiguous use of module client; please set `openai.api_type` or the `OPENAI_API_TYPE` environment variable to `openai` or `azure`" + ) + + +def _has_openai_credentials() -> bool: + return _os.environ.get("OPENAI_API_KEY") is not None + + +def _has_azure_credentials() -> bool: + return azure_endpoint is not None or _os.environ.get("AZURE_OPENAI_API_KEY") is not None + + +def _has_azure_ad_credentials() -> bool: + return ( + _os.environ.get("AZURE_OPENAI_AD_TOKEN") is not None + or azure_ad_token is not None + or azure_ad_token_provider is not None + ) + + +_client: OpenAI | None = None + + +def _load_client() -> OpenAI: # type: ignore[reportUnusedFunction] + global _client + + if _client is None: + global api_type, azure_endpoint, azure_ad_token, api_version + + if azure_endpoint is None: + azure_endpoint = _os.environ.get("AZURE_OPENAI_ENDPOINT") + + if azure_ad_token is None: + azure_ad_token = _os.environ.get("AZURE_OPENAI_AD_TOKEN") + + if api_version is None: + api_version = _os.environ.get("OPENAI_API_VERSION") + + if api_type is None: + has_openai = _has_openai_credentials() + has_azure = _has_azure_credentials() + has_azure_ad = _has_azure_ad_credentials() + + if has_openai and (has_azure or has_azure_ad): + raise _AmbiguousModuleClientUsageError() + + if (azure_ad_token is not None or azure_ad_token_provider is not None) and _os.environ.get( + "AZURE_OPENAI_API_KEY" + ) is not None: + raise _AmbiguousModuleClientUsageError() + + if has_azure or has_azure_ad: + api_type = "azure" + else: + api_type = "openai" + + if api_type == "azure": + _client = _AzureModuleClient( # type: ignore + api_version=api_version, + azure_endpoint=azure_endpoint, + api_key=api_key, + azure_ad_token=azure_ad_token, + azure_ad_token_provider=azure_ad_token_provider, + organization=organization, + base_url=base_url, + timeout=timeout, + max_retries=max_retries, + default_headers=default_headers, + default_query=default_query, + http_client=http_client, + ) + return _client + + _client = _ModuleClient( + api_key=api_key, + organization=organization, + base_url=base_url, + timeout=timeout, + max_retries=max_retries, + default_headers=default_headers, + default_query=default_query, + http_client=http_client, + ) + return _client + + return _client + + +def _reset_client() -> None: # type: ignore[reportUnusedFunction] + global _client + + _client = None + + +from ._module_client import chat as chat +from ._module_client import audio as audio +from ._module_client import edits as edits +from ._module_client import files as files +from ._module_client import images as images +from ._module_client import models as models +from ._module_client import embeddings as embeddings +from ._module_client import fine_tunes as fine_tunes +from ._module_client import completions as completions +from ._module_client import fine_tuning as fine_tuning +from ._module_client import moderations as moderations diff --git a/src/openai/__main__.py b/src/openai/__main__.py new file mode 100644 index 0000000000..4e28416e10 --- /dev/null +++ b/src/openai/__main__.py @@ -0,0 +1,3 @@ +from .cli import main + +main() diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py new file mode 100644 index 0000000000..22f90050d7 --- /dev/null +++ b/src/openai/_base_client.py @@ -0,0 +1,1768 @@ +from __future__ import annotations + +import os +import json +import time +import uuid +import email +import inspect +import logging +import platform +import warnings +import email.utils +from types import TracebackType +from random import random +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Type, + Union, + Generic, + Mapping, + TypeVar, + Iterable, + Iterator, + Optional, + Generator, + AsyncIterator, + cast, + overload, +) +from functools import lru_cache +from typing_extensions import Literal, override + +import anyio +import httpx +import distro +import pydantic +from httpx import URL, Limits +from pydantic import PrivateAttr + +from . import _exceptions +from ._qs import Querystring +from ._files import to_httpx_files, async_to_httpx_files +from ._types import ( + NOT_GIVEN, + Body, + Omit, + Query, + ModelT, + Headers, + Timeout, + NotGiven, + ResponseT, + Transport, + AnyMapping, + PostParser, + ProxiesTypes, + RequestFiles, + AsyncTransport, + RequestOptions, + UnknownResponse, + ModelBuilderProtocol, + BinaryResponseContent, +) +from ._utils import is_dict, is_given, is_mapping +from ._compat import model_copy, model_dump +from ._models import GenericModel, FinalRequestOptions, validate_type, construct_type +from ._response import APIResponse +from ._constants import ( + DEFAULT_LIMITS, + DEFAULT_TIMEOUT, + DEFAULT_MAX_RETRIES, + RAW_RESPONSE_HEADER, +) +from ._streaming import Stream, AsyncStream +from ._exceptions import APIStatusError, APITimeoutError, APIConnectionError + +log: logging.Logger = logging.getLogger(__name__) + +# TODO: make base page type vars covariant +SyncPageT = TypeVar("SyncPageT", bound="BaseSyncPage[Any]") +AsyncPageT = TypeVar("AsyncPageT", bound="BaseAsyncPage[Any]") + + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) + +_StreamT = TypeVar("_StreamT", bound=Stream[Any]) +_AsyncStreamT = TypeVar("_AsyncStreamT", bound=AsyncStream[Any]) + +if TYPE_CHECKING: + from httpx._config import DEFAULT_TIMEOUT_CONFIG as HTTPX_DEFAULT_TIMEOUT +else: + try: + from httpx._config import DEFAULT_TIMEOUT_CONFIG as HTTPX_DEFAULT_TIMEOUT + except ImportError: + # taken from https://github.com/encode/httpx/blob/3ba5fe0d7ac70222590e759c31442b1cab263791/httpx/_config.py#L366 + HTTPX_DEFAULT_TIMEOUT = Timeout(5.0) + + +class PageInfo: + """Stores the necesary information to build the request to retrieve the next page. + + Either `url` or `params` must be set. + """ + + url: URL | NotGiven + params: Query | NotGiven + + @overload + def __init__( + self, + *, + url: URL, + ) -> None: + ... + + @overload + def __init__( + self, + *, + params: Query, + ) -> None: + ... + + def __init__( + self, + *, + url: URL | NotGiven = NOT_GIVEN, + params: Query | NotGiven = NOT_GIVEN, + ) -> None: + self.url = url + self.params = params + + +class BasePage(GenericModel, Generic[ModelT]): + """ + Defines the core interface for pagination. + + Type Args: + ModelT: The pydantic model that represents an item in the response. + + Methods: + has_next_page(): Check if there is another page available + next_page_info(): Get the necessary information to make a request for the next page + """ + + _options: FinalRequestOptions = PrivateAttr() + _model: Type[ModelT] = PrivateAttr() + + def has_next_page(self) -> bool: + items = self._get_page_items() + if not items: + return False + return self.next_page_info() is not None + + def next_page_info(self) -> Optional[PageInfo]: + ... + + def _get_page_items(self) -> Iterable[ModelT]: # type: ignore[empty-body] + ... + + def _params_from_url(http://github.com/self,%20url:%20URL) -> httpx.QueryParams: + # TODO: do we have to preprocess params here? + return httpx.QueryParams(cast(Any, self._options.params)).merge(url.params) + + def _info_to_options(self, info: PageInfo) -> FinalRequestOptions: + options = model_copy(self._options) + options._strip_raw_response_header() + + if not isinstance(info.params, NotGiven): + options.params = {**options.params, **info.params} + return options + + if not isinstance(info.url, NotGiven): + params = self._params_from_url(http://github.com/info.url) + url = info.url.copy_with(params=params) + options.params = dict(url.params) + options.url = str(url) + return options + + raise ValueError("Unexpected PageInfo state") + + +class BaseSyncPage(BasePage[ModelT], Generic[ModelT]): + _client: SyncAPIClient = pydantic.PrivateAttr() + + def _set_private_attributes( + self, + client: SyncAPIClient, + model: Type[ModelT], + options: FinalRequestOptions, + ) -> None: + self._model = model + self._client = client + self._options = options + + # Pydantic uses a custom `__iter__` method to support casting BaseModels + # to dictionaries. e.g. dict(model). + # As we want to support `for item in page`, this is inherently incompatible + # with the default pydantic behaviour. It is not possible to support both + # use cases at once. Fortunately, this is not a big deal as all other pydantic + # methods should continue to work as expected as there is an alternative method + # to cast a model to a dictionary, model.dict(), which is used internally + # by pydantic. + def __iter__(self) -> Iterator[ModelT]: # type: ignore + for page in self.iter_pages(): + for item in page._get_page_items(): + yield item + + def iter_pages(self: SyncPageT) -> Iterator[SyncPageT]: + page = self + while True: + yield page + if page.has_next_page(): + page = page.get_next_page() + else: + return + + def get_next_page(self: SyncPageT) -> SyncPageT: + info = self.next_page_info() + if not info: + raise RuntimeError( + "No next page expected; please check `.has_next_page()` before calling `.get_next_page()`." + ) + + options = self._info_to_options(info) + return self._client._request_api_list(self._model, page=self.__class__, options=options) + + +class AsyncPaginator(Generic[ModelT, AsyncPageT]): + def __init__( + self, + client: AsyncAPIClient, + options: FinalRequestOptions, + page_cls: Type[AsyncPageT], + model: Type[ModelT], + ) -> None: + self._model = model + self._client = client + self._options = options + self._page_cls = page_cls + + def __await__(self) -> Generator[Any, None, AsyncPageT]: + return self._get_page().__await__() + + async def _get_page(self) -> AsyncPageT: + def _parser(resp: AsyncPageT) -> AsyncPageT: + resp._set_private_attributes( + model=self._model, + options=self._options, + client=self._client, + ) + return resp + + self._options.post_parser = _parser + + return await self._client.request(self._page_cls, self._options) + + async def __aiter__(self) -> AsyncIterator[ModelT]: + # https://github.com/microsoft/pyright/issues/3464 + page = cast( + AsyncPageT, + await self, # type: ignore + ) + async for item in page: + yield item + + +class BaseAsyncPage(BasePage[ModelT], Generic[ModelT]): + _client: AsyncAPIClient = pydantic.PrivateAttr() + + def _set_private_attributes( + self, + model: Type[ModelT], + client: AsyncAPIClient, + options: FinalRequestOptions, + ) -> None: + self._model = model + self._client = client + self._options = options + + async def __aiter__(self) -> AsyncIterator[ModelT]: + async for page in self.iter_pages(): + for item in page._get_page_items(): + yield item + + async def iter_pages(self: AsyncPageT) -> AsyncIterator[AsyncPageT]: + page = self + while True: + yield page + if page.has_next_page(): + page = await page.get_next_page() + else: + return + + async def get_next_page(self: AsyncPageT) -> AsyncPageT: + info = self.next_page_info() + if not info: + raise RuntimeError( + "No next page expected; please check `.has_next_page()` before calling `.get_next_page()`." + ) + + options = self._info_to_options(info) + return await self._client._request_api_list(self._model, page=self.__class__, options=options) + + +_HttpxClientT = TypeVar("_HttpxClientT", bound=Union[httpx.Client, httpx.AsyncClient]) +_DefaultStreamT = TypeVar("_DefaultStreamT", bound=Union[Stream[Any], AsyncStream[Any]]) + + +class BaseClient(Generic[_HttpxClientT, _DefaultStreamT]): + _client: _HttpxClientT + _version: str + _base_url: URL + max_retries: int + timeout: Union[float, Timeout, None] + _limits: httpx.Limits + _proxies: ProxiesTypes | None + _transport: Transport | AsyncTransport | None + _strict_response_validation: bool + _idempotency_header: str | None + _default_stream_cls: type[_DefaultStreamT] | None = None + + def __init__( + self, + *, + version: str, + base_url: str | URL, + _strict_response_validation: bool, + max_retries: int = DEFAULT_MAX_RETRIES, + timeout: float | Timeout | None = DEFAULT_TIMEOUT, + limits: httpx.Limits, + transport: Transport | AsyncTransport | None, + proxies: ProxiesTypes | None, + custom_headers: Mapping[str, str] | None = None, + custom_query: Mapping[str, object] | None = None, + ) -> None: + self._version = version + self._base_url = self._enforce_trailing_slash(URL(base_url)) + self.max_retries = max_retries + self.timeout = timeout + self._limits = limits + self._proxies = proxies + self._transport = transport + self._custom_headers = custom_headers or {} + self._custom_query = custom_query or {} + self._strict_response_validation = _strict_response_validation + self._idempotency_header = None + + def _enforce_trailing_slash(self, url: URL) -> URL: + if url.raw_path.endswith(b"/"): + return url + return url.copy_with(raw_path=url.raw_path + b"/") + + def _make_status_error_from_response( + self, + response: httpx.Response, + ) -> APIStatusError: + err_text = response.text.strip() + body = err_text + + try: + body = json.loads(err_text) + err_msg = f"Error code: {response.status_code} - {body}" + except Exception: + err_msg = err_text or f"Error code: {response.status_code}" + + return self._make_status_error(err_msg, body=body, response=response) + + def _make_status_error( + self, + err_msg: str, + *, + body: object, + response: httpx.Response, + ) -> _exceptions.APIStatusError: + raise NotImplementedError() + + def _remaining_retries( + self, + remaining_retries: Optional[int], + options: FinalRequestOptions, + ) -> int: + return remaining_retries if remaining_retries is not None else options.get_max_retries(self.max_retries) + + def _build_headers(self, options: FinalRequestOptions) -> httpx.Headers: + custom_headers = options.headers or {} + headers_dict = _merge_mappings(self.default_headers, custom_headers) + self._validate_headers(headers_dict, custom_headers) + + headers = httpx.Headers(headers_dict) + + idempotency_header = self._idempotency_header + if idempotency_header and options.method.lower() != "get" and idempotency_header not in headers: + if not options.idempotency_key: + options.idempotency_key = self._idempotency_key() + + headers[idempotency_header] = options.idempotency_key + + return headers + + def _prepare_url(http://github.com/self,%20url:%20str) -> URL: + """ + Merge a URL argument together with any 'base_url' on the client, + to create the URL used for the outgoing request. + """ + # Copied from httpx's `_merge_url` method. + merge_url = URL(url) + if merge_url.is_relative_url: + merge_raw_path = self.base_url.raw_path + merge_url.raw_path.lstrip(b"/") + return self.base_url.copy_with(raw_path=merge_raw_path) + + return merge_url + + def _build_request( + self, + options: FinalRequestOptions, + ) -> httpx.Request: + if log.isEnabledFor(logging.DEBUG): + log.debug("Request options: %s", model_dump(options, exclude_unset=True)) + + kwargs: dict[str, Any] = {} + + json_data = options.json_data + if options.extra_json is not None: + if json_data is None: + json_data = cast(Body, options.extra_json) + elif is_mapping(json_data): + json_data = _merge_mappings(json_data, options.extra_json) + else: + raise RuntimeError(f"Unexpected JSON data type, {type(json_data)}, cannot merge with `extra_body`") + + headers = self._build_headers(options) + params = _merge_mappings(self._custom_query, options.params) + + # If the given Content-Type header is multipart/form-data then it + # has to be removed so that httpx can generate the header with + # additional information for us as it has to be in this form + # for the server to be able to correctly parse the request: + # multipart/form-data; boundary=---abc-- + if headers.get("Content-Type") == "multipart/form-data": + headers.pop("Content-Type") + + # As we are now sending multipart/form-data instead of application/json + # we need to tell httpx to use it, https://www.python-httpx.org/advanced/#multipart-file-encoding + if json_data: + if not is_dict(json_data): + raise TypeError( + f"Expected query input to be a dictionary for multipart requests but got {type(json_data)} instead." + ) + kwargs["data"] = self._serialize_multipartform(json_data) + + # TODO: report this error to httpx + return self._client.build_request( # pyright: ignore[reportUnknownMemberType] + headers=headers, + timeout=self.timeout if isinstance(options.timeout, NotGiven) else options.timeout, + method=options.method, + url=self._prepare_url(http://github.com/options.url), + # the `Query` type that we use is incompatible with qs' + # `Params` type as it needs to be typed as `Mapping[str, object]` + # so that passing a `TypedDict` doesn't cause an error. + # https://github.com/microsoft/pyright/issues/3526#event-6715453066 + params=self.qs.stringify(cast(Mapping[str, Any], params)) if params else None, + json=json_data, + files=options.files, + **kwargs, + ) + + def _serialize_multipartform(self, data: Mapping[object, object]) -> dict[str, object]: + items = self.qs.stringify_items( + # TODO: type ignore is required as stringify_items is well typed but we can't be + # well typed without heavy validation. + data, # type: ignore + array_format="brackets", + ) + serialized: dict[str, object] = {} + for key, value in items: + if key in serialized: + raise ValueError(f"Duplicate key encountered: {key}; This behaviour is not supported") + serialized[key] = value + return serialized + + def _process_response( + self, + *, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + response: httpx.Response, + stream: bool, + stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None, + ) -> ResponseT: + api_response = APIResponse( + raw=response, + client=self, + cast_to=cast_to, + stream=stream, + stream_cls=stream_cls, + options=options, + ) + + if response.request.headers.get(RAW_RESPONSE_HEADER) == "true": + return cast(ResponseT, api_response) + + return api_response.parse() + + def _process_response_data( + self, + *, + data: object, + cast_to: type[ResponseT], + response: httpx.Response, + ) -> ResponseT: + if data is None: + return cast(ResponseT, None) + + if cast_to is UnknownResponse: + return cast(ResponseT, data) + + if inspect.isclass(cast_to) and issubclass(cast_to, ModelBuilderProtocol): + return cast(ResponseT, cast_to.build(response=response, data=data)) + + if self._strict_response_validation: + return cast(ResponseT, validate_type(type_=cast_to, value=data)) + + return cast(ResponseT, construct_type(type_=cast_to, value=data)) + + @property + def qs(self) -> Querystring: + return Querystring() + + @property + def custom_auth(self) -> httpx.Auth | None: + return None + + @property + def auth_headers(self) -> dict[str, str]: + return {} + + @property + def default_headers(self) -> dict[str, str | Omit]: + return { + "Accept": "application/json", + "Content-Type": "application/json", + "User-Agent": self.user_agent, + **self.platform_headers(), + **self.auth_headers, + **self._custom_headers, + } + + def _validate_headers( + self, + headers: Headers, # noqa: ARG002 + custom_headers: Headers, # noqa: ARG002 + ) -> None: + """Validate the given default headers and custom headers. + + Does nothing by default. + """ + return + + @property + def user_agent(self) -> str: + return f"{self.__class__.__name__}/Python {self._version}" + + @property + def base_url(http://github.com/self) -> URL: + return self._base_url + + @base_url.setter + def base_url(http://github.com/self,%20url:%20URL%20|%20str) -> None: + self._client.base_url = url if isinstance(url, URL) else URL(url) + + @lru_cache(maxsize=None) + def platform_headers(self) -> Dict[str, str]: + return { + "X-Stainless-Lang": "python", + "X-Stainless-Package-Version": self._version, + "X-Stainless-OS": str(get_platform()), + "X-Stainless-Arch": str(get_architecture()), + "X-Stainless-Runtime": platform.python_implementation(), + "X-Stainless-Runtime-Version": platform.python_version(), + } + + def _calculate_retry_timeout( + self, + remaining_retries: int, + options: FinalRequestOptions, + response_headers: Optional[httpx.Headers] = None, + ) -> float: + max_retries = options.get_max_retries(self.max_retries) + try: + # About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After + # + # ". See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#syntax for + # details. + if response_headers is not None: + retry_header = response_headers.get("retry-after") + try: + retry_after = int(retry_header) + except Exception: + retry_date_tuple = email.utils.parsedate_tz(retry_header) + if retry_date_tuple is None: + retry_after = -1 + else: + retry_date = email.utils.mktime_tz(retry_date_tuple) + retry_after = int(retry_date - time.time()) + else: + retry_after = -1 + + except Exception: + retry_after = -1 + + # If the API asks us to wait a certain amount of time (and it's a reasonable amount), just do what it says. + if 0 < retry_after <= 60: + return retry_after + + initial_retry_delay = 0.5 + max_retry_delay = 8.0 + nb_retries = max_retries - remaining_retries + + # Apply exponential backoff, but not more than the max. + sleep_seconds = min(initial_retry_delay * pow(2.0, nb_retries), max_retry_delay) + + # Apply some jitter, plus-or-minus half a second. + jitter = 1 - 0.25 * random() + timeout = sleep_seconds * jitter + return timeout if timeout >= 0 else 0 + + def _should_retry(self, response: httpx.Response) -> bool: + # Note: this is not a standard header + should_retry_header = response.headers.get("x-should-retry") + + # If the server explicitly says whether or not to retry, obey. + if should_retry_header == "true": + return True + if should_retry_header == "false": + return False + + # Retry on request timeouts. + if response.status_code == 408: + return True + + # Retry on lock timeouts. + if response.status_code == 409: + return True + + # Retry on rate limits. + if response.status_code == 429: + return True + + # Retry internal errors. + if response.status_code >= 500: + return True + + return False + + def _idempotency_key(self) -> str: + return f"stainless-python-retry-{uuid.uuid4()}" + + +class SyncAPIClient(BaseClient[httpx.Client, Stream[Any]]): + _client: httpx.Client + _has_custom_http_client: bool + _default_stream_cls: type[Stream[Any]] | None = None + + def __init__( + self, + *, + version: str, + base_url: str | URL, + max_retries: int = DEFAULT_MAX_RETRIES, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + transport: Transport | None = None, + proxies: ProxiesTypes | None = None, + limits: Limits | None = None, + http_client: httpx.Client | None = None, + custom_headers: Mapping[str, str] | None = None, + custom_query: Mapping[str, object] | None = None, + _strict_response_validation: bool, + ) -> None: + if limits is not None: + warnings.warn( + "The `connection_pool_limits` argument is deprecated. The `http_client` argument should be passed instead", + category=DeprecationWarning, + stacklevel=3, + ) + if http_client is not None: + raise ValueError("The `http_client` argument is mutually exclusive with `connection_pool_limits`") + else: + limits = DEFAULT_LIMITS + + if transport is not None: + warnings.warn( + "The `transport` argument is deprecated. The `http_client` argument should be passed instead", + category=DeprecationWarning, + stacklevel=3, + ) + if http_client is not None: + raise ValueError("The `http_client` argument is mutually exclusive with `transport`") + + if proxies is not None: + warnings.warn( + "The `proxies` argument is deprecated. The `http_client` argument should be passed instead", + category=DeprecationWarning, + stacklevel=3, + ) + if http_client is not None: + raise ValueError("The `http_client` argument is mutually exclusive with `proxies`") + + if not is_given(timeout): + # if the user passed in a custom http client with a non-default + # timeout set then we use that timeout. + # + # note: there is an edge case here where the user passes in a client + # where they've explicitly set the timeout to match the default timeout + # as this check is structural, meaning that we'll think they didn't + # pass in a timeout and will ignore it + if http_client and http_client.timeout != HTTPX_DEFAULT_TIMEOUT: + timeout = http_client.timeout + else: + timeout = DEFAULT_TIMEOUT + + super().__init__( + version=version, + limits=limits, + # cast to a valid type because mypy doesn't understand our type narrowing + timeout=cast(Timeout, timeout), + proxies=proxies, + base_url=base_url, + transport=transport, + max_retries=max_retries, + custom_query=custom_query, + custom_headers=custom_headers, + _strict_response_validation=_strict_response_validation, + ) + self._client = http_client or httpx.Client( + base_url=base_url, + # cast to a valid type because mypy doesn't understand our type narrowing + timeout=cast(Timeout, timeout), + proxies=proxies, + transport=transport, + limits=limits, + ) + self._has_custom_http_client = bool(http_client) + + def is_closed(self) -> bool: + return self._client.is_closed + + def close(self) -> None: + """Close the underlying HTTPX client. + + The client will *not* be usable after this. + """ + # If an error is thrown while constructing a client, self._client + # may not be present + if hasattr(self, "_client"): + self._client.close() + + def __enter__(self: _T) -> _T: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.close() + + def _prepare_options( + self, + options: FinalRequestOptions, # noqa: ARG002 + ) -> None: + """Hook for mutating the given options""" + return None + + def _prepare_request( + self, + request: httpx.Request, # noqa: ARG002 + ) -> None: + """This method is used as a callback for mutating the `Request` object + after it has been constructed. + This is useful for cases where you want to add certain headers based off of + the request properties, e.g. `url`, `method` etc. + """ + return None + + @overload + def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + remaining_retries: Optional[int] = None, + *, + stream: Literal[True], + stream_cls: Type[_StreamT], + ) -> _StreamT: + ... + + @overload + def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + remaining_retries: Optional[int] = None, + *, + stream: Literal[False] = False, + ) -> ResponseT: + ... + + @overload + def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + remaining_retries: Optional[int] = None, + *, + stream: bool = False, + stream_cls: Type[_StreamT] | None = None, + ) -> ResponseT | _StreamT: + ... + + def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + remaining_retries: Optional[int] = None, + *, + stream: bool = False, + stream_cls: type[_StreamT] | None = None, + ) -> ResponseT | _StreamT: + return self._request( + cast_to=cast_to, + options=options, + stream=stream, + stream_cls=stream_cls, + remaining_retries=remaining_retries, + ) + + def _request( + self, + *, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + remaining_retries: int | None, + stream: bool, + stream_cls: type[_StreamT] | None, + ) -> ResponseT | _StreamT: + self._prepare_options(options) + + retries = self._remaining_retries(remaining_retries, options) + request = self._build_request(options) + self._prepare_request(request) + + try: + response = self._client.send(request, auth=self.custom_auth, stream=stream) + log.debug( + 'HTTP Request: %s %s "%i %s"', request.method, request.url, response.status_code, response.reason_phrase + ) + response.raise_for_status() + except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code + if retries > 0 and self._should_retry(err.response): + return self._retry_request( + options, + cast_to, + retries, + err.response.headers, + stream=stream, + stream_cls=stream_cls, + ) + + # If the response is streamed then we need to explicitly read the response + # to completion before attempting to access the response text. + err.response.read() + raise self._make_status_error_from_response(err.response) from None + except httpx.TimeoutException as err: + if retries > 0: + return self._retry_request( + options, + cast_to, + retries, + stream=stream, + stream_cls=stream_cls, + ) + raise APITimeoutError(request=request) from err + except Exception as err: + if retries > 0: + return self._retry_request( + options, + cast_to, + retries, + stream=stream, + stream_cls=stream_cls, + ) + raise APIConnectionError(request=request) from err + + return self._process_response( + cast_to=cast_to, + options=options, + response=response, + stream=stream, + stream_cls=stream_cls, + ) + + def _retry_request( + self, + options: FinalRequestOptions, + cast_to: Type[ResponseT], + remaining_retries: int, + response_headers: Optional[httpx.Headers] = None, + *, + stream: bool, + stream_cls: type[_StreamT] | None, + ) -> ResponseT | _StreamT: + remaining = remaining_retries - 1 + timeout = self._calculate_retry_timeout(remaining, options, response_headers) + log.info("Retrying request to %s in %f seconds", options.url, timeout) + + # In a synchronous context we are blocking the entire thread. Up to the library user to run the client in a + # different thread if necessary. + time.sleep(timeout) + + return self._request( + options=options, + cast_to=cast_to, + remaining_retries=remaining, + stream=stream, + stream_cls=stream_cls, + ) + + def _request_api_list( + self, + model: Type[ModelT], + page: Type[SyncPageT], + options: FinalRequestOptions, + ) -> SyncPageT: + def _parser(resp: SyncPageT) -> SyncPageT: + resp._set_private_attributes( + client=self, + model=model, + options=options, + ) + return resp + + options.post_parser = _parser + + return self.request(page, options, stream=False) + + @overload + def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: Literal[False] = False, + ) -> ResponseT: + ... + + @overload + def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: Literal[True], + stream_cls: type[_StreamT], + ) -> _StreamT: + ... + + @overload + def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: bool, + stream_cls: type[_StreamT] | None = None, + ) -> ResponseT | _StreamT: + ... + + def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: bool = False, + stream_cls: type[_StreamT] | None = None, + ) -> ResponseT | _StreamT: + opts = FinalRequestOptions.construct(method="get", url=path, **options) + # cast is required because mypy complains about returning Any even though + # it understands the type variables + return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)) + + @overload + def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + options: RequestOptions = {}, + files: RequestFiles | None = None, + stream: Literal[False] = False, + ) -> ResponseT: + ... + + @overload + def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + options: RequestOptions = {}, + files: RequestFiles | None = None, + stream: Literal[True], + stream_cls: type[_StreamT], + ) -> _StreamT: + ... + + @overload + def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + options: RequestOptions = {}, + files: RequestFiles | None = None, + stream: bool, + stream_cls: type[_StreamT] | None = None, + ) -> ResponseT | _StreamT: + ... + + def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + options: RequestOptions = {}, + files: RequestFiles | None = None, + stream: bool = False, + stream_cls: type[_StreamT] | None = None, + ) -> ResponseT | _StreamT: + opts = FinalRequestOptions.construct( + method="post", url=path, json_data=body, files=to_httpx_files(files), **options + ) + return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls)) + + def patch( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + options: RequestOptions = {}, + ) -> ResponseT: + opts = FinalRequestOptions.construct(method="patch", url=path, json_data=body, **options) + return self.request(cast_to, opts) + + def put( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + ) -> ResponseT: + opts = FinalRequestOptions.construct( + method="put", url=path, json_data=body, files=to_httpx_files(files), **options + ) + return self.request(cast_to, opts) + + def delete( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + options: RequestOptions = {}, + ) -> ResponseT: + opts = FinalRequestOptions.construct(method="delete", url=path, json_data=body, **options) + return self.request(cast_to, opts) + + def get_api_list( + self, + path: str, + *, + model: Type[ModelT], + page: Type[SyncPageT], + body: Body | None = None, + options: RequestOptions = {}, + method: str = "get", + ) -> SyncPageT: + opts = FinalRequestOptions.construct(method=method, url=path, json_data=body, **options) + return self._request_api_list(model, page, opts) + + +class AsyncAPIClient(BaseClient[httpx.AsyncClient, AsyncStream[Any]]): + _client: httpx.AsyncClient + _has_custom_http_client: bool + _default_stream_cls: type[AsyncStream[Any]] | None = None + + def __init__( + self, + *, + version: str, + base_url: str | URL, + _strict_response_validation: bool, + max_retries: int = DEFAULT_MAX_RETRIES, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + transport: AsyncTransport | None = None, + proxies: ProxiesTypes | None = None, + limits: Limits | None = None, + http_client: httpx.AsyncClient | None = None, + custom_headers: Mapping[str, str] | None = None, + custom_query: Mapping[str, object] | None = None, + ) -> None: + if limits is not None: + warnings.warn( + "The `connection_pool_limits` argument is deprecated. The `http_client` argument should be passed instead", + category=DeprecationWarning, + stacklevel=3, + ) + if http_client is not None: + raise ValueError("The `http_client` argument is mutually exclusive with `connection_pool_limits`") + else: + limits = DEFAULT_LIMITS + + if transport is not None: + warnings.warn( + "The `transport` argument is deprecated. The `http_client` argument should be passed instead", + category=DeprecationWarning, + stacklevel=3, + ) + if http_client is not None: + raise ValueError("The `http_client` argument is mutually exclusive with `transport`") + + if proxies is not None: + warnings.warn( + "The `proxies` argument is deprecated. The `http_client` argument should be passed instead", + category=DeprecationWarning, + stacklevel=3, + ) + if http_client is not None: + raise ValueError("The `http_client` argument is mutually exclusive with `proxies`") + + if not is_given(timeout): + # if the user passed in a custom http client with a non-default + # timeout set then we use that timeout. + # + # note: there is an edge case here where the user passes in a client + # where they've explicitly set the timeout to match the default timeout + # as this check is structural, meaning that we'll think they didn't + # pass in a timeout and will ignore it + if http_client and http_client.timeout != HTTPX_DEFAULT_TIMEOUT: + timeout = http_client.timeout + else: + timeout = DEFAULT_TIMEOUT + + super().__init__( + version=version, + base_url=base_url, + limits=limits, + # cast to a valid type because mypy doesn't understand our type narrowing + timeout=cast(Timeout, timeout), + proxies=proxies, + transport=transport, + max_retries=max_retries, + custom_query=custom_query, + custom_headers=custom_headers, + _strict_response_validation=_strict_response_validation, + ) + self._client = http_client or httpx.AsyncClient( + base_url=base_url, + # cast to a valid type because mypy doesn't understand our type narrowing + timeout=cast(Timeout, timeout), + proxies=proxies, + transport=transport, + limits=limits, + ) + self._has_custom_http_client = bool(http_client) + + def is_closed(self) -> bool: + return self._client.is_closed + + async def close(self) -> None: + """Close the underlying HTTPX client. + + The client will *not* be usable after this. + """ + await self._client.aclose() + + async def __aenter__(self: _T) -> _T: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + await self.close() + + async def _prepare_options( + self, + options: FinalRequestOptions, # noqa: ARG002 + ) -> None: + """Hook for mutating the given options""" + return None + + async def _prepare_request( + self, + request: httpx.Request, # noqa: ARG002 + ) -> None: + """This method is used as a callback for mutating the `Request` object + after it has been constructed. + This is useful for cases where you want to add certain headers based off of + the request properties, e.g. `url`, `method` etc. + """ + return None + + @overload + async def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: Literal[False] = False, + remaining_retries: Optional[int] = None, + ) -> ResponseT: + ... + + @overload + async def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: Literal[True], + stream_cls: type[_AsyncStreamT], + remaining_retries: Optional[int] = None, + ) -> _AsyncStreamT: + ... + + @overload + async def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: bool, + stream_cls: type[_AsyncStreamT] | None = None, + remaining_retries: Optional[int] = None, + ) -> ResponseT | _AsyncStreamT: + ... + + async def request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: bool = False, + stream_cls: type[_AsyncStreamT] | None = None, + remaining_retries: Optional[int] = None, + ) -> ResponseT | _AsyncStreamT: + return await self._request( + cast_to=cast_to, + options=options, + stream=stream, + stream_cls=stream_cls, + remaining_retries=remaining_retries, + ) + + async def _request( + self, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + *, + stream: bool, + stream_cls: type[_AsyncStreamT] | None, + remaining_retries: int | None, + ) -> ResponseT | _AsyncStreamT: + await self._prepare_options(options) + + retries = self._remaining_retries(remaining_retries, options) + request = self._build_request(options) + await self._prepare_request(request) + + try: + response = await self._client.send(request, auth=self.custom_auth, stream=stream) + log.debug( + 'HTTP Request: %s %s "%i %s"', request.method, request.url, response.status_code, response.reason_phrase + ) + response.raise_for_status() + except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code + if retries > 0 and self._should_retry(err.response): + return await self._retry_request( + options, + cast_to, + retries, + err.response.headers, + stream=stream, + stream_cls=stream_cls, + ) + + # If the response is streamed then we need to explicitly read the response + # to completion before attempting to access the response text. + await err.response.aread() + raise self._make_status_error_from_response(err.response) from None + except httpx.ConnectTimeout as err: + if retries > 0: + return await self._retry_request(options, cast_to, retries, stream=stream, stream_cls=stream_cls) + raise APITimeoutError(request=request) from err + except httpx.ReadTimeout as err: + # We explicitly do not retry on ReadTimeout errors as this means + # that the server processing the request has taken 60 seconds + # (our default timeout). This likely indicates that something + # is not working as expected on the server side. + raise + except httpx.TimeoutException as err: + if retries > 0: + return await self._retry_request(options, cast_to, retries, stream=stream, stream_cls=stream_cls) + raise APITimeoutError(request=request) from err + except Exception as err: + if retries > 0: + return await self._retry_request(options, cast_to, retries, stream=stream, stream_cls=stream_cls) + raise APIConnectionError(request=request) from err + + return self._process_response( + cast_to=cast_to, + options=options, + response=response, + stream=stream, + stream_cls=stream_cls, + ) + + async def _retry_request( + self, + options: FinalRequestOptions, + cast_to: Type[ResponseT], + remaining_retries: int, + response_headers: Optional[httpx.Headers] = None, + *, + stream: bool, + stream_cls: type[_AsyncStreamT] | None, + ) -> ResponseT | _AsyncStreamT: + remaining = remaining_retries - 1 + timeout = self._calculate_retry_timeout(remaining, options, response_headers) + log.info("Retrying request to %s in %f seconds", options.url, timeout) + + await anyio.sleep(timeout) + + return await self._request( + options=options, + cast_to=cast_to, + remaining_retries=remaining, + stream=stream, + stream_cls=stream_cls, + ) + + def _request_api_list( + self, + model: Type[ModelT], + page: Type[AsyncPageT], + options: FinalRequestOptions, + ) -> AsyncPaginator[ModelT, AsyncPageT]: + return AsyncPaginator(client=self, options=options, page_cls=page, model=model) + + @overload + async def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: Literal[False] = False, + ) -> ResponseT: + ... + + @overload + async def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: Literal[True], + stream_cls: type[_AsyncStreamT], + ) -> _AsyncStreamT: + ... + + @overload + async def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: bool, + stream_cls: type[_AsyncStreamT] | None = None, + ) -> ResponseT | _AsyncStreamT: + ... + + async def get( + self, + path: str, + *, + cast_to: Type[ResponseT], + options: RequestOptions = {}, + stream: bool = False, + stream_cls: type[_AsyncStreamT] | None = None, + ) -> ResponseT | _AsyncStreamT: + opts = FinalRequestOptions.construct(method="get", url=path, **options) + return await self.request(cast_to, opts, stream=stream, stream_cls=stream_cls) + + @overload + async def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + stream: Literal[False] = False, + ) -> ResponseT: + ... + + @overload + async def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + stream: Literal[True], + stream_cls: type[_AsyncStreamT], + ) -> _AsyncStreamT: + ... + + @overload + async def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + stream: bool, + stream_cls: type[_AsyncStreamT] | None = None, + ) -> ResponseT | _AsyncStreamT: + ... + + async def post( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + stream: bool = False, + stream_cls: type[_AsyncStreamT] | None = None, + ) -> ResponseT | _AsyncStreamT: + opts = FinalRequestOptions.construct( + method="post", url=path, json_data=body, files=await async_to_httpx_files(files), **options + ) + return await self.request(cast_to, opts, stream=stream, stream_cls=stream_cls) + + async def patch( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + options: RequestOptions = {}, + ) -> ResponseT: + opts = FinalRequestOptions.construct(method="patch", url=path, json_data=body, **options) + return await self.request(cast_to, opts) + + async def put( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + files: RequestFiles | None = None, + options: RequestOptions = {}, + ) -> ResponseT: + opts = FinalRequestOptions.construct( + method="put", url=path, json_data=body, files=await async_to_httpx_files(files), **options + ) + return await self.request(cast_to, opts) + + async def delete( + self, + path: str, + *, + cast_to: Type[ResponseT], + body: Body | None = None, + options: RequestOptions = {}, + ) -> ResponseT: + opts = FinalRequestOptions.construct(method="delete", url=path, json_data=body, **options) + return await self.request(cast_to, opts) + + def get_api_list( + self, + path: str, + *, + # TODO: support paginating `str` + model: Type[ModelT], + page: Type[AsyncPageT], + body: Body | None = None, + options: RequestOptions = {}, + method: str = "get", + ) -> AsyncPaginator[ModelT, AsyncPageT]: + opts = FinalRequestOptions.construct(method=method, url=path, json_data=body, **options) + return self._request_api_list(model, page, opts) + + +def make_request_options( + *, + query: Query | None = None, + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + idempotency_key: str | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + post_parser: PostParser | NotGiven = NOT_GIVEN, +) -> RequestOptions: + """Create a dict of type RequestOptions without keys of NotGiven values.""" + options: RequestOptions = {} + if extra_headers is not None: + options["headers"] = extra_headers + + if extra_body is not None: + options["extra_json"] = cast(AnyMapping, extra_body) + + if query is not None: + options["params"] = query + + if extra_query is not None: + options["params"] = {**options.get("params", {}), **extra_query} + + if not isinstance(timeout, NotGiven): + options["timeout"] = timeout + + if idempotency_key is not None: + options["idempotency_key"] = idempotency_key + + if is_given(post_parser): + # internal + options["post_parser"] = post_parser # type: ignore + + return options + + +class OtherPlatform: + def __init__(self, name: str) -> None: + self.name = name + + @override + def __str__(self) -> str: + return f"Other:{self.name}" + + +Platform = Union[ + OtherPlatform, + Literal[ + "MacOS", + "Linux", + "Windows", + "FreeBSD", + "OpenBSD", + "iOS", + "Android", + "Unknown", + ], +] + + +def get_platform() -> Platform: + system = platform.system().lower() + platform_name = platform.platform().lower() + if "iphone" in platform_name or "ipad" in platform_name: + # Tested using Python3IDE on an iPhone 11 and Pythonista on an iPad 7 + # system is Darwin and platform_name is a string like: + # - Darwin-21.6.0-iPhone12,1-64bit + # - Darwin-21.6.0-iPad7,11-64bit + return "iOS" + + if system == "darwin": + return "MacOS" + + if system == "windows": + return "Windows" + + if "android" in platform_name: + # Tested using Pydroid 3 + # system is Linux and platform_name is a string like 'Linux-5.10.81-android12-9-00001-geba40aecb3b7-ab8534902-aarch64-with-libc' + return "Android" + + if system == "linux": + # https://distro.readthedocs.io/en/latest/#distro.id + distro_id = distro.id() + if distro_id == "freebsd": + return "FreeBSD" + + if distro_id == "openbsd": + return "OpenBSD" + + return "Linux" + + if platform_name: + return OtherPlatform(platform_name) + + return "Unknown" + + +class OtherArch: + def __init__(self, name: str) -> None: + self.name = name + + @override + def __str__(self) -> str: + return f"other:{self.name}" + + +Arch = Union[OtherArch, Literal["x32", "x64", "arm", "arm64", "unknown"]] + + +def get_architecture() -> Arch: + python_bitness, _ = platform.architecture() + machine = platform.machine().lower() + if machine in ("arm64", "aarch64"): + return "arm64" + + # TODO: untested + if machine == "arm": + return "arm" + + if machine == "x86_64": + return "x64" + + # TODO: untested + if python_bitness == "32bit": + return "x32" + + if machine: + return OtherArch(machine) + + return "unknown" + + +def _merge_mappings( + obj1: Mapping[_T_co, Union[_T, Omit]], + obj2: Mapping[_T_co, Union[_T, Omit]], +) -> Dict[_T_co, _T]: + """Merge two mappings of the same type, removing any values that are instances of `Omit`. + + In cases with duplicate keys the second mapping takes precedence. + """ + merged = {**obj1, **obj2} + return {key: value for key, value in merged.items() if not isinstance(value, Omit)} + + +class HttpxBinaryResponseContent(BinaryResponseContent): + response: httpx.Response + + def __init__(self, response: httpx.Response) -> None: + self.response = response + + @property + @override + def content(self) -> bytes: + return self.response.content + + @property + @override + def text(self) -> str: + return self.response.text + + @property + @override + def encoding(self) -> Optional[str]: + return self.response.encoding + + @property + @override + def charset_encoding(self) -> Optional[str]: + return self.response.charset_encoding + + @override + def json(self, **kwargs: Any) -> Any: + return self.response.json(**kwargs) + + @override + def read(self) -> bytes: + return self.response.read() + + @override + def iter_bytes(self, chunk_size: Optional[int] = None) -> Iterator[bytes]: + return self.response.iter_bytes(chunk_size) + + @override + def iter_text(self, chunk_size: Optional[int] = None) -> Iterator[str]: + return self.response.iter_text(chunk_size) + + @override + def iter_lines(self) -> Iterator[str]: + return self.response.iter_lines() + + @override + def iter_raw(self, chunk_size: Optional[int] = None) -> Iterator[bytes]: + return self.response.iter_raw(chunk_size) + + @override + def stream_to_file(self, file: str | os.PathLike[str]) -> None: + with open(file, mode="wb") as f: + for data in self.response.iter_bytes(): + f.write(data) + + @override + def close(self) -> None: + return self.response.close() + + @override + async def aread(self) -> bytes: + return await self.response.aread() + + @override + async def aiter_bytes(self, chunk_size: Optional[int] = None) -> AsyncIterator[bytes]: + return self.response.aiter_bytes(chunk_size) + + @override + async def aiter_text(self, chunk_size: Optional[int] = None) -> AsyncIterator[str]: + return self.response.aiter_text(chunk_size) + + @override + async def aiter_lines(self) -> AsyncIterator[str]: + return self.response.aiter_lines() + + @override + async def aiter_raw(self, chunk_size: Optional[int] = None) -> AsyncIterator[bytes]: + return self.response.aiter_raw(chunk_size) + + @override + async def astream_to_file(self, file: str | os.PathLike[str]) -> None: + path = anyio.Path(file) + async with await path.open(mode="wb") as f: + async for data in self.response.aiter_bytes(): + await f.write(data) + + @override + async def aclose(self) -> None: + return await self.response.aclose() diff --git a/src/openai/_client.py b/src/openai/_client.py new file mode 100644 index 0000000000..9df7eabf9a --- /dev/null +++ b/src/openai/_client.py @@ -0,0 +1,488 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import os +import asyncio +from typing import Union, Mapping +from typing_extensions import override + +import httpx + +from . import resources, _exceptions +from ._qs import Querystring +from ._types import ( + NOT_GIVEN, + Omit, + Timeout, + NotGiven, + Transport, + ProxiesTypes, + RequestOptions, +) +from ._utils import is_given +from ._version import __version__ +from ._streaming import Stream as Stream +from ._streaming import AsyncStream as AsyncStream +from ._exceptions import OpenAIError, APIStatusError +from ._base_client import DEFAULT_MAX_RETRIES, SyncAPIClient, AsyncAPIClient + +__all__ = [ + "Timeout", + "Transport", + "ProxiesTypes", + "RequestOptions", + "resources", + "OpenAI", + "AsyncOpenAI", + "Client", + "AsyncClient", +] + + +class OpenAI(SyncAPIClient): + completions: resources.Completions + chat: resources.Chat + edits: resources.Edits + embeddings: resources.Embeddings + files: resources.Files + images: resources.Images + audio: resources.Audio + moderations: resources.Moderations + models: resources.Models + fine_tuning: resources.FineTuning + fine_tunes: resources.FineTunes + with_raw_response: OpenAIWithRawResponse + + # client options + api_key: str + organization: str | None + + def __init__( + self, + *, + api_key: str | None = None, + organization: str | None = None, + base_url: str | httpx.URL | None = None, + timeout: Union[float, Timeout, None, NotGiven] = NOT_GIVEN, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + # Configure a custom httpx client. See the [httpx documentation](https://www.python-httpx.org/api/#client) for more details. + http_client: httpx.Client | None = None, + # Enable or disable schema validation for data returned by the API. + # When enabled an error APIResponseValidationError is raised + # if the API responds with invalid data for the expected schema. + # + # This parameter may be removed or changed in the future. + # If you rely on this feature, please open a GitHub issue + # outlining your use-case to help us decide if it should be + # part of our public interface in the future. + _strict_response_validation: bool = False, + ) -> None: + """Construct a new synchronous openai client instance. + + This automatically infers the following arguments from their corresponding environment variables if they are not provided: + - `api_key` from `OPENAI_API_KEY` + - `organization` from `OPENAI_ORG_ID` + """ + if api_key is None: + api_key = os.environ.get("OPENAI_API_KEY") + if api_key is None: + raise OpenAIError( + "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" + ) + self.api_key = api_key + + if organization is None: + organization = os.environ.get("OPENAI_ORG_ID") + self.organization = organization + + if base_url is None: + base_url = f"https://api.openai.com/v1" + + super().__init__( + version=__version__, + base_url=base_url, + max_retries=max_retries, + timeout=timeout, + http_client=http_client, + custom_headers=default_headers, + custom_query=default_query, + _strict_response_validation=_strict_response_validation, + ) + + self._default_stream_cls = Stream + + self.completions = resources.Completions(self) + self.chat = resources.Chat(self) + self.edits = resources.Edits(self) + self.embeddings = resources.Embeddings(self) + self.files = resources.Files(self) + self.images = resources.Images(self) + self.audio = resources.Audio(self) + self.moderations = resources.Moderations(self) + self.models = resources.Models(self) + self.fine_tuning = resources.FineTuning(self) + self.fine_tunes = resources.FineTunes(self) + self.with_raw_response = OpenAIWithRawResponse(self) + + @property + @override + def qs(self) -> Querystring: + return Querystring(array_format="comma") + + @property + @override + def auth_headers(self) -> dict[str, str]: + api_key = self.api_key + return {"Authorization": f"Bearer {api_key}"} + + @property + @override + def default_headers(self) -> dict[str, str | Omit]: + return { + **super().default_headers, + "OpenAI-Organization": self.organization if self.organization is not None else Omit(), + **self._custom_headers, + } + + def copy( + self, + *, + api_key: str | None = None, + organization: str | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + http_client: httpx.Client | None = None, + max_retries: int | NotGiven = NOT_GIVEN, + default_headers: Mapping[str, str] | None = None, + set_default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + set_default_query: Mapping[str, object] | None = None, + ) -> OpenAI: + """ + Create a new client instance re-using the same options given to the current client with optional overriding. + + It should be noted that this does not share the underlying httpx client class which may lead + to performance issues. + """ + if default_headers is not None and set_default_headers is not None: + raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive") + + if default_query is not None and set_default_query is not None: + raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive") + + headers = self._custom_headers + if default_headers is not None: + headers = {**headers, **default_headers} + elif set_default_headers is not None: + headers = set_default_headers + + params = self._custom_query + if default_query is not None: + params = {**params, **default_query} + elif set_default_query is not None: + params = set_default_query + + http_client = http_client or self._client + return self.__class__( + api_key=api_key or self.api_key, + organization=organization or self.organization, + base_url=base_url or str(self.base_url), + timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, + http_client=http_client, + max_retries=max_retries if is_given(max_retries) else self.max_retries, + default_headers=headers, + default_query=params, + ) + + # Alias for `copy` for nicer inline usage, e.g. + # client.with_options(timeout=10).foo.create(...) + with_options = copy + + def __del__(self) -> None: + if not hasattr(self, "_has_custom_http_client") or not hasattr(self, "close"): + # this can happen if the '__init__' method raised an error + return + + if self._has_custom_http_client: + return + + self.close() + + @override + def _make_status_error( + self, + err_msg: str, + *, + body: object, + response: httpx.Response, + ) -> APIStatusError: + if response.status_code == 400: + return _exceptions.BadRequestError(err_msg, response=response, body=body) + + if response.status_code == 401: + return _exceptions.AuthenticationError(err_msg, response=response, body=body) + + if response.status_code == 403: + return _exceptions.PermissionDeniedError(err_msg, response=response, body=body) + + if response.status_code == 404: + return _exceptions.NotFoundError(err_msg, response=response, body=body) + + if response.status_code == 409: + return _exceptions.ConflictError(err_msg, response=response, body=body) + + if response.status_code == 422: + return _exceptions.UnprocessableEntityError(err_msg, response=response, body=body) + + if response.status_code == 429: + return _exceptions.RateLimitError(err_msg, response=response, body=body) + + if response.status_code >= 500: + return _exceptions.InternalServerError(err_msg, response=response, body=body) + return APIStatusError(err_msg, response=response, body=body) + + +class AsyncOpenAI(AsyncAPIClient): + completions: resources.AsyncCompletions + chat: resources.AsyncChat + edits: resources.AsyncEdits + embeddings: resources.AsyncEmbeddings + files: resources.AsyncFiles + images: resources.AsyncImages + audio: resources.AsyncAudio + moderations: resources.AsyncModerations + models: resources.AsyncModels + fine_tuning: resources.AsyncFineTuning + fine_tunes: resources.AsyncFineTunes + with_raw_response: AsyncOpenAIWithRawResponse + + # client options + api_key: str + organization: str | None + + def __init__( + self, + *, + api_key: str | None = None, + organization: str | None = None, + base_url: str | httpx.URL | None = None, + timeout: Union[float, Timeout, None, NotGiven] = NOT_GIVEN, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + # Configure a custom httpx client. See the [httpx documentation](https://www.python-httpx.org/api/#asyncclient) for more details. + http_client: httpx.AsyncClient | None = None, + # Enable or disable schema validation for data returned by the API. + # When enabled an error APIResponseValidationError is raised + # if the API responds with invalid data for the expected schema. + # + # This parameter may be removed or changed in the future. + # If you rely on this feature, please open a GitHub issue + # outlining your use-case to help us decide if it should be + # part of our public interface in the future. + _strict_response_validation: bool = False, + ) -> None: + """Construct a new async openai client instance. + + This automatically infers the following arguments from their corresponding environment variables if they are not provided: + - `api_key` from `OPENAI_API_KEY` + - `organization` from `OPENAI_ORG_ID` + """ + if api_key is None: + api_key = os.environ.get("OPENAI_API_KEY") + if api_key is None: + raise OpenAIError( + "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" + ) + self.api_key = api_key + + if organization is None: + organization = os.environ.get("OPENAI_ORG_ID") + self.organization = organization + + if base_url is None: + base_url = f"https://api.openai.com/v1" + + super().__init__( + version=__version__, + base_url=base_url, + max_retries=max_retries, + timeout=timeout, + http_client=http_client, + custom_headers=default_headers, + custom_query=default_query, + _strict_response_validation=_strict_response_validation, + ) + + self._default_stream_cls = AsyncStream + + self.completions = resources.AsyncCompletions(self) + self.chat = resources.AsyncChat(self) + self.edits = resources.AsyncEdits(self) + self.embeddings = resources.AsyncEmbeddings(self) + self.files = resources.AsyncFiles(self) + self.images = resources.AsyncImages(self) + self.audio = resources.AsyncAudio(self) + self.moderations = resources.AsyncModerations(self) + self.models = resources.AsyncModels(self) + self.fine_tuning = resources.AsyncFineTuning(self) + self.fine_tunes = resources.AsyncFineTunes(self) + self.with_raw_response = AsyncOpenAIWithRawResponse(self) + + @property + @override + def qs(self) -> Querystring: + return Querystring(array_format="comma") + + @property + @override + def auth_headers(self) -> dict[str, str]: + api_key = self.api_key + return {"Authorization": f"Bearer {api_key}"} + + @property + @override + def default_headers(self) -> dict[str, str | Omit]: + return { + **super().default_headers, + "OpenAI-Organization": self.organization if self.organization is not None else Omit(), + **self._custom_headers, + } + + def copy( + self, + *, + api_key: str | None = None, + organization: str | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + http_client: httpx.AsyncClient | None = None, + max_retries: int | NotGiven = NOT_GIVEN, + default_headers: Mapping[str, str] | None = None, + set_default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + set_default_query: Mapping[str, object] | None = None, + ) -> AsyncOpenAI: + """ + Create a new client instance re-using the same options given to the current client with optional overriding. + + It should be noted that this does not share the underlying httpx client class which may lead + to performance issues. + """ + if default_headers is not None and set_default_headers is not None: + raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive") + + if default_query is not None and set_default_query is not None: + raise ValueError("The `default_query` and `set_default_query` arguments are mutually exclusive") + + headers = self._custom_headers + if default_headers is not None: + headers = {**headers, **default_headers} + elif set_default_headers is not None: + headers = set_default_headers + + params = self._custom_query + if default_query is not None: + params = {**params, **default_query} + elif set_default_query is not None: + params = set_default_query + + http_client = http_client or self._client + return self.__class__( + api_key=api_key or self.api_key, + organization=organization or self.organization, + base_url=base_url or str(self.base_url), + timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, + http_client=http_client, + max_retries=max_retries if is_given(max_retries) else self.max_retries, + default_headers=headers, + default_query=params, + ) + + # Alias for `copy` for nicer inline usage, e.g. + # client.with_options(timeout=10).foo.create(...) + with_options = copy + + def __del__(self) -> None: + if not hasattr(self, "_has_custom_http_client") or not hasattr(self, "close"): + # this can happen if the '__init__' method raised an error + return + + if self._has_custom_http_client: + return + + try: + asyncio.get_running_loop().create_task(self.close()) + except Exception: + pass + + @override + def _make_status_error( + self, + err_msg: str, + *, + body: object, + response: httpx.Response, + ) -> APIStatusError: + if response.status_code == 400: + return _exceptions.BadRequestError(err_msg, response=response, body=body) + + if response.status_code == 401: + return _exceptions.AuthenticationError(err_msg, response=response, body=body) + + if response.status_code == 403: + return _exceptions.PermissionDeniedError(err_msg, response=response, body=body) + + if response.status_code == 404: + return _exceptions.NotFoundError(err_msg, response=response, body=body) + + if response.status_code == 409: + return _exceptions.ConflictError(err_msg, response=response, body=body) + + if response.status_code == 422: + return _exceptions.UnprocessableEntityError(err_msg, response=response, body=body) + + if response.status_code == 429: + return _exceptions.RateLimitError(err_msg, response=response, body=body) + + if response.status_code >= 500: + return _exceptions.InternalServerError(err_msg, response=response, body=body) + return APIStatusError(err_msg, response=response, body=body) + + +class OpenAIWithRawResponse: + def __init__(self, client: OpenAI) -> None: + self.completions = resources.CompletionsWithRawResponse(client.completions) + self.chat = resources.ChatWithRawResponse(client.chat) + self.edits = resources.EditsWithRawResponse(client.edits) + self.embeddings = resources.EmbeddingsWithRawResponse(client.embeddings) + self.files = resources.FilesWithRawResponse(client.files) + self.images = resources.ImagesWithRawResponse(client.images) + self.audio = resources.AudioWithRawResponse(client.audio) + self.moderations = resources.ModerationsWithRawResponse(client.moderations) + self.models = resources.ModelsWithRawResponse(client.models) + self.fine_tuning = resources.FineTuningWithRawResponse(client.fine_tuning) + self.fine_tunes = resources.FineTunesWithRawResponse(client.fine_tunes) + + +class AsyncOpenAIWithRawResponse: + def __init__(self, client: AsyncOpenAI) -> None: + self.completions = resources.AsyncCompletionsWithRawResponse(client.completions) + self.chat = resources.AsyncChatWithRawResponse(client.chat) + self.edits = resources.AsyncEditsWithRawResponse(client.edits) + self.embeddings = resources.AsyncEmbeddingsWithRawResponse(client.embeddings) + self.files = resources.AsyncFilesWithRawResponse(client.files) + self.images = resources.AsyncImagesWithRawResponse(client.images) + self.audio = resources.AsyncAudioWithRawResponse(client.audio) + self.moderations = resources.AsyncModerationsWithRawResponse(client.moderations) + self.models = resources.AsyncModelsWithRawResponse(client.models) + self.fine_tuning = resources.AsyncFineTuningWithRawResponse(client.fine_tuning) + self.fine_tunes = resources.AsyncFineTunesWithRawResponse(client.fine_tunes) + + +Client = OpenAI + +AsyncClient = AsyncOpenAI diff --git a/src/openai/_compat.py b/src/openai/_compat.py new file mode 100644 index 0000000000..34323c9b7e --- /dev/null +++ b/src/openai/_compat.py @@ -0,0 +1,173 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union, TypeVar, cast +from datetime import date, datetime + +import pydantic +from pydantic.fields import FieldInfo + +from ._types import StrBytesIntFloat + +_ModelT = TypeVar("_ModelT", bound=pydantic.BaseModel) + +# --------------- Pydantic v2 compatibility --------------- + +# Pyright incorrectly reports some of our functions as overriding a method when they don't +# pyright: reportIncompatibleMethodOverride=false + +PYDANTIC_V2 = pydantic.VERSION.startswith("2.") + +# v1 re-exports +if TYPE_CHECKING: + + def parse_date(value: date | StrBytesIntFloat) -> date: # noqa: ARG001 + ... + + def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime: # noqa: ARG001 + ... + + def get_args(t: type[Any]) -> tuple[Any, ...]: # noqa: ARG001 + ... + + def is_union(tp: type[Any] | None) -> bool: # noqa: ARG001 + ... + + def get_origin(t: type[Any]) -> type[Any] | None: # noqa: ARG001 + ... + + def is_literal_type(type_: type[Any]) -> bool: # noqa: ARG001 + ... + + def is_typeddict(type_: type[Any]) -> bool: # noqa: ARG001 + ... + +else: + if PYDANTIC_V2: + from pydantic.v1.typing import get_args as get_args + from pydantic.v1.typing import is_union as is_union + from pydantic.v1.typing import get_origin as get_origin + from pydantic.v1.typing import is_typeddict as is_typeddict + from pydantic.v1.typing import is_literal_type as is_literal_type + from pydantic.v1.datetime_parse import parse_date as parse_date + from pydantic.v1.datetime_parse import parse_datetime as parse_datetime + else: + from pydantic.typing import get_args as get_args + from pydantic.typing import is_union as is_union + from pydantic.typing import get_origin as get_origin + from pydantic.typing import is_typeddict as is_typeddict + from pydantic.typing import is_literal_type as is_literal_type + from pydantic.datetime_parse import parse_date as parse_date + from pydantic.datetime_parse import parse_datetime as parse_datetime + + +# refactored config +if TYPE_CHECKING: + from pydantic import ConfigDict as ConfigDict +else: + if PYDANTIC_V2: + from pydantic import ConfigDict + else: + # TODO: provide an error message here? + ConfigDict = None + + +# renamed methods / properties +def parse_obj(model: type[_ModelT], value: object) -> _ModelT: + if PYDANTIC_V2: + return model.model_validate(value) + else: + return cast(_ModelT, model.parse_obj(value)) # pyright: ignore[reportDeprecated, reportUnnecessaryCast] + + +def field_is_required(field: FieldInfo) -> bool: + if PYDANTIC_V2: + return field.is_required() + return field.required # type: ignore + + +def field_get_default(field: FieldInfo) -> Any: + value = field.get_default() + if PYDANTIC_V2: + from pydantic_core import PydanticUndefined + + if value == PydanticUndefined: + return None + return value + return value + + +def field_outer_type(field: FieldInfo) -> Any: + if PYDANTIC_V2: + return field.annotation + return field.outer_type_ # type: ignore + + +def get_model_config(model: type[pydantic.BaseModel]) -> Any: + if PYDANTIC_V2: + return model.model_config + return model.__config__ # type: ignore + + +def get_model_fields(model: type[pydantic.BaseModel]) -> dict[str, FieldInfo]: + if PYDANTIC_V2: + return model.model_fields + return model.__fields__ # type: ignore + + +def model_copy(model: _ModelT) -> _ModelT: + if PYDANTIC_V2: + return model.model_copy() + return model.copy() # type: ignore + + +def model_json(model: pydantic.BaseModel, *, indent: int | None = None) -> str: + if PYDANTIC_V2: + return model.model_dump_json(indent=indent) + return model.json(indent=indent) # type: ignore + + +def model_dump( + model: pydantic.BaseModel, + *, + exclude_unset: bool = False, + exclude_defaults: bool = False, +) -> dict[str, Any]: + if PYDANTIC_V2: + return model.model_dump( + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + ) + return cast( + "dict[str, Any]", + model.dict( # pyright: ignore[reportDeprecated, reportUnnecessaryCast] + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + ), + ) + + +def model_parse(model: type[_ModelT], data: Any) -> _ModelT: + if PYDANTIC_V2: + return model.model_validate(data) + return model.parse_obj(data) # pyright: ignore[reportDeprecated] + + +# generic models +if TYPE_CHECKING: + + class GenericModel(pydantic.BaseModel): + ... + +else: + if PYDANTIC_V2: + # there no longer needs to be a distinction in v2 but + # we still have to create our own subclass to avoid + # inconsistent MRO ordering errors + class GenericModel(pydantic.BaseModel): + ... + + else: + import pydantic.generics + + class GenericModel(pydantic.generics.GenericModel, pydantic.BaseModel): + ... diff --git a/src/openai/_constants.py b/src/openai/_constants.py new file mode 100644 index 0000000000..2e402300d3 --- /dev/null +++ b/src/openai/_constants.py @@ -0,0 +1,10 @@ +# File generated from our OpenAPI spec by Stainless. + +import httpx + +RAW_RESPONSE_HEADER = "X-Stainless-Raw-Response" + +# default timeout is 10 minutes +DEFAULT_TIMEOUT = httpx.Timeout(timeout=600.0, connect=5.0) +DEFAULT_MAX_RETRIES = 2 +DEFAULT_LIMITS = httpx.Limits(max_connections=100, max_keepalive_connections=20) diff --git a/src/openai/_exceptions.py b/src/openai/_exceptions.py new file mode 100644 index 0000000000..b79ac5fd64 --- /dev/null +++ b/src/openai/_exceptions.py @@ -0,0 +1,123 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Any, Optional, cast +from typing_extensions import Literal + +import httpx + +from ._utils import is_dict + +__all__ = [ + "BadRequestError", + "AuthenticationError", + "PermissionDeniedError", + "NotFoundError", + "ConflictError", + "UnprocessableEntityError", + "RateLimitError", + "InternalServerError", +] + + +class OpenAIError(Exception): + pass + + +class APIError(OpenAIError): + message: str + request: httpx.Request + + body: object | None + """The API response body. + + If the API responded with a valid JSON structure then this property will be the + decoded result. + + If it isn't a valid JSON structure then this will be the raw response. + + If there was no response associated with this error then it will be `None`. + """ + + code: Optional[str] + param: Optional[str] + type: Optional[str] + + def __init__(self, message: str, request: httpx.Request, *, body: object | None) -> None: + super().__init__(message) + self.request = request + self.message = message + + if is_dict(body): + self.code = cast(Any, body.get("code")) + self.param = cast(Any, body.get("param")) + self.type = cast(Any, body.get("type")) + else: + self.code = None + self.param = None + self.type = None + + +class APIResponseValidationError(APIError): + response: httpx.Response + status_code: int + + def __init__(self, response: httpx.Response, body: object | None, *, message: str | None = None) -> None: + super().__init__(message or "Data returned by API invalid for expected schema.", response.request, body=body) + self.response = response + self.status_code = response.status_code + + +class APIStatusError(APIError): + """Raised when an API response has a status code of 4xx or 5xx.""" + + response: httpx.Response + status_code: int + + def __init__(self, message: str, *, response: httpx.Response, body: object | None) -> None: + super().__init__(message, response.request, body=body) + self.response = response + self.status_code = response.status_code + + +class APIConnectionError(APIError): + def __init__(self, *, message: str = "Connection error.", request: httpx.Request) -> None: + super().__init__(message, request, body=None) + + +class APITimeoutError(APIConnectionError): + def __init__(self, request: httpx.Request) -> None: + super().__init__(message="Request timed out.", request=request) + + +class BadRequestError(APIStatusError): + status_code: Literal[400] = 400 # pyright: ignore[reportIncompatibleVariableOverride] + + +class AuthenticationError(APIStatusError): + status_code: Literal[401] = 401 # pyright: ignore[reportIncompatibleVariableOverride] + + +class PermissionDeniedError(APIStatusError): + status_code: Literal[403] = 403 # pyright: ignore[reportIncompatibleVariableOverride] + + +class NotFoundError(APIStatusError): + status_code: Literal[404] = 404 # pyright: ignore[reportIncompatibleVariableOverride] + + +class ConflictError(APIStatusError): + status_code: Literal[409] = 409 # pyright: ignore[reportIncompatibleVariableOverride] + + +class UnprocessableEntityError(APIStatusError): + status_code: Literal[422] = 422 # pyright: ignore[reportIncompatibleVariableOverride] + + +class RateLimitError(APIStatusError): + status_code: Literal[429] = 429 # pyright: ignore[reportIncompatibleVariableOverride] + + +class InternalServerError(APIStatusError): + pass diff --git a/src/openai/_extras/__init__.py b/src/openai/_extras/__init__.py new file mode 100644 index 0000000000..dc6625c5dc --- /dev/null +++ b/src/openai/_extras/__init__.py @@ -0,0 +1,3 @@ +from .numpy_proxy import numpy as numpy +from .numpy_proxy import has_numpy as has_numpy +from .pandas_proxy import pandas as pandas diff --git a/src/openai/_extras/_common.py b/src/openai/_extras/_common.py new file mode 100644 index 0000000000..6e71720e64 --- /dev/null +++ b/src/openai/_extras/_common.py @@ -0,0 +1,21 @@ +from .._exceptions import OpenAIError + +INSTRUCTIONS = """ + +OpenAI error: + + missing `{library}` + +This feature requires additional dependencies: + + $ pip install openai[{extra}] + +""" + + +def format_instructions(*, library: str, extra: str) -> str: + return INSTRUCTIONS.format(library=library, extra=extra) + + +class MissingDependencyError(OpenAIError): + pass diff --git a/src/openai/_extras/numpy_proxy.py b/src/openai/_extras/numpy_proxy.py new file mode 100644 index 0000000000..408eaebd3b --- /dev/null +++ b/src/openai/_extras/numpy_proxy.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any +from typing_extensions import ClassVar, override + +from .._utils import LazyProxy +from ._common import MissingDependencyError, format_instructions + +if TYPE_CHECKING: + import numpy as numpy + + +NUMPY_INSTRUCTIONS = format_instructions(library="numpy", extra="datalib") + + +class NumpyProxy(LazyProxy[Any]): + should_cache: ClassVar[bool] = True + + @override + def __load__(self) -> Any: + try: + import numpy + except ImportError: + raise MissingDependencyError(NUMPY_INSTRUCTIONS) + + return numpy + + +if not TYPE_CHECKING: + numpy = NumpyProxy() + + +def has_numpy() -> bool: + try: + import numpy # noqa: F401 # pyright: ignore[reportUnusedImport] + except ImportError: + return False + + return True diff --git a/src/openai/_extras/pandas_proxy.py b/src/openai/_extras/pandas_proxy.py new file mode 100644 index 0000000000..2fc0d2a7eb --- /dev/null +++ b/src/openai/_extras/pandas_proxy.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any +from typing_extensions import ClassVar, override + +from .._utils import LazyProxy +from ._common import MissingDependencyError, format_instructions + +if TYPE_CHECKING: + import pandas as pandas + + +PANDAS_INSTRUCTIONS = format_instructions(library="pandas", extra="datalib") + + +class PandasProxy(LazyProxy[Any]): + should_cache: ClassVar[bool] = True + + @override + def __load__(self) -> Any: + try: + import pandas + except ImportError: + raise MissingDependencyError(PANDAS_INSTRUCTIONS) + + return pandas + + +if not TYPE_CHECKING: + pandas = PandasProxy() diff --git a/src/openai/_files.py b/src/openai/_files.py new file mode 100644 index 0000000000..49e3536243 --- /dev/null +++ b/src/openai/_files.py @@ -0,0 +1,122 @@ +from __future__ import annotations + +import io +import os +import pathlib +from typing import overload +from typing_extensions import TypeGuard + +import anyio + +from ._types import ( + FileTypes, + FileContent, + RequestFiles, + HttpxFileTypes, + HttpxFileContent, + HttpxRequestFiles, +) +from ._utils import is_tuple_t, is_mapping_t, is_sequence_t + + +def is_file_content(obj: object) -> TypeGuard[FileContent]: + return ( + isinstance(obj, bytes) or isinstance(obj, tuple) or isinstance(obj, io.IOBase) or isinstance(obj, os.PathLike) + ) + + +def assert_is_file_content(obj: object, *, key: str | None = None) -> None: + if not is_file_content(obj): + prefix = f"Expected entry at `{key}`" if key is not None else f"Expected file input `{obj!r}`" + raise RuntimeError( + f"{prefix} to be bytes, an io.IOBase instance, PathLike or a tuple but received {type(obj)} instead. See https://github.com/openai/openai-python/tree/v1#file-uploads" + ) from None + + +@overload +def to_httpx_files(files: None) -> None: + ... + + +@overload +def to_httpx_files(files: RequestFiles) -> HttpxRequestFiles: + ... + + +def to_httpx_files(files: RequestFiles | None) -> HttpxRequestFiles | None: + if files is None: + return None + + if is_mapping_t(files): + files = {key: _transform_file(file) for key, file in files.items()} + elif is_sequence_t(files): + files = [(key, _transform_file(file)) for key, file in files] + else: + raise TypeError(f"Unexpected file type input {type(files)}, expected mapping or sequence") + + return files + + +def _transform_file(file: FileTypes) -> HttpxFileTypes: + if is_file_content(file): + if isinstance(file, os.PathLike): + path = pathlib.Path(file) + return (path.name, path.read_bytes()) + + return file + + if is_tuple_t(file): + return (file[0], _read_file_content(file[1]), *file[2:]) + + raise TypeError(f"Expected file types input to be a FileContent type or to be a tuple") + + +def _read_file_content(file: FileContent) -> HttpxFileContent: + if isinstance(file, os.PathLike): + return pathlib.Path(file).read_bytes() + return file + + +@overload +async def async_to_httpx_files(files: None) -> None: + ... + + +@overload +async def async_to_httpx_files(files: RequestFiles) -> HttpxRequestFiles: + ... + + +async def async_to_httpx_files(files: RequestFiles | None) -> HttpxRequestFiles | None: + if files is None: + return None + + if is_mapping_t(files): + files = {key: await _async_transform_file(file) for key, file in files.items()} + elif is_sequence_t(files): + files = [(key, await _async_transform_file(file)) for key, file in files] + else: + raise TypeError("Unexpected file type input {type(files)}, expected mapping or sequence") + + return files + + +async def _async_transform_file(file: FileTypes) -> HttpxFileTypes: + if is_file_content(file): + if isinstance(file, os.PathLike): + path = anyio.Path(file) + return (path.name, await path.read_bytes()) + + return file + + if is_tuple_t(file): + return (file[0], await _async_read_file_content(file[1]), *file[2:]) + + raise TypeError(f"Expected file types input to be a FileContent type or to be a tuple") + + +async def _async_read_file_content(file: FileContent) -> HttpxFileContent: + if isinstance(file, os.PathLike): + return await anyio.Path(file).read_bytes() + + return file diff --git a/src/openai/_models.py b/src/openai/_models.py new file mode 100644 index 0000000000..00d787ca87 --- /dev/null +++ b/src/openai/_models.py @@ -0,0 +1,460 @@ +from __future__ import annotations + +import inspect +from typing import TYPE_CHECKING, Any, Type, Union, Generic, TypeVar, Callable, cast +from datetime import date, datetime +from typing_extensions import ( + Unpack, + Literal, + ClassVar, + Protocol, + Required, + TypedDict, + final, + override, + runtime_checkable, +) + +import pydantic +import pydantic.generics +from pydantic.fields import FieldInfo + +from ._types import ( + Body, + IncEx, + Query, + ModelT, + Headers, + Timeout, + NotGiven, + AnyMapping, + HttpxRequestFiles, +) +from ._utils import ( + is_list, + is_given, + is_mapping, + parse_date, + parse_datetime, + strip_not_given, +) +from ._compat import PYDANTIC_V2, ConfigDict +from ._compat import GenericModel as BaseGenericModel +from ._compat import ( + get_args, + is_union, + parse_obj, + get_origin, + is_literal_type, + get_model_config, + get_model_fields, + field_get_default, +) +from ._constants import RAW_RESPONSE_HEADER + +__all__ = ["BaseModel", "GenericModel"] + +_T = TypeVar("_T") + + +@runtime_checkable +class _ConfigProtocol(Protocol): + allow_population_by_field_name: bool + + +class BaseModel(pydantic.BaseModel): + if PYDANTIC_V2: + model_config: ClassVar[ConfigDict] = ConfigDict(extra="allow") + else: + + @property + @override + def model_fields_set(self) -> set[str]: + # a forwards-compat shim for pydantic v2 + return self.__fields_set__ # type: ignore + + class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated] + extra: Any = pydantic.Extra.allow # type: ignore + + @override + def __str__(self) -> str: + # mypy complains about an invalid self arg + return f'{self.__repr_name__()}({self.__repr_str__(", ")})' # type: ignore[misc] + + # Override the 'construct' method in a way that supports recursive parsing without validation. + # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836. + @classmethod + @override + def construct( + cls: Type[ModelT], + _fields_set: set[str] | None = None, + **values: object, + ) -> ModelT: + m = cls.__new__(cls) + fields_values: dict[str, object] = {} + + config = get_model_config(cls) + populate_by_name = ( + config.allow_population_by_field_name + if isinstance(config, _ConfigProtocol) + else config.get("populate_by_name") + ) + + if _fields_set is None: + _fields_set = set() + + model_fields = get_model_fields(cls) + for name, field in model_fields.items(): + key = field.alias + if key is None or (key not in values and populate_by_name): + key = name + + if key in values: + fields_values[name] = _construct_field(value=values[key], field=field, key=key) + _fields_set.add(name) + else: + fields_values[name] = field_get_default(field) + + _extra = {} + for key, value in values.items(): + if key not in model_fields: + if PYDANTIC_V2: + _extra[key] = value + else: + fields_values[key] = value + + object.__setattr__(m, "__dict__", fields_values) + + if PYDANTIC_V2: + # these properties are copied from Pydantic's `model_construct()` method + object.__setattr__(m, "__pydantic_private__", None) + object.__setattr__(m, "__pydantic_extra__", _extra) + object.__setattr__(m, "__pydantic_fields_set__", _fields_set) + else: + # init_private_attributes() does not exist in v2 + m._init_private_attributes() # type: ignore + + # copied from Pydantic v1's `construct()` method + object.__setattr__(m, "__fields_set__", _fields_set) + + return m + + if not TYPE_CHECKING: + # type checkers incorrectly complain about this assignment + # because the type signatures are technically different + # although not in practice + model_construct = construct + + if not PYDANTIC_V2: + # we define aliases for some of the new pydantic v2 methods so + # that we can just document these methods without having to specify + # a specifc pydantic version as some users may not know which + # pydantic version they are currently using + + @override + def model_dump( + self, + *, + mode: Literal["json", "python"] | str = "python", + include: IncEx = None, + exclude: IncEx = None, + by_alias: bool = False, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + round_trip: bool = False, + warnings: bool = True, + ) -> dict[str, Any]: + """Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump + + Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. + + Args: + mode: The mode in which `to_python` should run. + If mode is 'json', the dictionary will only contain JSON serializable types. + If mode is 'python', the dictionary may contain any Python objects. + include: A list of fields to include in the output. + exclude: A list of fields to exclude from the output. + by_alias: Whether to use the field's alias in the dictionary key if defined. + exclude_unset: Whether to exclude fields that are unset or None from the output. + exclude_defaults: Whether to exclude fields that are set to their default value from the output. + exclude_none: Whether to exclude fields that have a value of `None` from the output. + round_trip: Whether to enable serialization and deserialization round-trip support. + warnings: Whether to log warnings when invalid fields are encountered. + + Returns: + A dictionary representation of the model. + """ + if mode != "python": + raise ValueError("mode is only supported in Pydantic v2") + if round_trip != False: + raise ValueError("round_trip is only supported in Pydantic v2") + if warnings != True: + raise ValueError("warnings is only supported in Pydantic v2") + return super().dict( # pyright: ignore[reportDeprecated] + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + + @override + def model_dump_json( + self, + *, + indent: int | None = None, + include: IncEx = None, + exclude: IncEx = None, + by_alias: bool = False, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + round_trip: bool = False, + warnings: bool = True, + ) -> str: + """Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump_json + + Generates a JSON representation of the model using Pydantic's `to_json` method. + + Args: + indent: Indentation to use in the JSON output. If None is passed, the output will be compact. + include: Field(s) to include in the JSON output. Can take either a string or set of strings. + exclude: Field(s) to exclude from the JSON output. Can take either a string or set of strings. + by_alias: Whether to serialize using field aliases. + exclude_unset: Whether to exclude fields that have not been explicitly set. + exclude_defaults: Whether to exclude fields that have the default value. + exclude_none: Whether to exclude fields that have a value of `None`. + round_trip: Whether to use serialization/deserialization between JSON and class instance. + warnings: Whether to show any warnings that occurred during serialization. + + Returns: + A JSON string representation of the model. + """ + if round_trip != False: + raise ValueError("round_trip is only supported in Pydantic v2") + if warnings != True: + raise ValueError("warnings is only supported in Pydantic v2") + return super().json( # type: ignore[reportDeprecated] + indent=indent, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + + +def _construct_field(value: object, field: FieldInfo, key: str) -> object: + if value is None: + return field_get_default(field) + + if PYDANTIC_V2: + type_ = field.annotation + else: + type_ = cast(type, field.outer_type_) # type: ignore + + if type_ is None: + raise RuntimeError(f"Unexpected field type is None for {key}") + + return construct_type(value=value, type_=type_) + + +def construct_type(*, value: object, type_: type) -> object: + """Loose coercion to the expected type with construction of nested values. + + If the given value does not match the expected type then it is returned as-is. + """ + + # we need to use the origin class for any types that are subscripted generics + # e.g. Dict[str, object] + origin = get_origin(type_) or type_ + args = get_args(type_) + + if is_union(origin): + try: + return validate_type(type_=type_, value=value) + except Exception: + pass + + # if the data is not valid, use the first variant that doesn't fail while deserializing + for variant in args: + try: + return construct_type(value=value, type_=variant) + except Exception: + continue + + raise RuntimeError(f"Could not convert data into a valid instance of {type_}") + + if origin == dict: + if not is_mapping(value): + return value + + _, items_type = get_args(type_) # Dict[_, items_type] + return {key: construct_type(value=item, type_=items_type) for key, item in value.items()} + + if not is_literal_type(type_) and (issubclass(origin, BaseModel) or issubclass(origin, GenericModel)): + if is_list(value): + return [cast(Any, type_).construct(**entry) if is_mapping(entry) else entry for entry in value] + + if is_mapping(value): + if issubclass(type_, BaseModel): + return type_.construct(**value) # type: ignore[arg-type] + + return cast(Any, type_).construct(**value) + + if origin == list: + if not is_list(value): + return value + + inner_type = args[0] # List[inner_type] + return [construct_type(value=entry, type_=inner_type) for entry in value] + + if origin == float: + if isinstance(value, int): + coerced = float(value) + if coerced != value: + return value + return coerced + + return value + + if type_ == datetime: + try: + return parse_datetime(value) # type: ignore + except Exception: + return value + + if type_ == date: + try: + return parse_date(value) # type: ignore + except Exception: + return value + + return value + + +def validate_type(*, type_: type[_T], value: object) -> _T: + """Strict validation that the given value matches the expected type""" + if inspect.isclass(type_) and issubclass(type_, pydantic.BaseModel): + return cast(_T, parse_obj(type_, value)) + + return cast(_T, _validate_non_model_type(type_=type_, value=value)) + + +# our use of subclasssing here causes weirdness for type checkers, +# so we just pretend that we don't subclass +if TYPE_CHECKING: + GenericModel = BaseModel +else: + + class GenericModel(BaseGenericModel, BaseModel): + pass + + +if PYDANTIC_V2: + from pydantic import TypeAdapter + + def _validate_non_model_type(*, type_: type[_T], value: object) -> _T: + return TypeAdapter(type_).validate_python(value) + +elif not TYPE_CHECKING: # TODO: condition is weird + + class RootModel(GenericModel, Generic[_T]): + """Used as a placeholder to easily convert runtime types to a Pydantic format + to provide validation. + + For example: + ```py + validated = RootModel[int](__root__='5').__root__ + # validated: 5 + ``` + """ + + __root__: _T + + def _validate_non_model_type(*, type_: type[_T], value: object) -> _T: + model = _create_pydantic_model(type_).validate(value) + return cast(_T, model.__root__) + + def _create_pydantic_model(type_: _T) -> Type[RootModel[_T]]: + return RootModel[type_] # type: ignore + + +class FinalRequestOptionsInput(TypedDict, total=False): + method: Required[str] + url: Required[str] + params: Query + headers: Headers + max_retries: int + timeout: float | Timeout | None + files: HttpxRequestFiles | None + idempotency_key: str + json_data: Body + extra_json: AnyMapping + + +@final +class FinalRequestOptions(pydantic.BaseModel): + method: str + url: str + params: Query = {} + headers: Union[Headers, NotGiven] = NotGiven() + max_retries: Union[int, NotGiven] = NotGiven() + timeout: Union[float, Timeout, None, NotGiven] = NotGiven() + files: Union[HttpxRequestFiles, None] = None + idempotency_key: Union[str, None] = None + post_parser: Union[Callable[[Any], Any], NotGiven] = NotGiven() + + # It should be noted that we cannot use `json` here as that would override + # a BaseModel method in an incompatible fashion. + json_data: Union[Body, None] = None + extra_json: Union[AnyMapping, None] = None + + if PYDANTIC_V2: + model_config: ClassVar[ConfigDict] = ConfigDict(arbitrary_types_allowed=True) + else: + + class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated] + arbitrary_types_allowed: bool = True + + def get_max_retries(self, max_retries: int) -> int: + if isinstance(self.max_retries, NotGiven): + return max_retries + return self.max_retries + + def _strip_raw_response_header(self) -> None: + if not is_given(self.headers): + return + + if self.headers.get(RAW_RESPONSE_HEADER): + self.headers = {**self.headers} + self.headers.pop(RAW_RESPONSE_HEADER) + + # override the `construct` method so that we can run custom transformations. + # this is necessary as we don't want to do any actual runtime type checking + # (which means we can't use validators) but we do want to ensure that `NotGiven` + # values are not present + # + # type ignore required because we're adding explicit types to `**values` + @classmethod + def construct( # type: ignore + cls, + _fields_set: set[str] | None = None, + **values: Unpack[FinalRequestOptionsInput], + ) -> FinalRequestOptions: + kwargs: dict[str, Any] = { + # we unconditionally call `strip_not_given` on any value + # as it will just ignore any non-mapping types + key: strip_not_given(value) + for key, value in values.items() + } + if PYDANTIC_V2: + return super().model_construct(_fields_set, **kwargs) + return cast(FinalRequestOptions, super().construct(_fields_set, **kwargs)) # pyright: ignore[reportDeprecated] + + if not TYPE_CHECKING: + # type checkers incorrectly complain about this assignment + model_construct = construct diff --git a/src/openai/_module_client.py b/src/openai/_module_client.py new file mode 100644 index 0000000000..ca80468e88 --- /dev/null +++ b/src/openai/_module_client.py @@ -0,0 +1,85 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing_extensions import override + +from . import resources, _load_client +from ._utils import LazyProxy + + +class ChatProxy(LazyProxy[resources.Chat]): + @override + def __load__(self) -> resources.Chat: + return _load_client().chat + + +class EditsProxy(LazyProxy[resources.Edits]): + @override + def __load__(self) -> resources.Edits: + return _load_client().edits + + +class FilesProxy(LazyProxy[resources.Files]): + @override + def __load__(self) -> resources.Files: + return _load_client().files + + +class AudioProxy(LazyProxy[resources.Audio]): + @override + def __load__(self) -> resources.Audio: + return _load_client().audio + + +class ImagesProxy(LazyProxy[resources.Images]): + @override + def __load__(self) -> resources.Images: + return _load_client().images + + +class ModelsProxy(LazyProxy[resources.Models]): + @override + def __load__(self) -> resources.Models: + return _load_client().models + + +class EmbeddingsProxy(LazyProxy[resources.Embeddings]): + @override + def __load__(self) -> resources.Embeddings: + return _load_client().embeddings + + +class FineTunesProxy(LazyProxy[resources.FineTunes]): + @override + def __load__(self) -> resources.FineTunes: + return _load_client().fine_tunes + + +class CompletionsProxy(LazyProxy[resources.Completions]): + @override + def __load__(self) -> resources.Completions: + return _load_client().completions + + +class ModerationsProxy(LazyProxy[resources.Moderations]): + @override + def __load__(self) -> resources.Moderations: + return _load_client().moderations + + +class FineTuningProxy(LazyProxy[resources.FineTuning]): + @override + def __load__(self) -> resources.FineTuning: + return _load_client().fine_tuning + + +chat: resources.Chat = ChatProxy().__as_proxied__() +edits: resources.Edits = EditsProxy().__as_proxied__() +files: resources.Files = FilesProxy().__as_proxied__() +audio: resources.Audio = AudioProxy().__as_proxied__() +images: resources.Images = ImagesProxy().__as_proxied__() +models: resources.Models = ModelsProxy().__as_proxied__() +embeddings: resources.Embeddings = EmbeddingsProxy().__as_proxied__() +fine_tunes: resources.FineTunes = FineTunesProxy().__as_proxied__() +completions: resources.Completions = CompletionsProxy().__as_proxied__() +moderations: resources.Moderations = ModerationsProxy().__as_proxied__() +fine_tuning: resources.FineTuning = FineTuningProxy().__as_proxied__() diff --git a/src/openai/_qs.py b/src/openai/_qs.py new file mode 100644 index 0000000000..274320ca5e --- /dev/null +++ b/src/openai/_qs.py @@ -0,0 +1,150 @@ +from __future__ import annotations + +from typing import Any, List, Tuple, Union, Mapping, TypeVar +from urllib.parse import parse_qs, urlencode +from typing_extensions import Literal, get_args + +from ._types import NOT_GIVEN, NotGiven, NotGivenOr +from ._utils import flatten + +_T = TypeVar("_T") + + +ArrayFormat = Literal["comma", "repeat", "indices", "brackets"] +NestedFormat = Literal["dots", "brackets"] + +PrimitiveData = Union[str, int, float, bool, None] +# this should be Data = Union[PrimitiveData, "List[Data]", "Tuple[Data]", "Mapping[str, Data]"] +# https://github.com/microsoft/pyright/issues/3555 +Data = Union[PrimitiveData, List[Any], Tuple[Any], "Mapping[str, Any]"] +Params = Mapping[str, Data] + + +class Querystring: + array_format: ArrayFormat + nested_format: NestedFormat + + def __init__( + self, + *, + array_format: ArrayFormat = "repeat", + nested_format: NestedFormat = "brackets", + ) -> None: + self.array_format = array_format + self.nested_format = nested_format + + def parse(self, query: str) -> Mapping[str, object]: + # Note: custom format syntax is not supported yet + return parse_qs(query) + + def stringify( + self, + params: Params, + *, + array_format: NotGivenOr[ArrayFormat] = NOT_GIVEN, + nested_format: NotGivenOr[NestedFormat] = NOT_GIVEN, + ) -> str: + return urlencode( + self.stringify_items( + params, + array_format=array_format, + nested_format=nested_format, + ) + ) + + def stringify_items( + self, + params: Params, + *, + array_format: NotGivenOr[ArrayFormat] = NOT_GIVEN, + nested_format: NotGivenOr[NestedFormat] = NOT_GIVEN, + ) -> list[tuple[str, str]]: + opts = Options( + qs=self, + array_format=array_format, + nested_format=nested_format, + ) + return flatten([self._stringify_item(key, value, opts) for key, value in params.items()]) + + def _stringify_item( + self, + key: str, + value: Data, + opts: Options, + ) -> list[tuple[str, str]]: + if isinstance(value, Mapping): + items: list[tuple[str, str]] = [] + nested_format = opts.nested_format + for subkey, subvalue in value.items(): + items.extend( + self._stringify_item( + # TODO: error if unknown format + f"{key}.{subkey}" if nested_format == "dots" else f"{key}[{subkey}]", + subvalue, + opts, + ) + ) + return items + + if isinstance(value, (list, tuple)): + array_format = opts.array_format + if array_format == "comma": + return [ + ( + key, + ",".join(self._primitive_value_to_str(item) for item in value if item is not None), + ), + ] + elif array_format == "repeat": + items = [] + for item in value: + items.extend(self._stringify_item(key, item, opts)) + return items + elif array_format == "indices": + raise NotImplementedError("The array indices format is not supported yet") + elif array_format == "brackets": + items = [] + key = key + "[]" + for item in value: + items.extend(self._stringify_item(key, item, opts)) + return items + else: + raise NotImplementedError( + f"Unknown array_format value: {array_format}, choose from {', '.join(get_args(ArrayFormat))}" + ) + + serialised = self._primitive_value_to_str(value) + if not serialised: + return [] + return [(key, serialised)] + + def _primitive_value_to_str(self, value: PrimitiveData) -> str: + # copied from httpx + if value is True: + return "true" + elif value is False: + return "false" + elif value is None: + return "" + return str(value) + + +_qs = Querystring() +parse = _qs.parse +stringify = _qs.stringify +stringify_items = _qs.stringify_items + + +class Options: + array_format: ArrayFormat + nested_format: NestedFormat + + def __init__( + self, + qs: Querystring = _qs, + *, + array_format: NotGivenOr[ArrayFormat] = NOT_GIVEN, + nested_format: NotGivenOr[NestedFormat] = NOT_GIVEN, + ) -> None: + self.array_format = qs.array_format if isinstance(array_format, NotGiven) else array_format + self.nested_format = qs.nested_format if isinstance(nested_format, NotGiven) else nested_format diff --git a/src/openai/_resource.py b/src/openai/_resource.py new file mode 100644 index 0000000000..db1b0fa45a --- /dev/null +++ b/src/openai/_resource.py @@ -0,0 +1,42 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import time +import asyncio +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._client import OpenAI, AsyncOpenAI + + +class SyncAPIResource: + _client: OpenAI + + def __init__(self, client: OpenAI) -> None: + self._client = client + self._get = client.get + self._post = client.post + self._patch = client.patch + self._put = client.put + self._delete = client.delete + self._get_api_list = client.get_api_list + + def _sleep(self, seconds: float) -> None: + time.sleep(seconds) + + +class AsyncAPIResource: + _client: AsyncOpenAI + + def __init__(self, client: AsyncOpenAI) -> None: + self._client = client + self._get = client.get + self._post = client.post + self._patch = client.patch + self._put = client.put + self._delete = client.delete + self._get_api_list = client.get_api_list + + async def _sleep(self, seconds: float) -> None: + await asyncio.sleep(seconds) diff --git a/src/openai/_response.py b/src/openai/_response.py new file mode 100644 index 0000000000..3cc8fd8cc1 --- /dev/null +++ b/src/openai/_response.py @@ -0,0 +1,252 @@ +from __future__ import annotations + +import inspect +import datetime +import functools +from typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, cast +from typing_extensions import Awaitable, ParamSpec, get_args, override, get_origin + +import httpx +import pydantic + +from ._types import NoneType, UnknownResponse, BinaryResponseContent +from ._utils import is_given +from ._models import BaseModel +from ._constants import RAW_RESPONSE_HEADER +from ._exceptions import APIResponseValidationError + +if TYPE_CHECKING: + from ._models import FinalRequestOptions + from ._base_client import Stream, BaseClient, AsyncStream + + +P = ParamSpec("P") +R = TypeVar("R") + + +class APIResponse(Generic[R]): + _cast_to: type[R] + _client: BaseClient[Any, Any] + _parsed: R | None + _stream: bool + _stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None + _options: FinalRequestOptions + + http_response: httpx.Response + + def __init__( + self, + *, + raw: httpx.Response, + cast_to: type[R], + client: BaseClient[Any, Any], + stream: bool, + stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None, + options: FinalRequestOptions, + ) -> None: + self._cast_to = cast_to + self._client = client + self._parsed = None + self._stream = stream + self._stream_cls = stream_cls + self._options = options + self.http_response = raw + + def parse(self) -> R: + if self._parsed is not None: + return self._parsed + + parsed = self._parse() + if is_given(self._options.post_parser): + parsed = self._options.post_parser(parsed) + + self._parsed = parsed + return parsed + + @property + def headers(self) -> httpx.Headers: + return self.http_response.headers + + @property + def http_request(self) -> httpx.Request: + return self.http_response.request + + @property + def status_code(self) -> int: + return self.http_response.status_code + + @property + def url(http://github.com/self) -> httpx.URL: + return self.http_response.url + + @property + def method(self) -> str: + return self.http_request.method + + @property + def content(self) -> bytes: + return self.http_response.content + + @property + def text(self) -> str: + return self.http_response.text + + @property + def http_version(self) -> str: + return self.http_response.http_version + + @property + def elapsed(self) -> datetime.timedelta: + """The time taken for the complete request/response cycle to complete.""" + return self.http_response.elapsed + + def _parse(self) -> R: + if self._stream: + if self._stream_cls: + return cast( + R, + self._stream_cls( + cast_to=_extract_stream_chunk_type(self._stream_cls), + response=self.http_response, + client=cast(Any, self._client), + ), + ) + + stream_cls = cast("type[Stream[Any]] | type[AsyncStream[Any]] | None", self._client._default_stream_cls) + if stream_cls is None: + raise MissingStreamClassError() + + return cast( + R, + stream_cls( + cast_to=self._cast_to, + response=self.http_response, + client=cast(Any, self._client), + ), + ) + + cast_to = self._cast_to + if cast_to is NoneType: + return cast(R, None) + + response = self.http_response + if cast_to == str: + return cast(R, response.text) + + origin = get_origin(cast_to) or cast_to + + if inspect.isclass(origin) and issubclass(origin, BinaryResponseContent): + return cast(R, cast_to(response)) # type: ignore + + if origin == APIResponse: + raise RuntimeError("Unexpected state - cast_to is `APIResponse`") + + if inspect.isclass(origin) and issubclass(origin, httpx.Response): + # Because of the invariance of our ResponseT TypeVar, users can subclass httpx.Response + # and pass that class to our request functions. We cannot change the variance to be either + # covariant or contravariant as that makes our usage of ResponseT illegal. We could construct + # the response class ourselves but that is something that should be supported directly in httpx + # as it would be easy to incorrectly construct the Response object due to the multitude of arguments. + if cast_to != httpx.Response: + raise ValueError(f"Subclasses of httpx.Response cannot be passed to `cast_to`") + return cast(R, response) + + # The check here is necessary as we are subverting the the type system + # with casts as the relationship between TypeVars and Types are very strict + # which means we must return *exactly* what was input or transform it in a + # way that retains the TypeVar state. As we cannot do that in this function + # then we have to resort to using `cast`. At the time of writing, we know this + # to be safe as we have handled all the types that could be bound to the + # `ResponseT` TypeVar, however if that TypeVar is ever updated in the future, then + # this function would become unsafe but a type checker would not report an error. + if ( + cast_to is not UnknownResponse + and not origin is list + and not origin is dict + and not origin is Union + and not issubclass(origin, BaseModel) + ): + raise RuntimeError( + f"Invalid state, expected {cast_to} to be a subclass type of {BaseModel}, {dict}, {list} or {Union}." + ) + + # split is required to handle cases where additional information is included + # in the response, e.g. application/json; charset=utf-8 + content_type, *_ = response.headers.get("content-type").split(";") + if content_type != "application/json": + if self._client._strict_response_validation: + raise APIResponseValidationError( + response=response, + message=f"Expected Content-Type response header to be `application/json` but received `{content_type}` instead.", + body=response.text, + ) + + # If the API responds with content that isn't JSON then we just return + # the (decoded) text without performing any parsing so that you can still + # handle the response however you need to. + return response.text # type: ignore + + data = response.json() + + try: + return self._client._process_response_data( + data=data, + cast_to=cast_to, # type: ignore + response=response, + ) + except pydantic.ValidationError as err: + raise APIResponseValidationError(response=response, body=data) from err + + @override + def __repr__(self) -> str: + return f"" + + +class MissingStreamClassError(TypeError): + def __init__(self) -> None: + super().__init__( + "The `stream` argument was set to `True` but the `stream_cls` argument was not given. See `openai._streaming` for reference", + ) + + +def _extract_stream_chunk_type(stream_cls: type) -> type: + args = get_args(stream_cls) + if not args: + raise TypeError( + f"Expected stream_cls to have been given a generic type argument, e.g. Stream[Foo] but received {stream_cls}", + ) + return cast(type, args[0]) + + +def to_raw_response_wrapper(func: Callable[P, R]) -> Callable[P, APIResponse[R]]: + """Higher order function that takes one of our bound API methods and wraps it + to support returning the raw `APIResponse` object directly. + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> APIResponse[R]: + extra_headers = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "true" + + kwargs["extra_headers"] = extra_headers + + return cast(APIResponse[R], func(*args, **kwargs)) + + return wrapped + + +def async_to_raw_response_wrapper(func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[APIResponse[R]]]: + """Higher order function that takes one of our bound API methods and wraps it + to support returning the raw `APIResponse` object directly. + """ + + @functools.wraps(func) + async def wrapped(*args: P.args, **kwargs: P.kwargs) -> APIResponse[R]: + extra_headers = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "true" + + kwargs["extra_headers"] = extra_headers + + return cast(APIResponse[R], await func(*args, **kwargs)) + + return wrapped diff --git a/src/openai/_streaming.py b/src/openai/_streaming.py new file mode 100644 index 0000000000..cee737f4f5 --- /dev/null +++ b/src/openai/_streaming.py @@ -0,0 +1,232 @@ +# Note: initially copied from https://github.com/florimondmanca/httpx-sse/blob/master/src/httpx_sse/_decoders.py +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, Any, Generic, Iterator, AsyncIterator +from typing_extensions import override + +import httpx + +from ._types import ResponseT +from ._utils import is_mapping +from ._exceptions import APIError + +if TYPE_CHECKING: + from ._base_client import SyncAPIClient, AsyncAPIClient + + +class Stream(Generic[ResponseT]): + """Provides the core interface to iterate over a synchronous stream response.""" + + response: httpx.Response + + def __init__( + self, + *, + cast_to: type[ResponseT], + response: httpx.Response, + client: SyncAPIClient, + ) -> None: + self.response = response + self._cast_to = cast_to + self._client = client + self._decoder = SSEDecoder() + self._iterator = self.__stream__() + + def __next__(self) -> ResponseT: + return self._iterator.__next__() + + def __iter__(self) -> Iterator[ResponseT]: + for item in self._iterator: + yield item + + def _iter_events(self) -> Iterator[ServerSentEvent]: + yield from self._decoder.iter(self.response.iter_lines()) + + def __stream__(self) -> Iterator[ResponseT]: + cast_to = self._cast_to + response = self.response + process_data = self._client._process_response_data + + for sse in self._iter_events(): + if sse.data.startswith("[DONE]"): + break + + if sse.event is None: + data = sse.json() + if is_mapping(data) and data.get("error"): + raise APIError( + message="An error ocurred during streaming", + request=self.response.request, + body=data["error"], + ) + + yield process_data(data=data, cast_to=cast_to, response=response) + + +class AsyncStream(Generic[ResponseT]): + """Provides the core interface to iterate over an asynchronous stream response.""" + + response: httpx.Response + + def __init__( + self, + *, + cast_to: type[ResponseT], + response: httpx.Response, + client: AsyncAPIClient, + ) -> None: + self.response = response + self._cast_to = cast_to + self._client = client + self._decoder = SSEDecoder() + self._iterator = self.__stream__() + + async def __anext__(self) -> ResponseT: + return await self._iterator.__anext__() + + async def __aiter__(self) -> AsyncIterator[ResponseT]: + async for item in self._iterator: + yield item + + async def _iter_events(self) -> AsyncIterator[ServerSentEvent]: + async for sse in self._decoder.aiter(self.response.aiter_lines()): + yield sse + + async def __stream__(self) -> AsyncIterator[ResponseT]: + cast_to = self._cast_to + response = self.response + process_data = self._client._process_response_data + + async for sse in self._iter_events(): + if sse.data.startswith("[DONE]"): + break + + if sse.event is None: + data = sse.json() + if is_mapping(data) and data.get("error"): + raise APIError( + message="An error ocurred during streaming", + request=self.response.request, + body=data["error"], + ) + + yield process_data(data=data, cast_to=cast_to, response=response) + + +class ServerSentEvent: + def __init__( + self, + *, + event: str | None = None, + data: str | None = None, + id: str | None = None, + retry: int | None = None, + ) -> None: + if data is None: + data = "" + + self._id = id + self._data = data + self._event = event or None + self._retry = retry + + @property + def event(self) -> str | None: + return self._event + + @property + def id(self) -> str | None: + return self._id + + @property + def retry(self) -> int | None: + return self._retry + + @property + def data(self) -> str: + return self._data + + def json(self) -> Any: + return json.loads(self.data) + + @override + def __repr__(self) -> str: + return f"ServerSentEvent(event={self.event}, data={self.data}, id={self.id}, retry={self.retry})" + + +class SSEDecoder: + _data: list[str] + _event: str | None + _retry: int | None + _last_event_id: str | None + + def __init__(self) -> None: + self._event = None + self._data = [] + self._last_event_id = None + self._retry = None + + def iter(self, iterator: Iterator[str]) -> Iterator[ServerSentEvent]: + """Given an iterator that yields lines, iterate over it & yield every event encountered""" + for line in iterator: + line = line.rstrip("\n") + sse = self.decode(line) + if sse is not None: + yield sse + + async def aiter(self, iterator: AsyncIterator[str]) -> AsyncIterator[ServerSentEvent]: + """Given an async iterator that yields lines, iterate over it & yield every event encountered""" + async for line in iterator: + line = line.rstrip("\n") + sse = self.decode(line) + if sse is not None: + yield sse + + def decode(self, line: str) -> ServerSentEvent | None: + # See: https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation # noqa: E501 + + if not line: + if not self._event and not self._data and not self._last_event_id and self._retry is None: + return None + + sse = ServerSentEvent( + event=self._event, + data="\n".join(self._data), + id=self._last_event_id, + retry=self._retry, + ) + + # NOTE: as per the SSE spec, do not reset last_event_id. + self._event = None + self._data = [] + self._retry = None + + return sse + + if line.startswith(":"): + return None + + fieldname, _, value = line.partition(":") + + if value.startswith(" "): + value = value[1:] + + if fieldname == "event": + self._event = value + elif fieldname == "data": + self._data.append(value) + elif fieldname == "id": + if "\0" in value: + pass + else: + self._last_event_id = value + elif fieldname == "retry": + try: + self._retry = int(value) + except (TypeError, ValueError): + pass + else: + pass # Field is ignored. + + return None diff --git a/src/openai/_types.py b/src/openai/_types.py new file mode 100644 index 0000000000..dabd15866f --- /dev/null +++ b/src/openai/_types.py @@ -0,0 +1,343 @@ +from __future__ import annotations + +from os import PathLike +from abc import ABC, abstractmethod +from typing import ( + IO, + TYPE_CHECKING, + Any, + Dict, + List, + Type, + Tuple, + Union, + Mapping, + TypeVar, + Callable, + Iterator, + Optional, + Sequence, + AsyncIterator, +) +from typing_extensions import ( + Literal, + Protocol, + TypeAlias, + TypedDict, + override, + runtime_checkable, +) + +import pydantic +from httpx import URL, Proxy, Timeout, Response, BaseTransport, AsyncBaseTransport + +if TYPE_CHECKING: + from ._models import BaseModel + +Transport = BaseTransport +AsyncTransport = AsyncBaseTransport +Query = Mapping[str, object] +Body = object +AnyMapping = Mapping[str, object] +ModelT = TypeVar("ModelT", bound=pydantic.BaseModel) +_T = TypeVar("_T") + + +class BinaryResponseContent(ABC): + def __init__( + self, + response: Any, + ) -> None: + ... + + @property + @abstractmethod + def content(self) -> bytes: + pass + + @property + @abstractmethod + def text(self) -> str: + pass + + @property + @abstractmethod + def encoding(self) -> Optional[str]: + """ + Return an encoding to use for decoding the byte content into text. + The priority for determining this is given by... + + * `.encoding = <>` has been set explicitly. + * The encoding as specified by the charset parameter in the Content-Type header. + * The encoding as determined by `default_encoding`, which may either be + a string like "utf-8" indicating the encoding to use, or may be a callable + which enables charset autodetection. + """ + pass + + @property + @abstractmethod + def charset_encoding(self) -> Optional[str]: + """ + Return the encoding, as specified by the Content-Type header. + """ + pass + + @abstractmethod + def json(self, **kwargs: Any) -> Any: + pass + + @abstractmethod + def read(self) -> bytes: + """ + Read and return the response content. + """ + pass + + @abstractmethod + def iter_bytes(self, chunk_size: Optional[int] = None) -> Iterator[bytes]: + """ + A byte-iterator over the decoded response content. + This allows us to handle gzip, deflate, and brotli encoded responses. + """ + pass + + @abstractmethod + def iter_text(self, chunk_size: Optional[int] = None) -> Iterator[str]: + """ + A str-iterator over the decoded response content + that handles both gzip, deflate, etc but also detects the content's + string encoding. + """ + pass + + @abstractmethod + def iter_lines(self) -> Iterator[str]: + pass + + @abstractmethod + def iter_raw(self, chunk_size: Optional[int] = None) -> Iterator[bytes]: + """ + A byte-iterator over the raw response content. + """ + pass + + @abstractmethod + def stream_to_file(self, file: str | PathLike[str]) -> None: + """ + Stream the output to the given file. + """ + pass + + @abstractmethod + def close(self) -> None: + """ + Close the response and release the connection. + Automatically called if the response body is read to completion. + """ + pass + + @abstractmethod + async def aread(self) -> bytes: + """ + Read and return the response content. + """ + pass + + @abstractmethod + async def aiter_bytes(self, chunk_size: Optional[int] = None) -> AsyncIterator[bytes]: + """ + A byte-iterator over the decoded response content. + This allows us to handle gzip, deflate, and brotli encoded responses. + """ + pass + + @abstractmethod + async def aiter_text(self, chunk_size: Optional[int] = None) -> AsyncIterator[str]: + """ + A str-iterator over the decoded response content + that handles both gzip, deflate, etc but also detects the content's + string encoding. + """ + pass + + @abstractmethod + async def aiter_lines(self) -> AsyncIterator[str]: + pass + + @abstractmethod + async def aiter_raw(self, chunk_size: Optional[int] = None) -> AsyncIterator[bytes]: + """ + A byte-iterator over the raw response content. + """ + pass + + async def astream_to_file(self, file: str | PathLike[str]) -> None: + """ + Stream the output to the given file. + """ + pass + + @abstractmethod + async def aclose(self) -> None: + """ + Close the response and release the connection. + Automatically called if the response body is read to completion. + """ + pass + + +# Approximates httpx internal ProxiesTypes and RequestFiles types +# while adding support for `PathLike` instances +ProxiesDict = Dict["str | URL", Union[None, str, URL, Proxy]] +ProxiesTypes = Union[str, Proxy, ProxiesDict] +if TYPE_CHECKING: + FileContent = Union[IO[bytes], bytes, PathLike[str]] +else: + FileContent = Union[IO[bytes], bytes, PathLike] # PathLike is not subscriptable in Python 3.8. +FileTypes = Union[ + # file (or bytes) + FileContent, + # (filename, file (or bytes)) + Tuple[Optional[str], FileContent], + # (filename, file (or bytes), content_type) + Tuple[Optional[str], FileContent, Optional[str]], + # (filename, file (or bytes), content_type, headers) + Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]], +] +RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]] + +# duplicate of the above but without our custom file support +HttpxFileContent = Union[IO[bytes], bytes] +HttpxFileTypes = Union[ + # file (or bytes) + HttpxFileContent, + # (filename, file (or bytes)) + Tuple[Optional[str], HttpxFileContent], + # (filename, file (or bytes), content_type) + Tuple[Optional[str], HttpxFileContent, Optional[str]], + # (filename, file (or bytes), content_type, headers) + Tuple[Optional[str], HttpxFileContent, Optional[str], Mapping[str, str]], +] +HttpxRequestFiles = Union[Mapping[str, HttpxFileTypes], Sequence[Tuple[str, HttpxFileTypes]]] + +# Workaround to support (cast_to: Type[ResponseT]) -> ResponseT +# where ResponseT includes `None`. In order to support directly +# passing `None`, overloads would have to be defined for every +# method that uses `ResponseT` which would lead to an unacceptable +# amount of code duplication and make it unreadable. See _base_client.py +# for example usage. +# +# This unfortunately means that you will either have +# to import this type and pass it explicitly: +# +# from openai import NoneType +# client.get('/foo', cast_to=NoneType) +# +# or build it yourself: +# +# client.get('/foo', cast_to=type(None)) +if TYPE_CHECKING: + NoneType: Type[None] +else: + NoneType = type(None) + + +class RequestOptions(TypedDict, total=False): + headers: Headers + max_retries: int + timeout: float | Timeout | None + params: Query + extra_json: AnyMapping + idempotency_key: str + + +# Sentinel class used when the response type is an object with an unknown schema +class UnknownResponse: + ... + + +# Sentinel class used until PEP 0661 is accepted +class NotGiven: + """ + A sentinel singleton class used to distinguish omitted keyword arguments + from those passed in with the value None (which may have different behavior). + + For example: + + ```py + def get(timeout: Union[int, NotGiven, None] = NotGiven()) -> Response: ... + + get(timout=1) # 1s timeout + get(timout=None) # No timeout + get() # Default timeout behavior, which may not be statically known at the method definition. + ``` + """ + + def __bool__(self) -> Literal[False]: + return False + + @override + def __repr__(self) -> str: + return "NOT_GIVEN" + + +NotGivenOr = Union[_T, NotGiven] +NOT_GIVEN = NotGiven() + + +class Omit: + """In certain situations you need to be able to represent a case where a default value has + to be explicitly removed and `None` is not an appropriate substitute, for example: + + ```py + # as the default `Content-Type` header is `application/json` that will be sent + client.post('/upload/files', files={'file': b'my raw file content'}) + + # you can't explicitly override the header as it has to be dynamically generated + # to look something like: 'multipart/form-data; boundary=0d8382fcf5f8c3be01ca2e11002d2983' + client.post(..., headers={'Content-Type': 'multipart/form-data'}) + + # instead you can remove the default `application/json` header by passing Omit + client.post(..., headers={'Content-Type': Omit()}) + ``` + """ + + def __bool__(self) -> Literal[False]: + return False + + +@runtime_checkable +class ModelBuilderProtocol(Protocol): + @classmethod + def build( + cls: type[_T], + *, + response: Response, + data: object, + ) -> _T: + ... + + +Headers = Mapping[str, Union[str, Omit]] + + +class HeadersLikeProtocol(Protocol): + def get(self, __key: str) -> str | None: + ... + + +HeadersLike = Union[Headers, HeadersLikeProtocol] + +ResponseT = TypeVar( + "ResponseT", + bound="Union[str, None, BaseModel, List[Any], Dict[str, Any], Response, UnknownResponse, ModelBuilderProtocol, BinaryResponseContent]", +) + +StrBytesIntFloat = Union[str, bytes, int, float] + +# Note: copied from Pydantic +# https://github.com/pydantic/pydantic/blob/32ea570bf96e84234d2992e1ddf40ab8a565925a/pydantic/main.py#L49 +IncEx: TypeAlias = "set[int] | set[str] | dict[int, Any] | dict[str, Any] | None" + +PostParser = Callable[[Any], Any] diff --git a/src/openai/_utils/__init__.py b/src/openai/_utils/__init__.py new file mode 100644 index 0000000000..d3397212de --- /dev/null +++ b/src/openai/_utils/__init__.py @@ -0,0 +1,36 @@ +from ._proxy import LazyProxy as LazyProxy +from ._utils import flatten as flatten +from ._utils import is_dict as is_dict +from ._utils import is_list as is_list +from ._utils import is_given as is_given +from ._utils import is_tuple as is_tuple +from ._utils import is_mapping as is_mapping +from ._utils import is_tuple_t as is_tuple_t +from ._utils import parse_date as parse_date +from ._utils import is_sequence as is_sequence +from ._utils import coerce_float as coerce_float +from ._utils import is_list_type as is_list_type +from ._utils import is_mapping_t as is_mapping_t +from ._utils import removeprefix as removeprefix +from ._utils import removesuffix as removesuffix +from ._utils import extract_files as extract_files +from ._utils import is_sequence_t as is_sequence_t +from ._utils import is_union_type as is_union_type +from ._utils import required_args as required_args +from ._utils import coerce_boolean as coerce_boolean +from ._utils import coerce_integer as coerce_integer +from ._utils import file_from_path as file_from_path +from ._utils import parse_datetime as parse_datetime +from ._utils import strip_not_given as strip_not_given +from ._utils import deepcopy_minimal as deepcopy_minimal +from ._utils import extract_type_arg as extract_type_arg +from ._utils import is_required_type as is_required_type +from ._utils import is_annotated_type as is_annotated_type +from ._utils import maybe_coerce_float as maybe_coerce_float +from ._utils import get_required_header as get_required_header +from ._utils import maybe_coerce_boolean as maybe_coerce_boolean +from ._utils import maybe_coerce_integer as maybe_coerce_integer +from ._utils import strip_annotated_type as strip_annotated_type +from ._transform import PropertyInfo as PropertyInfo +from ._transform import transform as transform +from ._transform import maybe_transform as maybe_transform diff --git a/src/openai/_utils/_logs.py b/src/openai/_utils/_logs.py new file mode 100644 index 0000000000..e5113fd8c0 --- /dev/null +++ b/src/openai/_utils/_logs.py @@ -0,0 +1,25 @@ +import os +import logging + +logger: logging.Logger = logging.getLogger("openai") +httpx_logger: logging.Logger = logging.getLogger("httpx") + + +def _basic_config() -> None: + # e.g. [2023-10-05 14:12:26 - openai._base_client:818 - DEBUG] HTTP Request: POST http://127.0.0.1:4010/foo/bar "200 OK" + logging.basicConfig( + format="[%(asctime)s - %(name)s:%(lineno)d - %(levelname)s] %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + ) + + +def setup_logging() -> None: + env = os.environ.get("OPENAI_LOG") + if env == "debug": + _basic_config() + logger.setLevel(logging.DEBUG) + httpx_logger.setLevel(logging.DEBUG) + elif env == "info": + _basic_config() + logger.setLevel(logging.INFO) + httpx_logger.setLevel(logging.INFO) diff --git a/src/openai/_utils/_proxy.py b/src/openai/_utils/_proxy.py new file mode 100644 index 0000000000..aa934a3fbc --- /dev/null +++ b/src/openai/_utils/_proxy.py @@ -0,0 +1,61 @@ +from __future__ import annotations + +from abc import ABC, abstractmethod +from typing import Generic, TypeVar, Iterable, cast +from typing_extensions import ClassVar, override + +T = TypeVar("T") + + +class LazyProxy(Generic[T], ABC): + """Implements data methods to pretend that an instance is another instance. + + This includes forwarding attribute access and othe methods. + """ + + should_cache: ClassVar[bool] = False + + def __init__(self) -> None: + self.__proxied: T | None = None + + def __getattr__(self, attr: str) -> object: + return getattr(self.__get_proxied__(), attr) + + @override + def __repr__(self) -> str: + return repr(self.__get_proxied__()) + + @override + def __str__(self) -> str: + return str(self.__get_proxied__()) + + @override + def __dir__(self) -> Iterable[str]: + return self.__get_proxied__().__dir__() + + @property # type: ignore + @override + def __class__(self) -> type: + return self.__get_proxied__().__class__ + + def __get_proxied__(self) -> T: + if not self.should_cache: + return self.__load__() + + proxied = self.__proxied + if proxied is not None: + return proxied + + self.__proxied = proxied = self.__load__() + return proxied + + def __set_proxied__(self, value: T) -> None: + self.__proxied = value + + def __as_proxied__(self) -> T: + """Helper method that returns the current proxy, typed as the loaded object""" + return cast(T, self) + + @abstractmethod + def __load__(self) -> T: + ... diff --git a/src/openai/_utils/_transform.py b/src/openai/_utils/_transform.py new file mode 100644 index 0000000000..db40bff27f --- /dev/null +++ b/src/openai/_utils/_transform.py @@ -0,0 +1,214 @@ +from __future__ import annotations + +from typing import Any, List, Mapping, TypeVar, cast +from datetime import date, datetime +from typing_extensions import Literal, get_args, override, get_type_hints + +import pydantic + +from ._utils import ( + is_list, + is_mapping, + is_list_type, + is_union_type, + extract_type_arg, + is_required_type, + is_annotated_type, + strip_annotated_type, +) +from .._compat import model_dump, is_typeddict + +_T = TypeVar("_T") + + +# TODO: support for drilling globals() and locals() +# TODO: ensure works correctly with forward references in all cases + + +PropertyFormat = Literal["iso8601", "custom"] + + +class PropertyInfo: + """Metadata class to be used in Annotated types to provide information about a given type. + + For example: + + class MyParams(TypedDict): + account_holder_name: Annotated[str, PropertyInfo(alias='accountHolderName')] + + This means that {'account_holder_name': 'Robert'} will be transformed to {'accountHolderName': 'Robert'} before being sent to the API. + """ + + alias: str | None + format: PropertyFormat | None + format_template: str | None + + def __init__( + self, + *, + alias: str | None = None, + format: PropertyFormat | None = None, + format_template: str | None = None, + ) -> None: + self.alias = alias + self.format = format + self.format_template = format_template + + @override + def __repr__(self) -> str: + return f"{self.__class__.__name__}(alias='{self.alias}', format={self.format}, format_template='{self.format_template}')" + + +def maybe_transform( + data: Mapping[str, object] | List[Any] | None, + expected_type: object, +) -> Any | None: + """Wrapper over `transform()` that allows `None` to be passed. + + See `transform()` for more details. + """ + if data is None: + return None + return transform(data, expected_type) + + +# Wrapper over _transform_recursive providing fake types +def transform( + data: _T, + expected_type: object, +) -> _T: + """Transform dictionaries based off of type information from the given type, for example: + + ```py + class Params(TypedDict, total=False): + card_id: Required[Annotated[str, PropertyInfo(alias='cardID')]] + + transformed = transform({'card_id': ''}, Params) + # {'cardID': ''} + ``` + + Any keys / data that does not have type information given will be included as is. + + It should be noted that the transformations that this function does are not represented in the type system. + """ + transformed = _transform_recursive(data, annotation=cast(type, expected_type)) + return cast(_T, transformed) + + +def _get_annoted_type(type_: type) -> type | None: + """If the given type is an `Annotated` type then it is returned, if not `None` is returned. + + This also unwraps the type when applicable, e.g. `Required[Annotated[T, ...]]` + """ + if is_required_type(type_): + # Unwrap `Required[Annotated[T, ...]]` to `Annotated[T, ...]` + type_ = get_args(type_)[0] + + if is_annotated_type(type_): + return type_ + + return None + + +def _maybe_transform_key(key: str, type_: type) -> str: + """Transform the given `data` based on the annotations provided in `type_`. + + Note: this function only looks at `Annotated` types that contain `PropertInfo` metadata. + """ + annotated_type = _get_annoted_type(type_) + if annotated_type is None: + # no `Annotated` definition for this type, no transformation needed + return key + + # ignore the first argument as it is the actual type + annotations = get_args(annotated_type)[1:] + for annotation in annotations: + if isinstance(annotation, PropertyInfo) and annotation.alias is not None: + return annotation.alias + + return key + + +def _transform_recursive( + data: object, + *, + annotation: type, + inner_type: type | None = None, +) -> object: + """Transform the given data against the expected type. + + Args: + annotation: The direct type annotation given to the particular piece of data. + This may or may not be wrapped in metadata types, e.g. `Required[T]`, `Annotated[T, ...]` etc + + inner_type: If applicable, this is the "inside" type. This is useful in certain cases where the outside type + is a container type such as `List[T]`. In that case `inner_type` should be set to `T` so that each entry in + the list can be transformed using the metadata from the container type. + + Defaults to the same value as the `annotation` argument. + """ + if inner_type is None: + inner_type = annotation + + stripped_type = strip_annotated_type(inner_type) + if is_typeddict(stripped_type) and is_mapping(data): + return _transform_typeddict(data, stripped_type) + + if is_list_type(stripped_type) and is_list(data): + inner_type = extract_type_arg(stripped_type, 0) + return [_transform_recursive(d, annotation=annotation, inner_type=inner_type) for d in data] + + if is_union_type(stripped_type): + # For union types we run the transformation against all subtypes to ensure that everything is transformed. + # + # TODO: there may be edge cases where the same normalized field name will transform to two different names + # in different subtypes. + for subtype in get_args(stripped_type): + data = _transform_recursive(data, annotation=annotation, inner_type=subtype) + return data + + if isinstance(data, pydantic.BaseModel): + return model_dump(data, exclude_unset=True, exclude_defaults=True) + + return _transform_value(data, annotation) + + +def _transform_value(data: object, type_: type) -> object: + annotated_type = _get_annoted_type(type_) + if annotated_type is None: + return data + + # ignore the first argument as it is the actual type + annotations = get_args(annotated_type)[1:] + for annotation in annotations: + if isinstance(annotation, PropertyInfo) and annotation.format is not None: + return _format_data(data, annotation.format, annotation.format_template) + + return data + + +def _format_data(data: object, format_: PropertyFormat, format_template: str | None) -> object: + if isinstance(data, (date, datetime)): + if format_ == "iso8601": + return data.isoformat() + + if format_ == "custom" and format_template is not None: + return data.strftime(format_template) + + return data + + +def _transform_typeddict( + data: Mapping[str, object], + expected_type: type, +) -> Mapping[str, object]: + result: dict[str, object] = {} + annotations = get_type_hints(expected_type, include_extras=True) + for key, value in data.items(): + type_ = annotations.get(key) + if type_ is None: + # we do not have a type annotation for this field, leave it as is + result[key] = value + else: + result[_maybe_transform_key(key, type_)] = _transform_recursive(value, annotation=type_) + return result diff --git a/src/openai/_utils/_utils.py b/src/openai/_utils/_utils.py new file mode 100644 index 0000000000..4b51dcb2e8 --- /dev/null +++ b/src/openai/_utils/_utils.py @@ -0,0 +1,408 @@ +from __future__ import annotations + +import os +import re +import inspect +import functools +from typing import ( + Any, + Tuple, + Mapping, + TypeVar, + Callable, + Iterable, + Sequence, + cast, + overload, +) +from pathlib import Path +from typing_extensions import Required, Annotated, TypeGuard, get_args, get_origin + +from .._types import Headers, NotGiven, FileTypes, NotGivenOr, HeadersLike +from .._compat import is_union as _is_union +from .._compat import parse_date as parse_date +from .._compat import parse_datetime as parse_datetime + +_T = TypeVar("_T") +_TupleT = TypeVar("_TupleT", bound=Tuple[object, ...]) +_MappingT = TypeVar("_MappingT", bound=Mapping[str, object]) +_SequenceT = TypeVar("_SequenceT", bound=Sequence[object]) +CallableT = TypeVar("CallableT", bound=Callable[..., Any]) + + +def flatten(t: Iterable[Iterable[_T]]) -> list[_T]: + return [item for sublist in t for item in sublist] + + +def extract_files( + # TODO: this needs to take Dict but variance issues..... + # create protocol type ? + query: Mapping[str, object], + *, + paths: Sequence[Sequence[str]], +) -> list[tuple[str, FileTypes]]: + """Recursively extract files from the given dictionary based on specified paths. + + A path may look like this ['foo', 'files', '', 'data']. + + Note: this mutates the given dictionary. + """ + files: list[tuple[str, FileTypes]] = [] + for path in paths: + files.extend(_extract_items(query, path, index=0, flattened_key=None)) + return files + + +def _extract_items( + obj: object, + path: Sequence[str], + *, + index: int, + flattened_key: str | None, +) -> list[tuple[str, FileTypes]]: + try: + key = path[index] + except IndexError: + if isinstance(obj, NotGiven): + # no value was provided - we can safely ignore + return [] + + # cyclical import + from .._files import assert_is_file_content + + # We have exhausted the path, return the entry we found. + assert_is_file_content(obj, key=flattened_key) + assert flattened_key is not None + return [(flattened_key, cast(FileTypes, obj))] + + index += 1 + if is_dict(obj): + try: + # We are at the last entry in the path so we must remove the field + if (len(path)) == index: + item = obj.pop(key) + else: + item = obj[key] + except KeyError: + # Key was not present in the dictionary, this is not indicative of an error + # as the given path may not point to a required field. We also do not want + # to enforce required fields as the API may differ from the spec in some cases. + return [] + if flattened_key is None: + flattened_key = key + else: + flattened_key += f"[{key}]" + return _extract_items( + item, + path, + index=index, + flattened_key=flattened_key, + ) + elif is_list(obj): + if key != "": + return [] + + return flatten( + [ + _extract_items( + item, + path, + index=index, + flattened_key=flattened_key + "[]" if flattened_key is not None else "[]", + ) + for item in obj + ] + ) + + # Something unexpected was passed, just ignore it. + return [] + + +def is_given(obj: NotGivenOr[_T]) -> TypeGuard[_T]: + return not isinstance(obj, NotGiven) + + +# Type safe methods for narrowing types with TypeVars. +# The default narrowing for isinstance(obj, dict) is dict[unknown, unknown], +# however this cause Pyright to rightfully report errors. As we know we don't +# care about the contained types we can safely use `object` in it's place. +# +# There are two separate functions defined, `is_*` and `is_*_t` for different use cases. +# `is_*` is for when you're dealing with an unknown input +# `is_*_t` is for when you're narrowing a known union type to a specific subset + + +def is_tuple(obj: object) -> TypeGuard[tuple[object, ...]]: + return isinstance(obj, tuple) + + +def is_tuple_t(obj: _TupleT | object) -> TypeGuard[_TupleT]: + return isinstance(obj, tuple) + + +def is_sequence(obj: object) -> TypeGuard[Sequence[object]]: + return isinstance(obj, Sequence) + + +def is_sequence_t(obj: _SequenceT | object) -> TypeGuard[_SequenceT]: + return isinstance(obj, Sequence) + + +def is_mapping(obj: object) -> TypeGuard[Mapping[str, object]]: + return isinstance(obj, Mapping) + + +def is_mapping_t(obj: _MappingT | object) -> TypeGuard[_MappingT]: + return isinstance(obj, Mapping) + + +def is_dict(obj: object) -> TypeGuard[dict[object, object]]: + return isinstance(obj, dict) + + +def is_list(obj: object) -> TypeGuard[list[object]]: + return isinstance(obj, list) + + +def is_annotated_type(typ: type) -> bool: + return get_origin(typ) == Annotated + + +def is_list_type(typ: type) -> bool: + return (get_origin(typ) or typ) == list + + +def is_union_type(typ: type) -> bool: + return _is_union(get_origin(typ)) + + +def is_required_type(typ: type) -> bool: + return get_origin(typ) == Required + + +# Extracts T from Annotated[T, ...] or from Required[Annotated[T, ...]] +def strip_annotated_type(typ: type) -> type: + if is_required_type(typ) or is_annotated_type(typ): + return strip_annotated_type(cast(type, get_args(typ)[0])) + + return typ + + +def extract_type_arg(typ: type, index: int) -> type: + args = get_args(typ) + try: + return cast(type, args[index]) + except IndexError: + raise RuntimeError(f"Expected type {typ} to have a type argument at index {index} but it did not") + + +def deepcopy_minimal(item: _T) -> _T: + """Minimal reimplementation of copy.deepcopy() that will only copy certain object types: + + - mappings, e.g. `dict` + - list + + This is done for performance reasons. + """ + if is_mapping(item): + return cast(_T, {k: deepcopy_minimal(v) for k, v in item.items()}) + if is_list(item): + return cast(_T, [deepcopy_minimal(entry) for entry in item]) + return item + + +# copied from https://github.com/Rapptz/RoboDanny +def human_join(seq: Sequence[str], *, delim: str = ", ", final: str = "or") -> str: + size = len(seq) + if size == 0: + return "" + + if size == 1: + return seq[0] + + if size == 2: + return f"{seq[0]} {final} {seq[1]}" + + return delim.join(seq[:-1]) + f" {final} {seq[-1]}" + + +def quote(string: str) -> str: + """Add single quotation marks around the given string. Does *not* do any escaping.""" + return "'" + string + "'" + + +def required_args(*variants: Sequence[str]) -> Callable[[CallableT], CallableT]: + """Decorator to enforce a given set of arguments or variants of arguments are passed to the decorated function. + + Useful for enforcing runtime validation of overloaded functions. + + Example usage: + ```py + @overload + def foo(*, a: str) -> str: + ... + + @overload + def foo(*, b: bool) -> str: + ... + + # This enforces the same constraints that a static type checker would + # i.e. that either a or b must be passed to the function + @required_args(['a'], ['b']) + def foo(*, a: str | None = None, b: bool | None = None) -> str: + ... + ``` + """ + + def inner(func: CallableT) -> CallableT: + params = inspect.signature(func).parameters + positional = [ + name + for name, param in params.items() + if param.kind + in { + param.POSITIONAL_ONLY, + param.POSITIONAL_OR_KEYWORD, + } + ] + + @functools.wraps(func) + def wrapper(*args: object, **kwargs: object) -> object: + given_params: set[str] = set() + for i, _ in enumerate(args): + try: + given_params.add(positional[i]) + except IndexError: + raise TypeError(f"{func.__name__}() takes {len(positional)} argument(s) but {len(args)} were given") + + for key in kwargs.keys(): + given_params.add(key) + + for variant in variants: + matches = all((param in given_params for param in variant)) + if matches: + break + else: # no break + if len(variants) > 1: + variations = human_join( + ["(" + human_join([quote(arg) for arg in variant], final="and") + ")" for variant in variants] + ) + msg = f"Missing required arguments; Expected either {variations} arguments to be given" + else: + # TODO: this error message is not deterministic + missing = list(set(variants[0]) - given_params) + if len(missing) > 1: + msg = f"Missing required arguments: {human_join([quote(arg) for arg in missing])}" + else: + msg = f"Missing required argument: {quote(missing[0])}" + raise TypeError(msg) + return func(*args, **kwargs) + + return wrapper # type: ignore + + return inner + + +_K = TypeVar("_K") +_V = TypeVar("_V") + + +@overload +def strip_not_given(obj: None) -> None: + ... + + +@overload +def strip_not_given(obj: Mapping[_K, _V | NotGiven]) -> dict[_K, _V]: + ... + + +@overload +def strip_not_given(obj: object) -> object: + ... + + +def strip_not_given(obj: object | None) -> object: + """Remove all top-level keys where their values are instances of `NotGiven`""" + if obj is None: + return None + + if not is_mapping(obj): + return obj + + return {key: value for key, value in obj.items() if not isinstance(value, NotGiven)} + + +def coerce_integer(val: str) -> int: + return int(val, base=10) + + +def coerce_float(val: str) -> float: + return float(val) + + +def coerce_boolean(val: str) -> bool: + return val == "true" or val == "1" or val == "on" + + +def maybe_coerce_integer(val: str | None) -> int | None: + if val is None: + return None + return coerce_integer(val) + + +def maybe_coerce_float(val: str | None) -> float | None: + if val is None: + return None + return coerce_float(val) + + +def maybe_coerce_boolean(val: str | None) -> bool | None: + if val is None: + return None + return coerce_boolean(val) + + +def removeprefix(string: str, prefix: str) -> str: + """Remove a prefix from a string. + + Backport of `str.removeprefix` for Python < 3.9 + """ + if string.startswith(prefix): + return string[len(prefix) :] + return string + + +def removesuffix(string: str, suffix: str) -> str: + """Remove a suffix from a string. + + Backport of `str.removesuffix` for Python < 3.9 + """ + if string.endswith(suffix): + return string[: -len(suffix)] + return string + + +def file_from_path(path: str) -> FileTypes: + contents = Path(path).read_bytes() + file_name = os.path.basename(path) + return (file_name, contents) + + +def get_required_header(headers: HeadersLike, header: str) -> str: + lower_header = header.lower() + if isinstance(headers, Mapping): + headers = cast(Headers, headers) + for k, v in headers.items(): + if k.lower() == lower_header and isinstance(v, str): + return v + + """ to deal with the case where the header looks like Stainless-Event-Id """ + intercaps_header = re.sub(r"([^\w])(\w)", lambda pat: pat.group(1) + pat.group(2).upper(), header.capitalize()) + + for normalized_header in [header, lower_header, header.upper(), intercaps_header]: + value = headers.get(normalized_header) + if value: + return value + + raise ValueError(f"Could not find {header} header") diff --git a/src/openai/_version.py b/src/openai/_version.py new file mode 100644 index 0000000000..e9a3efc55c --- /dev/null +++ b/src/openai/_version.py @@ -0,0 +1,4 @@ +# File generated from our OpenAPI spec by Stainless. + +__title__ = "openai" +__version__ = "1.0.0" diff --git a/src/openai/cli/__init__.py b/src/openai/cli/__init__.py new file mode 100644 index 0000000000..d453d5e179 --- /dev/null +++ b/src/openai/cli/__init__.py @@ -0,0 +1 @@ +from ._cli import main as main diff --git a/src/openai/cli/_api/__init__.py b/src/openai/cli/_api/__init__.py new file mode 100644 index 0000000000..56a0260a6d --- /dev/null +++ b/src/openai/cli/_api/__init__.py @@ -0,0 +1 @@ +from ._main import register_commands as register_commands diff --git a/src/openai/cli/_api/_main.py b/src/openai/cli/_api/_main.py new file mode 100644 index 0000000000..fe5a5e6fc0 --- /dev/null +++ b/src/openai/cli/_api/_main.py @@ -0,0 +1,16 @@ +from __future__ import annotations + +from argparse import ArgumentParser + +from . import chat, audio, files, image, models, completions + + +def register_commands(parser: ArgumentParser) -> None: + subparsers = parser.add_subparsers(help="All API subcommands") + + chat.register(subparsers) + image.register(subparsers) + audio.register(subparsers) + files.register(subparsers) + models.register(subparsers) + completions.register(subparsers) diff --git a/src/openai/cli/_api/audio.py b/src/openai/cli/_api/audio.py new file mode 100644 index 0000000000..eaf57748ad --- /dev/null +++ b/src/openai/cli/_api/audio.py @@ -0,0 +1,94 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, cast +from argparse import ArgumentParser + +from .._utils import get_client, print_model +from ..._types import NOT_GIVEN +from .._models import BaseModel +from .._progress import BufferReader + +if TYPE_CHECKING: + from argparse import _SubParsersAction + + +def register(subparser: _SubParsersAction[ArgumentParser]) -> None: + # transcriptions + sub = subparser.add_parser("audio.transcriptions.create") + + # Required + sub.add_argument("-m", "--model", type=str, default="whisper-1") + sub.add_argument("-f", "--file", type=str, required=True) + # Optional + sub.add_argument("--response-format", type=str) + sub.add_argument("--language", type=str) + sub.add_argument("-t", "--temperature", type=float) + sub.add_argument("--prompt", type=str) + sub.set_defaults(func=CLIAudio.transcribe, args_model=CLITranscribeArgs) + + # translations + sub = subparser.add_parser("audio.translations.create") + + # Required + sub.add_argument("-f", "--file", type=str, required=True) + # Optional + sub.add_argument("-m", "--model", type=str, default="whisper-1") + sub.add_argument("--response-format", type=str) + # TODO: doesn't seem to be supported by the API + # sub.add_argument("--language", type=str) + sub.add_argument("-t", "--temperature", type=float) + sub.add_argument("--prompt", type=str) + sub.set_defaults(func=CLIAudio.translate, args_model=CLITranslationArgs) + + +class CLITranscribeArgs(BaseModel): + model: str + file: str + response_format: Optional[str] = None + language: Optional[str] = None + temperature: Optional[float] = None + prompt: Optional[str] = None + + +class CLITranslationArgs(BaseModel): + model: str + file: str + response_format: Optional[str] = None + language: Optional[str] = None + temperature: Optional[float] = None + prompt: Optional[str] = None + + +class CLIAudio: + @staticmethod + def transcribe(args: CLITranscribeArgs) -> None: + with open(args.file, "rb") as file_reader: + buffer_reader = BufferReader(file_reader.read(), desc="Upload progress") + + model = get_client().audio.transcriptions.create( + file=buffer_reader, + model=args.model, + language=args.language or NOT_GIVEN, + temperature=args.temperature or NOT_GIVEN, + prompt=args.prompt or NOT_GIVEN, + # casts required because the API is typed for enums + # but we don't want to validate that here for forwards-compat + response_format=cast(Any, args.response_format), + ) + print_model(model) + + @staticmethod + def translate(args: CLITranslationArgs) -> None: + with open(args.file, "rb") as file_reader: + buffer_reader = BufferReader(file_reader.read(), desc="Upload progress") + + model = get_client().audio.translations.create( + file=buffer_reader, + model=args.model, + temperature=args.temperature or NOT_GIVEN, + prompt=args.prompt or NOT_GIVEN, + # casts required because the API is typed for enums + # but we don't want to validate that here for forwards-compat + response_format=cast(Any, args.response_format), + ) + print_model(model) diff --git a/src/openai/cli/_api/chat/__init__.py b/src/openai/cli/_api/chat/__init__.py new file mode 100644 index 0000000000..87d971630a --- /dev/null +++ b/src/openai/cli/_api/chat/__init__.py @@ -0,0 +1,13 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING +from argparse import ArgumentParser + +from . import completions + +if TYPE_CHECKING: + from argparse import _SubParsersAction + + +def register(subparser: _SubParsersAction[ArgumentParser]) -> None: + completions.register(subparser) diff --git a/src/openai/cli/_api/chat/completions.py b/src/openai/cli/_api/chat/completions.py new file mode 100644 index 0000000000..e7566b143d --- /dev/null +++ b/src/openai/cli/_api/chat/completions.py @@ -0,0 +1,154 @@ +from __future__ import annotations + +import sys +from typing import TYPE_CHECKING, List, Optional, cast +from argparse import ArgumentParser +from typing_extensions import NamedTuple + +from ..._utils import get_client +from ..._models import BaseModel +from ...._streaming import Stream +from ....types.chat import ( + ChatCompletionRole, + ChatCompletionChunk, + CompletionCreateParams, +) +from ....types.chat.completion_create_params import ( + CompletionCreateParamsStreaming, + CompletionCreateParamsNonStreaming, +) + +if TYPE_CHECKING: + from argparse import _SubParsersAction + + +def register(subparser: _SubParsersAction[ArgumentParser]) -> None: + sub = subparser.add_parser("chat.completions.create") + + sub._action_groups.pop() + req = sub.add_argument_group("required arguments") + opt = sub.add_argument_group("optional arguments") + + req.add_argument( + "-g", + "--message", + action="http://github.com/append", + nargs=2, + metavar=("ROLE", "CONTENT"), + help="A message in `{role} {content}` format. Use this argument multiple times to add multiple messages.", + required=True, + ) + req.add_argument( + "-m", + "--model", + help="The model to use.", + required=True, + ) + + opt.add_argument( + "-n", + "--n", + help="How many completions to generate for the conversation.", + type=int, + ) + opt.add_argument("-M", "--max-tokens", help="The maximum number of tokens to generate.", type=int) + opt.add_argument( + "-t", + "--temperature", + help="""What sampling temperature to use. Higher values means the model will take more risks. Try 0.9 for more creative applications, and 0 (argmax sampling) for ones with a well-defined answer. + +Mutually exclusive with `top_p`.""", + type=float, + ) + opt.add_argument( + "-P", + "--top_p", + help="""An alternative to sampling with temperature, called nucleus sampling, where the considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10%% probability mass are considered. + + Mutually exclusive with `temperature`.""", + type=float, + ) + opt.add_argument( + "--stop", + help="A stop sequence at which to stop generating tokens for the message.", + ) + opt.add_argument("--stream", help="Stream messages as they're ready.", action="http://github.com/store_true") + sub.set_defaults(func=CLIChatCompletion.create, args_model=CLIChatCompletionCreateArgs) + + +class CLIMessage(NamedTuple): + role: ChatCompletionRole + content: str + + +class CLIChatCompletionCreateArgs(BaseModel): + message: List[CLIMessage] + model: str + n: Optional[int] = None + max_tokens: Optional[int] = None + temperature: Optional[float] = None + top_p: Optional[float] = None + stop: Optional[str] = None + stream: bool = False + + +class CLIChatCompletion: + @staticmethod + def create(args: CLIChatCompletionCreateArgs) -> None: + params: CompletionCreateParams = { + "model": args.model, + "messages": [{"role": message.role, "content": message.content} for message in args.message], + "n": args.n, + "temperature": args.temperature, + "top_p": args.top_p, + "stop": args.stop, + # type checkers are not good at inferring union types so we have to set stream afterwards + "stream": False, + } + if args.stream: + params["stream"] = args.stream # type: ignore + if args.max_tokens is not None: + params["max_tokens"] = args.max_tokens + + if args.stream: + return CLIChatCompletion._stream_create(cast(CompletionCreateParamsStreaming, params)) + + return CLIChatCompletion._create(cast(CompletionCreateParamsNonStreaming, params)) + + @staticmethod + def _create(params: CompletionCreateParamsNonStreaming) -> None: + completion = get_client().chat.completions.create(**params) + should_print_header = len(completion.choices) > 1 + for choice in completion.choices: + if should_print_header: + sys.stdout.write("===== Chat Completion {} =====\n".format(choice.index)) + + content = choice.message.content if choice.message.content is not None else "None" + sys.stdout.write(content) + + if should_print_header or not content.endswith("\n"): + sys.stdout.write("\n") + + sys.stdout.flush() + + @staticmethod + def _stream_create(params: CompletionCreateParamsStreaming) -> None: + # cast is required for mypy + stream = cast( # pyright: ignore[reportUnnecessaryCast] + Stream[ChatCompletionChunk], get_client().chat.completions.create(**params) + ) + for chunk in stream: + should_print_header = len(chunk.choices) > 1 + for choice in chunk.choices: + if should_print_header: + sys.stdout.write("===== Chat Completion {} =====\n".format(choice.index)) + + content = choice.delta.content or "" + sys.stdout.write(content) + + if should_print_header: + sys.stdout.write("\n") + + sys.stdout.flush() + + sys.stdout.write("\n") diff --git a/src/openai/cli/_api/completions.py b/src/openai/cli/_api/completions.py new file mode 100644 index 0000000000..ce1036b224 --- /dev/null +++ b/src/openai/cli/_api/completions.py @@ -0,0 +1,173 @@ +from __future__ import annotations + +import sys +from typing import TYPE_CHECKING, Optional, cast +from argparse import ArgumentParser +from functools import partial + +from openai.types.completion import Completion + +from .._utils import get_client +from ..._types import NOT_GIVEN, NotGivenOr +from ..._utils import is_given +from .._errors import CLIError +from .._models import BaseModel +from ..._streaming import Stream + +if TYPE_CHECKING: + from argparse import _SubParsersAction + + +def register(subparser: _SubParsersAction[ArgumentParser]) -> None: + sub = subparser.add_parser("completions.create") + + # Required + sub.add_argument( + "-m", + "--model", + help="The model to use", + required=True, + ) + + # Optional + sub.add_argument("-p", "--prompt", help="An optional prompt to complete from") + sub.add_argument("--stream", help="Stream tokens as they're ready.", action="http://github.com/store_true") + sub.add_argument("-M", "--max-tokens", help="The maximum number of tokens to generate", type=int) + sub.add_argument( + "-t", + "--temperature", + help="""What sampling temperature to use. Higher values means the model will take more risks. Try 0.9 for more creative applications, and 0 (argmax sampling) for ones with a well-defined answer. + +Mutually exclusive with `top_p`.""", + type=float, + ) + sub.add_argument( + "-P", + "--top_p", + help="""An alternative to sampling with temperature, called nucleus sampling, where the considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10%% probability mass are considered. + + Mutually exclusive with `temperature`.""", + type=float, + ) + sub.add_argument( + "-n", + "--n", + help="How many sub-completions to generate for each prompt.", + type=int, + ) + sub.add_argument( + "--logprobs", + help="Include the log probabilites on the `logprobs` most likely tokens, as well the chosen tokens. So for example, if `logprobs` is 10, the API will return a list of the 10 most likely tokens. If `logprobs` is 0, only the chosen tokens will have logprobs returned.", + type=int, + ) + sub.add_argument( + "--best_of", + help="Generates `best_of` completions server-side and returns the 'best' (the one with the highest log probability per token). Results cannot be streamed.", + type=int, + ) + sub.add_argument( + "--echo", + help="Echo back the prompt in addition to the completion", + action="http://github.com/store_true", + ) + sub.add_argument( + "--frequency_penalty", + help="Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.", + type=float, + ) + sub.add_argument( + "--presence_penalty", + help="Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.", + type=float, + ) + sub.add_argument("--suffix", help="The suffix that comes after a completion of inserted text.") + sub.add_argument("--stop", help="A stop sequence at which to stop generating tokens.") + sub.add_argument( + "--user", + help="A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse.", + ) + # TODO: add support for logit_bias + sub.set_defaults(func=CLICompletions.create, args_model=CLICompletionCreateArgs) + + +class CLICompletionCreateArgs(BaseModel): + model: str + stream: bool = False + + prompt: Optional[str] = None + n: NotGivenOr[int] = NOT_GIVEN + stop: NotGivenOr[str] = NOT_GIVEN + user: NotGivenOr[str] = NOT_GIVEN + echo: NotGivenOr[bool] = NOT_GIVEN + suffix: NotGivenOr[str] = NOT_GIVEN + best_of: NotGivenOr[int] = NOT_GIVEN + top_p: NotGivenOr[float] = NOT_GIVEN + logprobs: NotGivenOr[int] = NOT_GIVEN + max_tokens: NotGivenOr[int] = NOT_GIVEN + temperature: NotGivenOr[float] = NOT_GIVEN + presence_penalty: NotGivenOr[float] = NOT_GIVEN + frequency_penalty: NotGivenOr[float] = NOT_GIVEN + + +class CLICompletions: + @staticmethod + def create(args: CLICompletionCreateArgs) -> None: + if is_given(args.n) and args.n > 1 and args.stream: + raise CLIError("Can't stream completions with n>1 with the current CLI") + + make_request = partial( + get_client().completions.create, + n=args.n, + echo=args.echo, + stop=args.stop, + user=args.user, + model=args.model, + top_p=args.top_p, + prompt=args.prompt, + suffix=args.suffix, + best_of=args.best_of, + logprobs=args.logprobs, + max_tokens=args.max_tokens, + temperature=args.temperature, + presence_penalty=args.presence_penalty, + frequency_penalty=args.frequency_penalty, + ) + + if args.stream: + return CLICompletions._stream_create( + # mypy doesn't understand the `partial` function but pyright does + cast(Stream[Completion], make_request(stream=True)) # pyright: ignore[reportUnnecessaryCast] + ) + + return CLICompletions._create(make_request()) + + @staticmethod + def _create(completion: Completion) -> None: + should_print_header = len(completion.choices) > 1 + for choice in completion.choices: + if should_print_header: + sys.stdout.write("===== Completion {} =====\n".format(choice.index)) + + sys.stdout.write(choice.text) + + if should_print_header or not choice.text.endswith("\n"): + sys.stdout.write("\n") + + sys.stdout.flush() + + @staticmethod + def _stream_create(stream: Stream[Completion]) -> None: + for completion in stream: + should_print_header = len(completion.choices) > 1 + for choice in sorted(completion.choices, key=lambda c: c.index): + if should_print_header: + sys.stdout.write("===== Chat Completion {} =====\n".format(choice.index)) + + sys.stdout.write(choice.text) + + if should_print_header: + sys.stdout.write("\n") + + sys.stdout.flush() + + sys.stdout.write("\n") diff --git a/src/openai/cli/_api/files.py b/src/openai/cli/_api/files.py new file mode 100644 index 0000000000..ae6dadf0f1 --- /dev/null +++ b/src/openai/cli/_api/files.py @@ -0,0 +1,75 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING +from argparse import ArgumentParser + +from .._utils import get_client, print_model +from .._models import BaseModel +from .._progress import BufferReader + +if TYPE_CHECKING: + from argparse import _SubParsersAction + + +def register(subparser: _SubParsersAction[ArgumentParser]) -> None: + sub = subparser.add_parser("files.create") + + sub.add_argument( + "-f", + "--file", + required=True, + help="File to upload", + ) + sub.add_argument( + "-p", + "--purpose", + help="Why are you uploading this file? (see https://platform.openai.com/docs/api-reference/ for purposes)", + required=True, + ) + sub.set_defaults(func=CLIFile.create, args_model=CLIFileCreateArgs) + + sub = subparser.add_parser("files.retrieve") + sub.add_argument("-i", "--id", required=True, help="The files ID") + sub.set_defaults(func=CLIFile.get, args_model=CLIFileCreateArgs) + + sub = subparser.add_parser("files.delete") + sub.add_argument("-i", "--id", required=True, help="The files ID") + sub.set_defaults(func=CLIFile.delete, args_model=CLIFileCreateArgs) + + sub = subparser.add_parser("files.list") + sub.set_defaults(func=CLIFile.list) + + +class CLIFileIDArgs(BaseModel): + id: str + + +class CLIFileCreateArgs(BaseModel): + file: str + purpose: str + + +class CLIFile: + @staticmethod + def create(args: CLIFileCreateArgs) -> None: + with open(args.file, "rb") as file_reader: + buffer_reader = BufferReader(file_reader.read(), desc="Upload progress") + + file = get_client().files.create(file=(args.file, buffer_reader), purpose=args.purpose) + print_model(file) + + @staticmethod + def get(args: CLIFileIDArgs) -> None: + file = get_client().files.retrieve(file_id=args.id) + print_model(file) + + @staticmethod + def delete(args: CLIFileIDArgs) -> None: + file = get_client().files.delete(file_id=args.id) + print_model(file) + + @staticmethod + def list() -> None: + files = get_client().files.list() + for file in files: + print_model(file) diff --git a/src/openai/cli/_api/image.py b/src/openai/cli/_api/image.py new file mode 100644 index 0000000000..e6149eeac4 --- /dev/null +++ b/src/openai/cli/_api/image.py @@ -0,0 +1,130 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, cast +from argparse import ArgumentParser + +from .._utils import get_client, print_model +from ..._types import NOT_GIVEN, NotGiven, NotGivenOr +from .._models import BaseModel +from .._progress import BufferReader + +if TYPE_CHECKING: + from argparse import _SubParsersAction + + +def register(subparser: _SubParsersAction[ArgumentParser]) -> None: + sub = subparser.add_parser("images.generate") + sub.add_argument("-p", "--prompt", type=str, required=True) + sub.add_argument("-n", "--num-images", type=int, default=1) + sub.add_argument("-s", "--size", type=str, default="1024x1024", help="Size of the output image") + sub.add_argument("--response-format", type=str, default="url") + sub.set_defaults(func=CLIImage.create, args_model=CLIImageCreateArgs) + + sub = subparser.add_parser("images.edit") + sub.add_argument("-p", "--prompt", type=str, required=True) + sub.add_argument("-n", "--num-images", type=int, default=1) + sub.add_argument( + "-I", + "--image", + type=str, + required=True, + help="Image to modify. Should be a local path and a PNG encoded image.", + ) + sub.add_argument("-s", "--size", type=str, default="1024x1024", help="Size of the output image") + sub.add_argument("--response-format", type=str, default="url") + sub.add_argument( + "-M", + "--mask", + type=str, + required=False, + help="Path to a mask image. It should be the same size as the image you're editing and a RGBA PNG image. The Alpha channel acts as the mask.", + ) + sub.set_defaults(func=CLIImage.edit, args_model=CLIImageEditArgs) + + sub = subparser.add_parser("images.create_variation") + sub.add_argument("-n", "--num-images", type=int, default=1) + sub.add_argument( + "-I", + "--image", + type=str, + required=True, + help="Image to modify. Should be a local path and a PNG encoded image.", + ) + sub.add_argument("-s", "--size", type=str, default="1024x1024", help="Size of the output image") + sub.add_argument("--response-format", type=str, default="url") + sub.set_defaults(func=CLIImage.create_variation, args_model=CLIImageCreateVariationArgs) + + +class CLIImageCreateArgs(BaseModel): + prompt: str + num_images: int + size: str + response_format: str + + +class CLIImageCreateVariationArgs(BaseModel): + image: str + num_images: int + size: str + response_format: str + + +class CLIImageEditArgs(BaseModel): + image: str + num_images: int + size: str + response_format: str + prompt: str + mask: NotGivenOr[str] = NOT_GIVEN + + +class CLIImage: + @staticmethod + def create(args: CLIImageCreateArgs) -> None: + image = get_client().images.generate( + prompt=args.prompt, + n=args.num_images, + # casts required because the API is typed for enums + # but we don't want to validate that here for forwards-compat + size=cast(Any, args.size), + response_format=cast(Any, args.response_format), + ) + print_model(image) + + @staticmethod + def create_variation(args: CLIImageCreateVariationArgs) -> None: + with open(args.image, "rb") as file_reader: + buffer_reader = BufferReader(file_reader.read(), desc="Upload progress") + + image = get_client().images.create_variation( + image=("image", buffer_reader), + n=args.num_images, + # casts required because the API is typed for enums + # but we don't want to validate that here for forwards-compat + size=cast(Any, args.size), + response_format=cast(Any, args.response_format), + ) + print_model(image) + + @staticmethod + def edit(args: CLIImageEditArgs) -> None: + with open(args.image, "rb") as file_reader: + buffer_reader = BufferReader(file_reader.read(), desc="Image upload progress") + + if isinstance(args.mask, NotGiven): + mask: NotGivenOr[BufferReader] = NOT_GIVEN + else: + with open(args.mask, "rb") as file_reader: + mask = BufferReader(file_reader.read(), desc="Mask progress") + + image = get_client().images.edit( + prompt=args.prompt, + image=("image", buffer_reader), + n=args.num_images, + mask=("mask", mask) if not isinstance(mask, NotGiven) else mask, + # casts required because the API is typed for enums + # but we don't want to validate that here for forwards-compat + size=cast(Any, args.size), + response_format=cast(Any, args.response_format), + ) + print_model(image) diff --git a/src/openai/cli/_api/models.py b/src/openai/cli/_api/models.py new file mode 100644 index 0000000000..017218fa6e --- /dev/null +++ b/src/openai/cli/_api/models.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING +from argparse import ArgumentParser + +from .._utils import get_client, print_model +from .._models import BaseModel + +if TYPE_CHECKING: + from argparse import _SubParsersAction + + +def register(subparser: _SubParsersAction[ArgumentParser]) -> None: + sub = subparser.add_parser("models.list") + sub.set_defaults(func=CLIModels.list) + + sub = subparser.add_parser("models.retrieve") + sub.add_argument("-i", "--id", required=True, help="The model ID") + sub.set_defaults(func=CLIModels.get, args_model=CLIModelIDArgs) + + sub = subparser.add_parser("models.delete") + sub.add_argument("-i", "--id", required=True, help="The model ID") + sub.set_defaults(func=CLIModels.delete, args_model=CLIModelIDArgs) + + +class CLIModelIDArgs(BaseModel): + id: str + + +class CLIModels: + @staticmethod + def get(args: CLIModelIDArgs) -> None: + model = get_client().models.retrieve(model=args.id) + print_model(model) + + @staticmethod + def delete(args: CLIModelIDArgs) -> None: + model = get_client().models.delete(model=args.id) + print_model(model) + + @staticmethod + def list() -> None: + models = get_client().models.list() + for model in models: + print_model(model) diff --git a/src/openai/cli/_cli.py b/src/openai/cli/_cli.py new file mode 100644 index 0000000000..72e5c923bd --- /dev/null +++ b/src/openai/cli/_cli.py @@ -0,0 +1,234 @@ +from __future__ import annotations + +import sys +import logging +import argparse +from typing import Any, List, Type, Optional +from typing_extensions import ClassVar + +import httpx +import pydantic + +import openai + +from . import _tools +from .. import _ApiType, __version__ +from ._api import register_commands +from ._utils import can_use_http2 +from .._types import ProxiesDict +from ._errors import CLIError, display_error +from .._compat import PYDANTIC_V2, ConfigDict, model_parse +from .._models import BaseModel +from .._exceptions import APIError + +logger = logging.getLogger() +formatter = logging.Formatter("[%(asctime)s] %(message)s") +handler = logging.StreamHandler(sys.stderr) +handler.setFormatter(formatter) +logger.addHandler(handler) + + +class Arguments(BaseModel): + if PYDANTIC_V2: + model_config: ClassVar[ConfigDict] = ConfigDict( + extra="ignore", + ) + else: + + class Config(pydantic.BaseConfig): # type: ignore + extra: Any = pydantic.Extra.ignore # type: ignore + + verbosity: int + version: Optional[str] = None + + api_key: Optional[str] + api_base: Optional[str] + organization: Optional[str] + proxy: Optional[List[str]] + api_type: Optional[_ApiType] = None + api_version: Optional[str] = None + + # azure + azure_endpoint: Optional[str] = None + azure_ad_token: Optional[str] = None + + # internal, set by subparsers to parse their specific args + args_model: Optional[Type[BaseModel]] = None + + # internal, used so that subparsers can forward unknown arguments + unknown_args: List[str] = [] + allow_unknown_args: bool = False + + +def _build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description=None, prog="openai") + parser.add_argument( + "-v", + "--verbose", + action="http://github.com/count", + dest="verbosity", + default=0, + help="Set verbosity.", + ) + parser.add_argument("-b", "--api-base", help="What API base url to use.") + parser.add_argument("-k", "--api-key", help="What API key to use.") + parser.add_argument("-p", "--proxy", nargs="+", help="What proxy to use.") + parser.add_argument( + "-o", + "--organization", + help="Which organization to run as (will use your default organization if not specified)", + ) + parser.add_argument( + "-t", + "--api-type", + type=str, + choices=("openai", "azure"), + help="The backend API to call, must be `openai` or `azure`", + ) + parser.add_argument( + "--api-version", + help="The Azure API version, e.g. 'https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#rest-api-versioning'", + ) + + # azure + parser.add_argument( + "--azure-endpoint", + help="The Azure endpoint, e.g. 'https://endpoint.openai.azure.com/'", + ) + parser.add_argument( + "--azure-ad-token", + help="A token from Azure Active Directory, https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id", + ) + + # prints the package version + parser.add_argument( + "-V", + "--version", + action="http://github.com/version", + version="%(prog)s " + __version__, + ) + + def help() -> None: + parser.print_help() + + parser.set_defaults(func=help) + + subparsers = parser.add_subparsers() + sub_api = subparsers.add_parser("api", help="Direct API calls") + + register_commands(sub_api) + + sub_tools = subparsers.add_parser("tools", help="Client side tools for convenience") + _tools.register_commands(sub_tools, subparsers) + + return parser + + +def main() -> int: + try: + _main() + except (APIError, CLIError, pydantic.ValidationError) as err: + display_error(err) + return 1 + except KeyboardInterrupt: + sys.stderr.write("\n") + return 1 + return 0 + + +def _parse_args(parser: argparse.ArgumentParser) -> tuple[argparse.Namespace, Arguments, list[str]]: + # argparse by default will strip out the `--` but we want to keep it for unknown arguments + if "--" in sys.argv: + idx = sys.argv.index("--") + known_args = sys.argv[1:idx] + unknown_args = sys.argv[idx:] + else: + known_args = sys.argv[1:] + unknown_args = [] + + parsed, remaining_unknown = parser.parse_known_args(known_args) + + # append any remaining unknown arguments from the initial parsing + remaining_unknown.extend(unknown_args) + + args = model_parse(Arguments, vars(parsed)) + if not args.allow_unknown_args: + # we have to parse twice to ensure any unknown arguments + # result in an error if that behaviour is desired + parser.parse_args() + + return parsed, args, remaining_unknown + + +def _main() -> None: + parser = _build_parser() + parsed, args, unknown = _parse_args(parser) + + if args.verbosity != 0: + sys.stderr.write("Warning: --verbosity isn't supported yet\n") + + proxies: ProxiesDict = {} + if args.proxy is not None: + for proxy in args.proxy: + key = "https://" if proxy.startswith("https") else "http://" + if key in proxies: + raise CLIError(f"Multiple {key} proxies given - only the last one would be used") + + proxies[key] = proxy + + http_client = httpx.Client( + proxies=proxies or None, + http2=can_use_http2(), + ) + openai.http_client = http_client + + if args.organization: + openai.organization = args.organization + + if args.api_key: + openai.api_key = args.api_key + + if args.api_base: + openai.base_url = args.api_base + + # azure + if args.api_type is not None: + openai.api_type = args.api_type + + if args.azure_endpoint is not None: + openai.azure_endpoint = args.azure_endpoint + + if args.api_version is not None: + openai.api_version = args.api_version + + if args.azure_ad_token is not None: + openai.azure_ad_token = args.azure_ad_token + + try: + if args.args_model: + parsed.func( + model_parse( + args.args_model, + { + **{ + # we omit None values so that they can be defaulted to `NotGiven` + # and we'll strip it from the API request + key: value + for key, value in vars(parsed).items() + if value is not None + }, + "unknown_args": unknown, + }, + ) + ) + else: + parsed.func() + finally: + try: + http_client.close() + except Exception: + pass + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/openai/cli/_errors.py b/src/openai/cli/_errors.py new file mode 100644 index 0000000000..ac2a3780d0 --- /dev/null +++ b/src/openai/cli/_errors.py @@ -0,0 +1,23 @@ +from __future__ import annotations + +import sys + +import pydantic + +from ._utils import Colours, organization_info +from .._exceptions import APIError, OpenAIError + + +class CLIError(OpenAIError): + ... + + +class SilentCLIError(CLIError): + ... + + +def display_error(err: CLIError | APIError | pydantic.ValidationError) -> None: + if isinstance(err, SilentCLIError): + return + + sys.stderr.write("{}{}Error:{} {}\n".format(organization_info(), Colours.FAIL, Colours.ENDC, err)) diff --git a/src/openai/cli/_models.py b/src/openai/cli/_models.py new file mode 100644 index 0000000000..5583db2609 --- /dev/null +++ b/src/openai/cli/_models.py @@ -0,0 +1,17 @@ +from typing import Any +from typing_extensions import ClassVar + +import pydantic + +from .. import _models +from .._compat import PYDANTIC_V2, ConfigDict + + +class BaseModel(_models.BaseModel): + if PYDANTIC_V2: + model_config: ClassVar[ConfigDict] = ConfigDict(extra="ignore", arbitrary_types_allowed=True) + else: + + class Config(pydantic.BaseConfig): # type: ignore + extra: Any = pydantic.Extra.ignore # type: ignore + arbitrary_types_allowed: bool = True diff --git a/src/openai/cli/_progress.py b/src/openai/cli/_progress.py new file mode 100644 index 0000000000..390aaa9dfe --- /dev/null +++ b/src/openai/cli/_progress.py @@ -0,0 +1,59 @@ +from __future__ import annotations + +import io +from typing import Callable +from typing_extensions import override + + +class CancelledError(Exception): + def __init__(self, msg: str) -> None: + self.msg = msg + super().__init__(msg) + + @override + def __str__(self) -> str: + return self.msg + + __repr__ = __str__ + + +class BufferReader(io.BytesIO): + def __init__(self, buf: bytes = b"", desc: str | None = None) -> None: + super().__init__(buf) + self._len = len(buf) + self._progress = 0 + self._callback = progress(len(buf), desc=desc) + + def __len__(self) -> int: + return self._len + + @override + def read(self, n: int | None = -1) -> bytes: + chunk = io.BytesIO.read(self, n) + self._progress += len(chunk) + + try: + self._callback(self._progress) + except Exception as e: # catches exception from the callback + raise CancelledError("The upload was cancelled: {}".format(e)) + + return chunk + + +def progress(total: float, desc: str | None) -> Callable[[float], None]: + import tqdm + + meter = tqdm.tqdm(total=total, unit_scale=True, desc=desc) + + def incr(progress: float) -> None: + meter.n = progress + if progress == total: + meter.close() + else: + meter.refresh() + + return incr + + +def MB(i: int) -> int: + return int(i // 1024**2) diff --git a/src/openai/cli/_tools/__init__.py b/src/openai/cli/_tools/__init__.py new file mode 100644 index 0000000000..56a0260a6d --- /dev/null +++ b/src/openai/cli/_tools/__init__.py @@ -0,0 +1 @@ +from ._main import register_commands as register_commands diff --git a/src/openai/cli/_tools/_main.py b/src/openai/cli/_tools/_main.py new file mode 100644 index 0000000000..bd6cda408f --- /dev/null +++ b/src/openai/cli/_tools/_main.py @@ -0,0 +1,17 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING +from argparse import ArgumentParser + +from . import migrate, fine_tunes + +if TYPE_CHECKING: + from argparse import _SubParsersAction + + +def register_commands(parser: ArgumentParser, subparser: _SubParsersAction[ArgumentParser]) -> None: + migrate.register(subparser) + + namespaced = parser.add_subparsers(title="Tools", help="Convenience client side tools") + + fine_tunes.register(namespaced) diff --git a/src/openai/cli/_tools/fine_tunes.py b/src/openai/cli/_tools/fine_tunes.py new file mode 100644 index 0000000000..2128b88952 --- /dev/null +++ b/src/openai/cli/_tools/fine_tunes.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +import sys +from typing import TYPE_CHECKING +from argparse import ArgumentParser + +from .._models import BaseModel +from ...lib._validators import ( + get_validators, + write_out_file, + read_any_format, + apply_validators, + apply_necessary_remediation, +) + +if TYPE_CHECKING: + from argparse import _SubParsersAction + + +def register(subparser: _SubParsersAction[ArgumentParser]) -> None: + sub = subparser.add_parser("fine_tunes.prepare_data") + sub.add_argument( + "-f", + "--file", + required=True, + help="JSONL, JSON, CSV, TSV, TXT or XLSX file containing prompt-completion examples to be analyzed." + "This should be the local file path.", + ) + sub.add_argument( + "-q", + "--quiet", + required=False, + action="http://github.com/store_true", + help="Auto accepts all suggestions, without asking for user input. To be used within scripts.", + ) + sub.set_defaults(func=prepare_data, args_model=PrepareDataArgs) + + +class PrepareDataArgs(BaseModel): + file: str + + quiet: bool + + +def prepare_data(args: PrepareDataArgs) -> None: + sys.stdout.write("Analyzing...\n") + fname = args.file + auto_accept = args.quiet + df, remediation = read_any_format(fname) + apply_necessary_remediation(None, remediation) + + validators = get_validators() + + assert df is not None + + apply_validators( + df, + fname, + remediation, + validators, + auto_accept, + write_out_file_func=write_out_file, + ) diff --git a/src/openai/cli/_tools/migrate.py b/src/openai/cli/_tools/migrate.py new file mode 100644 index 0000000000..714bead8e3 --- /dev/null +++ b/src/openai/cli/_tools/migrate.py @@ -0,0 +1,181 @@ +from __future__ import annotations + +import os +import sys +import json +import shutil +import tarfile +import platform +import subprocess +from typing import TYPE_CHECKING, List +from pathlib import Path +from argparse import ArgumentParser + +import httpx + +from .._errors import CLIError, SilentCLIError +from .._models import BaseModel + +if TYPE_CHECKING: + from argparse import _SubParsersAction + + +def register(subparser: _SubParsersAction[ArgumentParser]) -> None: + sub = subparser.add_parser("migrate") + sub.set_defaults(func=migrate, args_model=MigrateArgs, allow_unknown_args=True) + + sub = subparser.add_parser("grit") + sub.set_defaults(func=grit, args_model=GritArgs, allow_unknown_args=True) + + +class GritArgs(BaseModel): + # internal + unknown_args: List[str] = [] + + +def grit(args: GritArgs) -> None: + grit_path = install() + + try: + subprocess.check_call([grit_path, *args.unknown_args]) + except subprocess.CalledProcessError: + # stdout and stderr are forwarded by subprocess so an error will already + # have been displayed + raise SilentCLIError() + + +class MigrateArgs(BaseModel): + # internal + unknown_args: List[str] = [] + + +def migrate(args: MigrateArgs) -> None: + grit_path = install() + + try: + subprocess.check_call([grit_path, "apply", "openai", *args.unknown_args]) + except subprocess.CalledProcessError: + # stdout and stderr are forwarded by subprocess so an error will already + # have been displayed + raise SilentCLIError() + + +# handles downloading the Grit CLI until they provide their own PyPi package + +KEYGEN_ACCOUNT = "custodian-dev" + + +def _cache_dir() -> Path: + xdg = os.environ.get("XDG_CACHE_HOME") + if xdg is not None: + return Path(xdg) + + return Path.home() / ".cache" + + +def _debug(message: str) -> None: + if not os.environ.get("DEBUG"): + return + + sys.stdout.write(f"[DEBUG]: {message}\n") + + +def install() -> Path: + """Installs the Grit CLI and returns the location of the binary""" + if sys.platform == "win32": + raise CLIError("Windows is not supported yet in the migration CLI") + + platform = "macos" if sys.platform == "darwin" else "linux" + + dir_name = _cache_dir() / "openai-python" + install_dir = dir_name / ".install" + target_dir = install_dir / "bin" + + target_path = target_dir / "marzano" + temp_file = target_dir / "marzano.tmp" + + if target_path.exists(): + _debug(f"{target_path} already exists") + sys.stdout.flush() + return target_path + + _debug(f"Using Grit CLI path: {target_path}") + + target_dir.mkdir(parents=True, exist_ok=True) + + if temp_file.exists(): + temp_file.unlink() + + arch = _get_arch() + _debug(f"Using architecture {arch}") + + file_name = f"marzano-{platform}-{arch}" + meta_url = f"https://api.keygen.sh/v1/accounts/%7BKEYGEN_ACCOUNT%7D/artifacts/%7Bfile_name%7D" + + sys.stdout.write(f"Retrieving Grit CLI metadata from {meta_url}\n") + with httpx.Client() as client: + response = client.get(meta_url) # pyright: ignore[reportUnknownMemberType] + + data = response.json() + errors = data.get("errors") + if errors: + for error in errors: + sys.stdout.write(f"{error}\n") + + raise CLIError("Could not locate Grit CLI binary - see above errors") + + write_manifest(install_dir, data["data"]["relationships"]["release"]["data"]["id"]) + + link = data["data"]["links"]["redirect"] + _debug(f"Redirect URL {link}") + + download_response = client.get(link) # pyright: ignore[reportUnknownMemberType] + with open(temp_file, "wb") as file: + for chunk in download_response.iter_bytes(): + file.write(chunk) + + unpacked_dir = target_dir / "cli-bin" + unpacked_dir.mkdir(parents=True, exist_ok=True) + + with tarfile.open(temp_file, "r:gz") as archive: + archive.extractall(unpacked_dir) + + for item in unpacked_dir.iterdir(): + item.rename(target_dir / item.name) + + shutil.rmtree(unpacked_dir) + os.remove(temp_file) + os.chmod(target_path, 0o755) + + sys.stdout.flush() + + return target_path + + +def _get_arch() -> str: + architecture = platform.machine().lower() + + # Map the architecture names to Node.js equivalents + arch_map = { + "x86_64": "x64", + "amd64": "x64", + "armv7l": "arm", + "aarch64": "arm64", + } + + return arch_map.get(architecture, architecture) + + +def write_manifest(install_path: Path, release: str) -> None: + manifest = { + "installPath": str(install_path), + "binaries": { + "marzano": { + "name": "marzano", + "release": release, + }, + }, + } + manifest_path = Path(install_path) / "manifests.json" + with open(manifest_path, "w") as f: + json.dump(manifest, f, indent=2) diff --git a/src/openai/cli/_utils.py b/src/openai/cli/_utils.py new file mode 100644 index 0000000000..027ab08de3 --- /dev/null +++ b/src/openai/cli/_utils.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +import sys + +import openai + +from .. import OpenAI, _load_client +from .._compat import model_json +from .._models import BaseModel + + +class Colours: + HEADER = "\033[95m" + OKBLUE = "\033[94m" + OKGREEN = "\033[92m" + WARNING = "\033[93m" + FAIL = "\033[91m" + ENDC = "\033[0m" + BOLD = "\033[1m" + UNDERLINE = "\033[4m" + + +def get_client() -> OpenAI: + return _load_client() + + +def organization_info() -> str: + organization = openai.organization + if organization is not None: + return "[organization={}] ".format(organization) + + return "" + + +def print_model(model: BaseModel) -> None: + sys.stdout.write(model_json(model, indent=2) + "\n") + + +def can_use_http2() -> bool: + try: + import h2 # type: ignore # noqa + except ImportError: + return False + + return True diff --git a/openai/validators.py b/src/openai/lib/_validators.py similarity index 80% rename from openai/validators.py rename to src/openai/lib/_validators.py index 078179a44b..8e4ed3c9f4 100644 --- a/openai/validators.py +++ b/src/openai/lib/_validators.py @@ -1,9 +1,12 @@ +# pyright: basic +from __future__ import annotations + import os import sys -from typing import Any, Callable, NamedTuple, Optional +from typing import Any, TypeVar, Callable, Optional, NamedTuple +from typing_extensions import TypeAlias -from openai.datalib.pandas_helper import assert_has_pandas -from openai.datalib.pandas_helper import pandas as pd +from .._extras import pandas as pd class Remediation(NamedTuple): @@ -16,7 +19,10 @@ class Remediation(NamedTuple): error_msg: Optional[str] = None -def num_examples_validator(df): +OptionalDataFrameT = TypeVar("OptionalDataFrameT", bound="Optional[pd.DataFrame]") + + +def num_examples_validator(df: pd.DataFrame) -> Remediation: """ This validator will only print out the number of examples and recommend to the user to increase the number of examples if less than 100. """ @@ -26,18 +32,16 @@ def num_examples_validator(df): if len(df) >= MIN_EXAMPLES else ". In general, we recommend having at least a few hundred examples. We've found that performance tends to linearly increase for every doubling of the number of examples" ) - immediate_msg = ( - f"\n- Your file contains {len(df)} prompt-completion pairs{optional_suggestion}" - ) + immediate_msg = f"\n- Your file contains {len(df)} prompt-completion pairs{optional_suggestion}" return Remediation(name="num_examples", immediate_msg=immediate_msg) -def necessary_column_validator(df, necessary_column): +def necessary_column_validator(df: pd.DataFrame, necessary_column: str) -> Remediation: """ This validator will ensure that the necessary column is present in the dataframe. """ - def lower_case_column(df, column): + def lower_case_column(df: pd.DataFrame, column: Any) -> pd.DataFrame: cols = [c for c in df.columns if str(c).lower() == column] df.rename(columns={cols[0]: column.lower()}, inplace=True) return df @@ -50,13 +54,11 @@ def lower_case_column(df, column): if necessary_column not in df.columns: if necessary_column in [str(c).lower() for c in df.columns]: - def lower_case_column_creator(df): + def lower_case_column_creator(df: pd.DataFrame) -> pd.DataFrame: return lower_case_column(df, necessary_column) necessary_fn = lower_case_column_creator - immediate_msg = ( - f"\n- The `{necessary_column}` column/key should be lowercase" - ) + immediate_msg = f"\n- The `{necessary_column}` column/key should be lowercase" necessary_msg = f"Lower case column name to `{necessary_column}`" else: error_msg = f"`{necessary_column}` column/key is missing. Please make sure you name your columns/keys appropriately, then retry" @@ -70,14 +72,15 @@ def lower_case_column_creator(df): ) -def additional_column_validator(df, fields=["prompt", "completion"]): +def additional_column_validator(df: pd.DataFrame, fields: list[str] = ["prompt", "completion"]) -> Remediation: """ This validator will remove additional columns from the dataframe. """ additional_columns = [] necessary_msg = None immediate_msg = None - necessary_fn = None + necessary_fn = None # type: ignore + if len(df.columns) > 2: additional_columns = [c for c in df.columns if c not in fields] warn_message = "" @@ -88,7 +91,7 @@ def additional_column_validator(df, fields=["prompt", "completion"]): immediate_msg = f"\n- The input file should contain exactly two columns/keys per row. Additional columns/keys present are: {additional_columns}{warn_message}" necessary_msg = f"Remove additional columns/keys: {additional_columns}" - def necessary_fn(x): + def necessary_fn(x: Any) -> Any: return x[fields] return Remediation( @@ -99,12 +102,12 @@ def necessary_fn(x): ) -def non_empty_field_validator(df, field="completion"): +def non_empty_field_validator(df: pd.DataFrame, field: str = "completion") -> Remediation: """ This validator will ensure that no completion is empty. """ necessary_msg = None - necessary_fn = None + necessary_fn = None # type: ignore immediate_msg = None if df[field].apply(lambda x: x == "").any() or df[field].isnull().any(): @@ -112,10 +115,11 @@ def non_empty_field_validator(df, field="completion"): empty_indexes = df.reset_index().index[empty_rows].tolist() immediate_msg = f"\n- `{field}` column/key should not contain empty strings. These are rows: {empty_indexes}" - def necessary_fn(x): + def necessary_fn(x: Any) -> Any: return x[x[field] != ""].dropna(subset=[field]) necessary_msg = f"Remove {len(empty_indexes)} rows with empty {field}s" + return Remediation( name=f"empty_{field}", immediate_msg=immediate_msg, @@ -124,7 +128,7 @@ def necessary_fn(x): ) -def duplicated_rows_validator(df, fields=["prompt", "completion"]): +def duplicated_rows_validator(df: pd.DataFrame, fields: list[str] = ["prompt", "completion"]) -> Remediation: """ This validator will suggest to the user to remove duplicate rows if they exist. """ @@ -132,13 +136,13 @@ def duplicated_rows_validator(df, fields=["prompt", "completion"]): duplicated_indexes = df.reset_index().index[duplicated_rows].tolist() immediate_msg = None optional_msg = None - optional_fn = None + optional_fn = None # type: ignore if len(duplicated_indexes) > 0: immediate_msg = f"\n- There are {len(duplicated_indexes)} duplicated {'-'.join(fields)} sets. These are rows: {duplicated_indexes}" optional_msg = f"Remove {len(duplicated_indexes)} duplicate rows" - def optional_fn(x): + def optional_fn(x: Any) -> Any: return x.drop_duplicates(subset=fields) return Remediation( @@ -149,21 +153,19 @@ def optional_fn(x): ) -def long_examples_validator(df): +def long_examples_validator(df: pd.DataFrame) -> Remediation: """ This validator will suggest to the user to remove examples that are too long. """ immediate_msg = None optional_msg = None - optional_fn = None + optional_fn = None # type: ignore ft_type = infer_task_type(df) if ft_type != "open-ended generation": - def get_long_indexes(d): - long_examples = d.apply( - lambda x: len(x.prompt) + len(x.completion) > 10000, axis=1 - ) + def get_long_indexes(d: pd.DataFrame) -> Any: + long_examples = d.apply(lambda x: len(x.prompt) + len(x.completion) > 10000, axis=1) return d.reset_index().index[long_examples].tolist() long_indexes = get_long_indexes(df) @@ -172,8 +174,7 @@ def get_long_indexes(d): immediate_msg = f"\n- There are {len(long_indexes)} examples that are very long. These are rows: {long_indexes}\nFor conditional generation, and for classification the examples shouldn't be longer than 2048 tokens." optional_msg = f"Remove {len(long_indexes)} long examples" - def optional_fn(x): - + def optional_fn(x: Any) -> Any: long_indexes_to_drop = get_long_indexes(x) if long_indexes != long_indexes_to_drop: sys.stdout.write( @@ -189,14 +190,14 @@ def optional_fn(x): ) -def common_prompt_suffix_validator(df): +def common_prompt_suffix_validator(df: pd.DataFrame) -> Remediation: """ This validator will suggest to add a common suffix to the prompt if one doesn't already exist in case of classification or conditional generation. """ error_msg = None immediate_msg = None optional_msg = None - optional_fn = None + optional_fn = None # type: ignore # Find a suffix which is not contained within the prompt otherwise suggested_suffix = "\n\n### =>\n\n" @@ -222,7 +223,7 @@ def common_prompt_suffix_validator(df): if ft_type == "open-ended generation": return Remediation(name="common_suffix") - def add_suffix(x, suffix): + def add_suffix(x: Any, suffix: Any) -> Any: x["prompt"] += suffix return x @@ -233,27 +234,19 @@ def add_suffix(x, suffix): if common_suffix != "": common_suffix_new_line_handled = common_suffix.replace("\n", "\\n") - immediate_msg = ( - f"\n- All prompts end with suffix `{common_suffix_new_line_handled}`" - ) + immediate_msg = f"\n- All prompts end with suffix `{common_suffix_new_line_handled}`" if len(common_suffix) > 10: immediate_msg += f". This suffix seems very long. Consider replacing with a shorter suffix, such as `{display_suggested_suffix}`" - if ( - df.prompt.str[: -len(common_suffix)] - .str.contains(common_suffix, regex=False) - .any() - ): + if df.prompt.str[: -len(common_suffix)].str.contains(common_suffix, regex=False).any(): immediate_msg += f"\n WARNING: Some of your prompts contain the suffix `{common_suffix}` more than once. We strongly suggest that you review your prompts and add a unique suffix" else: immediate_msg = "\n- Your data does not contain a common separator at the end of your prompts. Having a separator string appended to the end of the prompt makes it clearer to the fine-tuned model where the completion should begin. See https://platform.openai.com/docs/guides/fine-tuning/preparing-your-dataset for more detail and examples. If you intend to do open-ended generation, then you should leave the prompts empty" if common_suffix == "": - optional_msg = ( - f"Add a suffix separator `{display_suggested_suffix}` to all prompts" - ) + optional_msg = f"Add a suffix separator `{display_suggested_suffix}` to all prompts" - def optional_fn(x): + def optional_fn(x: Any) -> Any: return add_suffix(x, suggested_suffix) return Remediation( @@ -265,7 +258,7 @@ def optional_fn(x): ) -def common_prompt_prefix_validator(df): +def common_prompt_prefix_validator(df: pd.DataFrame) -> Remediation: """ This validator will suggest to remove a common prefix from the prompt if a long one exist. """ @@ -273,13 +266,13 @@ def common_prompt_prefix_validator(df): immediate_msg = None optional_msg = None - optional_fn = None + optional_fn = None # type: ignore common_prefix = get_common_xfix(df.prompt, xfix="prefix") if common_prefix == "": return Remediation(name="common_prefix") - def remove_common_prefix(x, prefix): + def remove_common_prefix(x: Any, prefix: Any) -> Any: x["prompt"] = x["prompt"].str[len(prefix) :] return x @@ -293,7 +286,7 @@ def remove_common_prefix(x, prefix): immediate_msg += ". Fine-tuning doesn't require the instruction specifying the task, or a few-shot example scenario. Most of the time you should only add the input data into the prompt, and the desired output into the completion" optional_msg = f"Remove prefix `{common_prefix}` from all prompts" - def optional_fn(x): + def optional_fn(x: Any) -> Any: return remove_common_prefix(x, common_prefix) return Remediation( @@ -304,7 +297,7 @@ def optional_fn(x): ) -def common_completion_prefix_validator(df): +def common_completion_prefix_validator(df: pd.DataFrame) -> Remediation: """ This validator will suggest to remove a common prefix from the completion if a long one exist. """ @@ -315,7 +308,7 @@ def common_completion_prefix_validator(df): if len(common_prefix) < MAX_PREFIX_LEN: return Remediation(name="common_prefix") - def remove_common_prefix(x, prefix, ws_prefix): + def remove_common_prefix(x: Any, prefix: Any, ws_prefix: Any) -> Any: x["completion"] = x["completion"].str[len(prefix) :] if ws_prefix: # keep the single whitespace as prefix @@ -329,7 +322,7 @@ def remove_common_prefix(x, prefix, ws_prefix): immediate_msg = f"\n- All completions start with prefix `{common_prefix}`. Most of the time you should only add the output data into the completion, without any prefix" optional_msg = f"Remove prefix `{common_prefix}` from all completions" - def optional_fn(x): + def optional_fn(x: Any) -> Any: return remove_common_prefix(x, common_prefix, ws_prefix) return Remediation( @@ -340,14 +333,14 @@ def optional_fn(x): ) -def common_completion_suffix_validator(df): +def common_completion_suffix_validator(df: pd.DataFrame) -> Remediation: """ This validator will suggest to add a common suffix to the completion if one doesn't already exist in case of classification or conditional generation. """ error_msg = None immediate_msg = None optional_msg = None - optional_fn = None + optional_fn = None # type: ignore ft_type = infer_task_type(df) if ft_type == "open-ended generation" or ft_type == "classification": @@ -378,33 +371,25 @@ def common_completion_suffix_validator(df): break display_suggested_suffix = suggested_suffix.replace("\n", "\\n") - def add_suffix(x, suffix): + def add_suffix(x: Any, suffix: Any) -> Any: x["completion"] += suffix return x if common_suffix != "": common_suffix_new_line_handled = common_suffix.replace("\n", "\\n") - immediate_msg = ( - f"\n- All completions end with suffix `{common_suffix_new_line_handled}`" - ) + immediate_msg = f"\n- All completions end with suffix `{common_suffix_new_line_handled}`" if len(common_suffix) > 10: immediate_msg += f". This suffix seems very long. Consider replacing with a shorter suffix, such as `{display_suggested_suffix}`" - if ( - df.completion.str[: -len(common_suffix)] - .str.contains(common_suffix, regex=False) - .any() - ): + if df.completion.str[: -len(common_suffix)].str.contains(common_suffix, regex=False).any(): immediate_msg += f"\n WARNING: Some of your completions contain the suffix `{common_suffix}` more than once. We suggest that you review your completions and add a unique ending" else: immediate_msg = "\n- Your data does not contain a common ending at the end of your completions. Having a common ending string appended to the end of the completion makes it clearer to the fine-tuned model where the completion should end. See https://platform.openai.com/docs/guides/fine-tuning/preparing-your-dataset for more detail and examples." if common_suffix == "": - optional_msg = ( - f"Add a suffix ending `{display_suggested_suffix}` to all completions" - ) + optional_msg = f"Add a suffix ending `{display_suggested_suffix}` to all completions" - def optional_fn(x): + def optional_fn(x: Any) -> Any: return add_suffix(x, suggested_suffix) return Remediation( @@ -416,15 +401,13 @@ def optional_fn(x): ) -def completions_space_start_validator(df): +def completions_space_start_validator(df: pd.DataFrame) -> Remediation: """ This validator will suggest to add a space at the start of the completion if it doesn't already exist. This helps with tokenization. """ - def add_space_start(x): - x["completion"] = x["completion"].apply( - lambda x: ("" if x[0] == " " else " ") + x - ) + def add_space_start(x: Any) -> Any: + x["completion"] = x["completion"].apply(lambda x: ("" if x[0] == " " else " ") + x) return x optional_msg = None @@ -443,25 +426,17 @@ def add_space_start(x): ) -def lower_case_validator(df, column): +def lower_case_validator(df: pd.DataFrame, column: Any) -> Remediation | None: """ This validator will suggest to lowercase the column values, if more than a third of letters are uppercase. """ - def lower_case(x): + def lower_case(x: Any) -> Any: x[column] = x[column].str.lower() return x - count_upper = ( - df[column] - .apply(lambda x: sum(1 for c in x if c.isalpha() and c.isupper())) - .sum() - ) - count_lower = ( - df[column] - .apply(lambda x: sum(1 for c in x if c.isalpha() and c.islower())) - .sum() - ) + count_upper = df[column].apply(lambda x: sum(1 for c in x if c.isalpha() and c.isupper())).sum() + count_lower = df[column].apply(lambda x: sum(1 for c in x if c.isalpha() and c.islower())).sum() if count_upper * 2 > count_lower: return Remediation( @@ -470,15 +445,17 @@ def lower_case(x): optional_msg=f"Lowercase all your data in column/key `{column}`", optional_fn=lower_case, ) + return None -def read_any_format(fname, fields=["prompt", "completion"]): +def read_any_format( + fname: str, fields: list[str] = ["prompt", "completion"] +) -> tuple[pd.DataFrame | None, Remediation]: """ This function will read a file saved in .csv, .json, .txt, .xlsx or .tsv format using pandas. - for .xlsx it will read the first sheet - for .txt it will assume completions and split on newline """ - assert_has_pandas() remediation = None necessary_msg = None immediate_msg = None @@ -488,13 +465,11 @@ def read_any_format(fname, fields=["prompt", "completion"]): if os.path.isfile(fname): try: if fname.lower().endswith(".csv") or fname.lower().endswith(".tsv"): - file_extension_str, separator = ( - ("CSV", ",") if fname.lower().endswith(".csv") else ("TSV", "\t") - ) - immediate_msg = f"\n- Based on your file extension, your file is formatted as a {file_extension_str} file" - necessary_msg = ( - f"Your format `{file_extension_str}` will be converted to `JSONL`" + file_extension_str, separator = ("CSV", ",") if fname.lower().endswith(".csv") else ("TSV", "\t") + immediate_msg = ( + f"\n- Based on your file extension, your file is formatted as a {file_extension_str} file" ) + necessary_msg = f"Your format `{file_extension_str}` will be converted to `JSONL`" df = pd.read_csv(fname, sep=separator, dtype=str).fillna("") elif fname.lower().endswith(".xlsx"): immediate_msg = "\n- Based on your file extension, your file is formatted as an Excel file" @@ -505,9 +480,7 @@ def read_any_format(fname, fields=["prompt", "completion"]): immediate_msg += "\n- Your Excel file contains more than one sheet. Please either save as csv or ensure all data is present in the first sheet. WARNING: Reading only the first sheet..." df = pd.read_excel(fname, dtype=str).fillna("") elif fname.lower().endswith(".txt"): - immediate_msg = ( - "\n- Based on your file extension, you provided a text file" - ) + immediate_msg = "\n- Based on your file extension, you provided a text file" necessary_msg = "Your format `TXT` will be converted to `JSONL`" with open(fname, "r") as f: content = f.read() @@ -517,32 +490,32 @@ def read_any_format(fname, fields=["prompt", "completion"]): dtype=str, ).fillna("") elif fname.lower().endswith(".jsonl"): - df = pd.read_json(fname, lines=True, dtype=str).fillna("") - if len(df) == 1: + df = pd.read_json(fname, lines=True, dtype=str).fillna("") # type: ignore + if len(df) == 1: # type: ignore # this is NOT what we expect for a .jsonl file immediate_msg = "\n- Your JSONL file appears to be in a JSON format. Your file will be converted to JSONL format" necessary_msg = "Your format `JSON` will be converted to `JSONL`" - df = pd.read_json(fname, dtype=str).fillna("") + df = pd.read_json(fname, dtype=str).fillna("") # type: ignore else: pass # this is what we expect for a .jsonl file elif fname.lower().endswith(".json"): try: # to handle case where .json file is actually a .jsonl file - df = pd.read_json(fname, lines=True, dtype=str).fillna("") - if len(df) == 1: + df = pd.read_json(fname, lines=True, dtype=str).fillna("") # type: ignore + if len(df) == 1: # type: ignore # this code path corresponds to a .json file that has one line - df = pd.read_json(fname, dtype=str).fillna("") + df = pd.read_json(fname, dtype=str).fillna("") # type: ignore else: # this is NOT what we expect for a .json file immediate_msg = "\n- Your JSON file appears to be in a JSONL format. Your file will be converted to JSONL format" - necessary_msg = ( - "Your format `JSON` will be converted to `JSONL`" - ) + necessary_msg = "Your format `JSON` will be converted to `JSONL`" except ValueError: # this code path corresponds to a .json file that has multiple lines (i.e. it is indented) - df = pd.read_json(fname, dtype=str).fillna("") + df = pd.read_json(fname, dtype=str).fillna("") # type: ignore else: - error_msg = "Your file must have one of the following extensions: .CSV, .TSV, .XLSX, .TXT, .JSON or .JSONL" + error_msg = ( + "Your file must have one of the following extensions: .CSV, .TSV, .XLSX, .TXT, .JSON or .JSONL" + ) if "." in fname: error_msg += f" Your file `{fname}` ends with the extension `.{fname.split('.')[-1]}` which is not supported." else: @@ -564,7 +537,7 @@ def read_any_format(fname, fields=["prompt", "completion"]): return df, remediation -def format_inferrer_validator(df): +def format_inferrer_validator(df: pd.DataFrame) -> Remediation: """ This validator will infer the likely fine-tuning format of the data, and display it to the user if it is classification. It will also suggest to use ada and explain train/validation split benefits. @@ -576,14 +549,12 @@ def format_inferrer_validator(df): return Remediation(name="num_examples", immediate_msg=immediate_msg) -def apply_necessary_remediation(df, remediation): +def apply_necessary_remediation(df: OptionalDataFrameT, remediation: Remediation) -> OptionalDataFrameT: """ This function will apply a necessary remediation to a dataframe, or print an error message if one exists. """ if remediation.error_msg is not None: - sys.stderr.write( - f"\n\nERROR in {remediation.name} validator: {remediation.error_msg}\n\nAborting..." - ) + sys.stderr.write(f"\n\nERROR in {remediation.name} validator: {remediation.error_msg}\n\nAborting...") sys.exit(1) if remediation.immediate_msg is not None: sys.stdout.write(remediation.immediate_msg) @@ -592,7 +563,7 @@ def apply_necessary_remediation(df, remediation): return df -def accept_suggestion(input_text, auto_accept): +def accept_suggestion(input_text: str, auto_accept: bool) -> bool: sys.stdout.write(input_text) if auto_accept: sys.stdout.write("Y\n") @@ -600,7 +571,9 @@ def accept_suggestion(input_text, auto_accept): return input().lower() != "n" -def apply_optional_remediation(df, remediation, auto_accept): +def apply_optional_remediation( + df: pd.DataFrame, remediation: Remediation, auto_accept: bool +) -> tuple[pd.DataFrame, bool]: """ This function will apply an optional remediation to a dataframe, based on the user input. """ @@ -608,6 +581,7 @@ def apply_optional_remediation(df, remediation, auto_accept): input_text = f"- [Recommended] {remediation.optional_msg} [Y/n]: " if remediation.optional_msg is not None: if accept_suggestion(input_text, auto_accept): + assert remediation.optional_fn is not None df = remediation.optional_fn(df) optional_applied = True if remediation.necessary_msg is not None: @@ -615,7 +589,7 @@ def apply_optional_remediation(df, remediation, auto_accept): return df, optional_applied -def estimate_fine_tuning_time(df): +def estimate_fine_tuning_time(df: pd.DataFrame) -> None: """ Estimate the time it'll take to fine-tune the dataset """ @@ -628,7 +602,7 @@ def estimate_fine_tuning_time(df): size = df.memory_usage(index=True).sum() expected_time = size * 0.0515 - def format_time(time): + def format_time(time: float) -> str: if time < 60: return f"{round(time, 2)} seconds" elif time < 3600: @@ -644,21 +618,20 @@ def format_time(time): ) -def get_outfnames(fname, split): +def get_outfnames(fname: str, split: bool) -> list[str]: suffixes = ["_train", "_valid"] if split else [""] i = 0 while True: index_suffix = f" ({i})" if i > 0 else "" candidate_fnames = [ - os.path.splitext(fname)[0] + "_prepared" + suffix + index_suffix + ".jsonl" - for suffix in suffixes + os.path.splitext(fname)[0] + "_prepared" + suffix + index_suffix + ".jsonl" for suffix in suffixes ] if not any(os.path.isfile(f) for f in candidate_fnames): return candidate_fnames i += 1 -def get_classification_hyperparams(df): +def get_classification_hyperparams(df: pd.DataFrame) -> tuple[int, object]: n_classes = df.completion.nunique() pos_class = None if n_classes == 2: @@ -666,7 +639,7 @@ def get_classification_hyperparams(df): return n_classes, pos_class -def write_out_file(df, fname, any_remediations, auto_accept): +def write_out_file(df: pd.DataFrame, fname: str, any_remediations: bool, auto_accept: bool) -> None: """ This function will write out a dataframe to a file, if the user would like to proceed, and also offer a fine-tuning command with the newly created file. For classification it will optionally ask the user if they would like to split the data into train/valid files, and modify the suggested command to include the valid set. @@ -683,9 +656,7 @@ def write_out_file(df, fname, any_remediations, auto_accept): additional_params = "" common_prompt_suffix_new_line_handled = common_prompt_suffix.replace("\n", "\\n") - common_completion_suffix_new_line_handled = common_completion_suffix.replace( - "\n", "\\n" - ) + common_completion_suffix_new_line_handled = common_completion_suffix.replace("\n", "\\n") optional_ending_string = ( f' Make sure to include `stop=["{common_completion_suffix_new_line_handled}"]` so that the generated texts ends at the expected place.' if len(common_completion_suffix_new_line_handled) > 0 @@ -708,12 +679,10 @@ def write_out_file(df, fname, any_remediations, auto_accept): n_train = max(len(df) - MAX_VALID_EXAMPLES, int(len(df) * 0.8)) df_train = df.sample(n=n_train, random_state=42) df_valid = df.drop(df_train.index) - df_train[["prompt", "completion"]].to_json( + df_train[["prompt", "completion"]].to_json( # type: ignore fnames[0], lines=True, orient="records", force_ascii=False ) - df_valid[["prompt", "completion"]].to_json( - fnames[1], lines=True, orient="records", force_ascii=False - ) + df_valid[["prompt", "completion"]].to_json(fnames[1], lines=True, orient="records", force_ascii=False) n_classes, pos_class = get_classification_hyperparams(df) additional_params += " --compute_classification_metrics" @@ -723,9 +692,7 @@ def write_out_file(df, fname, any_remediations, auto_accept): additional_params += f" --classification_n_classes {n_classes}" else: assert len(fnames) == 1 - df[["prompt", "completion"]].to_json( - fnames[0], lines=True, orient="records", force_ascii=False - ) + df[["prompt", "completion"]].to_json(fnames[0], lines=True, orient="records", force_ascii=False) # Add -v VALID_FILE if we split the file into train / valid files_string = ("s" if split else "") + " to `" + ("` and `".join(fnames)) @@ -743,7 +710,7 @@ def write_out_file(df, fname, any_remediations, auto_accept): sys.stdout.write("Aborting... did not write the file\n") -def infer_task_type(df): +def infer_task_type(df: pd.DataFrame) -> str: """ Infer the likely fine-tuning task type from the data """ @@ -757,31 +724,28 @@ def infer_task_type(df): return "conditional generation" -def get_common_xfix(series, xfix="suffix"): +def get_common_xfix(series: Any, xfix: str = "suffix") -> str: """ Finds the longest common suffix or prefix of all the values in a series """ common_xfix = "" while True: common_xfixes = ( - series.str[-(len(common_xfix) + 1) :] - if xfix == "suffix" - else series.str[: len(common_xfix) + 1] + series.str[-(len(common_xfix) + 1) :] if xfix == "suffix" else series.str[: len(common_xfix) + 1] ) # first few or last few characters - if ( - common_xfixes.nunique() != 1 - ): # we found the character at which we don't have a unique xfix anymore + if common_xfixes.nunique() != 1: # we found the character at which we don't have a unique xfix anymore break - elif ( - common_xfix == common_xfixes.values[0] - ): # the entire first row is a prefix of every other row + elif common_xfix == common_xfixes.values[0]: # the entire first row is a prefix of every other row break else: # the first or last few characters are still common across all rows - let's try to add one more common_xfix = common_xfixes.values[0] return common_xfix -def get_validators(): +Validator: TypeAlias = "Callable[[pd.DataFrame], Remediation | None]" + + +def get_validators() -> list[Validator]: return [ num_examples_validator, lambda x: necessary_column_validator(x, "prompt"), @@ -802,14 +766,14 @@ def get_validators(): def apply_validators( - df, - fname, - remediation, - validators, - auto_accept, - write_out_file_func, -): - optional_remediations = [] + df: pd.DataFrame, + fname: str, + remediation: Remediation | None, + validators: list[Validator], + auto_accept: bool, + write_out_file_func: Callable[..., Any], +) -> None: + optional_remediations: list[Remediation] = [] if remediation is not None: optional_remediations.append(remediation) for validator in validators: @@ -822,27 +786,18 @@ def apply_validators( [ remediation for remediation in optional_remediations - if remediation.optional_msg is not None - or remediation.necessary_msg is not None + if remediation.optional_msg is not None or remediation.necessary_msg is not None ] ) any_necessary_applied = any( - [ - remediation - for remediation in optional_remediations - if remediation.necessary_msg is not None - ] + [remediation for remediation in optional_remediations if remediation.necessary_msg is not None] ) any_optional_applied = False if any_optional_or_necessary_remediations: - sys.stdout.write( - "\n\nBased on the analysis we will perform the following actions:\n" - ) + sys.stdout.write("\n\nBased on the analysis we will perform the following actions:\n") for remediation in optional_remediations: - df, optional_applied = apply_optional_remediation( - df, remediation, auto_accept - ) + df, optional_applied = apply_optional_remediation(df, remediation, auto_accept) any_optional_applied = any_optional_applied or optional_applied else: sys.stdout.write("\n\nNo remediations found.\n") diff --git a/src/openai/lib/azure.py b/src/openai/lib/azure.py new file mode 100644 index 0000000000..f5fcd24fd1 --- /dev/null +++ b/src/openai/lib/azure.py @@ -0,0 +1,439 @@ +from __future__ import annotations + +import os +import inspect +from typing import Any, Union, Mapping, TypeVar, Callable, Awaitable, overload +from typing_extensions import override + +import httpx + +from .._types import NOT_GIVEN, Omit, Timeout, NotGiven +from .._utils import is_given, is_mapping +from .._client import OpenAI, AsyncOpenAI +from .._models import FinalRequestOptions +from .._streaming import Stream, AsyncStream +from .._exceptions import OpenAIError +from .._base_client import DEFAULT_MAX_RETRIES, BaseClient + +_deployments_endpoints = set( + [ + "/completions", + "/chat/completions", + "/embeddings", + "/audio/transcriptions", + "/audio/translations", + ] +) + + +AzureADTokenProvider = Callable[[], str] +AsyncAzureADTokenProvider = Callable[[], "str | Awaitable[str]"] +_HttpxClientT = TypeVar("_HttpxClientT", bound=Union[httpx.Client, httpx.AsyncClient]) +_DefaultStreamT = TypeVar("_DefaultStreamT", bound=Union[Stream[Any], AsyncStream[Any]]) + + +# we need to use a sentinel API key value for Azure AD +# as we don't want to make the `api_key` in the main client Optional +# and Azure AD tokens may be retrieved on a per-request basis +API_KEY_SENTINEL = "".join(["<", "missing API key", ">"]) + + +class MutuallyExclusiveAuthError(OpenAIError): + def __init__(self) -> None: + super().__init__( + "The `api_key`, `azure_ad_token` and `azure_ad_token_provider` arguments are mutually exclusive; Only one can be passed at a time" + ) + + +class BaseAzureClient(BaseClient[_HttpxClientT, _DefaultStreamT]): + @override + def _build_request( + self, + options: FinalRequestOptions, + ) -> httpx.Request: + if options.url in _deployments_endpoints and is_mapping(options.json_data): + model = options.json_data.get("model") + if model is not None and not "/deployments" in str(self.base_url): + options.url = f"/deployments/{model}{options.url}" + + return super()._build_request(options) + + +class AzureOpenAI(BaseAzureClient[httpx.Client, Stream[Any]], OpenAI): + @overload + def __init__( + self, + *, + azure_endpoint: str, + azure_deployment: str | None = None, + api_version: str | None = None, + api_key: str | None = None, + azure_ad_token: str | None = None, + azure_ad_token_provider: AzureADTokenProvider | None = None, + organization: str | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + http_client: httpx.Client | None = None, + _strict_response_validation: bool = False, + ) -> None: + ... + + @overload + def __init__( + self, + *, + azure_deployment: str | None = None, + api_version: str | None = None, + api_key: str | None = None, + azure_ad_token: str | None = None, + azure_ad_token_provider: AzureADTokenProvider | None = None, + organization: str | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + http_client: httpx.Client | None = None, + _strict_response_validation: bool = False, + ) -> None: + ... + + @overload + def __init__( + self, + *, + base_url: str, + api_version: str | None = None, + api_key: str | None = None, + azure_ad_token: str | None = None, + azure_ad_token_provider: AzureADTokenProvider | None = None, + organization: str | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + http_client: httpx.Client | None = None, + _strict_response_validation: bool = False, + ) -> None: + ... + + def __init__( + self, + *, + api_version: str | None = None, + azure_endpoint: str | None = None, + azure_deployment: str | None = None, + api_key: str | None = None, + azure_ad_token: str | None = None, + azure_ad_token_provider: AzureADTokenProvider | None = None, + organization: str | None = None, + base_url: str | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + http_client: httpx.Client | None = None, + _strict_response_validation: bool = False, + ) -> None: + """Construct a new synchronous azure openai client instance. + + This automatically infers the following arguments from their corresponding environment variables if they are not provided: + - `api_key` from `AZURE_OPENAI_API_KEY` + - `organization` from `OPENAI_ORG_ID` + - `azure_ad_token` from `AZURE_OPENAI_AD_TOKEN` + - `api_version` from `OPENAI_API_VERSION` + - `azure_endpoint` from `AZURE_OPENAI_ENDPOINT` + + Args: + azure_endpoint: Your Azure endpoint, including the resource, e.g. `https://example-resource.azure.openai.com/` + + azure_ad_token: Your Azure Active Directory token, https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id + + azure_ad_token_provider: A function that returns an Azure Active Directory token, will be invoked on every request. + + azure_deployment: A model deployment, if given sets the base client URL to include `/deployments/{azure_deployment}`. + Note: this means you won't be able to use non-deployment endpoints. + """ + if api_key is None: + api_key = os.environ.get("AZURE_OPENAI_API_KEY") + + if azure_ad_token is None: + azure_ad_token = os.environ.get("AZURE_OPENAI_AD_TOKEN") + + if api_key is None and azure_ad_token is None and azure_ad_token_provider is None: + raise OpenAIError( + "Missing credentials. Please pass one of `api_key`, `azure_ad_token`, `azure_ad_token_provider`, or the `AZURE_OPENAI_API_KEY` or `AZURE_OPENAI_AD_TOKEN` environment variables." + ) + + if api_version is None: + api_version = os.environ.get("OPENAI_API_VERSION") + + if api_version is None: + raise ValueError( + "Must provide either the `api_version` argument or the `OPENAI_API_VERSION` environment variable" + ) + + if default_query is None: + default_query = {"api-version": api_version} + else: + default_query = {"api-version": api_version, **default_query} + + if base_url is None: + if azure_endpoint is None: + azure_endpoint = os.environ.get("AZURE_OPENAI_ENDPOINT") + + if azure_endpoint is None: + raise ValueError( + "Must provide one of the `base_url` or `azure_endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable" + ) + + if azure_deployment is not None: + base_url = f"{azure_endpoint}/openai/deployments/{azure_deployment}" + else: + base_url = f"{azure_endpoint}/openai" + else: + if azure_endpoint is not None: + raise ValueError("base_url and azure_endpoint are mutually exclusive") + + if api_key is None: + # define a sentinel value to avoid any typing issues + api_key = API_KEY_SENTINEL + + super().__init__( + api_key=api_key, + organization=organization, + base_url=base_url, + timeout=timeout, + max_retries=max_retries, + default_headers=default_headers, + default_query=default_query, + http_client=http_client, + _strict_response_validation=_strict_response_validation, + ) + self._azure_ad_token = azure_ad_token + self._azure_ad_token_provider = azure_ad_token_provider + + def _get_azure_ad_token(self) -> str | None: + if self._azure_ad_token is not None: + return self._azure_ad_token + + provider = self._azure_ad_token_provider + if provider is not None: + token = provider() + if not token or not isinstance(token, str): # pyright: ignore[reportUnnecessaryIsInstance] + raise ValueError( + f"Expected `azure_ad_token_provider` argument to return a string but it returned {token}", + ) + return token + + return None + + @override + def _prepare_options(self, options: FinalRequestOptions) -> None: + headers: dict[str, str | Omit] = {**options.headers} if is_given(options.headers) else {} + options.headers = headers + + azure_ad_token = self._get_azure_ad_token() + if azure_ad_token is not None: + if headers.get("Authorization") is None: + headers["Authorization"] = f"Bearer {azure_ad_token}" + elif self.api_key is not API_KEY_SENTINEL: + if headers.get("api-key") is None: + headers["api-key"] = self.api_key + else: + # should never be hit + raise ValueError("Unable to handle auth") + + return super()._prepare_options(options) + + +class AsyncAzureOpenAI(BaseAzureClient[httpx.AsyncClient, AsyncStream[Any]], AsyncOpenAI): + @overload + def __init__( + self, + *, + azure_endpoint: str, + azure_deployment: str | None = None, + api_version: str | None = None, + api_key: str | None = None, + azure_ad_token: str | None = None, + azure_ad_token_provider: AsyncAzureADTokenProvider | None = None, + organization: str | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + http_client: httpx.AsyncClient | None = None, + _strict_response_validation: bool = False, + ) -> None: + ... + + @overload + def __init__( + self, + *, + azure_deployment: str | None = None, + api_version: str | None = None, + api_key: str | None = None, + azure_ad_token: str | None = None, + azure_ad_token_provider: AsyncAzureADTokenProvider | None = None, + organization: str | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + http_client: httpx.AsyncClient | None = None, + _strict_response_validation: bool = False, + ) -> None: + ... + + @overload + def __init__( + self, + *, + base_url: str, + api_version: str | None = None, + api_key: str | None = None, + azure_ad_token: str | None = None, + azure_ad_token_provider: AsyncAzureADTokenProvider | None = None, + organization: str | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + http_client: httpx.AsyncClient | None = None, + _strict_response_validation: bool = False, + ) -> None: + ... + + def __init__( + self, + *, + azure_endpoint: str | None = None, + azure_deployment: str | None = None, + api_version: str | None = None, + api_key: str | None = None, + azure_ad_token: str | None = None, + azure_ad_token_provider: AsyncAzureADTokenProvider | None = None, + organization: str | None = None, + base_url: str | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + max_retries: int = DEFAULT_MAX_RETRIES, + default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + http_client: httpx.AsyncClient | None = None, + _strict_response_validation: bool = False, + ) -> None: + """Construct a new asynchronous azure openai client instance. + + This automatically infers the following arguments from their corresponding environment variables if they are not provided: + - `api_key` from `AZURE_OPENAI_API_KEY` + - `organization` from `OPENAI_ORG_ID` + - `azure_ad_token` from `AZURE_OPENAI_AD_TOKEN` + - `api_version` from `OPENAI_API_VERSION` + - `azure_endpoint` from `AZURE_OPENAI_ENDPOINT` + + Args: + azure_endpoint: Your Azure endpoint, including the resource, e.g. `https://example-resource.azure.openai.com/` + + azure_ad_token: Your Azure Active Directory token, https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id + + azure_ad_token_provider: A function that returns an Azure Active Directory token, will be invoked on every request. + + azure_deployment: A model deployment, if given sets the base client URL to include `/deployments/{azure_deployment}`. + Note: this means you won't be able to use non-deployment endpoints. + """ + if api_key is None: + api_key = os.environ.get("AZURE_OPENAI_API_KEY") + + if azure_ad_token is None: + azure_ad_token = os.environ.get("AZURE_OPENAI_AD_TOKEN") + + if api_key is None and azure_ad_token is None and azure_ad_token_provider is None: + raise OpenAIError( + "Missing credentials. Please pass one of `api_key`, `azure_ad_token`, `azure_ad_token_provider`, or the `AZURE_OPENAI_API_KEY` or `AZURE_OPENAI_AD_TOKEN` environment variables." + ) + + if api_version is None: + api_version = os.environ.get("OPENAI_API_VERSION") + + if api_version is None: + raise ValueError( + "Must provide either the `api_version` argument or the `OPENAI_API_VERSION` environment variable" + ) + + if default_query is None: + default_query = {"api-version": api_version} + else: + default_query = {"api-version": api_version, **default_query} + + if base_url is None: + if azure_endpoint is None: + azure_endpoint = os.environ.get("AZURE_OPENAI_ENDPOINT") + + if azure_endpoint is None: + raise ValueError( + "Must provide one of the `base_url` or `azure_endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable" + ) + + if azure_deployment is not None: + base_url = f"{azure_endpoint}/openai/deployments/{azure_deployment}" + else: + base_url = f"{azure_endpoint}/openai" + else: + if azure_endpoint is not None: + raise ValueError("base_url and azure_endpoint are mutually exclusive") + + if api_key is None: + # define a sentinel value to avoid any typing issues + api_key = API_KEY_SENTINEL + + super().__init__( + api_key=api_key, + organization=organization, + base_url=base_url, + timeout=timeout, + max_retries=max_retries, + default_headers=default_headers, + default_query=default_query, + http_client=http_client, + _strict_response_validation=_strict_response_validation, + ) + self._azure_ad_token = azure_ad_token + self._azure_ad_token_provider = azure_ad_token_provider + + async def _get_azure_ad_token(self) -> str | None: + if self._azure_ad_token is not None: + return self._azure_ad_token + + provider = self._azure_ad_token_provider + if provider is not None: + token = provider() + if inspect.isawaitable(token): + token = await token + if not token or not isinstance(token, str): + raise ValueError( + f"Expected `azure_ad_token_provider` argument to return a string but it returned {token}", + ) + return token + + return None + + @override + async def _prepare_options(self, options: FinalRequestOptions) -> None: + headers: dict[str, str | Omit] = {**options.headers} if is_given(options.headers) else {} + options.headers = headers + + azure_ad_token = await self._get_azure_ad_token() + if azure_ad_token is not None: + if headers.get("Authorization") is None: + headers["Authorization"] = f"Bearer {azure_ad_token}" + elif self.api_key is not API_KEY_SENTINEL: + if headers.get("api-key") is None: + headers["api-key"] = self.api_key + else: + # should never be hit + raise ValueError("Unable to handle auth") + + return await super()._prepare_options(options) diff --git a/src/openai/pagination.py b/src/openai/pagination.py new file mode 100644 index 0000000000..ff45f39517 --- /dev/null +++ b/src/openai/pagination.py @@ -0,0 +1,95 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Any, List, Generic, TypeVar, Optional, cast +from typing_extensions import Protocol, override, runtime_checkable + +from ._types import ModelT +from ._models import BaseModel +from ._base_client import BasePage, PageInfo, BaseSyncPage, BaseAsyncPage + +__all__ = ["SyncPage", "AsyncPage", "SyncCursorPage", "AsyncCursorPage"] + +_BaseModelT = TypeVar("_BaseModelT", bound=BaseModel) + + +@runtime_checkable +class CursorPageItem(Protocol): + id: str + + +class SyncPage(BaseSyncPage[ModelT], BasePage[ModelT], Generic[ModelT]): + """Note: no pagination actually occurs yet, this is for forwards-compatibility.""" + + data: List[ModelT] + object: str + + @override + def _get_page_items(self) -> List[ModelT]: + return self.data + + @override + def next_page_info(self) -> None: + """ + This page represents a response that isn't actually paginated at the API level + so there will never be a next page. + """ + return None + + +class AsyncPage(BaseAsyncPage[ModelT], BasePage[ModelT], Generic[ModelT]): + """Note: no pagination actually occurs yet, this is for forwards-compatibility.""" + + data: List[ModelT] + object: str + + @override + def _get_page_items(self) -> List[ModelT]: + return self.data + + @override + def next_page_info(self) -> None: + """ + This page represents a response that isn't actually paginated at the API level + so there will never be a next page. + """ + return None + + +class SyncCursorPage(BaseSyncPage[ModelT], BasePage[ModelT], Generic[ModelT]): + data: List[ModelT] + + @override + def _get_page_items(self) -> List[ModelT]: + return self.data + + @override + def next_page_info(self) -> Optional[PageInfo]: + if not self.data: + return None + + item = cast(Any, self.data[-1]) + if not isinstance(item, CursorPageItem): + # TODO emit warning log + return None + + return PageInfo(params={"after": item.id}) + + +class AsyncCursorPage(BaseAsyncPage[ModelT], BasePage[ModelT], Generic[ModelT]): + data: List[ModelT] + + @override + def _get_page_items(self) -> List[ModelT]: + return self.data + + @override + def next_page_info(self) -> Optional[PageInfo]: + if not self.data: + return None + + item = cast(Any, self.data[-1]) + if not isinstance(item, CursorPageItem): + # TODO emit warning log + return None + + return PageInfo(params={"after": item.id}) diff --git a/openai/py.typed b/src/openai/py.typed similarity index 100% rename from openai/py.typed rename to src/openai/py.typed diff --git a/src/openai/resources/__init__.py b/src/openai/resources/__init__.py new file mode 100644 index 0000000000..e0a26c72d2 --- /dev/null +++ b/src/openai/resources/__init__.py @@ -0,0 +1,95 @@ +# File generated from our OpenAPI spec by Stainless. + +from .chat import Chat, AsyncChat, ChatWithRawResponse, AsyncChatWithRawResponse +from .audio import Audio, AsyncAudio, AudioWithRawResponse, AsyncAudioWithRawResponse +from .edits import Edits, AsyncEdits, EditsWithRawResponse, AsyncEditsWithRawResponse +from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse +from .images import ( + Images, + AsyncImages, + ImagesWithRawResponse, + AsyncImagesWithRawResponse, +) +from .models import ( + Models, + AsyncModels, + ModelsWithRawResponse, + AsyncModelsWithRawResponse, +) +from .embeddings import ( + Embeddings, + AsyncEmbeddings, + EmbeddingsWithRawResponse, + AsyncEmbeddingsWithRawResponse, +) +from .fine_tunes import ( + FineTunes, + AsyncFineTunes, + FineTunesWithRawResponse, + AsyncFineTunesWithRawResponse, +) +from .completions import ( + Completions, + AsyncCompletions, + CompletionsWithRawResponse, + AsyncCompletionsWithRawResponse, +) +from .fine_tuning import ( + FineTuning, + AsyncFineTuning, + FineTuningWithRawResponse, + AsyncFineTuningWithRawResponse, +) +from .moderations import ( + Moderations, + AsyncModerations, + ModerationsWithRawResponse, + AsyncModerationsWithRawResponse, +) + +__all__ = [ + "Completions", + "AsyncCompletions", + "CompletionsWithRawResponse", + "AsyncCompletionsWithRawResponse", + "Chat", + "AsyncChat", + "ChatWithRawResponse", + "AsyncChatWithRawResponse", + "Edits", + "AsyncEdits", + "EditsWithRawResponse", + "AsyncEditsWithRawResponse", + "Embeddings", + "AsyncEmbeddings", + "EmbeddingsWithRawResponse", + "AsyncEmbeddingsWithRawResponse", + "Files", + "AsyncFiles", + "FilesWithRawResponse", + "AsyncFilesWithRawResponse", + "Images", + "AsyncImages", + "ImagesWithRawResponse", + "AsyncImagesWithRawResponse", + "Audio", + "AsyncAudio", + "AudioWithRawResponse", + "AsyncAudioWithRawResponse", + "Moderations", + "AsyncModerations", + "ModerationsWithRawResponse", + "AsyncModerationsWithRawResponse", + "Models", + "AsyncModels", + "ModelsWithRawResponse", + "AsyncModelsWithRawResponse", + "FineTuning", + "AsyncFineTuning", + "FineTuningWithRawResponse", + "AsyncFineTuningWithRawResponse", + "FineTunes", + "AsyncFineTunes", + "FineTunesWithRawResponse", + "AsyncFineTunesWithRawResponse", +] diff --git a/src/openai/resources/audio/__init__.py b/src/openai/resources/audio/__init__.py new file mode 100644 index 0000000000..771bfe9da2 --- /dev/null +++ b/src/openai/resources/audio/__init__.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. + +from .audio import Audio, AsyncAudio, AudioWithRawResponse, AsyncAudioWithRawResponse +from .translations import ( + Translations, + AsyncTranslations, + TranslationsWithRawResponse, + AsyncTranslationsWithRawResponse, +) +from .transcriptions import ( + Transcriptions, + AsyncTranscriptions, + TranscriptionsWithRawResponse, + AsyncTranscriptionsWithRawResponse, +) + +__all__ = [ + "Transcriptions", + "AsyncTranscriptions", + "TranscriptionsWithRawResponse", + "AsyncTranscriptionsWithRawResponse", + "Translations", + "AsyncTranslations", + "TranslationsWithRawResponse", + "AsyncTranslationsWithRawResponse", + "Audio", + "AsyncAudio", + "AudioWithRawResponse", + "AsyncAudioWithRawResponse", +] diff --git a/src/openai/resources/audio/audio.py b/src/openai/resources/audio/audio.py new file mode 100644 index 0000000000..8e8872c5b5 --- /dev/null +++ b/src/openai/resources/audio/audio.py @@ -0,0 +1,60 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from ..._resource import SyncAPIResource, AsyncAPIResource +from .translations import ( + Translations, + AsyncTranslations, + TranslationsWithRawResponse, + AsyncTranslationsWithRawResponse, +) +from .transcriptions import ( + Transcriptions, + AsyncTranscriptions, + TranscriptionsWithRawResponse, + AsyncTranscriptionsWithRawResponse, +) + +if TYPE_CHECKING: + from ..._client import OpenAI, AsyncOpenAI + +__all__ = ["Audio", "AsyncAudio"] + + +class Audio(SyncAPIResource): + transcriptions: Transcriptions + translations: Translations + with_raw_response: AudioWithRawResponse + + def __init__(self, client: OpenAI) -> None: + super().__init__(client) + self.transcriptions = Transcriptions(client) + self.translations = Translations(client) + self.with_raw_response = AudioWithRawResponse(self) + + +class AsyncAudio(AsyncAPIResource): + transcriptions: AsyncTranscriptions + translations: AsyncTranslations + with_raw_response: AsyncAudioWithRawResponse + + def __init__(self, client: AsyncOpenAI) -> None: + super().__init__(client) + self.transcriptions = AsyncTranscriptions(client) + self.translations = AsyncTranslations(client) + self.with_raw_response = AsyncAudioWithRawResponse(self) + + +class AudioWithRawResponse: + def __init__(self, audio: Audio) -> None: + self.transcriptions = TranscriptionsWithRawResponse(audio.transcriptions) + self.translations = TranslationsWithRawResponse(audio.translations) + + +class AsyncAudioWithRawResponse: + def __init__(self, audio: AsyncAudio) -> None: + self.transcriptions = AsyncTranscriptionsWithRawResponse(audio.transcriptions) + self.translations = AsyncTranslationsWithRawResponse(audio.translations) diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py new file mode 100644 index 0000000000..ca61f8bd42 --- /dev/null +++ b/src/openai/resources/audio/transcriptions.py @@ -0,0 +1,206 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import TYPE_CHECKING, Union, Mapping, cast +from typing_extensions import Literal + +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes +from ..._utils import extract_files, maybe_transform, deepcopy_minimal +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from ...types.audio import Transcription, transcription_create_params +from ..._base_client import make_request_options + +if TYPE_CHECKING: + from ..._client import OpenAI, AsyncOpenAI + +__all__ = ["Transcriptions", "AsyncTranscriptions"] + + +class Transcriptions(SyncAPIResource): + with_raw_response: TranscriptionsWithRawResponse + + def __init__(self, client: OpenAI) -> None: + super().__init__(client) + self.with_raw_response = TranscriptionsWithRawResponse(self) + + def create( + self, + *, + file: FileTypes, + model: Union[str, Literal["whisper-1"]], + language: str | NotGiven = NOT_GIVEN, + prompt: str | NotGiven = NOT_GIVEN, + response_format: Literal["json", "text", "srt", "verbose_json", "vtt"] | NotGiven = NOT_GIVEN, + temperature: float | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Transcription: + """ + Transcribes audio into the input language. + + Args: + file: + The audio file object (not file name) to transcribe, in one of these formats: + flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. + + model: ID of the model to use. Only `whisper-1` is currently available. + + language: The language of the input audio. Supplying the input language in + [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format will + improve accuracy and latency. + + prompt: An optional text to guide the model's style or continue a previous audio + segment. The + [prompt](https://platform.openai.com/docs/guides/speech-to-text/prompting) + should match the audio language. + + response_format: The format of the transcript output, in one of these options: json, text, srt, + verbose_json, or vtt. + + temperature: The sampling temperature, between 0 and 1. Higher values like 0.8 will make the + output more random, while lower values like 0.2 will make it more focused and + deterministic. If set to 0, the model will use + [log probability](https://en.wikipedia.org/wiki/Log_probability) to + automatically increase the temperature until certain thresholds are hit. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + body = deepcopy_minimal( + { + "file": file, + "model": model, + "language": language, + "prompt": prompt, + "response_format": response_format, + "temperature": temperature, + } + ) + files = extract_files(cast(Mapping[str, object], body), paths=[["file"]]) + if files: + # It should be noted that the actual Content-Type header that will be + # sent to the server will contain a `boundary` parameter, e.g. + # multipart/form-data; boundary=---abc-- + extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} + + return self._post( + "/audio/transcriptions", + body=maybe_transform(body, transcription_create_params.TranscriptionCreateParams), + files=files, + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Transcription, + ) + + +class AsyncTranscriptions(AsyncAPIResource): + with_raw_response: AsyncTranscriptionsWithRawResponse + + def __init__(self, client: AsyncOpenAI) -> None: + super().__init__(client) + self.with_raw_response = AsyncTranscriptionsWithRawResponse(self) + + async def create( + self, + *, + file: FileTypes, + model: Union[str, Literal["whisper-1"]], + language: str | NotGiven = NOT_GIVEN, + prompt: str | NotGiven = NOT_GIVEN, + response_format: Literal["json", "text", "srt", "verbose_json", "vtt"] | NotGiven = NOT_GIVEN, + temperature: float | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Transcription: + """ + Transcribes audio into the input language. + + Args: + file: + The audio file object (not file name) to transcribe, in one of these formats: + flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. + + model: ID of the model to use. Only `whisper-1` is currently available. + + language: The language of the input audio. Supplying the input language in + [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format will + improve accuracy and latency. + + prompt: An optional text to guide the model's style or continue a previous audio + segment. The + [prompt](https://platform.openai.com/docs/guides/speech-to-text/prompting) + should match the audio language. + + response_format: The format of the transcript output, in one of these options: json, text, srt, + verbose_json, or vtt. + + temperature: The sampling temperature, between 0 and 1. Higher values like 0.8 will make the + output more random, while lower values like 0.2 will make it more focused and + deterministic. If set to 0, the model will use + [log probability](https://en.wikipedia.org/wiki/Log_probability) to + automatically increase the temperature until certain thresholds are hit. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + body = deepcopy_minimal( + { + "file": file, + "model": model, + "language": language, + "prompt": prompt, + "response_format": response_format, + "temperature": temperature, + } + ) + files = extract_files(cast(Mapping[str, object], body), paths=[["file"]]) + if files: + # It should be noted that the actual Content-Type header that will be + # sent to the server will contain a `boundary` parameter, e.g. + # multipart/form-data; boundary=---abc-- + extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} + + return await self._post( + "/audio/transcriptions", + body=maybe_transform(body, transcription_create_params.TranscriptionCreateParams), + files=files, + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Transcription, + ) + + +class TranscriptionsWithRawResponse: + def __init__(self, transcriptions: Transcriptions) -> None: + self.create = to_raw_response_wrapper( + transcriptions.create, + ) + + +class AsyncTranscriptionsWithRawResponse: + def __init__(self, transcriptions: AsyncTranscriptions) -> None: + self.create = async_to_raw_response_wrapper( + transcriptions.create, + ) diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py new file mode 100644 index 0000000000..0b499b9865 --- /dev/null +++ b/src/openai/resources/audio/translations.py @@ -0,0 +1,192 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import TYPE_CHECKING, Union, Mapping, cast +from typing_extensions import Literal + +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes +from ..._utils import extract_files, maybe_transform, deepcopy_minimal +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from ...types.audio import Translation, translation_create_params +from ..._base_client import make_request_options + +if TYPE_CHECKING: + from ..._client import OpenAI, AsyncOpenAI + +__all__ = ["Translations", "AsyncTranslations"] + + +class Translations(SyncAPIResource): + with_raw_response: TranslationsWithRawResponse + + def __init__(self, client: OpenAI) -> None: + super().__init__(client) + self.with_raw_response = TranslationsWithRawResponse(self) + + def create( + self, + *, + file: FileTypes, + model: Union[str, Literal["whisper-1"]], + prompt: str | NotGiven = NOT_GIVEN, + response_format: str | NotGiven = NOT_GIVEN, + temperature: float | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Translation: + """ + Translates audio into English. + + Args: + file: The audio file object (not file name) translate, in one of these formats: flac, + mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. + + model: ID of the model to use. Only `whisper-1` is currently available. + + prompt: An optional text to guide the model's style or continue a previous audio + segment. The + [prompt](https://platform.openai.com/docs/guides/speech-to-text/prompting) + should be in English. + + response_format: The format of the transcript output, in one of these options: json, text, srt, + verbose_json, or vtt. + + temperature: The sampling temperature, between 0 and 1. Higher values like 0.8 will make the + output more random, while lower values like 0.2 will make it more focused and + deterministic. If set to 0, the model will use + [log probability](https://en.wikipedia.org/wiki/Log_probability) to + automatically increase the temperature until certain thresholds are hit. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + body = deepcopy_minimal( + { + "file": file, + "model": model, + "prompt": prompt, + "response_format": response_format, + "temperature": temperature, + } + ) + files = extract_files(cast(Mapping[str, object], body), paths=[["file"]]) + if files: + # It should be noted that the actual Content-Type header that will be + # sent to the server will contain a `boundary` parameter, e.g. + # multipart/form-data; boundary=---abc-- + extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} + + return self._post( + "/audio/translations", + body=maybe_transform(body, translation_create_params.TranslationCreateParams), + files=files, + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Translation, + ) + + +class AsyncTranslations(AsyncAPIResource): + with_raw_response: AsyncTranslationsWithRawResponse + + def __init__(self, client: AsyncOpenAI) -> None: + super().__init__(client) + self.with_raw_response = AsyncTranslationsWithRawResponse(self) + + async def create( + self, + *, + file: FileTypes, + model: Union[str, Literal["whisper-1"]], + prompt: str | NotGiven = NOT_GIVEN, + response_format: str | NotGiven = NOT_GIVEN, + temperature: float | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Translation: + """ + Translates audio into English. + + Args: + file: The audio file object (not file name) translate, in one of these formats: flac, + mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. + + model: ID of the model to use. Only `whisper-1` is currently available. + + prompt: An optional text to guide the model's style or continue a previous audio + segment. The + [prompt](https://platform.openai.com/docs/guides/speech-to-text/prompting) + should be in English. + + response_format: The format of the transcript output, in one of these options: json, text, srt, + verbose_json, or vtt. + + temperature: The sampling temperature, between 0 and 1. Higher values like 0.8 will make the + output more random, while lower values like 0.2 will make it more focused and + deterministic. If set to 0, the model will use + [log probability](https://en.wikipedia.org/wiki/Log_probability) to + automatically increase the temperature until certain thresholds are hit. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + body = deepcopy_minimal( + { + "file": file, + "model": model, + "prompt": prompt, + "response_format": response_format, + "temperature": temperature, + } + ) + files = extract_files(cast(Mapping[str, object], body), paths=[["file"]]) + if files: + # It should be noted that the actual Content-Type header that will be + # sent to the server will contain a `boundary` parameter, e.g. + # multipart/form-data; boundary=---abc-- + extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} + + return await self._post( + "/audio/translations", + body=maybe_transform(body, translation_create_params.TranslationCreateParams), + files=files, + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Translation, + ) + + +class TranslationsWithRawResponse: + def __init__(self, translations: Translations) -> None: + self.create = to_raw_response_wrapper( + translations.create, + ) + + +class AsyncTranslationsWithRawResponse: + def __init__(self, translations: AsyncTranslations) -> None: + self.create = async_to_raw_response_wrapper( + translations.create, + ) diff --git a/src/openai/resources/chat/__init__.py b/src/openai/resources/chat/__init__.py new file mode 100644 index 0000000000..2e56c0cbfa --- /dev/null +++ b/src/openai/resources/chat/__init__.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. + +from .chat import Chat, AsyncChat, ChatWithRawResponse, AsyncChatWithRawResponse +from .completions import ( + Completions, + AsyncCompletions, + CompletionsWithRawResponse, + AsyncCompletionsWithRawResponse, +) + +__all__ = [ + "Completions", + "AsyncCompletions", + "CompletionsWithRawResponse", + "AsyncCompletionsWithRawResponse", + "Chat", + "AsyncChat", + "ChatWithRawResponse", + "AsyncChatWithRawResponse", +] diff --git a/src/openai/resources/chat/chat.py b/src/openai/resources/chat/chat.py new file mode 100644 index 0000000000..3847b20512 --- /dev/null +++ b/src/openai/resources/chat/chat.py @@ -0,0 +1,48 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from ..._resource import SyncAPIResource, AsyncAPIResource +from .completions import ( + Completions, + AsyncCompletions, + CompletionsWithRawResponse, + AsyncCompletionsWithRawResponse, +) + +if TYPE_CHECKING: + from ..._client import OpenAI, AsyncOpenAI + +__all__ = ["Chat", "AsyncChat"] + + +class Chat(SyncAPIResource): + completions: Completions + with_raw_response: ChatWithRawResponse + + def __init__(self, client: OpenAI) -> None: + super().__init__(client) + self.completions = Completions(client) + self.with_raw_response = ChatWithRawResponse(self) + + +class AsyncChat(AsyncAPIResource): + completions: AsyncCompletions + with_raw_response: AsyncChatWithRawResponse + + def __init__(self, client: AsyncOpenAI) -> None: + super().__init__(client) + self.completions = AsyncCompletions(client) + self.with_raw_response = AsyncChatWithRawResponse(self) + + +class ChatWithRawResponse: + def __init__(self, chat: Chat) -> None: + self.completions = CompletionsWithRawResponse(chat.completions) + + +class AsyncChatWithRawResponse: + def __init__(self, chat: AsyncChat) -> None: + self.completions = AsyncCompletionsWithRawResponse(chat.completions) diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py new file mode 100644 index 0000000000..e6e6ce52b8 --- /dev/null +++ b/src/openai/resources/chat/completions.py @@ -0,0 +1,942 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import TYPE_CHECKING, Dict, List, Union, Optional, overload +from typing_extensions import Literal + +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ..._utils import required_args, maybe_transform +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from ..._streaming import Stream, AsyncStream +from ...types.chat import ( + ChatCompletion, + ChatCompletionChunk, + ChatCompletionMessageParam, + completion_create_params, +) +from ..._base_client import make_request_options + +if TYPE_CHECKING: + from ..._client import OpenAI, AsyncOpenAI + +__all__ = ["Completions", "AsyncCompletions"] + + +class Completions(SyncAPIResource): + with_raw_response: CompletionsWithRawResponse + + def __init__(self, client: OpenAI) -> None: + super().__init__(client) + self.with_raw_response = CompletionsWithRawResponse(self) + + @overload + def create( + self, + *, + messages: List[ChatCompletionMessageParam], + model: Union[ + str, + Literal[ + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0301", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-16k-0613", + ], + ], + frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, + function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, + functions: List[completion_create_params.Function] | NotGiven = NOT_GIVEN, + logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + n: Optional[int] | NotGiven = NOT_GIVEN, + presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> ChatCompletion: + """ + Creates a model response for the given chat conversation. + + Args: + messages: A list of messages comprising the conversation so far. + [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models). + + model: ID of the model to use. See the + [model endpoint compatibility](https://platform.openai.com/docs/models/model-endpoint-compatibility) + table for details on which models work with the Chat API. + + frequency_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on their + existing frequency in the text so far, decreasing the model's likelihood to + repeat the same line verbatim. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + + function_call: Controls how the model calls functions. "none" means the model will not call a + function and instead generates a message. "auto" means the model can pick + between generating a message or calling a function. Specifying a particular + function via `{"name": "my_function"}` forces the model to call that function. + "none" is the default when no functions are present. "auto" is the default if + functions are present. + + functions: A list of functions the model may generate JSON inputs for. + + logit_bias: Modify the likelihood of specified tokens appearing in the completion. + + Accepts a json object that maps tokens (specified by their token ID in the + tokenizer) to an associated bias value from -100 to 100. Mathematically, the + bias is added to the logits generated by the model prior to sampling. The exact + effect will vary per model, but values between -1 and 1 should decrease or + increase likelihood of selection; values like -100 or 100 should result in a ban + or exclusive selection of the relevant token. + + max_tokens: The maximum number of [tokens](/tokenizer) to generate in the chat completion. + + The total length of input tokens and generated tokens is limited by the model's + context length. + [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + for counting tokens. + + n: How many chat completion choices to generate for each input message. + + presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on + whether they appear in the text so far, increasing the model's likelihood to + talk about new topics. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + + stop: Up to 4 sequences where the API will stop generating further tokens. + + stream: If set, partial message deltas will be sent, like in ChatGPT. Tokens will be + sent as data-only + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available, with the stream terminated by a `data: [DONE]` + message. + [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + + We generally recommend altering this or `top_p` but not both. + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + def create( + self, + *, + messages: List[ChatCompletionMessageParam], + model: Union[ + str, + Literal[ + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0301", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-16k-0613", + ], + ], + stream: Literal[True], + frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, + function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, + functions: List[completion_create_params.Function] | NotGiven = NOT_GIVEN, + logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + n: Optional[int] | NotGiven = NOT_GIVEN, + presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Stream[ChatCompletionChunk]: + """ + Creates a model response for the given chat conversation. + + Args: + messages: A list of messages comprising the conversation so far. + [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models). + + model: ID of the model to use. See the + [model endpoint compatibility](https://platform.openai.com/docs/models/model-endpoint-compatibility) + table for details on which models work with the Chat API. + + stream: If set, partial message deltas will be sent, like in ChatGPT. Tokens will be + sent as data-only + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available, with the stream terminated by a `data: [DONE]` + message. + [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + + frequency_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on their + existing frequency in the text so far, decreasing the model's likelihood to + repeat the same line verbatim. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + + function_call: Controls how the model calls functions. "none" means the model will not call a + function and instead generates a message. "auto" means the model can pick + between generating a message or calling a function. Specifying a particular + function via `{"name": "my_function"}` forces the model to call that function. + "none" is the default when no functions are present. "auto" is the default if + functions are present. + + functions: A list of functions the model may generate JSON inputs for. + + logit_bias: Modify the likelihood of specified tokens appearing in the completion. + + Accepts a json object that maps tokens (specified by their token ID in the + tokenizer) to an associated bias value from -100 to 100. Mathematically, the + bias is added to the logits generated by the model prior to sampling. The exact + effect will vary per model, but values between -1 and 1 should decrease or + increase likelihood of selection; values like -100 or 100 should result in a ban + or exclusive selection of the relevant token. + + max_tokens: The maximum number of [tokens](/tokenizer) to generate in the chat completion. + + The total length of input tokens and generated tokens is limited by the model's + context length. + [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + for counting tokens. + + n: How many chat completion choices to generate for each input message. + + presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on + whether they appear in the text so far, increasing the model's likelihood to + talk about new topics. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + + stop: Up to 4 sequences where the API will stop generating further tokens. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + + We generally recommend altering this or `top_p` but not both. + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + def create( + self, + *, + messages: List[ChatCompletionMessageParam], + model: Union[ + str, + Literal[ + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0301", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-16k-0613", + ], + ], + stream: bool, + frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, + function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, + functions: List[completion_create_params.Function] | NotGiven = NOT_GIVEN, + logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + n: Optional[int] | NotGiven = NOT_GIVEN, + presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> ChatCompletion | Stream[ChatCompletionChunk]: + """ + Creates a model response for the given chat conversation. + + Args: + messages: A list of messages comprising the conversation so far. + [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models). + + model: ID of the model to use. See the + [model endpoint compatibility](https://platform.openai.com/docs/models/model-endpoint-compatibility) + table for details on which models work with the Chat API. + + stream: If set, partial message deltas will be sent, like in ChatGPT. Tokens will be + sent as data-only + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available, with the stream terminated by a `data: [DONE]` + message. + [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + + frequency_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on their + existing frequency in the text so far, decreasing the model's likelihood to + repeat the same line verbatim. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + + function_call: Controls how the model calls functions. "none" means the model will not call a + function and instead generates a message. "auto" means the model can pick + between generating a message or calling a function. Specifying a particular + function via `{"name": "my_function"}` forces the model to call that function. + "none" is the default when no functions are present. "auto" is the default if + functions are present. + + functions: A list of functions the model may generate JSON inputs for. + + logit_bias: Modify the likelihood of specified tokens appearing in the completion. + + Accepts a json object that maps tokens (specified by their token ID in the + tokenizer) to an associated bias value from -100 to 100. Mathematically, the + bias is added to the logits generated by the model prior to sampling. The exact + effect will vary per model, but values between -1 and 1 should decrease or + increase likelihood of selection; values like -100 or 100 should result in a ban + or exclusive selection of the relevant token. + + max_tokens: The maximum number of [tokens](/tokenizer) to generate in the chat completion. + + The total length of input tokens and generated tokens is limited by the model's + context length. + [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + for counting tokens. + + n: How many chat completion choices to generate for each input message. + + presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on + whether they appear in the text so far, increasing the model's likelihood to + talk about new topics. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + + stop: Up to 4 sequences where the API will stop generating further tokens. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + + We generally recommend altering this or `top_p` but not both. + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @required_args(["messages", "model"], ["messages", "model", "stream"]) + def create( + self, + *, + messages: List[ChatCompletionMessageParam], + model: Union[ + str, + Literal[ + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0301", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-16k-0613", + ], + ], + frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, + function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, + functions: List[completion_create_params.Function] | NotGiven = NOT_GIVEN, + logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + n: Optional[int] | NotGiven = NOT_GIVEN, + presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> ChatCompletion | Stream[ChatCompletionChunk]: + return self._post( + "/chat/completions", + body=maybe_transform( + { + "messages": messages, + "model": model, + "frequency_penalty": frequency_penalty, + "function_call": function_call, + "functions": functions, + "logit_bias": logit_bias, + "max_tokens": max_tokens, + "n": n, + "presence_penalty": presence_penalty, + "stop": stop, + "stream": stream, + "temperature": temperature, + "top_p": top_p, + "user": user, + }, + completion_create_params.CompletionCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ChatCompletion, + stream=stream or False, + stream_cls=Stream[ChatCompletionChunk], + ) + + +class AsyncCompletions(AsyncAPIResource): + with_raw_response: AsyncCompletionsWithRawResponse + + def __init__(self, client: AsyncOpenAI) -> None: + super().__init__(client) + self.with_raw_response = AsyncCompletionsWithRawResponse(self) + + @overload + async def create( + self, + *, + messages: List[ChatCompletionMessageParam], + model: Union[ + str, + Literal[ + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0301", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-16k-0613", + ], + ], + frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, + function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, + functions: List[completion_create_params.Function] | NotGiven = NOT_GIVEN, + logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + n: Optional[int] | NotGiven = NOT_GIVEN, + presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> ChatCompletion: + """ + Creates a model response for the given chat conversation. + + Args: + messages: A list of messages comprising the conversation so far. + [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models). + + model: ID of the model to use. See the + [model endpoint compatibility](https://platform.openai.com/docs/models/model-endpoint-compatibility) + table for details on which models work with the Chat API. + + frequency_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on their + existing frequency in the text so far, decreasing the model's likelihood to + repeat the same line verbatim. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + + function_call: Controls how the model calls functions. "none" means the model will not call a + function and instead generates a message. "auto" means the model can pick + between generating a message or calling a function. Specifying a particular + function via `{"name": "my_function"}` forces the model to call that function. + "none" is the default when no functions are present. "auto" is the default if + functions are present. + + functions: A list of functions the model may generate JSON inputs for. + + logit_bias: Modify the likelihood of specified tokens appearing in the completion. + + Accepts a json object that maps tokens (specified by their token ID in the + tokenizer) to an associated bias value from -100 to 100. Mathematically, the + bias is added to the logits generated by the model prior to sampling. The exact + effect will vary per model, but values between -1 and 1 should decrease or + increase likelihood of selection; values like -100 or 100 should result in a ban + or exclusive selection of the relevant token. + + max_tokens: The maximum number of [tokens](/tokenizer) to generate in the chat completion. + + The total length of input tokens and generated tokens is limited by the model's + context length. + [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + for counting tokens. + + n: How many chat completion choices to generate for each input message. + + presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on + whether they appear in the text so far, increasing the model's likelihood to + talk about new topics. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + + stop: Up to 4 sequences where the API will stop generating further tokens. + + stream: If set, partial message deltas will be sent, like in ChatGPT. Tokens will be + sent as data-only + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available, with the stream terminated by a `data: [DONE]` + message. + [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + + We generally recommend altering this or `top_p` but not both. + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + async def create( + self, + *, + messages: List[ChatCompletionMessageParam], + model: Union[ + str, + Literal[ + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0301", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-16k-0613", + ], + ], + stream: Literal[True], + frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, + function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, + functions: List[completion_create_params.Function] | NotGiven = NOT_GIVEN, + logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + n: Optional[int] | NotGiven = NOT_GIVEN, + presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> AsyncStream[ChatCompletionChunk]: + """ + Creates a model response for the given chat conversation. + + Args: + messages: A list of messages comprising the conversation so far. + [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models). + + model: ID of the model to use. See the + [model endpoint compatibility](https://platform.openai.com/docs/models/model-endpoint-compatibility) + table for details on which models work with the Chat API. + + stream: If set, partial message deltas will be sent, like in ChatGPT. Tokens will be + sent as data-only + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available, with the stream terminated by a `data: [DONE]` + message. + [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + + frequency_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on their + existing frequency in the text so far, decreasing the model's likelihood to + repeat the same line verbatim. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + + function_call: Controls how the model calls functions. "none" means the model will not call a + function and instead generates a message. "auto" means the model can pick + between generating a message or calling a function. Specifying a particular + function via `{"name": "my_function"}` forces the model to call that function. + "none" is the default when no functions are present. "auto" is the default if + functions are present. + + functions: A list of functions the model may generate JSON inputs for. + + logit_bias: Modify the likelihood of specified tokens appearing in the completion. + + Accepts a json object that maps tokens (specified by their token ID in the + tokenizer) to an associated bias value from -100 to 100. Mathematically, the + bias is added to the logits generated by the model prior to sampling. The exact + effect will vary per model, but values between -1 and 1 should decrease or + increase likelihood of selection; values like -100 or 100 should result in a ban + or exclusive selection of the relevant token. + + max_tokens: The maximum number of [tokens](/tokenizer) to generate in the chat completion. + + The total length of input tokens and generated tokens is limited by the model's + context length. + [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + for counting tokens. + + n: How many chat completion choices to generate for each input message. + + presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on + whether they appear in the text so far, increasing the model's likelihood to + talk about new topics. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + + stop: Up to 4 sequences where the API will stop generating further tokens. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + + We generally recommend altering this or `top_p` but not both. + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + async def create( + self, + *, + messages: List[ChatCompletionMessageParam], + model: Union[ + str, + Literal[ + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0301", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-16k-0613", + ], + ], + stream: bool, + frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, + function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, + functions: List[completion_create_params.Function] | NotGiven = NOT_GIVEN, + logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + n: Optional[int] | NotGiven = NOT_GIVEN, + presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> ChatCompletion | AsyncStream[ChatCompletionChunk]: + """ + Creates a model response for the given chat conversation. + + Args: + messages: A list of messages comprising the conversation so far. + [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models). + + model: ID of the model to use. See the + [model endpoint compatibility](https://platform.openai.com/docs/models/model-endpoint-compatibility) + table for details on which models work with the Chat API. + + stream: If set, partial message deltas will be sent, like in ChatGPT. Tokens will be + sent as data-only + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available, with the stream terminated by a `data: [DONE]` + message. + [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + + frequency_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on their + existing frequency in the text so far, decreasing the model's likelihood to + repeat the same line verbatim. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + + function_call: Controls how the model calls functions. "none" means the model will not call a + function and instead generates a message. "auto" means the model can pick + between generating a message or calling a function. Specifying a particular + function via `{"name": "my_function"}` forces the model to call that function. + "none" is the default when no functions are present. "auto" is the default if + functions are present. + + functions: A list of functions the model may generate JSON inputs for. + + logit_bias: Modify the likelihood of specified tokens appearing in the completion. + + Accepts a json object that maps tokens (specified by their token ID in the + tokenizer) to an associated bias value from -100 to 100. Mathematically, the + bias is added to the logits generated by the model prior to sampling. The exact + effect will vary per model, but values between -1 and 1 should decrease or + increase likelihood of selection; values like -100 or 100 should result in a ban + or exclusive selection of the relevant token. + + max_tokens: The maximum number of [tokens](/tokenizer) to generate in the chat completion. + + The total length of input tokens and generated tokens is limited by the model's + context length. + [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + for counting tokens. + + n: How many chat completion choices to generate for each input message. + + presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on + whether they appear in the text so far, increasing the model's likelihood to + talk about new topics. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + + stop: Up to 4 sequences where the API will stop generating further tokens. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + + We generally recommend altering this or `top_p` but not both. + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @required_args(["messages", "model"], ["messages", "model", "stream"]) + async def create( + self, + *, + messages: List[ChatCompletionMessageParam], + model: Union[ + str, + Literal[ + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0301", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-16k-0613", + ], + ], + frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, + function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, + functions: List[completion_create_params.Function] | NotGiven = NOT_GIVEN, + logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + n: Optional[int] | NotGiven = NOT_GIVEN, + presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> ChatCompletion | AsyncStream[ChatCompletionChunk]: + return await self._post( + "/chat/completions", + body=maybe_transform( + { + "messages": messages, + "model": model, + "frequency_penalty": frequency_penalty, + "function_call": function_call, + "functions": functions, + "logit_bias": logit_bias, + "max_tokens": max_tokens, + "n": n, + "presence_penalty": presence_penalty, + "stop": stop, + "stream": stream, + "temperature": temperature, + "top_p": top_p, + "user": user, + }, + completion_create_params.CompletionCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ChatCompletion, + stream=stream or False, + stream_cls=AsyncStream[ChatCompletionChunk], + ) + + +class CompletionsWithRawResponse: + def __init__(self, completions: Completions) -> None: + self.create = to_raw_response_wrapper( + completions.create, + ) + + +class AsyncCompletionsWithRawResponse: + def __init__(self, completions: AsyncCompletions) -> None: + self.create = async_to_raw_response_wrapper( + completions.create, + ) diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py new file mode 100644 index 0000000000..26a34524c6 --- /dev/null +++ b/src/openai/resources/completions.py @@ -0,0 +1,1117 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import TYPE_CHECKING, Dict, List, Union, Optional, overload +from typing_extensions import Literal + +from ..types import Completion, completion_create_params +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._utils import required_args, maybe_transform +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from .._streaming import Stream, AsyncStream +from .._base_client import make_request_options + +if TYPE_CHECKING: + from .._client import OpenAI, AsyncOpenAI + +__all__ = ["Completions", "AsyncCompletions"] + + +class Completions(SyncAPIResource): + with_raw_response: CompletionsWithRawResponse + + def __init__(self, client: OpenAI) -> None: + super().__init__(client) + self.with_raw_response = CompletionsWithRawResponse(self) + + @overload + def create( + self, + *, + model: Union[ + str, + Literal[ + "babbage-002", + "davinci-002", + "gpt-3.5-turbo-instruct", + "text-davinci-003", + "text-davinci-002", + "text-davinci-001", + "code-davinci-002", + "text-curie-001", + "text-babbage-001", + "text-ada-001", + ], + ], + prompt: Union[str, List[str], List[int], List[List[int]], None], + best_of: Optional[int] | NotGiven = NOT_GIVEN, + echo: Optional[bool] | NotGiven = NOT_GIVEN, + frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, + logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + logprobs: Optional[int] | NotGiven = NOT_GIVEN, + max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + n: Optional[int] | NotGiven = NOT_GIVEN, + presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, + suffix: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Completion: + """ + Creates a completion for the provided prompt and parameters. + + Args: + model: ID of the model to use. You can use the + [List models](https://platform.openai.com/docs/api-reference/models/list) API to + see all of your available models, or see our + [Model overview](https://platform.openai.com/docs/models/overview) for + descriptions of them. + + prompt: The prompt(s) to generate completions for, encoded as a string, array of + strings, array of tokens, or array of token arrays. + + Note that <|endoftext|> is the document separator that the model sees during + training, so if a prompt is not specified the model will generate as if from the + beginning of a new document. + + best_of: Generates `best_of` completions server-side and returns the "best" (the one with + the highest log probability per token). Results cannot be streamed. + + When used with `n`, `best_of` controls the number of candidate completions and + `n` specifies how many to return – `best_of` must be greater than `n`. + + **Note:** Because this parameter generates many completions, it can quickly + consume your token quota. Use carefully and ensure that you have reasonable + settings for `max_tokens` and `stop`. + + echo: Echo back the prompt in addition to the completion + + frequency_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on their + existing frequency in the text so far, decreasing the model's likelihood to + repeat the same line verbatim. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + + logit_bias: Modify the likelihood of specified tokens appearing in the completion. + + Accepts a json object that maps tokens (specified by their token ID in the GPT + tokenizer) to an associated bias value from -100 to 100. You can use this + [tokenizer tool](/tokenizer?view=bpe) (which works for both GPT-2 and GPT-3) to + convert text to token IDs. Mathematically, the bias is added to the logits + generated by the model prior to sampling. The exact effect will vary per model, + but values between -1 and 1 should decrease or increase likelihood of selection; + values like -100 or 100 should result in a ban or exclusive selection of the + relevant token. + + As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token + from being generated. + + logprobs: Include the log probabilities on the `logprobs` most likely tokens, as well the + chosen tokens. For example, if `logprobs` is 5, the API will return a list of + the 5 most likely tokens. The API will always return the `logprob` of the + sampled token, so there may be up to `logprobs+1` elements in the response. + + The maximum value for `logprobs` is 5. + + max_tokens: The maximum number of [tokens](/tokenizer) to generate in the completion. + + The token count of your prompt plus `max_tokens` cannot exceed the model's + context length. + [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + for counting tokens. + + n: How many completions to generate for each prompt. + + **Note:** Because this parameter generates many completions, it can quickly + consume your token quota. Use carefully and ensure that you have reasonable + settings for `max_tokens` and `stop`. + + presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on + whether they appear in the text so far, increasing the model's likelihood to + talk about new topics. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + + stop: Up to 4 sequences where the API will stop generating further tokens. The + returned text will not contain the stop sequence. + + stream: Whether to stream back partial progress. If set, tokens will be sent as + data-only + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available, with the stream terminated by a `data: [DONE]` + message. + [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + + suffix: The suffix that comes after a completion of inserted text. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + + We generally recommend altering this or `top_p` but not both. + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + def create( + self, + *, + model: Union[ + str, + Literal[ + "babbage-002", + "davinci-002", + "gpt-3.5-turbo-instruct", + "text-davinci-003", + "text-davinci-002", + "text-davinci-001", + "code-davinci-002", + "text-curie-001", + "text-babbage-001", + "text-ada-001", + ], + ], + prompt: Union[str, List[str], List[int], List[List[int]], None], + stream: Literal[True], + best_of: Optional[int] | NotGiven = NOT_GIVEN, + echo: Optional[bool] | NotGiven = NOT_GIVEN, + frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, + logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + logprobs: Optional[int] | NotGiven = NOT_GIVEN, + max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + n: Optional[int] | NotGiven = NOT_GIVEN, + presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, + suffix: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Stream[Completion]: + """ + Creates a completion for the provided prompt and parameters. + + Args: + model: ID of the model to use. You can use the + [List models](https://platform.openai.com/docs/api-reference/models/list) API to + see all of your available models, or see our + [Model overview](https://platform.openai.com/docs/models/overview) for + descriptions of them. + + prompt: The prompt(s) to generate completions for, encoded as a string, array of + strings, array of tokens, or array of token arrays. + + Note that <|endoftext|> is the document separator that the model sees during + training, so if a prompt is not specified the model will generate as if from the + beginning of a new document. + + stream: Whether to stream back partial progress. If set, tokens will be sent as + data-only + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available, with the stream terminated by a `data: [DONE]` + message. + [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + + best_of: Generates `best_of` completions server-side and returns the "best" (the one with + the highest log probability per token). Results cannot be streamed. + + When used with `n`, `best_of` controls the number of candidate completions and + `n` specifies how many to return – `best_of` must be greater than `n`. + + **Note:** Because this parameter generates many completions, it can quickly + consume your token quota. Use carefully and ensure that you have reasonable + settings for `max_tokens` and `stop`. + + echo: Echo back the prompt in addition to the completion + + frequency_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on their + existing frequency in the text so far, decreasing the model's likelihood to + repeat the same line verbatim. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + + logit_bias: Modify the likelihood of specified tokens appearing in the completion. + + Accepts a json object that maps tokens (specified by their token ID in the GPT + tokenizer) to an associated bias value from -100 to 100. You can use this + [tokenizer tool](/tokenizer?view=bpe) (which works for both GPT-2 and GPT-3) to + convert text to token IDs. Mathematically, the bias is added to the logits + generated by the model prior to sampling. The exact effect will vary per model, + but values between -1 and 1 should decrease or increase likelihood of selection; + values like -100 or 100 should result in a ban or exclusive selection of the + relevant token. + + As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token + from being generated. + + logprobs: Include the log probabilities on the `logprobs` most likely tokens, as well the + chosen tokens. For example, if `logprobs` is 5, the API will return a list of + the 5 most likely tokens. The API will always return the `logprob` of the + sampled token, so there may be up to `logprobs+1` elements in the response. + + The maximum value for `logprobs` is 5. + + max_tokens: The maximum number of [tokens](/tokenizer) to generate in the completion. + + The token count of your prompt plus `max_tokens` cannot exceed the model's + context length. + [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + for counting tokens. + + n: How many completions to generate for each prompt. + + **Note:** Because this parameter generates many completions, it can quickly + consume your token quota. Use carefully and ensure that you have reasonable + settings for `max_tokens` and `stop`. + + presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on + whether they appear in the text so far, increasing the model's likelihood to + talk about new topics. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + + stop: Up to 4 sequences where the API will stop generating further tokens. The + returned text will not contain the stop sequence. + + suffix: The suffix that comes after a completion of inserted text. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + + We generally recommend altering this or `top_p` but not both. + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + def create( + self, + *, + model: Union[ + str, + Literal[ + "babbage-002", + "davinci-002", + "gpt-3.5-turbo-instruct", + "text-davinci-003", + "text-davinci-002", + "text-davinci-001", + "code-davinci-002", + "text-curie-001", + "text-babbage-001", + "text-ada-001", + ], + ], + prompt: Union[str, List[str], List[int], List[List[int]], None], + stream: bool, + best_of: Optional[int] | NotGiven = NOT_GIVEN, + echo: Optional[bool] | NotGiven = NOT_GIVEN, + frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, + logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + logprobs: Optional[int] | NotGiven = NOT_GIVEN, + max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + n: Optional[int] | NotGiven = NOT_GIVEN, + presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, + suffix: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Completion | Stream[Completion]: + """ + Creates a completion for the provided prompt and parameters. + + Args: + model: ID of the model to use. You can use the + [List models](https://platform.openai.com/docs/api-reference/models/list) API to + see all of your available models, or see our + [Model overview](https://platform.openai.com/docs/models/overview) for + descriptions of them. + + prompt: The prompt(s) to generate completions for, encoded as a string, array of + strings, array of tokens, or array of token arrays. + + Note that <|endoftext|> is the document separator that the model sees during + training, so if a prompt is not specified the model will generate as if from the + beginning of a new document. + + stream: Whether to stream back partial progress. If set, tokens will be sent as + data-only + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available, with the stream terminated by a `data: [DONE]` + message. + [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + + best_of: Generates `best_of` completions server-side and returns the "best" (the one with + the highest log probability per token). Results cannot be streamed. + + When used with `n`, `best_of` controls the number of candidate completions and + `n` specifies how many to return – `best_of` must be greater than `n`. + + **Note:** Because this parameter generates many completions, it can quickly + consume your token quota. Use carefully and ensure that you have reasonable + settings for `max_tokens` and `stop`. + + echo: Echo back the prompt in addition to the completion + + frequency_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on their + existing frequency in the text so far, decreasing the model's likelihood to + repeat the same line verbatim. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + + logit_bias: Modify the likelihood of specified tokens appearing in the completion. + + Accepts a json object that maps tokens (specified by their token ID in the GPT + tokenizer) to an associated bias value from -100 to 100. You can use this + [tokenizer tool](/tokenizer?view=bpe) (which works for both GPT-2 and GPT-3) to + convert text to token IDs. Mathematically, the bias is added to the logits + generated by the model prior to sampling. The exact effect will vary per model, + but values between -1 and 1 should decrease or increase likelihood of selection; + values like -100 or 100 should result in a ban or exclusive selection of the + relevant token. + + As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token + from being generated. + + logprobs: Include the log probabilities on the `logprobs` most likely tokens, as well the + chosen tokens. For example, if `logprobs` is 5, the API will return a list of + the 5 most likely tokens. The API will always return the `logprob` of the + sampled token, so there may be up to `logprobs+1` elements in the response. + + The maximum value for `logprobs` is 5. + + max_tokens: The maximum number of [tokens](/tokenizer) to generate in the completion. + + The token count of your prompt plus `max_tokens` cannot exceed the model's + context length. + [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + for counting tokens. + + n: How many completions to generate for each prompt. + + **Note:** Because this parameter generates many completions, it can quickly + consume your token quota. Use carefully and ensure that you have reasonable + settings for `max_tokens` and `stop`. + + presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on + whether they appear in the text so far, increasing the model's likelihood to + talk about new topics. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + + stop: Up to 4 sequences where the API will stop generating further tokens. The + returned text will not contain the stop sequence. + + suffix: The suffix that comes after a completion of inserted text. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + + We generally recommend altering this or `top_p` but not both. + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @required_args(["model", "prompt"], ["model", "prompt", "stream"]) + def create( + self, + *, + model: Union[ + str, + Literal[ + "babbage-002", + "davinci-002", + "gpt-3.5-turbo-instruct", + "text-davinci-003", + "text-davinci-002", + "text-davinci-001", + "code-davinci-002", + "text-curie-001", + "text-babbage-001", + "text-ada-001", + ], + ], + prompt: Union[str, List[str], List[int], List[List[int]], None], + best_of: Optional[int] | NotGiven = NOT_GIVEN, + echo: Optional[bool] | NotGiven = NOT_GIVEN, + frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, + logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + logprobs: Optional[int] | NotGiven = NOT_GIVEN, + max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + n: Optional[int] | NotGiven = NOT_GIVEN, + presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + suffix: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Completion | Stream[Completion]: + return self._post( + "/completions", + body=maybe_transform( + { + "model": model, + "prompt": prompt, + "best_of": best_of, + "echo": echo, + "frequency_penalty": frequency_penalty, + "logit_bias": logit_bias, + "logprobs": logprobs, + "max_tokens": max_tokens, + "n": n, + "presence_penalty": presence_penalty, + "stop": stop, + "stream": stream, + "suffix": suffix, + "temperature": temperature, + "top_p": top_p, + "user": user, + }, + completion_create_params.CompletionCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Completion, + stream=stream or False, + stream_cls=Stream[Completion], + ) + + +class AsyncCompletions(AsyncAPIResource): + with_raw_response: AsyncCompletionsWithRawResponse + + def __init__(self, client: AsyncOpenAI) -> None: + super().__init__(client) + self.with_raw_response = AsyncCompletionsWithRawResponse(self) + + @overload + async def create( + self, + *, + model: Union[ + str, + Literal[ + "babbage-002", + "davinci-002", + "gpt-3.5-turbo-instruct", + "text-davinci-003", + "text-davinci-002", + "text-davinci-001", + "code-davinci-002", + "text-curie-001", + "text-babbage-001", + "text-ada-001", + ], + ], + prompt: Union[str, List[str], List[int], List[List[int]], None], + best_of: Optional[int] | NotGiven = NOT_GIVEN, + echo: Optional[bool] | NotGiven = NOT_GIVEN, + frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, + logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + logprobs: Optional[int] | NotGiven = NOT_GIVEN, + max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + n: Optional[int] | NotGiven = NOT_GIVEN, + presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, + suffix: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Completion: + """ + Creates a completion for the provided prompt and parameters. + + Args: + model: ID of the model to use. You can use the + [List models](https://platform.openai.com/docs/api-reference/models/list) API to + see all of your available models, or see our + [Model overview](https://platform.openai.com/docs/models/overview) for + descriptions of them. + + prompt: The prompt(s) to generate completions for, encoded as a string, array of + strings, array of tokens, or array of token arrays. + + Note that <|endoftext|> is the document separator that the model sees during + training, so if a prompt is not specified the model will generate as if from the + beginning of a new document. + + best_of: Generates `best_of` completions server-side and returns the "best" (the one with + the highest log probability per token). Results cannot be streamed. + + When used with `n`, `best_of` controls the number of candidate completions and + `n` specifies how many to return – `best_of` must be greater than `n`. + + **Note:** Because this parameter generates many completions, it can quickly + consume your token quota. Use carefully and ensure that you have reasonable + settings for `max_tokens` and `stop`. + + echo: Echo back the prompt in addition to the completion + + frequency_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on their + existing frequency in the text so far, decreasing the model's likelihood to + repeat the same line verbatim. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + + logit_bias: Modify the likelihood of specified tokens appearing in the completion. + + Accepts a json object that maps tokens (specified by their token ID in the GPT + tokenizer) to an associated bias value from -100 to 100. You can use this + [tokenizer tool](/tokenizer?view=bpe) (which works for both GPT-2 and GPT-3) to + convert text to token IDs. Mathematically, the bias is added to the logits + generated by the model prior to sampling. The exact effect will vary per model, + but values between -1 and 1 should decrease or increase likelihood of selection; + values like -100 or 100 should result in a ban or exclusive selection of the + relevant token. + + As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token + from being generated. + + logprobs: Include the log probabilities on the `logprobs` most likely tokens, as well the + chosen tokens. For example, if `logprobs` is 5, the API will return a list of + the 5 most likely tokens. The API will always return the `logprob` of the + sampled token, so there may be up to `logprobs+1` elements in the response. + + The maximum value for `logprobs` is 5. + + max_tokens: The maximum number of [tokens](/tokenizer) to generate in the completion. + + The token count of your prompt plus `max_tokens` cannot exceed the model's + context length. + [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + for counting tokens. + + n: How many completions to generate for each prompt. + + **Note:** Because this parameter generates many completions, it can quickly + consume your token quota. Use carefully and ensure that you have reasonable + settings for `max_tokens` and `stop`. + + presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on + whether they appear in the text so far, increasing the model's likelihood to + talk about new topics. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + + stop: Up to 4 sequences where the API will stop generating further tokens. The + returned text will not contain the stop sequence. + + stream: Whether to stream back partial progress. If set, tokens will be sent as + data-only + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available, with the stream terminated by a `data: [DONE]` + message. + [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + + suffix: The suffix that comes after a completion of inserted text. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + + We generally recommend altering this or `top_p` but not both. + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + async def create( + self, + *, + model: Union[ + str, + Literal[ + "babbage-002", + "davinci-002", + "gpt-3.5-turbo-instruct", + "text-davinci-003", + "text-davinci-002", + "text-davinci-001", + "code-davinci-002", + "text-curie-001", + "text-babbage-001", + "text-ada-001", + ], + ], + prompt: Union[str, List[str], List[int], List[List[int]], None], + stream: Literal[True], + best_of: Optional[int] | NotGiven = NOT_GIVEN, + echo: Optional[bool] | NotGiven = NOT_GIVEN, + frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, + logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + logprobs: Optional[int] | NotGiven = NOT_GIVEN, + max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + n: Optional[int] | NotGiven = NOT_GIVEN, + presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, + suffix: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> AsyncStream[Completion]: + """ + Creates a completion for the provided prompt and parameters. + + Args: + model: ID of the model to use. You can use the + [List models](https://platform.openai.com/docs/api-reference/models/list) API to + see all of your available models, or see our + [Model overview](https://platform.openai.com/docs/models/overview) for + descriptions of them. + + prompt: The prompt(s) to generate completions for, encoded as a string, array of + strings, array of tokens, or array of token arrays. + + Note that <|endoftext|> is the document separator that the model sees during + training, so if a prompt is not specified the model will generate as if from the + beginning of a new document. + + stream: Whether to stream back partial progress. If set, tokens will be sent as + data-only + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available, with the stream terminated by a `data: [DONE]` + message. + [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + + best_of: Generates `best_of` completions server-side and returns the "best" (the one with + the highest log probability per token). Results cannot be streamed. + + When used with `n`, `best_of` controls the number of candidate completions and + `n` specifies how many to return – `best_of` must be greater than `n`. + + **Note:** Because this parameter generates many completions, it can quickly + consume your token quota. Use carefully and ensure that you have reasonable + settings for `max_tokens` and `stop`. + + echo: Echo back the prompt in addition to the completion + + frequency_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on their + existing frequency in the text so far, decreasing the model's likelihood to + repeat the same line verbatim. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + + logit_bias: Modify the likelihood of specified tokens appearing in the completion. + + Accepts a json object that maps tokens (specified by their token ID in the GPT + tokenizer) to an associated bias value from -100 to 100. You can use this + [tokenizer tool](/tokenizer?view=bpe) (which works for both GPT-2 and GPT-3) to + convert text to token IDs. Mathematically, the bias is added to the logits + generated by the model prior to sampling. The exact effect will vary per model, + but values between -1 and 1 should decrease or increase likelihood of selection; + values like -100 or 100 should result in a ban or exclusive selection of the + relevant token. + + As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token + from being generated. + + logprobs: Include the log probabilities on the `logprobs` most likely tokens, as well the + chosen tokens. For example, if `logprobs` is 5, the API will return a list of + the 5 most likely tokens. The API will always return the `logprob` of the + sampled token, so there may be up to `logprobs+1` elements in the response. + + The maximum value for `logprobs` is 5. + + max_tokens: The maximum number of [tokens](/tokenizer) to generate in the completion. + + The token count of your prompt plus `max_tokens` cannot exceed the model's + context length. + [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + for counting tokens. + + n: How many completions to generate for each prompt. + + **Note:** Because this parameter generates many completions, it can quickly + consume your token quota. Use carefully and ensure that you have reasonable + settings for `max_tokens` and `stop`. + + presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on + whether they appear in the text so far, increasing the model's likelihood to + talk about new topics. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + + stop: Up to 4 sequences where the API will stop generating further tokens. The + returned text will not contain the stop sequence. + + suffix: The suffix that comes after a completion of inserted text. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + + We generally recommend altering this or `top_p` but not both. + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + async def create( + self, + *, + model: Union[ + str, + Literal[ + "babbage-002", + "davinci-002", + "gpt-3.5-turbo-instruct", + "text-davinci-003", + "text-davinci-002", + "text-davinci-001", + "code-davinci-002", + "text-curie-001", + "text-babbage-001", + "text-ada-001", + ], + ], + prompt: Union[str, List[str], List[int], List[List[int]], None], + stream: bool, + best_of: Optional[int] | NotGiven = NOT_GIVEN, + echo: Optional[bool] | NotGiven = NOT_GIVEN, + frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, + logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + logprobs: Optional[int] | NotGiven = NOT_GIVEN, + max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + n: Optional[int] | NotGiven = NOT_GIVEN, + presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, + suffix: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Completion | AsyncStream[Completion]: + """ + Creates a completion for the provided prompt and parameters. + + Args: + model: ID of the model to use. You can use the + [List models](https://platform.openai.com/docs/api-reference/models/list) API to + see all of your available models, or see our + [Model overview](https://platform.openai.com/docs/models/overview) for + descriptions of them. + + prompt: The prompt(s) to generate completions for, encoded as a string, array of + strings, array of tokens, or array of token arrays. + + Note that <|endoftext|> is the document separator that the model sees during + training, so if a prompt is not specified the model will generate as if from the + beginning of a new document. + + stream: Whether to stream back partial progress. If set, tokens will be sent as + data-only + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available, with the stream terminated by a `data: [DONE]` + message. + [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + + best_of: Generates `best_of` completions server-side and returns the "best" (the one with + the highest log probability per token). Results cannot be streamed. + + When used with `n`, `best_of` controls the number of candidate completions and + `n` specifies how many to return – `best_of` must be greater than `n`. + + **Note:** Because this parameter generates many completions, it can quickly + consume your token quota. Use carefully and ensure that you have reasonable + settings for `max_tokens` and `stop`. + + echo: Echo back the prompt in addition to the completion + + frequency_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on their + existing frequency in the text so far, decreasing the model's likelihood to + repeat the same line verbatim. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + + logit_bias: Modify the likelihood of specified tokens appearing in the completion. + + Accepts a json object that maps tokens (specified by their token ID in the GPT + tokenizer) to an associated bias value from -100 to 100. You can use this + [tokenizer tool](/tokenizer?view=bpe) (which works for both GPT-2 and GPT-3) to + convert text to token IDs. Mathematically, the bias is added to the logits + generated by the model prior to sampling. The exact effect will vary per model, + but values between -1 and 1 should decrease or increase likelihood of selection; + values like -100 or 100 should result in a ban or exclusive selection of the + relevant token. + + As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token + from being generated. + + logprobs: Include the log probabilities on the `logprobs` most likely tokens, as well the + chosen tokens. For example, if `logprobs` is 5, the API will return a list of + the 5 most likely tokens. The API will always return the `logprob` of the + sampled token, so there may be up to `logprobs+1` elements in the response. + + The maximum value for `logprobs` is 5. + + max_tokens: The maximum number of [tokens](/tokenizer) to generate in the completion. + + The token count of your prompt plus `max_tokens` cannot exceed the model's + context length. + [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + for counting tokens. + + n: How many completions to generate for each prompt. + + **Note:** Because this parameter generates many completions, it can quickly + consume your token quota. Use carefully and ensure that you have reasonable + settings for `max_tokens` and `stop`. + + presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on + whether they appear in the text so far, increasing the model's likelihood to + talk about new topics. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + + stop: Up to 4 sequences where the API will stop generating further tokens. The + returned text will not contain the stop sequence. + + suffix: The suffix that comes after a completion of inserted text. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + + We generally recommend altering this or `top_p` but not both. + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @required_args(["model", "prompt"], ["model", "prompt", "stream"]) + async def create( + self, + *, + model: Union[ + str, + Literal[ + "babbage-002", + "davinci-002", + "gpt-3.5-turbo-instruct", + "text-davinci-003", + "text-davinci-002", + "text-davinci-001", + "code-davinci-002", + "text-curie-001", + "text-babbage-001", + "text-ada-001", + ], + ], + prompt: Union[str, List[str], List[int], List[List[int]], None], + best_of: Optional[int] | NotGiven = NOT_GIVEN, + echo: Optional[bool] | NotGiven = NOT_GIVEN, + frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, + logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + logprobs: Optional[int] | NotGiven = NOT_GIVEN, + max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + n: Optional[int] | NotGiven = NOT_GIVEN, + presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + suffix: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Completion | AsyncStream[Completion]: + return await self._post( + "/completions", + body=maybe_transform( + { + "model": model, + "prompt": prompt, + "best_of": best_of, + "echo": echo, + "frequency_penalty": frequency_penalty, + "logit_bias": logit_bias, + "logprobs": logprobs, + "max_tokens": max_tokens, + "n": n, + "presence_penalty": presence_penalty, + "stop": stop, + "stream": stream, + "suffix": suffix, + "temperature": temperature, + "top_p": top_p, + "user": user, + }, + completion_create_params.CompletionCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Completion, + stream=stream or False, + stream_cls=AsyncStream[Completion], + ) + + +class CompletionsWithRawResponse: + def __init__(self, completions: Completions) -> None: + self.create = to_raw_response_wrapper( + completions.create, + ) + + +class AsyncCompletionsWithRawResponse: + def __init__(self, completions: AsyncCompletions) -> None: + self.create = async_to_raw_response_wrapper( + completions.create, + ) diff --git a/src/openai/resources/edits.py b/src/openai/resources/edits.py new file mode 100644 index 0000000000..5c114c915f --- /dev/null +++ b/src/openai/resources/edits.py @@ -0,0 +1,191 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import typing_extensions +from typing import TYPE_CHECKING, Union, Optional +from typing_extensions import Literal + +from ..types import Edit, edit_create_params +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._utils import maybe_transform +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from .._base_client import make_request_options + +if TYPE_CHECKING: + from .._client import OpenAI, AsyncOpenAI + +__all__ = ["Edits", "AsyncEdits"] + + +class Edits(SyncAPIResource): + with_raw_response: EditsWithRawResponse + + def __init__(self, client: OpenAI) -> None: + super().__init__(client) + self.with_raw_response = EditsWithRawResponse(self) + + @typing_extensions.deprecated( + "The Edits API is deprecated; please use Chat Completions instead.\n\nhttps://openai.com/blog/gpt-4-api-general-availability#deprecation-of-the-edits-api\n" + ) + def create( + self, + *, + instruction: str, + model: Union[str, Literal["text-davinci-edit-001", "code-davinci-edit-001"]], + input: Optional[str] | NotGiven = NOT_GIVEN, + n: Optional[int] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Edit: + """ + Creates a new edit for the provided input, instruction, and parameters. + + Args: + instruction: The instruction that tells the model how to edit the prompt. + + model: ID of the model to use. You can use the `text-davinci-edit-001` or + `code-davinci-edit-001` model with this endpoint. + + input: The input text to use as a starting point for the edit. + + n: How many edits to generate for the input and instruction. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + + We generally recommend altering this or `top_p` but not both. + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._post( + "/edits", + body=maybe_transform( + { + "instruction": instruction, + "model": model, + "input": input, + "n": n, + "temperature": temperature, + "top_p": top_p, + }, + edit_create_params.EditCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Edit, + ) + + +class AsyncEdits(AsyncAPIResource): + with_raw_response: AsyncEditsWithRawResponse + + def __init__(self, client: AsyncOpenAI) -> None: + super().__init__(client) + self.with_raw_response = AsyncEditsWithRawResponse(self) + + @typing_extensions.deprecated( + "The Edits API is deprecated; please use Chat Completions instead.\n\nhttps://openai.com/blog/gpt-4-api-general-availability#deprecation-of-the-edits-api\n" + ) + async def create( + self, + *, + instruction: str, + model: Union[str, Literal["text-davinci-edit-001", "code-davinci-edit-001"]], + input: Optional[str] | NotGiven = NOT_GIVEN, + n: Optional[int] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Edit: + """ + Creates a new edit for the provided input, instruction, and parameters. + + Args: + instruction: The instruction that tells the model how to edit the prompt. + + model: ID of the model to use. You can use the `text-davinci-edit-001` or + `code-davinci-edit-001` model with this endpoint. + + input: The input text to use as a starting point for the edit. + + n: How many edits to generate for the input and instruction. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + + We generally recommend altering this or `top_p` but not both. + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._post( + "/edits", + body=maybe_transform( + { + "instruction": instruction, + "model": model, + "input": input, + "n": n, + "temperature": temperature, + "top_p": top_p, + }, + edit_create_params.EditCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Edit, + ) + + +class EditsWithRawResponse: + def __init__(self, edits: Edits) -> None: + self.create = to_raw_response_wrapper( # pyright: ignore[reportDeprecated] + edits.create # pyright: ignore[reportDeprecated], + ) + + +class AsyncEditsWithRawResponse: + def __init__(self, edits: AsyncEdits) -> None: + self.create = async_to_raw_response_wrapper( # pyright: ignore[reportDeprecated] + edits.create # pyright: ignore[reportDeprecated], + ) diff --git a/src/openai/resources/embeddings.py b/src/openai/resources/embeddings.py new file mode 100644 index 0000000000..dd540fc796 --- /dev/null +++ b/src/openai/resources/embeddings.py @@ -0,0 +1,221 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import base64 +from typing import TYPE_CHECKING, List, Union, cast +from typing_extensions import Literal + +from ..types import CreateEmbeddingResponse, embedding_create_params +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._utils import is_given, maybe_transform +from .._extras import numpy as np +from .._extras import has_numpy +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from .._base_client import make_request_options + +if TYPE_CHECKING: + from .._client import OpenAI, AsyncOpenAI + +__all__ = ["Embeddings", "AsyncEmbeddings"] + + +class Embeddings(SyncAPIResource): + with_raw_response: EmbeddingsWithRawResponse + + def __init__(self, client: OpenAI) -> None: + super().__init__(client) + self.with_raw_response = EmbeddingsWithRawResponse(self) + + def create( + self, + *, + input: Union[str, List[str], List[int], List[List[int]]], + model: Union[str, Literal["text-embedding-ada-002"]], + encoding_format: Literal["float", "base64"] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> CreateEmbeddingResponse: + """ + Creates an embedding vector representing the input text. + + Args: + input: Input text to embed, encoded as a string or array of tokens. To embed multiple + inputs in a single request, pass an array of strings or array of token arrays. + The input must not exceed the max input tokens for the model (8192 tokens for + `text-embedding-ada-002`) and cannot be an empty string. + [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + for counting tokens. + + model: ID of the model to use. You can use the + [List models](https://platform.openai.com/docs/api-reference/models/list) API to + see all of your available models, or see our + [Model overview](https://platform.openai.com/docs/models/overview) for + descriptions of them. + + encoding_format: The format to return the embeddings in. Can be either `float` or + [`base64`](https://pypi.org/project/pybase64/). + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + params = { + "input": input, + "model": model, + "user": user, + "encoding_format": encoding_format, + } + if not is_given(encoding_format) and has_numpy(): + params["encoding_format"] = "base64" + + def parser(obj: CreateEmbeddingResponse) -> CreateEmbeddingResponse: + if is_given(encoding_format): + # don't modify the response object if a user explicitly asked for a format + return obj + + for embedding in obj.data: + data = cast(object, embedding.embedding) + if not isinstance(data, str): + # numpy is not installed / base64 optimisation isn't enabled for this model yet + continue + + embedding.embedding = np.frombuffer( # type: ignore[no-untyped-call] + base64.b64decode(data), dtype="float32" + ).tolist() + + return obj + + return self._post( + "/embeddings", + body=maybe_transform(params, embedding_create_params.EmbeddingCreateParams), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + post_parser=parser, + ), + cast_to=CreateEmbeddingResponse, + ) + + +class AsyncEmbeddings(AsyncAPIResource): + with_raw_response: AsyncEmbeddingsWithRawResponse + + def __init__(self, client: AsyncOpenAI) -> None: + super().__init__(client) + self.with_raw_response = AsyncEmbeddingsWithRawResponse(self) + + async def create( + self, + *, + input: Union[str, List[str], List[int], List[List[int]]], + model: Union[str, Literal["text-embedding-ada-002"]], + encoding_format: Literal["float", "base64"] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> CreateEmbeddingResponse: + """ + Creates an embedding vector representing the input text. + + Args: + input: Input text to embed, encoded as a string or array of tokens. To embed multiple + inputs in a single request, pass an array of strings or array of token arrays. + The input must not exceed the max input tokens for the model (8192 tokens for + `text-embedding-ada-002`) and cannot be an empty string. + [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + for counting tokens. + + model: ID of the model to use. You can use the + [List models](https://platform.openai.com/docs/api-reference/models/list) API to + see all of your available models, or see our + [Model overview](https://platform.openai.com/docs/models/overview) for + descriptions of them. + + encoding_format: The format to return the embeddings in. Can be either `float` or + [`base64`](https://pypi.org/project/pybase64/). + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + params = { + "input": input, + "model": model, + "user": user, + "encoding_format": encoding_format, + } + if not is_given(encoding_format) and has_numpy(): + params["encoding_format"] = "base64" + + def parser(obj: CreateEmbeddingResponse) -> CreateEmbeddingResponse: + if is_given(encoding_format): + # don't modify the response object if a user explicitly asked for a format + return obj + + for embedding in obj.data: + data = cast(object, embedding.embedding) + if not isinstance(data, str): + # numpy is not installed / base64 optimisation isn't enabled for this model yet + continue + + embedding.embedding = np.frombuffer( # type: ignore[no-untyped-call] + base64.b64decode(data), dtype="float32" + ).tolist() + + return obj + + return await self._post( + "/embeddings", + body=maybe_transform(params, embedding_create_params.EmbeddingCreateParams), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + post_parser=parser, + ), + cast_to=CreateEmbeddingResponse, + ) + + +class EmbeddingsWithRawResponse: + def __init__(self, embeddings: Embeddings) -> None: + self.create = to_raw_response_wrapper( + embeddings.create, + ) + + +class AsyncEmbeddingsWithRawResponse: + def __init__(self, embeddings: AsyncEmbeddings) -> None: + self.create = async_to_raw_response_wrapper( + embeddings.create, + ) diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py new file mode 100644 index 0000000000..d2e674c942 --- /dev/null +++ b/src/openai/resources/files.py @@ -0,0 +1,471 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import time +from typing import TYPE_CHECKING, Mapping, cast + +from ..types import FileObject, FileDeleted, file_create_params +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes +from .._utils import extract_files, maybe_transform, deepcopy_minimal +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from ..pagination import SyncPage, AsyncPage +from .._base_client import AsyncPaginator, make_request_options + +if TYPE_CHECKING: + from .._client import OpenAI, AsyncOpenAI + +__all__ = ["Files", "AsyncFiles"] + + +class Files(SyncAPIResource): + with_raw_response: FilesWithRawResponse + + def __init__(self, client: OpenAI) -> None: + super().__init__(client) + self.with_raw_response = FilesWithRawResponse(self) + + def create( + self, + *, + file: FileTypes, + purpose: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> FileObject: + """Upload a file that can be used across various endpoints/features. + + Currently, the + size of all the files uploaded by one organization can be up to 1 GB. Please + [contact us](https://help.openai.com/) if you need to increase the storage + limit. + + Args: + file: The file object (not file name) to be uploaded. + + If the `purpose` is set to "fine-tune", the file will be used for fine-tuning. + + purpose: The intended purpose of the uploaded file. + + Use "fine-tune" for + [fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning). This + allows us to validate the format of the uploaded file is correct for + fine-tuning. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + body = deepcopy_minimal( + { + "file": file, + "purpose": purpose, + } + ) + files = extract_files(cast(Mapping[str, object], body), paths=[["file"]]) + if files: + # It should be noted that the actual Content-Type header that will be + # sent to the server will contain a `boundary` parameter, e.g. + # multipart/form-data; boundary=---abc-- + extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} + + return self._post( + "/files", + body=maybe_transform(body, file_create_params.FileCreateParams), + files=files, + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=FileObject, + ) + + def retrieve( + self, + file_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> FileObject: + """ + Returns information about a specific file. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + f"/files/{file_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=FileObject, + ) + + def list( + self, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> SyncPage[FileObject]: + """Returns a list of files that belong to the user's organization.""" + return self._get_api_list( + "/files", + page=SyncPage[FileObject], + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + model=FileObject, + ) + + def delete( + self, + file_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> FileDeleted: + """ + Delete a file. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._delete( + f"/files/{file_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=FileDeleted, + ) + + def retrieve_content( + self, + file_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> str: + """ + Returns the contents of the specified file. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"Accept": "application/json", **(extra_headers or {})} + return self._get( + f"/files/{file_id}/content", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=str, + ) + + def wait_for_processing( + self, + id: str, + *, + poll_interval: float = 5.0, + max_wait_seconds: float = 30 * 60, + ) -> FileObject: + """Waits for the given file to be processed, default timeout is 30 mins.""" + TERMINAL_STATES = {"processed", "error", "deleted"} + + start = time.time() + file = self.retrieve(id) + while file.status not in TERMINAL_STATES: + self._sleep(poll_interval) + + file = self.retrieve(id) + if time.time() - start > max_wait_seconds: + raise RuntimeError( + f"Giving up on waiting for file {id} to finish processing after {max_wait_seconds} seconds." + ) + + return file + + +class AsyncFiles(AsyncAPIResource): + with_raw_response: AsyncFilesWithRawResponse + + def __init__(self, client: AsyncOpenAI) -> None: + super().__init__(client) + self.with_raw_response = AsyncFilesWithRawResponse(self) + + async def create( + self, + *, + file: FileTypes, + purpose: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> FileObject: + """Upload a file that can be used across various endpoints/features. + + Currently, the + size of all the files uploaded by one organization can be up to 1 GB. Please + [contact us](https://help.openai.com/) if you need to increase the storage + limit. + + Args: + file: The file object (not file name) to be uploaded. + + If the `purpose` is set to "fine-tune", the file will be used for fine-tuning. + + purpose: The intended purpose of the uploaded file. + + Use "fine-tune" for + [fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning). This + allows us to validate the format of the uploaded file is correct for + fine-tuning. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + body = deepcopy_minimal( + { + "file": file, + "purpose": purpose, + } + ) + files = extract_files(cast(Mapping[str, object], body), paths=[["file"]]) + if files: + # It should be noted that the actual Content-Type header that will be + # sent to the server will contain a `boundary` parameter, e.g. + # multipart/form-data; boundary=---abc-- + extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} + + return await self._post( + "/files", + body=maybe_transform(body, file_create_params.FileCreateParams), + files=files, + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=FileObject, + ) + + async def retrieve( + self, + file_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> FileObject: + """ + Returns information about a specific file. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + f"/files/{file_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=FileObject, + ) + + def list( + self, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> AsyncPaginator[FileObject, AsyncPage[FileObject]]: + """Returns a list of files that belong to the user's organization.""" + return self._get_api_list( + "/files", + page=AsyncPage[FileObject], + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + model=FileObject, + ) + + async def delete( + self, + file_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> FileDeleted: + """ + Delete a file. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._delete( + f"/files/{file_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=FileDeleted, + ) + + async def retrieve_content( + self, + file_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> str: + """ + Returns the contents of the specified file. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"Accept": "application/json", **(extra_headers or {})} + return await self._get( + f"/files/{file_id}/content", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=str, + ) + + async def wait_for_processing( + self, + id: str, + *, + poll_interval: float = 5.0, + max_wait_seconds: float = 30 * 60, + ) -> FileObject: + """Waits for the given file to be processed, default timeout is 30 mins.""" + TERMINAL_STATES = {"processed", "error", "deleted"} + + start = time.time() + file = await self.retrieve(id) + while file.status not in TERMINAL_STATES: + await self._sleep(poll_interval) + + file = await self.retrieve(id) + if time.time() - start > max_wait_seconds: + raise RuntimeError( + f"Giving up on waiting for file {id} to finish processing after {max_wait_seconds} seconds." + ) + + return file + + +class FilesWithRawResponse: + def __init__(self, files: Files) -> None: + self.create = to_raw_response_wrapper( + files.create, + ) + self.retrieve = to_raw_response_wrapper( + files.retrieve, + ) + self.list = to_raw_response_wrapper( + files.list, + ) + self.delete = to_raw_response_wrapper( + files.delete, + ) + self.retrieve_content = to_raw_response_wrapper( + files.retrieve_content, + ) + + +class AsyncFilesWithRawResponse: + def __init__(self, files: AsyncFiles) -> None: + self.create = async_to_raw_response_wrapper( + files.create, + ) + self.retrieve = async_to_raw_response_wrapper( + files.retrieve, + ) + self.list = async_to_raw_response_wrapper( + files.list, + ) + self.delete = async_to_raw_response_wrapper( + files.delete, + ) + self.retrieve_content = async_to_raw_response_wrapper( + files.retrieve_content, + ) diff --git a/src/openai/resources/fine_tunes.py b/src/openai/resources/fine_tunes.py new file mode 100644 index 0000000000..28f4225102 --- /dev/null +++ b/src/openai/resources/fine_tunes.py @@ -0,0 +1,820 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import TYPE_CHECKING, List, Union, Optional, overload +from typing_extensions import Literal + +from ..types import ( + FineTune, + FineTuneEvent, + FineTuneEventsListResponse, + fine_tune_create_params, + fine_tune_list_events_params, +) +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._utils import maybe_transform +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from .._streaming import Stream, AsyncStream +from ..pagination import SyncPage, AsyncPage +from .._base_client import AsyncPaginator, make_request_options + +if TYPE_CHECKING: + from .._client import OpenAI, AsyncOpenAI + +__all__ = ["FineTunes", "AsyncFineTunes"] + + +class FineTunes(SyncAPIResource): + with_raw_response: FineTunesWithRawResponse + + def __init__(self, client: OpenAI) -> None: + super().__init__(client) + self.with_raw_response = FineTunesWithRawResponse(self) + + def create( + self, + *, + training_file: str, + batch_size: Optional[int] | NotGiven = NOT_GIVEN, + classification_betas: Optional[List[float]] | NotGiven = NOT_GIVEN, + classification_n_classes: Optional[int] | NotGiven = NOT_GIVEN, + classification_positive_class: Optional[str] | NotGiven = NOT_GIVEN, + compute_classification_metrics: Optional[bool] | NotGiven = NOT_GIVEN, + hyperparameters: fine_tune_create_params.Hyperparameters | NotGiven = NOT_GIVEN, + learning_rate_multiplier: Optional[float] | NotGiven = NOT_GIVEN, + model: Union[str, Literal["ada", "babbage", "curie", "davinci"], None] | NotGiven = NOT_GIVEN, + prompt_loss_weight: Optional[float] | NotGiven = NOT_GIVEN, + suffix: Optional[str] | NotGiven = NOT_GIVEN, + validation_file: Optional[str] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> FineTune: + """ + Creates a job that fine-tunes a specified model from a given dataset. + + Response includes details of the enqueued job including job status and the name + of the fine-tuned models once complete. + + [Learn more about fine-tuning](https://platform.openai.com/docs/guides/legacy-fine-tuning) + + Args: + training_file: The ID of an uploaded file that contains training data. + + See [upload file](https://platform.openai.com/docs/api-reference/files/upload) + for how to upload a file. + + Your dataset must be formatted as a JSONL file, where each training example is a + JSON object with the keys "prompt" and "completion". Additionally, you must + upload your file with the purpose `fine-tune`. + + See the + [fine-tuning guide](https://platform.openai.com/docs/guides/legacy-fine-tuning/creating-training-data) + for more details. + + batch_size: The batch size to use for training. The batch size is the number of training + examples used to train a single forward and backward pass. + + By default, the batch size will be dynamically configured to be ~0.2% of the + number of examples in the training set, capped at 256 - in general, we've found + that larger batch sizes tend to work better for larger datasets. + + classification_betas: If this is provided, we calculate F-beta scores at the specified beta values. + The F-beta score is a generalization of F-1 score. This is only used for binary + classification. + + With a beta of 1 (i.e. the F-1 score), precision and recall are given the same + weight. A larger beta score puts more weight on recall and less on precision. A + smaller beta score puts more weight on precision and less on recall. + + classification_n_classes: The number of classes in a classification task. + + This parameter is required for multiclass classification. + + classification_positive_class: The positive class in binary classification. + + This parameter is needed to generate precision, recall, and F1 metrics when + doing binary classification. + + compute_classification_metrics: If set, we calculate classification-specific metrics such as accuracy and F-1 + score using the validation set at the end of every epoch. These metrics can be + viewed in the + [results file](https://platform.openai.com/docs/guides/legacy-fine-tuning/analyzing-your-fine-tuned-model). + + In order to compute classification metrics, you must provide a + `validation_file`. Additionally, you must specify `classification_n_classes` for + multiclass classification or `classification_positive_class` for binary + classification. + + hyperparameters: The hyperparameters used for the fine-tuning job. + + learning_rate_multiplier: The learning rate multiplier to use for training. The fine-tuning learning rate + is the original learning rate used for pretraining multiplied by this value. + + By default, the learning rate multiplier is the 0.05, 0.1, or 0.2 depending on + final `batch_size` (larger learning rates tend to perform better with larger + batch sizes). We recommend experimenting with values in the range 0.02 to 0.2 to + see what produces the best results. + + model: The name of the base model to fine-tune. You can select one of "ada", "babbage", + "curie", "davinci", or a fine-tuned model created after 2022-04-21 and before + 2023-08-22. To learn more about these models, see the + [Models](https://platform.openai.com/docs/models) documentation. + + prompt_loss_weight: The weight to use for loss on the prompt tokens. This controls how much the + model tries to learn to generate the prompt (as compared to the completion which + always has a weight of 1.0), and can add a stabilizing effect to training when + completions are short. + + If prompts are extremely long (relative to completions), it may make sense to + reduce this weight so as to avoid over-prioritizing learning the prompt. + + suffix: A string of up to 40 characters that will be added to your fine-tuned model + name. + + For example, a `suffix` of "custom-model-name" would produce a model name like + `ada:ft-your-org:custom-model-name-2022-02-15-04-21-04`. + + validation_file: The ID of an uploaded file that contains validation data. + + If you provide this file, the data is used to generate validation metrics + periodically during fine-tuning. These metrics can be viewed in the + [fine-tuning results file](https://platform.openai.com/docs/guides/legacy-fine-tuning/analyzing-your-fine-tuned-model). + Your train and validation data should be mutually exclusive. + + Your dataset must be formatted as a JSONL file, where each validation example is + a JSON object with the keys "prompt" and "completion". Additionally, you must + upload your file with the purpose `fine-tune`. + + See the + [fine-tuning guide](https://platform.openai.com/docs/guides/legacy-fine-tuning/creating-training-data) + for more details. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._post( + "/fine-tunes", + body=maybe_transform( + { + "training_file": training_file, + "batch_size": batch_size, + "classification_betas": classification_betas, + "classification_n_classes": classification_n_classes, + "classification_positive_class": classification_positive_class, + "compute_classification_metrics": compute_classification_metrics, + "hyperparameters": hyperparameters, + "learning_rate_multiplier": learning_rate_multiplier, + "model": model, + "prompt_loss_weight": prompt_loss_weight, + "suffix": suffix, + "validation_file": validation_file, + }, + fine_tune_create_params.FineTuneCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=FineTune, + ) + + def retrieve( + self, + fine_tune_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> FineTune: + """ + Gets info about the fine-tune job. + + [Learn more about fine-tuning](https://platform.openai.com/docs/guides/legacy-fine-tuning) + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + f"/fine-tunes/{fine_tune_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=FineTune, + ) + + def list( + self, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> SyncPage[FineTune]: + """List your organization's fine-tuning jobs""" + return self._get_api_list( + "/fine-tunes", + page=SyncPage[FineTune], + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + model=FineTune, + ) + + def cancel( + self, + fine_tune_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> FineTune: + """ + Immediately cancel a fine-tune job. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._post( + f"/fine-tunes/{fine_tune_id}/cancel", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=FineTune, + ) + + @overload + def list_events( + self, + fine_tune_id: str, + *, + stream: Literal[False] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = 86400, + ) -> FineTuneEventsListResponse: + """ + Get fine-grained status updates for a fine-tune job. + + Args: + stream: Whether to stream events for the fine-tune job. If set to true, events will be + sent as data-only + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available. The stream will terminate with a `data: [DONE]` + message when the job is finished (succeeded, cancelled, or failed). + + If set to false, only events generated so far will be returned. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + def list_events( + self, + fine_tune_id: str, + *, + stream: Literal[True], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = 86400, + ) -> Stream[FineTuneEvent]: + """ + Get fine-grained status updates for a fine-tune job. + + Args: + stream: Whether to stream events for the fine-tune job. If set to true, events will be + sent as data-only + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available. The stream will terminate with a `data: [DONE]` + message when the job is finished (succeeded, cancelled, or failed). + + If set to false, only events generated so far will be returned. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + def list_events( + self, + fine_tune_id: str, + *, + stream: bool, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = 86400, + ) -> FineTuneEventsListResponse | Stream[FineTuneEvent]: + """ + Get fine-grained status updates for a fine-tune job. + + Args: + stream: Whether to stream events for the fine-tune job. If set to true, events will be + sent as data-only + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available. The stream will terminate with a `data: [DONE]` + message when the job is finished (succeeded, cancelled, or failed). + + If set to false, only events generated so far will be returned. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + def list_events( + self, + fine_tune_id: str, + *, + stream: Literal[False] | Literal[True] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = 86400, + ) -> FineTuneEventsListResponse | Stream[FineTuneEvent]: + return self._get( + f"/fine-tunes/{fine_tune_id}/events", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform({"stream": stream}, fine_tune_list_events_params.FineTuneListEventsParams), + ), + cast_to=FineTuneEventsListResponse, + stream=stream or False, + stream_cls=Stream[FineTuneEvent], + ) + + +class AsyncFineTunes(AsyncAPIResource): + with_raw_response: AsyncFineTunesWithRawResponse + + def __init__(self, client: AsyncOpenAI) -> None: + super().__init__(client) + self.with_raw_response = AsyncFineTunesWithRawResponse(self) + + async def create( + self, + *, + training_file: str, + batch_size: Optional[int] | NotGiven = NOT_GIVEN, + classification_betas: Optional[List[float]] | NotGiven = NOT_GIVEN, + classification_n_classes: Optional[int] | NotGiven = NOT_GIVEN, + classification_positive_class: Optional[str] | NotGiven = NOT_GIVEN, + compute_classification_metrics: Optional[bool] | NotGiven = NOT_GIVEN, + hyperparameters: fine_tune_create_params.Hyperparameters | NotGiven = NOT_GIVEN, + learning_rate_multiplier: Optional[float] | NotGiven = NOT_GIVEN, + model: Union[str, Literal["ada", "babbage", "curie", "davinci"], None] | NotGiven = NOT_GIVEN, + prompt_loss_weight: Optional[float] | NotGiven = NOT_GIVEN, + suffix: Optional[str] | NotGiven = NOT_GIVEN, + validation_file: Optional[str] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> FineTune: + """ + Creates a job that fine-tunes a specified model from a given dataset. + + Response includes details of the enqueued job including job status and the name + of the fine-tuned models once complete. + + [Learn more about fine-tuning](https://platform.openai.com/docs/guides/legacy-fine-tuning) + + Args: + training_file: The ID of an uploaded file that contains training data. + + See [upload file](https://platform.openai.com/docs/api-reference/files/upload) + for how to upload a file. + + Your dataset must be formatted as a JSONL file, where each training example is a + JSON object with the keys "prompt" and "completion". Additionally, you must + upload your file with the purpose `fine-tune`. + + See the + [fine-tuning guide](https://platform.openai.com/docs/guides/legacy-fine-tuning/creating-training-data) + for more details. + + batch_size: The batch size to use for training. The batch size is the number of training + examples used to train a single forward and backward pass. + + By default, the batch size will be dynamically configured to be ~0.2% of the + number of examples in the training set, capped at 256 - in general, we've found + that larger batch sizes tend to work better for larger datasets. + + classification_betas: If this is provided, we calculate F-beta scores at the specified beta values. + The F-beta score is a generalization of F-1 score. This is only used for binary + classification. + + With a beta of 1 (i.e. the F-1 score), precision and recall are given the same + weight. A larger beta score puts more weight on recall and less on precision. A + smaller beta score puts more weight on precision and less on recall. + + classification_n_classes: The number of classes in a classification task. + + This parameter is required for multiclass classification. + + classification_positive_class: The positive class in binary classification. + + This parameter is needed to generate precision, recall, and F1 metrics when + doing binary classification. + + compute_classification_metrics: If set, we calculate classification-specific metrics such as accuracy and F-1 + score using the validation set at the end of every epoch. These metrics can be + viewed in the + [results file](https://platform.openai.com/docs/guides/legacy-fine-tuning/analyzing-your-fine-tuned-model). + + In order to compute classification metrics, you must provide a + `validation_file`. Additionally, you must specify `classification_n_classes` for + multiclass classification or `classification_positive_class` for binary + classification. + + hyperparameters: The hyperparameters used for the fine-tuning job. + + learning_rate_multiplier: The learning rate multiplier to use for training. The fine-tuning learning rate + is the original learning rate used for pretraining multiplied by this value. + + By default, the learning rate multiplier is the 0.05, 0.1, or 0.2 depending on + final `batch_size` (larger learning rates tend to perform better with larger + batch sizes). We recommend experimenting with values in the range 0.02 to 0.2 to + see what produces the best results. + + model: The name of the base model to fine-tune. You can select one of "ada", "babbage", + "curie", "davinci", or a fine-tuned model created after 2022-04-21 and before + 2023-08-22. To learn more about these models, see the + [Models](https://platform.openai.com/docs/models) documentation. + + prompt_loss_weight: The weight to use for loss on the prompt tokens. This controls how much the + model tries to learn to generate the prompt (as compared to the completion which + always has a weight of 1.0), and can add a stabilizing effect to training when + completions are short. + + If prompts are extremely long (relative to completions), it may make sense to + reduce this weight so as to avoid over-prioritizing learning the prompt. + + suffix: A string of up to 40 characters that will be added to your fine-tuned model + name. + + For example, a `suffix` of "custom-model-name" would produce a model name like + `ada:ft-your-org:custom-model-name-2022-02-15-04-21-04`. + + validation_file: The ID of an uploaded file that contains validation data. + + If you provide this file, the data is used to generate validation metrics + periodically during fine-tuning. These metrics can be viewed in the + [fine-tuning results file](https://platform.openai.com/docs/guides/legacy-fine-tuning/analyzing-your-fine-tuned-model). + Your train and validation data should be mutually exclusive. + + Your dataset must be formatted as a JSONL file, where each validation example is + a JSON object with the keys "prompt" and "completion". Additionally, you must + upload your file with the purpose `fine-tune`. + + See the + [fine-tuning guide](https://platform.openai.com/docs/guides/legacy-fine-tuning/creating-training-data) + for more details. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._post( + "/fine-tunes", + body=maybe_transform( + { + "training_file": training_file, + "batch_size": batch_size, + "classification_betas": classification_betas, + "classification_n_classes": classification_n_classes, + "classification_positive_class": classification_positive_class, + "compute_classification_metrics": compute_classification_metrics, + "hyperparameters": hyperparameters, + "learning_rate_multiplier": learning_rate_multiplier, + "model": model, + "prompt_loss_weight": prompt_loss_weight, + "suffix": suffix, + "validation_file": validation_file, + }, + fine_tune_create_params.FineTuneCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=FineTune, + ) + + async def retrieve( + self, + fine_tune_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> FineTune: + """ + Gets info about the fine-tune job. + + [Learn more about fine-tuning](https://platform.openai.com/docs/guides/legacy-fine-tuning) + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + f"/fine-tunes/{fine_tune_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=FineTune, + ) + + def list( + self, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> AsyncPaginator[FineTune, AsyncPage[FineTune]]: + """List your organization's fine-tuning jobs""" + return self._get_api_list( + "/fine-tunes", + page=AsyncPage[FineTune], + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + model=FineTune, + ) + + async def cancel( + self, + fine_tune_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> FineTune: + """ + Immediately cancel a fine-tune job. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._post( + f"/fine-tunes/{fine_tune_id}/cancel", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=FineTune, + ) + + @overload + async def list_events( + self, + fine_tune_id: str, + *, + stream: Literal[False] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = 86400, + ) -> FineTuneEventsListResponse: + """ + Get fine-grained status updates for a fine-tune job. + + Args: + stream: Whether to stream events for the fine-tune job. If set to true, events will be + sent as data-only + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available. The stream will terminate with a `data: [DONE]` + message when the job is finished (succeeded, cancelled, or failed). + + If set to false, only events generated so far will be returned. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + async def list_events( + self, + fine_tune_id: str, + *, + stream: Literal[True], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = 86400, + ) -> AsyncStream[FineTuneEvent]: + """ + Get fine-grained status updates for a fine-tune job. + + Args: + stream: Whether to stream events for the fine-tune job. If set to true, events will be + sent as data-only + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available. The stream will terminate with a `data: [DONE]` + message when the job is finished (succeeded, cancelled, or failed). + + If set to false, only events generated so far will be returned. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + async def list_events( + self, + fine_tune_id: str, + *, + stream: bool, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = 86400, + ) -> FineTuneEventsListResponse | AsyncStream[FineTuneEvent]: + """ + Get fine-grained status updates for a fine-tune job. + + Args: + stream: Whether to stream events for the fine-tune job. If set to true, events will be + sent as data-only + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available. The stream will terminate with a `data: [DONE]` + message when the job is finished (succeeded, cancelled, or failed). + + If set to false, only events generated so far will be returned. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + async def list_events( + self, + fine_tune_id: str, + *, + stream: Literal[False] | Literal[True] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = 86400, + ) -> FineTuneEventsListResponse | AsyncStream[FineTuneEvent]: + return await self._get( + f"/fine-tunes/{fine_tune_id}/events", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform({"stream": stream}, fine_tune_list_events_params.FineTuneListEventsParams), + ), + cast_to=FineTuneEventsListResponse, + stream=stream or False, + stream_cls=AsyncStream[FineTuneEvent], + ) + + +class FineTunesWithRawResponse: + def __init__(self, fine_tunes: FineTunes) -> None: + self.create = to_raw_response_wrapper( + fine_tunes.create, + ) + self.retrieve = to_raw_response_wrapper( + fine_tunes.retrieve, + ) + self.list = to_raw_response_wrapper( + fine_tunes.list, + ) + self.cancel = to_raw_response_wrapper( + fine_tunes.cancel, + ) + self.list_events = to_raw_response_wrapper( + fine_tunes.list_events, + ) + + +class AsyncFineTunesWithRawResponse: + def __init__(self, fine_tunes: AsyncFineTunes) -> None: + self.create = async_to_raw_response_wrapper( + fine_tunes.create, + ) + self.retrieve = async_to_raw_response_wrapper( + fine_tunes.retrieve, + ) + self.list = async_to_raw_response_wrapper( + fine_tunes.list, + ) + self.cancel = async_to_raw_response_wrapper( + fine_tunes.cancel, + ) + self.list_events = async_to_raw_response_wrapper( + fine_tunes.list_events, + ) diff --git a/src/openai/resources/fine_tuning/__init__.py b/src/openai/resources/fine_tuning/__init__.py new file mode 100644 index 0000000000..9133c25d4a --- /dev/null +++ b/src/openai/resources/fine_tuning/__init__.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. + +from .jobs import Jobs, AsyncJobs, JobsWithRawResponse, AsyncJobsWithRawResponse +from .fine_tuning import ( + FineTuning, + AsyncFineTuning, + FineTuningWithRawResponse, + AsyncFineTuningWithRawResponse, +) + +__all__ = [ + "Jobs", + "AsyncJobs", + "JobsWithRawResponse", + "AsyncJobsWithRawResponse", + "FineTuning", + "AsyncFineTuning", + "FineTuningWithRawResponse", + "AsyncFineTuningWithRawResponse", +] diff --git a/src/openai/resources/fine_tuning/fine_tuning.py b/src/openai/resources/fine_tuning/fine_tuning.py new file mode 100644 index 0000000000..2e5f36e546 --- /dev/null +++ b/src/openai/resources/fine_tuning/fine_tuning.py @@ -0,0 +1,43 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from .jobs import Jobs, AsyncJobs, JobsWithRawResponse, AsyncJobsWithRawResponse +from ..._resource import SyncAPIResource, AsyncAPIResource + +if TYPE_CHECKING: + from ..._client import OpenAI, AsyncOpenAI + +__all__ = ["FineTuning", "AsyncFineTuning"] + + +class FineTuning(SyncAPIResource): + jobs: Jobs + with_raw_response: FineTuningWithRawResponse + + def __init__(self, client: OpenAI) -> None: + super().__init__(client) + self.jobs = Jobs(client) + self.with_raw_response = FineTuningWithRawResponse(self) + + +class AsyncFineTuning(AsyncAPIResource): + jobs: AsyncJobs + with_raw_response: AsyncFineTuningWithRawResponse + + def __init__(self, client: AsyncOpenAI) -> None: + super().__init__(client) + self.jobs = AsyncJobs(client) + self.with_raw_response = AsyncFineTuningWithRawResponse(self) + + +class FineTuningWithRawResponse: + def __init__(self, fine_tuning: FineTuning) -> None: + self.jobs = JobsWithRawResponse(fine_tuning.jobs) + + +class AsyncFineTuningWithRawResponse: + def __init__(self, fine_tuning: AsyncFineTuning) -> None: + self.jobs = AsyncJobsWithRawResponse(fine_tuning.jobs) diff --git a/src/openai/resources/fine_tuning/jobs.py b/src/openai/resources/fine_tuning/jobs.py new file mode 100644 index 0000000000..b721c892b5 --- /dev/null +++ b/src/openai/resources/fine_tuning/jobs.py @@ -0,0 +1,567 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import TYPE_CHECKING, Union, Optional +from typing_extensions import Literal + +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ..._utils import maybe_transform +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from ...pagination import SyncCursorPage, AsyncCursorPage +from ..._base_client import AsyncPaginator, make_request_options +from ...types.fine_tuning import ( + FineTuningJob, + FineTuningJobEvent, + job_list_params, + job_create_params, + job_list_events_params, +) + +if TYPE_CHECKING: + from ..._client import OpenAI, AsyncOpenAI + +__all__ = ["Jobs", "AsyncJobs"] + + +class Jobs(SyncAPIResource): + with_raw_response: JobsWithRawResponse + + def __init__(self, client: OpenAI) -> None: + super().__init__(client) + self.with_raw_response = JobsWithRawResponse(self) + + def create( + self, + *, + model: Union[str, Literal["babbage-002", "davinci-002", "gpt-3.5-turbo"]], + training_file: str, + hyperparameters: job_create_params.Hyperparameters | NotGiven = NOT_GIVEN, + suffix: Optional[str] | NotGiven = NOT_GIVEN, + validation_file: Optional[str] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> FineTuningJob: + """ + Creates a job that fine-tunes a specified model from a given dataset. + + Response includes details of the enqueued job including job status and the name + of the fine-tuned models once complete. + + [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) + + Args: + model: The name of the model to fine-tune. You can select one of the + [supported models](https://platform.openai.com/docs/guides/fine-tuning/what-models-can-be-fine-tuned). + + training_file: The ID of an uploaded file that contains training data. + + See [upload file](https://platform.openai.com/docs/api-reference/files/upload) + for how to upload a file. + + Your dataset must be formatted as a JSONL file. Additionally, you must upload + your file with the purpose `fine-tune`. + + See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) + for more details. + + hyperparameters: The hyperparameters used for the fine-tuning job. + + suffix: A string of up to 18 characters that will be added to your fine-tuned model + name. + + For example, a `suffix` of "custom-model-name" would produce a model name like + `ft:gpt-3.5-turbo:openai:custom-model-name:7p4lURel`. + + validation_file: The ID of an uploaded file that contains validation data. + + If you provide this file, the data is used to generate validation metrics + periodically during fine-tuning. These metrics can be viewed in the fine-tuning + results file. The same data should not be present in both train and validation + files. + + Your dataset must be formatted as a JSONL file. You must upload your file with + the purpose `fine-tune`. + + See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) + for more details. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._post( + "/fine_tuning/jobs", + body=maybe_transform( + { + "model": model, + "training_file": training_file, + "hyperparameters": hyperparameters, + "suffix": suffix, + "validation_file": validation_file, + }, + job_create_params.JobCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=FineTuningJob, + ) + + def retrieve( + self, + fine_tuning_job_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> FineTuningJob: + """ + Get info about a fine-tuning job. + + [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + f"/fine_tuning/jobs/{fine_tuning_job_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=FineTuningJob, + ) + + def list( + self, + *, + after: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> SyncCursorPage[FineTuningJob]: + """ + List your organization's fine-tuning jobs + + Args: + after: Identifier for the last job from the previous pagination request. + + limit: Number of fine-tuning jobs to retrieve. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get_api_list( + "/fine_tuning/jobs", + page=SyncCursorPage[FineTuningJob], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "limit": limit, + }, + job_list_params.JobListParams, + ), + ), + model=FineTuningJob, + ) + + def cancel( + self, + fine_tuning_job_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> FineTuningJob: + """ + Immediately cancel a fine-tune job. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._post( + f"/fine_tuning/jobs/{fine_tuning_job_id}/cancel", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=FineTuningJob, + ) + + def list_events( + self, + fine_tuning_job_id: str, + *, + after: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> SyncCursorPage[FineTuningJobEvent]: + """ + Get status updates for a fine-tuning job. + + Args: + after: Identifier for the last event from the previous pagination request. + + limit: Number of events to retrieve. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get_api_list( + f"/fine_tuning/jobs/{fine_tuning_job_id}/events", + page=SyncCursorPage[FineTuningJobEvent], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "limit": limit, + }, + job_list_events_params.JobListEventsParams, + ), + ), + model=FineTuningJobEvent, + ) + + +class AsyncJobs(AsyncAPIResource): + with_raw_response: AsyncJobsWithRawResponse + + def __init__(self, client: AsyncOpenAI) -> None: + super().__init__(client) + self.with_raw_response = AsyncJobsWithRawResponse(self) + + async def create( + self, + *, + model: Union[str, Literal["babbage-002", "davinci-002", "gpt-3.5-turbo"]], + training_file: str, + hyperparameters: job_create_params.Hyperparameters | NotGiven = NOT_GIVEN, + suffix: Optional[str] | NotGiven = NOT_GIVEN, + validation_file: Optional[str] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> FineTuningJob: + """ + Creates a job that fine-tunes a specified model from a given dataset. + + Response includes details of the enqueued job including job status and the name + of the fine-tuned models once complete. + + [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) + + Args: + model: The name of the model to fine-tune. You can select one of the + [supported models](https://platform.openai.com/docs/guides/fine-tuning/what-models-can-be-fine-tuned). + + training_file: The ID of an uploaded file that contains training data. + + See [upload file](https://platform.openai.com/docs/api-reference/files/upload) + for how to upload a file. + + Your dataset must be formatted as a JSONL file. Additionally, you must upload + your file with the purpose `fine-tune`. + + See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) + for more details. + + hyperparameters: The hyperparameters used for the fine-tuning job. + + suffix: A string of up to 18 characters that will be added to your fine-tuned model + name. + + For example, a `suffix` of "custom-model-name" would produce a model name like + `ft:gpt-3.5-turbo:openai:custom-model-name:7p4lURel`. + + validation_file: The ID of an uploaded file that contains validation data. + + If you provide this file, the data is used to generate validation metrics + periodically during fine-tuning. These metrics can be viewed in the fine-tuning + results file. The same data should not be present in both train and validation + files. + + Your dataset must be formatted as a JSONL file. You must upload your file with + the purpose `fine-tune`. + + See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) + for more details. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._post( + "/fine_tuning/jobs", + body=maybe_transform( + { + "model": model, + "training_file": training_file, + "hyperparameters": hyperparameters, + "suffix": suffix, + "validation_file": validation_file, + }, + job_create_params.JobCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=FineTuningJob, + ) + + async def retrieve( + self, + fine_tuning_job_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> FineTuningJob: + """ + Get info about a fine-tuning job. + + [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + f"/fine_tuning/jobs/{fine_tuning_job_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=FineTuningJob, + ) + + def list( + self, + *, + after: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> AsyncPaginator[FineTuningJob, AsyncCursorPage[FineTuningJob]]: + """ + List your organization's fine-tuning jobs + + Args: + after: Identifier for the last job from the previous pagination request. + + limit: Number of fine-tuning jobs to retrieve. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get_api_list( + "/fine_tuning/jobs", + page=AsyncCursorPage[FineTuningJob], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "limit": limit, + }, + job_list_params.JobListParams, + ), + ), + model=FineTuningJob, + ) + + async def cancel( + self, + fine_tuning_job_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> FineTuningJob: + """ + Immediately cancel a fine-tune job. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._post( + f"/fine_tuning/jobs/{fine_tuning_job_id}/cancel", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=FineTuningJob, + ) + + def list_events( + self, + fine_tuning_job_id: str, + *, + after: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> AsyncPaginator[FineTuningJobEvent, AsyncCursorPage[FineTuningJobEvent]]: + """ + Get status updates for a fine-tuning job. + + Args: + after: Identifier for the last event from the previous pagination request. + + limit: Number of events to retrieve. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get_api_list( + f"/fine_tuning/jobs/{fine_tuning_job_id}/events", + page=AsyncCursorPage[FineTuningJobEvent], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "limit": limit, + }, + job_list_events_params.JobListEventsParams, + ), + ), + model=FineTuningJobEvent, + ) + + +class JobsWithRawResponse: + def __init__(self, jobs: Jobs) -> None: + self.create = to_raw_response_wrapper( + jobs.create, + ) + self.retrieve = to_raw_response_wrapper( + jobs.retrieve, + ) + self.list = to_raw_response_wrapper( + jobs.list, + ) + self.cancel = to_raw_response_wrapper( + jobs.cancel, + ) + self.list_events = to_raw_response_wrapper( + jobs.list_events, + ) + + +class AsyncJobsWithRawResponse: + def __init__(self, jobs: AsyncJobs) -> None: + self.create = async_to_raw_response_wrapper( + jobs.create, + ) + self.retrieve = async_to_raw_response_wrapper( + jobs.retrieve, + ) + self.list = async_to_raw_response_wrapper( + jobs.list, + ) + self.cancel = async_to_raw_response_wrapper( + jobs.cancel, + ) + self.list_events = async_to_raw_response_wrapper( + jobs.list_events, + ) diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py new file mode 100644 index 0000000000..1fd39b43a6 --- /dev/null +++ b/src/openai/resources/images.py @@ -0,0 +1,479 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import TYPE_CHECKING, Mapping, Optional, cast +from typing_extensions import Literal + +from ..types import ( + ImagesResponse, + image_edit_params, + image_generate_params, + image_create_variation_params, +) +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes +from .._utils import extract_files, maybe_transform, deepcopy_minimal +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from .._base_client import make_request_options + +if TYPE_CHECKING: + from .._client import OpenAI, AsyncOpenAI + +__all__ = ["Images", "AsyncImages"] + + +class Images(SyncAPIResource): + with_raw_response: ImagesWithRawResponse + + def __init__(self, client: OpenAI) -> None: + super().__init__(client) + self.with_raw_response = ImagesWithRawResponse(self) + + def create_variation( + self, + *, + image: FileTypes, + n: Optional[int] | NotGiven = NOT_GIVEN, + response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN, + size: Optional[Literal["256x256", "512x512", "1024x1024"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> ImagesResponse: + """ + Creates a variation of a given image. + + Args: + image: The image to use as the basis for the variation(s). Must be a valid PNG file, + less than 4MB, and square. + + n: The number of images to generate. Must be between 1 and 10. + + response_format: The format in which the generated images are returned. Must be one of `url` or + `b64_json`. + + size: The size of the generated images. Must be one of `256x256`, `512x512`, or + `1024x1024`. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + body = deepcopy_minimal( + { + "image": image, + "n": n, + "response_format": response_format, + "size": size, + "user": user, + } + ) + files = extract_files(cast(Mapping[str, object], body), paths=[["image"]]) + if files: + # It should be noted that the actual Content-Type header that will be + # sent to the server will contain a `boundary` parameter, e.g. + # multipart/form-data; boundary=---abc-- + extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} + + return self._post( + "/images/variations", + body=maybe_transform(body, image_create_variation_params.ImageCreateVariationParams), + files=files, + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ImagesResponse, + ) + + def edit( + self, + *, + image: FileTypes, + prompt: str, + mask: FileTypes | NotGiven = NOT_GIVEN, + n: Optional[int] | NotGiven = NOT_GIVEN, + response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN, + size: Optional[Literal["256x256", "512x512", "1024x1024"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> ImagesResponse: + """ + Creates an edited or extended image given an original image and a prompt. + + Args: + image: The image to edit. Must be a valid PNG file, less than 4MB, and square. If mask + is not provided, image must have transparency, which will be used as the mask. + + prompt: A text description of the desired image(s). The maximum length is 1000 + characters. + + mask: An additional image whose fully transparent areas (e.g. where alpha is zero) + indicate where `image` should be edited. Must be a valid PNG file, less than + 4MB, and have the same dimensions as `image`. + + n: The number of images to generate. Must be between 1 and 10. + + response_format: The format in which the generated images are returned. Must be one of `url` or + `b64_json`. + + size: The size of the generated images. Must be one of `256x256`, `512x512`, or + `1024x1024`. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + body = deepcopy_minimal( + { + "image": image, + "prompt": prompt, + "mask": mask, + "n": n, + "response_format": response_format, + "size": size, + "user": user, + } + ) + files = extract_files(cast(Mapping[str, object], body), paths=[["image"], ["mask"]]) + if files: + # It should be noted that the actual Content-Type header that will be + # sent to the server will contain a `boundary` parameter, e.g. + # multipart/form-data; boundary=---abc-- + extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} + + return self._post( + "/images/edits", + body=maybe_transform(body, image_edit_params.ImageEditParams), + files=files, + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ImagesResponse, + ) + + def generate( + self, + *, + prompt: str, + n: Optional[int] | NotGiven = NOT_GIVEN, + response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN, + size: Optional[Literal["256x256", "512x512", "1024x1024"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> ImagesResponse: + """ + Creates an image given a prompt. + + Args: + prompt: A text description of the desired image(s). The maximum length is 1000 + characters. + + n: The number of images to generate. Must be between 1 and 10. + + response_format: The format in which the generated images are returned. Must be one of `url` or + `b64_json`. + + size: The size of the generated images. Must be one of `256x256`, `512x512`, or + `1024x1024`. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._post( + "/images/generations", + body=maybe_transform( + { + "prompt": prompt, + "n": n, + "response_format": response_format, + "size": size, + "user": user, + }, + image_generate_params.ImageGenerateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ImagesResponse, + ) + + +class AsyncImages(AsyncAPIResource): + with_raw_response: AsyncImagesWithRawResponse + + def __init__(self, client: AsyncOpenAI) -> None: + super().__init__(client) + self.with_raw_response = AsyncImagesWithRawResponse(self) + + async def create_variation( + self, + *, + image: FileTypes, + n: Optional[int] | NotGiven = NOT_GIVEN, + response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN, + size: Optional[Literal["256x256", "512x512", "1024x1024"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> ImagesResponse: + """ + Creates a variation of a given image. + + Args: + image: The image to use as the basis for the variation(s). Must be a valid PNG file, + less than 4MB, and square. + + n: The number of images to generate. Must be between 1 and 10. + + response_format: The format in which the generated images are returned. Must be one of `url` or + `b64_json`. + + size: The size of the generated images. Must be one of `256x256`, `512x512`, or + `1024x1024`. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + body = deepcopy_minimal( + { + "image": image, + "n": n, + "response_format": response_format, + "size": size, + "user": user, + } + ) + files = extract_files(cast(Mapping[str, object], body), paths=[["image"]]) + if files: + # It should be noted that the actual Content-Type header that will be + # sent to the server will contain a `boundary` parameter, e.g. + # multipart/form-data; boundary=---abc-- + extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} + + return await self._post( + "/images/variations", + body=maybe_transform(body, image_create_variation_params.ImageCreateVariationParams), + files=files, + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ImagesResponse, + ) + + async def edit( + self, + *, + image: FileTypes, + prompt: str, + mask: FileTypes | NotGiven = NOT_GIVEN, + n: Optional[int] | NotGiven = NOT_GIVEN, + response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN, + size: Optional[Literal["256x256", "512x512", "1024x1024"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> ImagesResponse: + """ + Creates an edited or extended image given an original image and a prompt. + + Args: + image: The image to edit. Must be a valid PNG file, less than 4MB, and square. If mask + is not provided, image must have transparency, which will be used as the mask. + + prompt: A text description of the desired image(s). The maximum length is 1000 + characters. + + mask: An additional image whose fully transparent areas (e.g. where alpha is zero) + indicate where `image` should be edited. Must be a valid PNG file, less than + 4MB, and have the same dimensions as `image`. + + n: The number of images to generate. Must be between 1 and 10. + + response_format: The format in which the generated images are returned. Must be one of `url` or + `b64_json`. + + size: The size of the generated images. Must be one of `256x256`, `512x512`, or + `1024x1024`. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + body = deepcopy_minimal( + { + "image": image, + "prompt": prompt, + "mask": mask, + "n": n, + "response_format": response_format, + "size": size, + "user": user, + } + ) + files = extract_files(cast(Mapping[str, object], body), paths=[["image"], ["mask"]]) + if files: + # It should be noted that the actual Content-Type header that will be + # sent to the server will contain a `boundary` parameter, e.g. + # multipart/form-data; boundary=---abc-- + extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} + + return await self._post( + "/images/edits", + body=maybe_transform(body, image_edit_params.ImageEditParams), + files=files, + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ImagesResponse, + ) + + async def generate( + self, + *, + prompt: str, + n: Optional[int] | NotGiven = NOT_GIVEN, + response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN, + size: Optional[Literal["256x256", "512x512", "1024x1024"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> ImagesResponse: + """ + Creates an image given a prompt. + + Args: + prompt: A text description of the desired image(s). The maximum length is 1000 + characters. + + n: The number of images to generate. Must be between 1 and 10. + + response_format: The format in which the generated images are returned. Must be one of `url` or + `b64_json`. + + size: The size of the generated images. Must be one of `256x256`, `512x512`, or + `1024x1024`. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._post( + "/images/generations", + body=maybe_transform( + { + "prompt": prompt, + "n": n, + "response_format": response_format, + "size": size, + "user": user, + }, + image_generate_params.ImageGenerateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ImagesResponse, + ) + + +class ImagesWithRawResponse: + def __init__(self, images: Images) -> None: + self.create_variation = to_raw_response_wrapper( + images.create_variation, + ) + self.edit = to_raw_response_wrapper( + images.edit, + ) + self.generate = to_raw_response_wrapper( + images.generate, + ) + + +class AsyncImagesWithRawResponse: + def __init__(self, images: AsyncImages) -> None: + self.create_variation = async_to_raw_response_wrapper( + images.create_variation, + ) + self.edit = async_to_raw_response_wrapper( + images.edit, + ) + self.generate = async_to_raw_response_wrapper( + images.generate, + ) diff --git a/src/openai/resources/models.py b/src/openai/resources/models.py new file mode 100644 index 0000000000..689bbd6621 --- /dev/null +++ b/src/openai/resources/models.py @@ -0,0 +1,235 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from ..types import Model, ModelDeleted +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from ..pagination import SyncPage, AsyncPage +from .._base_client import AsyncPaginator, make_request_options + +if TYPE_CHECKING: + from .._client import OpenAI, AsyncOpenAI + +__all__ = ["Models", "AsyncModels"] + + +class Models(SyncAPIResource): + with_raw_response: ModelsWithRawResponse + + def __init__(self, client: OpenAI) -> None: + super().__init__(client) + self.with_raw_response = ModelsWithRawResponse(self) + + def retrieve( + self, + model: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Model: + """ + Retrieves a model instance, providing basic information about the model such as + the owner and permissioning. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + f"/models/{model}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Model, + ) + + def list( + self, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> SyncPage[Model]: + """ + Lists the currently available models, and provides basic information about each + one such as the owner and availability. + """ + return self._get_api_list( + "/models", + page=SyncPage[Model], + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + model=Model, + ) + + def delete( + self, + model: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> ModelDeleted: + """Delete a fine-tuned model. + + You must have the Owner role in your organization to + delete a model. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._delete( + f"/models/{model}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ModelDeleted, + ) + + +class AsyncModels(AsyncAPIResource): + with_raw_response: AsyncModelsWithRawResponse + + def __init__(self, client: AsyncOpenAI) -> None: + super().__init__(client) + self.with_raw_response = AsyncModelsWithRawResponse(self) + + async def retrieve( + self, + model: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Model: + """ + Retrieves a model instance, providing basic information about the model such as + the owner and permissioning. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + f"/models/{model}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Model, + ) + + def list( + self, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> AsyncPaginator[Model, AsyncPage[Model]]: + """ + Lists the currently available models, and provides basic information about each + one such as the owner and availability. + """ + return self._get_api_list( + "/models", + page=AsyncPage[Model], + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + model=Model, + ) + + async def delete( + self, + model: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> ModelDeleted: + """Delete a fine-tuned model. + + You must have the Owner role in your organization to + delete a model. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._delete( + f"/models/{model}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ModelDeleted, + ) + + +class ModelsWithRawResponse: + def __init__(self, models: Models) -> None: + self.retrieve = to_raw_response_wrapper( + models.retrieve, + ) + self.list = to_raw_response_wrapper( + models.list, + ) + self.delete = to_raw_response_wrapper( + models.delete, + ) + + +class AsyncModelsWithRawResponse: + def __init__(self, models: AsyncModels) -> None: + self.retrieve = async_to_raw_response_wrapper( + models.retrieve, + ) + self.list = async_to_raw_response_wrapper( + models.list, + ) + self.delete = async_to_raw_response_wrapper( + models.delete, + ) diff --git a/src/openai/resources/moderations.py b/src/openai/resources/moderations.py new file mode 100644 index 0000000000..1ee3e72564 --- /dev/null +++ b/src/openai/resources/moderations.py @@ -0,0 +1,148 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import TYPE_CHECKING, List, Union +from typing_extensions import Literal + +from ..types import ModerationCreateResponse, moderation_create_params +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._utils import maybe_transform +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from .._base_client import make_request_options + +if TYPE_CHECKING: + from .._client import OpenAI, AsyncOpenAI + +__all__ = ["Moderations", "AsyncModerations"] + + +class Moderations(SyncAPIResource): + with_raw_response: ModerationsWithRawResponse + + def __init__(self, client: OpenAI) -> None: + super().__init__(client) + self.with_raw_response = ModerationsWithRawResponse(self) + + def create( + self, + *, + input: Union[str, List[str]], + model: Union[str, Literal["text-moderation-latest", "text-moderation-stable"]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> ModerationCreateResponse: + """ + Classifies if text violates OpenAI's Content Policy + + Args: + input: The input text to classify + + model: Two content moderations models are available: `text-moderation-stable` and + `text-moderation-latest`. + + The default is `text-moderation-latest` which will be automatically upgraded + over time. This ensures you are always using our most accurate model. If you use + `text-moderation-stable`, we will provide advanced notice before updating the + model. Accuracy of `text-moderation-stable` may be slightly lower than for + `text-moderation-latest`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._post( + "/moderations", + body=maybe_transform( + { + "input": input, + "model": model, + }, + moderation_create_params.ModerationCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ModerationCreateResponse, + ) + + +class AsyncModerations(AsyncAPIResource): + with_raw_response: AsyncModerationsWithRawResponse + + def __init__(self, client: AsyncOpenAI) -> None: + super().__init__(client) + self.with_raw_response = AsyncModerationsWithRawResponse(self) + + async def create( + self, + *, + input: Union[str, List[str]], + model: Union[str, Literal["text-moderation-latest", "text-moderation-stable"]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> ModerationCreateResponse: + """ + Classifies if text violates OpenAI's Content Policy + + Args: + input: The input text to classify + + model: Two content moderations models are available: `text-moderation-stable` and + `text-moderation-latest`. + + The default is `text-moderation-latest` which will be automatically upgraded + over time. This ensures you are always using our most accurate model. If you use + `text-moderation-stable`, we will provide advanced notice before updating the + model. Accuracy of `text-moderation-stable` may be slightly lower than for + `text-moderation-latest`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._post( + "/moderations", + body=maybe_transform( + { + "input": input, + "model": model, + }, + moderation_create_params.ModerationCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ModerationCreateResponse, + ) + + +class ModerationsWithRawResponse: + def __init__(self, moderations: Moderations) -> None: + self.create = to_raw_response_wrapper( + moderations.create, + ) + + +class AsyncModerationsWithRawResponse: + def __init__(self, moderations: AsyncModerations) -> None: + self.create = async_to_raw_response_wrapper( + moderations.create, + ) diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py new file mode 100644 index 0000000000..defaf13446 --- /dev/null +++ b/src/openai/types/__init__.py @@ -0,0 +1,42 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from .edit import Edit as Edit +from .image import Image as Image +from .model import Model as Model +from .embedding import Embedding as Embedding +from .fine_tune import FineTune as FineTune +from .completion import Completion as Completion +from .moderation import Moderation as Moderation +from .file_object import FileObject as FileObject +from .file_content import FileContent as FileContent +from .file_deleted import FileDeleted as FileDeleted +from .model_deleted import ModelDeleted as ModelDeleted +from .fine_tune_event import FineTuneEvent as FineTuneEvent +from .images_response import ImagesResponse as ImagesResponse +from .completion_usage import CompletionUsage as CompletionUsage +from .completion_choice import CompletionChoice as CompletionChoice +from .image_edit_params import ImageEditParams as ImageEditParams +from .edit_create_params import EditCreateParams as EditCreateParams +from .file_create_params import FileCreateParams as FileCreateParams +from .image_generate_params import ImageGenerateParams as ImageGenerateParams +from .embedding_create_params import EmbeddingCreateParams as EmbeddingCreateParams +from .fine_tune_create_params import FineTuneCreateParams as FineTuneCreateParams +from .completion_create_params import CompletionCreateParams as CompletionCreateParams +from .moderation_create_params import ModerationCreateParams as ModerationCreateParams +from .create_embedding_response import ( + CreateEmbeddingResponse as CreateEmbeddingResponse, +) +from .moderation_create_response import ( + ModerationCreateResponse as ModerationCreateResponse, +) +from .fine_tune_list_events_params import ( + FineTuneListEventsParams as FineTuneListEventsParams, +) +from .image_create_variation_params import ( + ImageCreateVariationParams as ImageCreateVariationParams, +) +from .fine_tune_events_list_response import ( + FineTuneEventsListResponse as FineTuneEventsListResponse, +) diff --git a/src/openai/types/audio/__init__.py b/src/openai/types/audio/__init__.py new file mode 100644 index 0000000000..469bc6f25b --- /dev/null +++ b/src/openai/types/audio/__init__.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from .translation import Translation as Translation +from .transcription import Transcription as Transcription +from .translation_create_params import ( + TranslationCreateParams as TranslationCreateParams, +) +from .transcription_create_params import ( + TranscriptionCreateParams as TranscriptionCreateParams, +) diff --git a/src/openai/types/audio/transcription.py b/src/openai/types/audio/transcription.py new file mode 100644 index 0000000000..d2274faa0e --- /dev/null +++ b/src/openai/types/audio/transcription.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. + +from ..._models import BaseModel + +__all__ = ["Transcription"] + + +class Transcription(BaseModel): + text: str diff --git a/src/openai/types/audio/transcription_create_params.py b/src/openai/types/audio/transcription_create_params.py new file mode 100644 index 0000000000..f8f193484a --- /dev/null +++ b/src/openai/types/audio/transcription_create_params.py @@ -0,0 +1,52 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, Required, TypedDict + +from ..._types import FileTypes + +__all__ = ["TranscriptionCreateParams"] + + +class TranscriptionCreateParams(TypedDict, total=False): + file: Required[FileTypes] + """ + The audio file object (not file name) to transcribe, in one of these formats: + flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. + """ + + model: Required[Union[str, Literal["whisper-1"]]] + """ID of the model to use. Only `whisper-1` is currently available.""" + + language: str + """The language of the input audio. + + Supplying the input language in + [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format will + improve accuracy and latency. + """ + + prompt: str + """An optional text to guide the model's style or continue a previous audio + segment. + + The [prompt](https://platform.openai.com/docs/guides/speech-to-text/prompting) + should match the audio language. + """ + + response_format: Literal["json", "text", "srt", "verbose_json", "vtt"] + """ + The format of the transcript output, in one of these options: json, text, srt, + verbose_json, or vtt. + """ + + temperature: float + """The sampling temperature, between 0 and 1. + + Higher values like 0.8 will make the output more random, while lower values like + 0.2 will make it more focused and deterministic. If set to 0, the model will use + [log probability](https://en.wikipedia.org/wiki/Log_probability) to + automatically increase the temperature until certain thresholds are hit. + """ diff --git a/src/openai/types/audio/translation.py b/src/openai/types/audio/translation.py new file mode 100644 index 0000000000..a01d622abc --- /dev/null +++ b/src/openai/types/audio/translation.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. + +from ..._models import BaseModel + +__all__ = ["Translation"] + + +class Translation(BaseModel): + text: str diff --git a/src/openai/types/audio/translation_create_params.py b/src/openai/types/audio/translation_create_params.py new file mode 100644 index 0000000000..bfa5fc56d2 --- /dev/null +++ b/src/openai/types/audio/translation_create_params.py @@ -0,0 +1,44 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, Required, TypedDict + +from ..._types import FileTypes + +__all__ = ["TranslationCreateParams"] + + +class TranslationCreateParams(TypedDict, total=False): + file: Required[FileTypes] + """ + The audio file object (not file name) translate, in one of these formats: flac, + mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. + """ + + model: Required[Union[str, Literal["whisper-1"]]] + """ID of the model to use. Only `whisper-1` is currently available.""" + + prompt: str + """An optional text to guide the model's style or continue a previous audio + segment. + + The [prompt](https://platform.openai.com/docs/guides/speech-to-text/prompting) + should be in English. + """ + + response_format: str + """ + The format of the transcript output, in one of these options: json, text, srt, + verbose_json, or vtt. + """ + + temperature: float + """The sampling temperature, between 0 and 1. + + Higher values like 0.8 will make the output more random, while lower values like + 0.2 will make it more focused and deterministic. If set to 0, the model will use + [log probability](https://en.wikipedia.org/wiki/Log_probability) to + automatically increase the temperature until certain thresholds are hit. + """ diff --git a/src/openai/types/chat/__init__.py b/src/openai/types/chat/__init__.py new file mode 100644 index 0000000000..2f23cf3ca4 --- /dev/null +++ b/src/openai/types/chat/__init__.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from .chat_completion import ChatCompletion as ChatCompletion +from .chat_completion_role import ChatCompletionRole as ChatCompletionRole +from .chat_completion_chunk import ChatCompletionChunk as ChatCompletionChunk +from .chat_completion_message import ChatCompletionMessage as ChatCompletionMessage +from .completion_create_params import CompletionCreateParams as CompletionCreateParams +from .chat_completion_message_param import ( + ChatCompletionMessageParam as ChatCompletionMessageParam, +) diff --git a/src/openai/types/chat/chat_completion.py b/src/openai/types/chat/chat_completion.py new file mode 100644 index 0000000000..8d7a0b9716 --- /dev/null +++ b/src/openai/types/chat/chat_completion.py @@ -0,0 +1,50 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import List, Optional +from typing_extensions import Literal + +from ..._models import BaseModel +from ..completion_usage import CompletionUsage +from .chat_completion_message import ChatCompletionMessage + +__all__ = ["ChatCompletion", "Choice"] + + +class Choice(BaseModel): + finish_reason: Literal["stop", "length", "function_call", "content_filter"] + """The reason the model stopped generating tokens. + + This will be `stop` if the model hit a natural stop point or a provided stop + sequence, `length` if the maximum number of tokens specified in the request was + reached, `content_filter` if content was omitted due to a flag from our content + filters, or `function_call` if the model called a function. + """ + + index: int + """The index of the choice in the list of choices.""" + + message: ChatCompletionMessage + """A chat completion message generated by the model.""" + + +class ChatCompletion(BaseModel): + id: str + """A unique identifier for the chat completion.""" + + choices: List[Choice] + """A list of chat completion choices. + + Can be more than one if `n` is greater than 1. + """ + + created: int + """The Unix timestamp (in seconds) of when the chat completion was created.""" + + model: str + """The model used for the chat completion.""" + + object: str + """The object type, which is always `chat.completion`.""" + + usage: Optional[CompletionUsage] = None + """Usage statistics for the completion request.""" diff --git a/src/openai/types/chat/chat_completion_chunk.py b/src/openai/types/chat/chat_completion_chunk.py new file mode 100644 index 0000000000..66610898b4 --- /dev/null +++ b/src/openai/types/chat/chat_completion_chunk.py @@ -0,0 +1,76 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import List, Optional +from typing_extensions import Literal + +from ..._models import BaseModel +from .chat_completion_role import ChatCompletionRole + +__all__ = ["ChatCompletionChunk", "Choice", "ChoiceDelta", "ChoiceDeltaFunctionCall"] + + +class ChoiceDeltaFunctionCall(BaseModel): + arguments: Optional[str] = None + """ + The arguments to call the function with, as generated by the model in JSON + format. Note that the model does not always generate valid JSON, and may + hallucinate parameters not defined by your function schema. Validate the + arguments in your code before calling your function. + """ + + name: Optional[str] = None + """The name of the function to call.""" + + +class ChoiceDelta(BaseModel): + content: Optional[str] = None + """The contents of the chunk message.""" + + function_call: Optional[ChoiceDeltaFunctionCall] = None + """ + The name and arguments of a function that should be called, as generated by the + model. + """ + + role: Optional[ChatCompletionRole] = None + """The role of the author of this message.""" + + +class Choice(BaseModel): + delta: ChoiceDelta + """A chat completion delta generated by streamed model responses.""" + + finish_reason: Optional[Literal["stop", "length", "function_call", "content_filter"]] + """The reason the model stopped generating tokens. + + This will be `stop` if the model hit a natural stop point or a provided stop + sequence, `length` if the maximum number of tokens specified in the request was + reached, `content_filter` if content was omitted due to a flag from our content + filters, or `function_call` if the model called a function. + """ + + index: int + """The index of the choice in the list of choices.""" + + +class ChatCompletionChunk(BaseModel): + id: str + """A unique identifier for the chat completion. Each chunk has the same ID.""" + + choices: List[Choice] + """A list of chat completion choices. + + Can be more than one if `n` is greater than 1. + """ + + created: int + """The Unix timestamp (in seconds) of when the chat completion was created. + + Each chunk has the same timestamp. + """ + + model: str + """The model to generate the completion.""" + + object: str + """The object type, which is always `chat.completion.chunk`.""" diff --git a/src/openai/types/chat/chat_completion_message.py b/src/openai/types/chat/chat_completion_message.py new file mode 100644 index 0000000000..531eb3d43c --- /dev/null +++ b/src/openai/types/chat/chat_completion_message.py @@ -0,0 +1,35 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Optional + +from ..._models import BaseModel +from .chat_completion_role import ChatCompletionRole + +__all__ = ["ChatCompletionMessage", "FunctionCall"] + + +class FunctionCall(BaseModel): + arguments: str + """ + The arguments to call the function with, as generated by the model in JSON + format. Note that the model does not always generate valid JSON, and may + hallucinate parameters not defined by your function schema. Validate the + arguments in your code before calling your function. + """ + + name: str + """The name of the function to call.""" + + +class ChatCompletionMessage(BaseModel): + content: Optional[str] + """The contents of the message.""" + + role: ChatCompletionRole + """The role of the author of this message.""" + + function_call: Optional[FunctionCall] = None + """ + The name and arguments of a function that should be called, as generated by the + model. + """ diff --git a/src/openai/types/chat/chat_completion_message_param.py b/src/openai/types/chat/chat_completion_message_param.py new file mode 100644 index 0000000000..29b8882573 --- /dev/null +++ b/src/openai/types/chat/chat_completion_message_param.py @@ -0,0 +1,50 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ChatCompletionMessageParam", "FunctionCall"] + + +class FunctionCall(TypedDict, total=False): + arguments: Required[str] + """ + The arguments to call the function with, as generated by the model in JSON + format. Note that the model does not always generate valid JSON, and may + hallucinate parameters not defined by your function schema. Validate the + arguments in your code before calling your function. + """ + + name: Required[str] + """The name of the function to call.""" + + +class ChatCompletionMessageParam(TypedDict, total=False): + content: Required[Optional[str]] + """The contents of the message. + + `content` is required for all messages, and may be null for assistant messages + with function calls. + """ + + role: Required[Literal["system", "user", "assistant", "function"]] + """The role of the messages author. + + One of `system`, `user`, `assistant`, or `function`. + """ + + function_call: FunctionCall + """ + The name and arguments of a function that should be called, as generated by the + model. + """ + + name: str + """The name of the author of this message. + + `name` is required if role is `function`, and it should be the name of the + function whose response is in the `content`. May contain a-z, A-Z, 0-9, and + underscores, with a maximum length of 64 characters. + """ diff --git a/src/openai/types/chat/chat_completion_role.py b/src/openai/types/chat/chat_completion_role.py new file mode 100644 index 0000000000..da8896a072 --- /dev/null +++ b/src/openai/types/chat/chat_completion_role.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing_extensions import Literal + +__all__ = ["ChatCompletionRole"] + +ChatCompletionRole = Literal["system", "user", "assistant", "function"] diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py new file mode 100644 index 0000000000..d681a90cd6 --- /dev/null +++ b/src/openai/types/chat/completion_create_params.py @@ -0,0 +1,194 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Dict, List, Union, Optional +from typing_extensions import Literal, Required, TypedDict + +from .chat_completion_message_param import ChatCompletionMessageParam + +__all__ = [ + "CompletionCreateParamsBase", + "FunctionCall", + "FunctionCallFunctionCallOption", + "Function", + "CompletionCreateParamsNonStreaming", + "CompletionCreateParamsStreaming", +] + + +class CompletionCreateParamsBase(TypedDict, total=False): + messages: Required[List[ChatCompletionMessageParam]] + """A list of messages comprising the conversation so far. + + [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models). + """ + + model: Required[ + Union[ + str, + Literal[ + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0301", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-16k-0613", + ], + ] + ] + """ID of the model to use. + + See the + [model endpoint compatibility](https://platform.openai.com/docs/models/model-endpoint-compatibility) + table for details on which models work with the Chat API. + """ + + frequency_penalty: Optional[float] + """Number between -2.0 and 2.0. + + Positive values penalize new tokens based on their existing frequency in the + text so far, decreasing the model's likelihood to repeat the same line verbatim. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + """ + + function_call: FunctionCall + """Controls how the model calls functions. + + "none" means the model will not call a function and instead generates a message. + "auto" means the model can pick between generating a message or calling a + function. Specifying a particular function via `{"name": "my_function"}` forces + the model to call that function. "none" is the default when no functions are + present. "auto" is the default if functions are present. + """ + + functions: List[Function] + """A list of functions the model may generate JSON inputs for.""" + + logit_bias: Optional[Dict[str, int]] + """Modify the likelihood of specified tokens appearing in the completion. + + Accepts a json object that maps tokens (specified by their token ID in the + tokenizer) to an associated bias value from -100 to 100. Mathematically, the + bias is added to the logits generated by the model prior to sampling. The exact + effect will vary per model, but values between -1 and 1 should decrease or + increase likelihood of selection; values like -100 or 100 should result in a ban + or exclusive selection of the relevant token. + """ + + max_tokens: Optional[int] + """The maximum number of [tokens](/tokenizer) to generate in the chat completion. + + The total length of input tokens and generated tokens is limited by the model's + context length. + [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + for counting tokens. + """ + + n: Optional[int] + """How many chat completion choices to generate for each input message.""" + + presence_penalty: Optional[float] + """Number between -2.0 and 2.0. + + Positive values penalize new tokens based on whether they appear in the text so + far, increasing the model's likelihood to talk about new topics. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + """ + + stop: Union[Optional[str], List[str]] + """Up to 4 sequences where the API will stop generating further tokens.""" + + temperature: Optional[float] + """What sampling temperature to use, between 0 and 2. + + Higher values like 0.8 will make the output more random, while lower values like + 0.2 will make it more focused and deterministic. + + We generally recommend altering this or `top_p` but not both. + """ + + top_p: Optional[float] + """ + An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + """ + + user: str + """ + A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + """ + + +class FunctionCallFunctionCallOption(TypedDict, total=False): + name: Required[str] + """The name of the function to call.""" + + +FunctionCall = Union[Literal["none", "auto"], FunctionCallFunctionCallOption] + + +class Function(TypedDict, total=False): + name: Required[str] + """The name of the function to be called. + + Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length + of 64. + """ + + parameters: Required[Dict[str, object]] + """The parameters the functions accepts, described as a JSON Schema object. + + See the [guide](https://platform.openai.com/docs/guides/gpt/function-calling) + for examples, and the + [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for + documentation about the format. + + To describe a function that accepts no parameters, provide the value + `{"type": "object", "properties": {}}`. + """ + + description: str + """ + A description of what the function does, used by the model to choose when and + how to call the function. + """ + + +class CompletionCreateParamsNonStreaming(CompletionCreateParamsBase): + stream: Optional[Literal[False]] + """If set, partial message deltas will be sent, like in ChatGPT. + + Tokens will be sent as data-only + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available, with the stream terminated by a `data: [DONE]` + message. + [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + """ + + +class CompletionCreateParamsStreaming(CompletionCreateParamsBase): + stream: Required[Literal[True]] + """If set, partial message deltas will be sent, like in ChatGPT. + + Tokens will be sent as data-only + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available, with the stream terminated by a `data: [DONE]` + message. + [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + """ + + +CompletionCreateParams = Union[CompletionCreateParamsNonStreaming, CompletionCreateParamsStreaming] diff --git a/src/openai/types/completion.py b/src/openai/types/completion.py new file mode 100644 index 0000000000..0a90838fd4 --- /dev/null +++ b/src/openai/types/completion.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import List, Optional + +from .._models import BaseModel +from .completion_usage import CompletionUsage +from .completion_choice import CompletionChoice + +__all__ = ["Completion"] + + +class Completion(BaseModel): + id: str + """A unique identifier for the completion.""" + + choices: List[CompletionChoice] + """The list of completion choices the model generated for the input prompt.""" + + created: int + """The Unix timestamp (in seconds) of when the completion was created.""" + + model: str + """The model used for completion.""" + + object: str + """The object type, which is always "text_completion" """ + + usage: Optional[CompletionUsage] = None + """Usage statistics for the completion request.""" diff --git a/src/openai/types/completion_choice.py b/src/openai/types/completion_choice.py new file mode 100644 index 0000000000..e86d706ed1 --- /dev/null +++ b/src/openai/types/completion_choice.py @@ -0,0 +1,35 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Dict, List, Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["CompletionChoice", "Logprobs"] + + +class Logprobs(BaseModel): + text_offset: Optional[List[int]] = None + + token_logprobs: Optional[List[float]] = None + + tokens: Optional[List[str]] = None + + top_logprobs: Optional[List[Dict[str, int]]] = None + + +class CompletionChoice(BaseModel): + finish_reason: Literal["stop", "length", "content_filter"] + """The reason the model stopped generating tokens. + + This will be `stop` if the model hit a natural stop point or a provided stop + sequence, `length` if the maximum number of tokens specified in the request was + reached, or `content_filter` if content was omitted due to a flag from our + content filters. + """ + + index: int + + logprobs: Optional[Logprobs] + + text: str diff --git a/src/openai/types/completion_create_params.py b/src/openai/types/completion_create_params.py new file mode 100644 index 0000000000..023c087d5f --- /dev/null +++ b/src/openai/types/completion_create_params.py @@ -0,0 +1,184 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Dict, List, Union, Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["CompletionCreateParamsBase", "CompletionCreateParamsNonStreaming", "CompletionCreateParamsStreaming"] + + +class CompletionCreateParamsBase(TypedDict, total=False): + model: Required[ + Union[ + str, + Literal[ + "babbage-002", + "davinci-002", + "gpt-3.5-turbo-instruct", + "text-davinci-003", + "text-davinci-002", + "text-davinci-001", + "code-davinci-002", + "text-curie-001", + "text-babbage-001", + "text-ada-001", + ], + ] + ] + """ID of the model to use. + + You can use the + [List models](https://platform.openai.com/docs/api-reference/models/list) API to + see all of your available models, or see our + [Model overview](https://platform.openai.com/docs/models/overview) for + descriptions of them. + """ + + prompt: Required[Union[str, List[str], List[int], List[List[int]], None]] + """ + The prompt(s) to generate completions for, encoded as a string, array of + strings, array of tokens, or array of token arrays. + + Note that <|endoftext|> is the document separator that the model sees during + training, so if a prompt is not specified the model will generate as if from the + beginning of a new document. + """ + + best_of: Optional[int] + """ + Generates `best_of` completions server-side and returns the "best" (the one with + the highest log probability per token). Results cannot be streamed. + + When used with `n`, `best_of` controls the number of candidate completions and + `n` specifies how many to return – `best_of` must be greater than `n`. + + **Note:** Because this parameter generates many completions, it can quickly + consume your token quota. Use carefully and ensure that you have reasonable + settings for `max_tokens` and `stop`. + """ + + echo: Optional[bool] + """Echo back the prompt in addition to the completion""" + + frequency_penalty: Optional[float] + """Number between -2.0 and 2.0. + + Positive values penalize new tokens based on their existing frequency in the + text so far, decreasing the model's likelihood to repeat the same line verbatim. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + """ + + logit_bias: Optional[Dict[str, int]] + """Modify the likelihood of specified tokens appearing in the completion. + + Accepts a json object that maps tokens (specified by their token ID in the GPT + tokenizer) to an associated bias value from -100 to 100. You can use this + [tokenizer tool](/tokenizer?view=bpe) (which works for both GPT-2 and GPT-3) to + convert text to token IDs. Mathematically, the bias is added to the logits + generated by the model prior to sampling. The exact effect will vary per model, + but values between -1 and 1 should decrease or increase likelihood of selection; + values like -100 or 100 should result in a ban or exclusive selection of the + relevant token. + + As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token + from being generated. + """ + + logprobs: Optional[int] + """ + Include the log probabilities on the `logprobs` most likely tokens, as well the + chosen tokens. For example, if `logprobs` is 5, the API will return a list of + the 5 most likely tokens. The API will always return the `logprob` of the + sampled token, so there may be up to `logprobs+1` elements in the response. + + The maximum value for `logprobs` is 5. + """ + + max_tokens: Optional[int] + """The maximum number of [tokens](/tokenizer) to generate in the completion. + + The token count of your prompt plus `max_tokens` cannot exceed the model's + context length. + [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + for counting tokens. + """ + + n: Optional[int] + """How many completions to generate for each prompt. + + **Note:** Because this parameter generates many completions, it can quickly + consume your token quota. Use carefully and ensure that you have reasonable + settings for `max_tokens` and `stop`. + """ + + presence_penalty: Optional[float] + """Number between -2.0 and 2.0. + + Positive values penalize new tokens based on whether they appear in the text so + far, increasing the model's likelihood to talk about new topics. + + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + """ + + stop: Union[Optional[str], List[str], None] + """Up to 4 sequences where the API will stop generating further tokens. + + The returned text will not contain the stop sequence. + """ + + suffix: Optional[str] + """The suffix that comes after a completion of inserted text.""" + + temperature: Optional[float] + """What sampling temperature to use, between 0 and 2. + + Higher values like 0.8 will make the output more random, while lower values like + 0.2 will make it more focused and deterministic. + + We generally recommend altering this or `top_p` but not both. + """ + + top_p: Optional[float] + """ + An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + """ + + user: str + """ + A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + """ + + +class CompletionCreateParamsNonStreaming(CompletionCreateParamsBase): + stream: Optional[Literal[False]] + """Whether to stream back partial progress. + + If set, tokens will be sent as data-only + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available, with the stream terminated by a `data: [DONE]` + message. + [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + """ + + +class CompletionCreateParamsStreaming(CompletionCreateParamsBase): + stream: Required[Literal[True]] + """Whether to stream back partial progress. + + If set, tokens will be sent as data-only + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available, with the stream terminated by a `data: [DONE]` + message. + [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + """ + + +CompletionCreateParams = Union[CompletionCreateParamsNonStreaming, CompletionCreateParamsStreaming] diff --git a/src/openai/types/completion_usage.py b/src/openai/types/completion_usage.py new file mode 100644 index 0000000000..b825d5529f --- /dev/null +++ b/src/openai/types/completion_usage.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. + +from .._models import BaseModel + +__all__ = ["CompletionUsage"] + + +class CompletionUsage(BaseModel): + completion_tokens: int + """Number of tokens in the generated completion.""" + + prompt_tokens: int + """Number of tokens in the prompt.""" + + total_tokens: int + """Total number of tokens used in the request (prompt + completion).""" diff --git a/src/openai/types/create_embedding_response.py b/src/openai/types/create_embedding_response.py new file mode 100644 index 0000000000..eccd148d3c --- /dev/null +++ b/src/openai/types/create_embedding_response.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import List + +from .._models import BaseModel +from .embedding import Embedding + +__all__ = ["CreateEmbeddingResponse", "Usage"] + + +class Usage(BaseModel): + prompt_tokens: int + """The number of tokens used by the prompt.""" + + total_tokens: int + """The total number of tokens used by the request.""" + + +class CreateEmbeddingResponse(BaseModel): + data: List[Embedding] + """The list of embeddings generated by the model.""" + + model: str + """The name of the model used to generate the embedding.""" + + object: str + """The object type, which is always "embedding".""" + + usage: Usage + """The usage information for the request.""" diff --git a/src/openai/types/edit.py b/src/openai/types/edit.py new file mode 100644 index 0000000000..41b327534e --- /dev/null +++ b/src/openai/types/edit.py @@ -0,0 +1,40 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import List +from typing_extensions import Literal + +from .._models import BaseModel +from .completion_usage import CompletionUsage + +__all__ = ["Edit", "Choice"] + + +class Choice(BaseModel): + finish_reason: Literal["stop", "length"] + """The reason the model stopped generating tokens. + + This will be `stop` if the model hit a natural stop point or a provided stop + sequence, `length` if the maximum number of tokens specified in the request was + reached, or `content_filter` if content was omitted due to a flag from our + content filters. + """ + + index: int + """The index of the choice in the list of choices.""" + + text: str + """The edited result.""" + + +class Edit(BaseModel): + choices: List[Choice] + """A list of edit choices. Can be more than one if `n` is greater than 1.""" + + created: int + """The Unix timestamp (in seconds) of when the edit was created.""" + + object: str + """The object type, which is always `edit`.""" + + usage: CompletionUsage + """Usage statistics for the completion request.""" diff --git a/src/openai/types/edit_create_params.py b/src/openai/types/edit_create_params.py new file mode 100644 index 0000000000..a23b79c369 --- /dev/null +++ b/src/openai/types/edit_create_params.py @@ -0,0 +1,44 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Union, Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["EditCreateParams"] + + +class EditCreateParams(TypedDict, total=False): + instruction: Required[str] + """The instruction that tells the model how to edit the prompt.""" + + model: Required[Union[str, Literal["text-davinci-edit-001", "code-davinci-edit-001"]]] + """ID of the model to use. + + You can use the `text-davinci-edit-001` or `code-davinci-edit-001` model with + this endpoint. + """ + + input: Optional[str] + """The input text to use as a starting point for the edit.""" + + n: Optional[int] + """How many edits to generate for the input and instruction.""" + + temperature: Optional[float] + """What sampling temperature to use, between 0 and 2. + + Higher values like 0.8 will make the output more random, while lower values like + 0.2 will make it more focused and deterministic. + + We generally recommend altering this or `top_p` but not both. + """ + + top_p: Optional[float] + """ + An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + """ diff --git a/src/openai/types/embedding.py b/src/openai/types/embedding.py new file mode 100644 index 0000000000..4579b9bb57 --- /dev/null +++ b/src/openai/types/embedding.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import List + +from .._models import BaseModel + +__all__ = ["Embedding"] + + +class Embedding(BaseModel): + embedding: List[float] + """The embedding vector, which is a list of floats. + + The length of vector depends on the model as listed in the + [embedding guide](https://platform.openai.com/docs/guides/embeddings). + """ + + index: int + """The index of the embedding in the list of embeddings.""" + + object: str + """The object type, which is always "embedding".""" diff --git a/src/openai/types/embedding_create_params.py b/src/openai/types/embedding_create_params.py new file mode 100644 index 0000000000..bc8535f880 --- /dev/null +++ b/src/openai/types/embedding_create_params.py @@ -0,0 +1,43 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import List, Union +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["EmbeddingCreateParams"] + + +class EmbeddingCreateParams(TypedDict, total=False): + input: Required[Union[str, List[str], List[int], List[List[int]]]] + """Input text to embed, encoded as a string or array of tokens. + + To embed multiple inputs in a single request, pass an array of strings or array + of token arrays. The input must not exceed the max input tokens for the model + (8192 tokens for `text-embedding-ada-002`) and cannot be an empty string. + [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + for counting tokens. + """ + + model: Required[Union[str, Literal["text-embedding-ada-002"]]] + """ID of the model to use. + + You can use the + [List models](https://platform.openai.com/docs/api-reference/models/list) API to + see all of your available models, or see our + [Model overview](https://platform.openai.com/docs/models/overview) for + descriptions of them. + """ + + encoding_format: Literal["float", "base64"] + """The format to return the embeddings in. + + Can be either `float` or [`base64`](https://pypi.org/project/pybase64/). + """ + + user: str + """ + A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + """ diff --git a/src/openai/types/file_content.py b/src/openai/types/file_content.py new file mode 100644 index 0000000000..92b316b9eb --- /dev/null +++ b/src/openai/types/file_content.py @@ -0,0 +1,6 @@ +# File generated from our OpenAPI spec by Stainless. + + +__all__ = ["FileContent"] + +FileContent = str diff --git a/src/openai/types/file_create_params.py b/src/openai/types/file_create_params.py new file mode 100644 index 0000000000..07b068c5c6 --- /dev/null +++ b/src/openai/types/file_create_params.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +from .._types import FileTypes + +__all__ = ["FileCreateParams"] + + +class FileCreateParams(TypedDict, total=False): + file: Required[FileTypes] + """The file object (not file name) to be uploaded. + + If the `purpose` is set to "fine-tune", the file will be used for fine-tuning. + """ + + purpose: Required[str] + """The intended purpose of the uploaded file. + + Use "fine-tune" for + [fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning). This + allows us to validate the format of the uploaded file is correct for + fine-tuning. + """ diff --git a/src/openai/types/file_deleted.py b/src/openai/types/file_deleted.py new file mode 100644 index 0000000000..a526b2b986 --- /dev/null +++ b/src/openai/types/file_deleted.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. + +from .._models import BaseModel + +__all__ = ["FileDeleted"] + + +class FileDeleted(BaseModel): + id: str + + deleted: bool + + object: str diff --git a/src/openai/types/file_object.py b/src/openai/types/file_object.py new file mode 100644 index 0000000000..dac24a88c5 --- /dev/null +++ b/src/openai/types/file_object.py @@ -0,0 +1,40 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Optional + +from .._models import BaseModel + +__all__ = ["FileObject"] + + +class FileObject(BaseModel): + id: str + """The file identifier, which can be referenced in the API endpoints.""" + + bytes: int + """The size of the file in bytes.""" + + created_at: int + """The Unix timestamp (in seconds) for when the file was created.""" + + filename: str + """The name of the file.""" + + object: str + """The object type, which is always "file".""" + + purpose: str + """The intended purpose of the file. Currently, only "fine-tune" is supported.""" + + status: Optional[str] = None + """ + The current status of the file, which can be either `uploaded`, `processed`, + `pending`, `error`, `deleting` or `deleted`. + """ + + status_details: Optional[str] = None + """Additional details about the status of the file. + + If the file is in the `error` state, this will include a message describing the + error. + """ diff --git a/src/openai/types/fine_tune.py b/src/openai/types/fine_tune.py new file mode 100644 index 0000000000..4124def2f5 --- /dev/null +++ b/src/openai/types/fine_tune.py @@ -0,0 +1,93 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import List, Optional + +from .._models import BaseModel +from .file_object import FileObject +from .fine_tune_event import FineTuneEvent + +__all__ = ["FineTune", "Hyperparams"] + + +class Hyperparams(BaseModel): + batch_size: int + """The batch size to use for training. + + The batch size is the number of training examples used to train a single forward + and backward pass. + """ + + learning_rate_multiplier: float + """The learning rate multiplier to use for training.""" + + n_epochs: int + """The number of epochs to train the model for. + + An epoch refers to one full cycle through the training dataset. + """ + + prompt_loss_weight: float + """The weight to use for loss on the prompt tokens.""" + + classification_n_classes: Optional[int] = None + """The number of classes to use for computing classification metrics.""" + + classification_positive_class: Optional[str] = None + """The positive class to use for computing classification metrics.""" + + compute_classification_metrics: Optional[bool] = None + """ + The classification metrics to compute using the validation dataset at the end of + every epoch. + """ + + +class FineTune(BaseModel): + id: str + """The object identifier, which can be referenced in the API endpoints.""" + + created_at: int + """The Unix timestamp (in seconds) for when the fine-tuning job was created.""" + + fine_tuned_model: Optional[str] + """The name of the fine-tuned model that is being created.""" + + hyperparams: Hyperparams + """The hyperparameters used for the fine-tuning job. + + See the + [fine-tuning guide](https://platform.openai.com/docs/guides/legacy-fine-tuning/hyperparameters) + for more details. + """ + + model: str + """The base model that is being fine-tuned.""" + + object: str + """The object type, which is always "fine-tune".""" + + organization_id: str + """The organization that owns the fine-tuning job.""" + + result_files: List[FileObject] + """The compiled results files for the fine-tuning job.""" + + status: str + """ + The current status of the fine-tuning job, which can be either `created`, + `running`, `succeeded`, `failed`, or `cancelled`. + """ + + training_files: List[FileObject] + """The list of files used for training.""" + + updated_at: int + """The Unix timestamp (in seconds) for when the fine-tuning job was last updated.""" + + validation_files: List[FileObject] + """The list of files used for validation.""" + + events: Optional[List[FineTuneEvent]] = None + """ + The list of events that have been observed in the lifecycle of the FineTune job. + """ diff --git a/src/openai/types/fine_tune_create_params.py b/src/openai/types/fine_tune_create_params.py new file mode 100644 index 0000000000..1be9c9ea04 --- /dev/null +++ b/src/openai/types/fine_tune_create_params.py @@ -0,0 +1,140 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import List, Union, Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["FineTuneCreateParams", "Hyperparameters"] + + +class FineTuneCreateParams(TypedDict, total=False): + training_file: Required[str] + """The ID of an uploaded file that contains training data. + + See [upload file](https://platform.openai.com/docs/api-reference/files/upload) + for how to upload a file. + + Your dataset must be formatted as a JSONL file, where each training example is a + JSON object with the keys "prompt" and "completion". Additionally, you must + upload your file with the purpose `fine-tune`. + + See the + [fine-tuning guide](https://platform.openai.com/docs/guides/legacy-fine-tuning/creating-training-data) + for more details. + """ + + batch_size: Optional[int] + """The batch size to use for training. + + The batch size is the number of training examples used to train a single forward + and backward pass. + + By default, the batch size will be dynamically configured to be ~0.2% of the + number of examples in the training set, capped at 256 - in general, we've found + that larger batch sizes tend to work better for larger datasets. + """ + + classification_betas: Optional[List[float]] + """If this is provided, we calculate F-beta scores at the specified beta values. + + The F-beta score is a generalization of F-1 score. This is only used for binary + classification. + + With a beta of 1 (i.e. the F-1 score), precision and recall are given the same + weight. A larger beta score puts more weight on recall and less on precision. A + smaller beta score puts more weight on precision and less on recall. + """ + + classification_n_classes: Optional[int] + """The number of classes in a classification task. + + This parameter is required for multiclass classification. + """ + + classification_positive_class: Optional[str] + """The positive class in binary classification. + + This parameter is needed to generate precision, recall, and F1 metrics when + doing binary classification. + """ + + compute_classification_metrics: Optional[bool] + """ + If set, we calculate classification-specific metrics such as accuracy and F-1 + score using the validation set at the end of every epoch. These metrics can be + viewed in the + [results file](https://platform.openai.com/docs/guides/legacy-fine-tuning/analyzing-your-fine-tuned-model). + + In order to compute classification metrics, you must provide a + `validation_file`. Additionally, you must specify `classification_n_classes` for + multiclass classification or `classification_positive_class` for binary + classification. + """ + + hyperparameters: Hyperparameters + """The hyperparameters used for the fine-tuning job.""" + + learning_rate_multiplier: Optional[float] + """ + The learning rate multiplier to use for training. The fine-tuning learning rate + is the original learning rate used for pretraining multiplied by this value. + + By default, the learning rate multiplier is the 0.05, 0.1, or 0.2 depending on + final `batch_size` (larger learning rates tend to perform better with larger + batch sizes). We recommend experimenting with values in the range 0.02 to 0.2 to + see what produces the best results. + """ + + model: Union[str, Literal["ada", "babbage", "curie", "davinci"], None] + """The name of the base model to fine-tune. + + You can select one of "ada", "babbage", "curie", "davinci", or a fine-tuned + model created after 2022-04-21 and before 2023-08-22. To learn more about these + models, see the [Models](https://platform.openai.com/docs/models) documentation. + """ + + prompt_loss_weight: Optional[float] + """The weight to use for loss on the prompt tokens. + + This controls how much the model tries to learn to generate the prompt (as + compared to the completion which always has a weight of 1.0), and can add a + stabilizing effect to training when completions are short. + + If prompts are extremely long (relative to completions), it may make sense to + reduce this weight so as to avoid over-prioritizing learning the prompt. + """ + + suffix: Optional[str] + """ + A string of up to 40 characters that will be added to your fine-tuned model + name. + + For example, a `suffix` of "custom-model-name" would produce a model name like + `ada:ft-your-org:custom-model-name-2022-02-15-04-21-04`. + """ + + validation_file: Optional[str] + """The ID of an uploaded file that contains validation data. + + If you provide this file, the data is used to generate validation metrics + periodically during fine-tuning. These metrics can be viewed in the + [fine-tuning results file](https://platform.openai.com/docs/guides/legacy-fine-tuning/analyzing-your-fine-tuned-model). + Your train and validation data should be mutually exclusive. + + Your dataset must be formatted as a JSONL file, where each validation example is + a JSON object with the keys "prompt" and "completion". Additionally, you must + upload your file with the purpose `fine-tune`. + + See the + [fine-tuning guide](https://platform.openai.com/docs/guides/legacy-fine-tuning/creating-training-data) + for more details. + """ + + +class Hyperparameters(TypedDict, total=False): + n_epochs: Union[Literal["auto"], int] + """The number of epochs to train the model for. + + An epoch refers to one full cycle through the training dataset. + """ diff --git a/src/openai/types/fine_tune_event.py b/src/openai/types/fine_tune_event.py new file mode 100644 index 0000000000..6499def98d --- /dev/null +++ b/src/openai/types/fine_tune_event.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. + +from .._models import BaseModel + +__all__ = ["FineTuneEvent"] + + +class FineTuneEvent(BaseModel): + created_at: int + + level: str + + message: str + + object: str diff --git a/src/openai/types/fine_tune_events_list_response.py b/src/openai/types/fine_tune_events_list_response.py new file mode 100644 index 0000000000..ca159d8772 --- /dev/null +++ b/src/openai/types/fine_tune_events_list_response.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import List + +from .._models import BaseModel +from .fine_tune_event import FineTuneEvent + +__all__ = ["FineTuneEventsListResponse"] + + +class FineTuneEventsListResponse(BaseModel): + data: List[FineTuneEvent] + + object: str diff --git a/src/openai/types/fine_tune_list_events_params.py b/src/openai/types/fine_tune_list_events_params.py new file mode 100644 index 0000000000..1f23b108e6 --- /dev/null +++ b/src/openai/types/fine_tune_list_events_params.py @@ -0,0 +1,41 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["FineTuneListEventsParamsBase", "FineTuneListEventsParamsNonStreaming", "FineTuneListEventsParamsStreaming"] + + +class FineTuneListEventsParamsBase(TypedDict, total=False): + pass + + +class FineTuneListEventsParamsNonStreaming(FineTuneListEventsParamsBase): + stream: Literal[False] + """Whether to stream events for the fine-tune job. + + If set to true, events will be sent as data-only + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available. The stream will terminate with a `data: [DONE]` + message when the job is finished (succeeded, cancelled, or failed). + + If set to false, only events generated so far will be returned. + """ + + +class FineTuneListEventsParamsStreaming(FineTuneListEventsParamsBase): + stream: Required[Literal[True]] + """Whether to stream events for the fine-tune job. + + If set to true, events will be sent as data-only + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available. The stream will terminate with a `data: [DONE]` + message when the job is finished (succeeded, cancelled, or failed). + + If set to false, only events generated so far will be returned. + """ + + +FineTuneListEventsParams = Union[FineTuneListEventsParamsNonStreaming, FineTuneListEventsParamsStreaming] diff --git a/src/openai/types/fine_tuning/__init__.py b/src/openai/types/fine_tuning/__init__.py new file mode 100644 index 0000000000..d24160c5bd --- /dev/null +++ b/src/openai/types/fine_tuning/__init__.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from .fine_tuning_job import FineTuningJob as FineTuningJob +from .job_list_params import JobListParams as JobListParams +from .job_create_params import JobCreateParams as JobCreateParams +from .fine_tuning_job_event import FineTuningJobEvent as FineTuningJobEvent +from .job_list_events_params import JobListEventsParams as JobListEventsParams diff --git a/src/openai/types/fine_tuning/fine_tuning_job.py b/src/openai/types/fine_tuning/fine_tuning_job.py new file mode 100644 index 0000000000..2ae1cbb473 --- /dev/null +++ b/src/openai/types/fine_tuning/fine_tuning_job.py @@ -0,0 +1,107 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import List, Union, Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["FineTuningJob", "Error", "Hyperparameters"] + + +class Error(BaseModel): + code: str + """A machine-readable error code.""" + + message: str + """A human-readable error message.""" + + param: Optional[str] + """The parameter that was invalid, usually `training_file` or `validation_file`. + + This field will be null if the failure was not parameter-specific. + """ + + +class Hyperparameters(BaseModel): + n_epochs: Union[Literal["auto"], int] + """The number of epochs to train the model for. + + An epoch refers to one full cycle through the training dataset. "auto" decides + the optimal number of epochs based on the size of the dataset. If setting the + number manually, we support any number between 1 and 50 epochs. + """ + + +class FineTuningJob(BaseModel): + id: str + """The object identifier, which can be referenced in the API endpoints.""" + + created_at: int + """The Unix timestamp (in seconds) for when the fine-tuning job was created.""" + + error: Optional[Error] + """ + For fine-tuning jobs that have `failed`, this will contain more information on + the cause of the failure. + """ + + fine_tuned_model: Optional[str] + """The name of the fine-tuned model that is being created. + + The value will be null if the fine-tuning job is still running. + """ + + finished_at: Optional[int] + """The Unix timestamp (in seconds) for when the fine-tuning job was finished. + + The value will be null if the fine-tuning job is still running. + """ + + hyperparameters: Hyperparameters + """The hyperparameters used for the fine-tuning job. + + See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) + for more details. + """ + + model: str + """The base model that is being fine-tuned.""" + + object: str + """The object type, which is always "fine_tuning.job".""" + + organization_id: str + """The organization that owns the fine-tuning job.""" + + result_files: List[str] + """The compiled results file ID(s) for the fine-tuning job. + + You can retrieve the results with the + [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + """ + + status: str + """ + The current status of the fine-tuning job, which can be either + `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`. + """ + + trained_tokens: Optional[int] + """The total number of billable tokens processed by this fine-tuning job. + + The value will be null if the fine-tuning job is still running. + """ + + training_file: str + """The file ID used for training. + + You can retrieve the training data with the + [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + """ + + validation_file: Optional[str] + """The file ID used for validation. + + You can retrieve the validation results with the + [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). + """ diff --git a/src/openai/types/fine_tuning/fine_tuning_job_event.py b/src/openai/types/fine_tuning/fine_tuning_job_event.py new file mode 100644 index 0000000000..c21a0503ab --- /dev/null +++ b/src/openai/types/fine_tuning/fine_tuning_job_event.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["FineTuningJobEvent"] + + +class FineTuningJobEvent(BaseModel): + id: str + + created_at: int + + level: Literal["info", "warn", "error"] + + message: str + + object: str diff --git a/src/openai/types/fine_tuning/job_create_params.py b/src/openai/types/fine_tuning/job_create_params.py new file mode 100644 index 0000000000..2a67b81817 --- /dev/null +++ b/src/openai/types/fine_tuning/job_create_params.py @@ -0,0 +1,65 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Union, Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["JobCreateParams", "Hyperparameters"] + + +class JobCreateParams(TypedDict, total=False): + model: Required[Union[str, Literal["babbage-002", "davinci-002", "gpt-3.5-turbo"]]] + """The name of the model to fine-tune. + + You can select one of the + [supported models](https://platform.openai.com/docs/guides/fine-tuning/what-models-can-be-fine-tuned). + """ + + training_file: Required[str] + """The ID of an uploaded file that contains training data. + + See [upload file](https://platform.openai.com/docs/api-reference/files/upload) + for how to upload a file. + + Your dataset must be formatted as a JSONL file. Additionally, you must upload + your file with the purpose `fine-tune`. + + See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) + for more details. + """ + + hyperparameters: Hyperparameters + """The hyperparameters used for the fine-tuning job.""" + + suffix: Optional[str] + """ + A string of up to 18 characters that will be added to your fine-tuned model + name. + + For example, a `suffix` of "custom-model-name" would produce a model name like + `ft:gpt-3.5-turbo:openai:custom-model-name:7p4lURel`. + """ + + validation_file: Optional[str] + """The ID of an uploaded file that contains validation data. + + If you provide this file, the data is used to generate validation metrics + periodically during fine-tuning. These metrics can be viewed in the fine-tuning + results file. The same data should not be present in both train and validation + files. + + Your dataset must be formatted as a JSONL file. You must upload your file with + the purpose `fine-tune`. + + See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) + for more details. + """ + + +class Hyperparameters(TypedDict, total=False): + n_epochs: Union[Literal["auto"], int] + """The number of epochs to train the model for. + + An epoch refers to one full cycle through the training dataset. + """ diff --git a/src/openai/types/fine_tuning/job_list_events_params.py b/src/openai/types/fine_tuning/job_list_events_params.py new file mode 100644 index 0000000000..7be3d53315 --- /dev/null +++ b/src/openai/types/fine_tuning/job_list_events_params.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["JobListEventsParams"] + + +class JobListEventsParams(TypedDict, total=False): + after: str + """Identifier for the last event from the previous pagination request.""" + + limit: int + """Number of events to retrieve.""" diff --git a/src/openai/types/fine_tuning/job_list_params.py b/src/openai/types/fine_tuning/job_list_params.py new file mode 100644 index 0000000000..8160136901 --- /dev/null +++ b/src/openai/types/fine_tuning/job_list_params.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["JobListParams"] + + +class JobListParams(TypedDict, total=False): + after: str + """Identifier for the last job from the previous pagination request.""" + + limit: int + """Number of fine-tuning jobs to retrieve.""" diff --git a/src/openai/types/image.py b/src/openai/types/image.py new file mode 100644 index 0000000000..4b8d1aaf18 --- /dev/null +++ b/src/openai/types/image.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Optional + +from .._models import BaseModel + +__all__ = ["Image"] + + +class Image(BaseModel): + b64_json: Optional[str] = None + """ + The base64-encoded JSON of the generated image, if `response_format` is + `b64_json`. + """ + + url: Optional[str] = None + """The URL of the generated image, if `response_format` is `url` (default).""" diff --git a/src/openai/types/image_create_variation_params.py b/src/openai/types/image_create_variation_params.py new file mode 100644 index 0000000000..d3b439070e --- /dev/null +++ b/src/openai/types/image_create_variation_params.py @@ -0,0 +1,40 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +from .._types import FileTypes + +__all__ = ["ImageCreateVariationParams"] + + +class ImageCreateVariationParams(TypedDict, total=False): + image: Required[FileTypes] + """The image to use as the basis for the variation(s). + + Must be a valid PNG file, less than 4MB, and square. + """ + + n: Optional[int] + """The number of images to generate. Must be between 1 and 10.""" + + response_format: Optional[Literal["url", "b64_json"]] + """The format in which the generated images are returned. + + Must be one of `url` or `b64_json`. + """ + + size: Optional[Literal["256x256", "512x512", "1024x1024"]] + """The size of the generated images. + + Must be one of `256x256`, `512x512`, or `1024x1024`. + """ + + user: str + """ + A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + """ diff --git a/src/openai/types/image_edit_params.py b/src/openai/types/image_edit_params.py new file mode 100644 index 0000000000..ce07a9cb30 --- /dev/null +++ b/src/openai/types/image_edit_params.py @@ -0,0 +1,54 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +from .._types import FileTypes + +__all__ = ["ImageEditParams"] + + +class ImageEditParams(TypedDict, total=False): + image: Required[FileTypes] + """The image to edit. + + Must be a valid PNG file, less than 4MB, and square. If mask is not provided, + image must have transparency, which will be used as the mask. + """ + + prompt: Required[str] + """A text description of the desired image(s). + + The maximum length is 1000 characters. + """ + + mask: FileTypes + """An additional image whose fully transparent areas (e.g. + + where alpha is zero) indicate where `image` should be edited. Must be a valid + PNG file, less than 4MB, and have the same dimensions as `image`. + """ + + n: Optional[int] + """The number of images to generate. Must be between 1 and 10.""" + + response_format: Optional[Literal["url", "b64_json"]] + """The format in which the generated images are returned. + + Must be one of `url` or `b64_json`. + """ + + size: Optional[Literal["256x256", "512x512", "1024x1024"]] + """The size of the generated images. + + Must be one of `256x256`, `512x512`, or `1024x1024`. + """ + + user: str + """ + A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + """ diff --git a/src/openai/types/image_generate_params.py b/src/openai/types/image_generate_params.py new file mode 100644 index 0000000000..4999ed958d --- /dev/null +++ b/src/openai/types/image_generate_params.py @@ -0,0 +1,38 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ImageGenerateParams"] + + +class ImageGenerateParams(TypedDict, total=False): + prompt: Required[str] + """A text description of the desired image(s). + + The maximum length is 1000 characters. + """ + + n: Optional[int] + """The number of images to generate. Must be between 1 and 10.""" + + response_format: Optional[Literal["url", "b64_json"]] + """The format in which the generated images are returned. + + Must be one of `url` or `b64_json`. + """ + + size: Optional[Literal["256x256", "512x512", "1024x1024"]] + """The size of the generated images. + + Must be one of `256x256`, `512x512`, or `1024x1024`. + """ + + user: str + """ + A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + """ diff --git a/src/openai/types/images_response.py b/src/openai/types/images_response.py new file mode 100644 index 0000000000..9d1bc95a42 --- /dev/null +++ b/src/openai/types/images_response.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import List + +from .image import Image +from .._models import BaseModel + +__all__ = ["ImagesResponse"] + + +class ImagesResponse(BaseModel): + created: int + + data: List[Image] diff --git a/src/openai/types/model.py b/src/openai/types/model.py new file mode 100644 index 0000000000..29e71b81a0 --- /dev/null +++ b/src/openai/types/model.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. + +from .._models import BaseModel + +__all__ = ["Model"] + + +class Model(BaseModel): + id: str + """The model identifier, which can be referenced in the API endpoints.""" + + created: int + """The Unix timestamp (in seconds) when the model was created.""" + + object: str + """The object type, which is always "model".""" + + owned_by: str + """The organization that owns the model.""" diff --git a/src/openai/types/model_deleted.py b/src/openai/types/model_deleted.py new file mode 100644 index 0000000000..5329da1378 --- /dev/null +++ b/src/openai/types/model_deleted.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. + +from .._models import BaseModel + +__all__ = ["ModelDeleted"] + + +class ModelDeleted(BaseModel): + id: str + + deleted: bool + + object: str diff --git a/src/openai/types/moderation.py b/src/openai/types/moderation.py new file mode 100644 index 0000000000..bf586fc24a --- /dev/null +++ b/src/openai/types/moderation.py @@ -0,0 +1,120 @@ +# File generated from our OpenAPI spec by Stainless. + +from pydantic import Field as FieldInfo + +from .._models import BaseModel + +__all__ = ["Moderation", "Categories", "CategoryScores"] + + +class Categories(BaseModel): + harassment: bool + """ + Content that expresses, incites, or promotes harassing language towards any + target. + """ + + harassment_threatening: bool = FieldInfo(alias="harassment/threatening") + """ + Harassment content that also includes violence or serious harm towards any + target. + """ + + hate: bool + """ + Content that expresses, incites, or promotes hate based on race, gender, + ethnicity, religion, nationality, sexual orientation, disability status, or + caste. Hateful content aimed at non-protected groups (e.g., chess players) is + harrassment. + """ + + hate_threatening: bool = FieldInfo(alias="hate/threatening") + """ + Hateful content that also includes violence or serious harm towards the targeted + group based on race, gender, ethnicity, religion, nationality, sexual + orientation, disability status, or caste. + """ + + self_minus_harm: bool = FieldInfo(alias="self-harm") + """ + Content that promotes, encourages, or depicts acts of self-harm, such as + suicide, cutting, and eating disorders. + """ + + self_minus_harm_instructions: bool = FieldInfo(alias="self-harm/instructions") + """ + Content that encourages performing acts of self-harm, such as suicide, cutting, + and eating disorders, or that gives instructions or advice on how to commit such + acts. + """ + + self_minus_harm_intent: bool = FieldInfo(alias="self-harm/intent") + """ + Content where the speaker expresses that they are engaging or intend to engage + in acts of self-harm, such as suicide, cutting, and eating disorders. + """ + + sexual: bool + """ + Content meant to arouse sexual excitement, such as the description of sexual + activity, or that promotes sexual services (excluding sex education and + wellness). + """ + + sexual_minors: bool = FieldInfo(alias="sexual/minors") + """Sexual content that includes an individual who is under 18 years old.""" + + violence: bool + """Content that depicts death, violence, or physical injury.""" + + violence_graphic: bool = FieldInfo(alias="violence/graphic") + """Content that depicts death, violence, or physical injury in graphic detail.""" + + +class CategoryScores(BaseModel): + harassment: float + """The score for the category 'harassment'.""" + + harassment_threatening: float = FieldInfo(alias="harassment/threatening") + """The score for the category 'harassment/threatening'.""" + + hate: float + """The score for the category 'hate'.""" + + hate_threatening: float = FieldInfo(alias="hate/threatening") + """The score for the category 'hate/threatening'.""" + + self_minus_harm: float = FieldInfo(alias="self-harm") + """The score for the category 'self-harm'.""" + + self_minus_harm_instructions: float = FieldInfo(alias="self-harm/instructions") + """The score for the category 'self-harm/instructions'.""" + + self_minus_harm_intent: float = FieldInfo(alias="self-harm/intent") + """The score for the category 'self-harm/intent'.""" + + sexual: float + """The score for the category 'sexual'.""" + + sexual_minors: float = FieldInfo(alias="sexual/minors") + """The score for the category 'sexual/minors'.""" + + violence: float + """The score for the category 'violence'.""" + + violence_graphic: float = FieldInfo(alias="violence/graphic") + """The score for the category 'violence/graphic'.""" + + +class Moderation(BaseModel): + categories: Categories + """A list of the categories, and whether they are flagged or not.""" + + category_scores: CategoryScores + """A list of the categories along with their scores as predicted by model.""" + + flagged: bool + """ + Whether the content violates + [OpenAI's usage policies](/policies/usage-policies). + """ diff --git a/src/openai/types/moderation_create_params.py b/src/openai/types/moderation_create_params.py new file mode 100644 index 0000000000..25ed3ce940 --- /dev/null +++ b/src/openai/types/moderation_create_params.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import List, Union +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ModerationCreateParams"] + + +class ModerationCreateParams(TypedDict, total=False): + input: Required[Union[str, List[str]]] + """The input text to classify""" + + model: Union[str, Literal["text-moderation-latest", "text-moderation-stable"]] + """ + Two content moderations models are available: `text-moderation-stable` and + `text-moderation-latest`. + + The default is `text-moderation-latest` which will be automatically upgraded + over time. This ensures you are always using our most accurate model. If you use + `text-moderation-stable`, we will provide advanced notice before updating the + model. Accuracy of `text-moderation-stable` may be slightly lower than for + `text-moderation-latest`. + """ diff --git a/src/openai/types/moderation_create_response.py b/src/openai/types/moderation_create_response.py new file mode 100644 index 0000000000..0962cdbfd9 --- /dev/null +++ b/src/openai/types/moderation_create_response.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import List + +from .._models import BaseModel +from .moderation import Moderation + +__all__ = ["ModerationCreateResponse"] + + +class ModerationCreateResponse(BaseModel): + id: str + """The unique identifier for the moderation request.""" + + model: str + """The model used to generate the moderation results.""" + + results: List[Moderation] + """A list of moderation objects.""" diff --git a/src/openai/version.py b/src/openai/version.py new file mode 100644 index 0000000000..01a08ab5a9 --- /dev/null +++ b/src/openai/version.py @@ -0,0 +1,3 @@ +from ._version import __version__ + +VERSION: str = __version__ diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000000..1016754ef3 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. diff --git a/tests/api_resources/__init__.py b/tests/api_resources/__init__.py new file mode 100644 index 0000000000..1016754ef3 --- /dev/null +++ b/tests/api_resources/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. diff --git a/tests/api_resources/audio/__init__.py b/tests/api_resources/audio/__init__.py new file mode 100644 index 0000000000..1016754ef3 --- /dev/null +++ b/tests/api_resources/audio/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. diff --git a/tests/api_resources/audio/test_transcriptions.py b/tests/api_resources/audio/test_transcriptions.py new file mode 100644 index 0000000000..aefdf1790f --- /dev/null +++ b/tests/api_resources/audio/test_transcriptions.py @@ -0,0 +1,87 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import os + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai._client import OpenAI, AsyncOpenAI +from openai.types.audio import Transcription + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") +api_key = "My API Key" + + +class TestTranscriptions: + strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + def test_method_create(self, client: OpenAI) -> None: + transcription = client.audio.transcriptions.create( + file=b"raw file contents", + model="whisper-1", + ) + assert_matches_type(Transcription, transcription, path=["response"]) + + @parametrize + def test_method_create_with_all_params(self, client: OpenAI) -> None: + transcription = client.audio.transcriptions.create( + file=b"raw file contents", + model="whisper-1", + language="string", + prompt="string", + response_format="json", + temperature=0, + ) + assert_matches_type(Transcription, transcription, path=["response"]) + + @parametrize + def test_raw_response_create(self, client: OpenAI) -> None: + response = client.audio.transcriptions.with_raw_response.create( + file=b"raw file contents", + model="whisper-1", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + transcription = response.parse() + assert_matches_type(Transcription, transcription, path=["response"]) + + +class TestAsyncTranscriptions: + strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + async def test_method_create(self, client: AsyncOpenAI) -> None: + transcription = await client.audio.transcriptions.create( + file=b"raw file contents", + model="whisper-1", + ) + assert_matches_type(Transcription, transcription, path=["response"]) + + @parametrize + async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: + transcription = await client.audio.transcriptions.create( + file=b"raw file contents", + model="whisper-1", + language="string", + prompt="string", + response_format="json", + temperature=0, + ) + assert_matches_type(Transcription, transcription, path=["response"]) + + @parametrize + async def test_raw_response_create(self, client: AsyncOpenAI) -> None: + response = await client.audio.transcriptions.with_raw_response.create( + file=b"raw file contents", + model="whisper-1", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + transcription = response.parse() + assert_matches_type(Transcription, transcription, path=["response"]) diff --git a/tests/api_resources/audio/test_translations.py b/tests/api_resources/audio/test_translations.py new file mode 100644 index 0000000000..0657e80eb8 --- /dev/null +++ b/tests/api_resources/audio/test_translations.py @@ -0,0 +1,85 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import os + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai._client import OpenAI, AsyncOpenAI +from openai.types.audio import Translation + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") +api_key = "My API Key" + + +class TestTranslations: + strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + def test_method_create(self, client: OpenAI) -> None: + translation = client.audio.translations.create( + file=b"raw file contents", + model="whisper-1", + ) + assert_matches_type(Translation, translation, path=["response"]) + + @parametrize + def test_method_create_with_all_params(self, client: OpenAI) -> None: + translation = client.audio.translations.create( + file=b"raw file contents", + model="whisper-1", + prompt="string", + response_format="string", + temperature=0, + ) + assert_matches_type(Translation, translation, path=["response"]) + + @parametrize + def test_raw_response_create(self, client: OpenAI) -> None: + response = client.audio.translations.with_raw_response.create( + file=b"raw file contents", + model="whisper-1", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + translation = response.parse() + assert_matches_type(Translation, translation, path=["response"]) + + +class TestAsyncTranslations: + strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + async def test_method_create(self, client: AsyncOpenAI) -> None: + translation = await client.audio.translations.create( + file=b"raw file contents", + model="whisper-1", + ) + assert_matches_type(Translation, translation, path=["response"]) + + @parametrize + async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: + translation = await client.audio.translations.create( + file=b"raw file contents", + model="whisper-1", + prompt="string", + response_format="string", + temperature=0, + ) + assert_matches_type(Translation, translation, path=["response"]) + + @parametrize + async def test_raw_response_create(self, client: AsyncOpenAI) -> None: + response = await client.audio.translations.with_raw_response.create( + file=b"raw file contents", + model="whisper-1", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + translation = response.parse() + assert_matches_type(Translation, translation, path=["response"]) diff --git a/tests/api_resources/chat/__init__.py b/tests/api_resources/chat/__init__.py new file mode 100644 index 0000000000..1016754ef3 --- /dev/null +++ b/tests/api_resources/chat/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py new file mode 100644 index 0000000000..dacf5d2596 --- /dev/null +++ b/tests/api_resources/chat/test_completions.py @@ -0,0 +1,281 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import os + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai._client import OpenAI, AsyncOpenAI +from openai.types.chat import ChatCompletion + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") +api_key = "My API Key" + + +class TestCompletions: + strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + def test_method_create_overload_1(self, client: OpenAI) -> None: + completion = client.chat.completions.create( + messages=[ + { + "content": "string", + "role": "system", + } + ], + model="gpt-3.5-turbo", + ) + assert_matches_type(ChatCompletion, completion, path=["response"]) + + @parametrize + def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: + completion = client.chat.completions.create( + messages=[ + { + "content": "string", + "function_call": { + "arguments": "string", + "name": "string", + }, + "name": "string", + "role": "system", + } + ], + model="gpt-3.5-turbo", + frequency_penalty=-2, + function_call="none", + functions=[ + { + "description": "string", + "name": "string", + "parameters": {"foo": "bar"}, + } + ], + logit_bias={"foo": 0}, + max_tokens=0, + n=1, + presence_penalty=-2, + stop="string", + stream=False, + temperature=1, + top_p=1, + user="user-1234", + ) + assert_matches_type(ChatCompletion, completion, path=["response"]) + + @parametrize + def test_raw_response_create_overload_1(self, client: OpenAI) -> None: + response = client.chat.completions.with_raw_response.create( + messages=[ + { + "content": "string", + "role": "system", + } + ], + model="gpt-3.5-turbo", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + completion = response.parse() + assert_matches_type(ChatCompletion, completion, path=["response"]) + + @parametrize + def test_method_create_overload_2(self, client: OpenAI) -> None: + client.chat.completions.create( + messages=[ + { + "content": "string", + "role": "system", + } + ], + model="gpt-3.5-turbo", + stream=True, + ) + + @parametrize + def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: + client.chat.completions.create( + messages=[ + { + "content": "string", + "function_call": { + "arguments": "string", + "name": "string", + }, + "name": "string", + "role": "system", + } + ], + model="gpt-3.5-turbo", + stream=True, + frequency_penalty=-2, + function_call="none", + functions=[ + { + "description": "string", + "name": "string", + "parameters": {"foo": "bar"}, + } + ], + logit_bias={"foo": 0}, + max_tokens=0, + n=1, + presence_penalty=-2, + stop="string", + temperature=1, + top_p=1, + user="user-1234", + ) + + @parametrize + def test_raw_response_create_overload_2(self, client: OpenAI) -> None: + response = client.chat.completions.with_raw_response.create( + messages=[ + { + "content": "string", + "role": "system", + } + ], + model="gpt-3.5-turbo", + stream=True, + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + response.parse() + + +class TestAsyncCompletions: + strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + async def test_method_create_overload_1(self, client: AsyncOpenAI) -> None: + completion = await client.chat.completions.create( + messages=[ + { + "content": "string", + "role": "system", + } + ], + model="gpt-3.5-turbo", + ) + assert_matches_type(ChatCompletion, completion, path=["response"]) + + @parametrize + async def test_method_create_with_all_params_overload_1(self, client: AsyncOpenAI) -> None: + completion = await client.chat.completions.create( + messages=[ + { + "content": "string", + "function_call": { + "arguments": "string", + "name": "string", + }, + "name": "string", + "role": "system", + } + ], + model="gpt-3.5-turbo", + frequency_penalty=-2, + function_call="none", + functions=[ + { + "description": "string", + "name": "string", + "parameters": {"foo": "bar"}, + } + ], + logit_bias={"foo": 0}, + max_tokens=0, + n=1, + presence_penalty=-2, + stop="string", + stream=False, + temperature=1, + top_p=1, + user="user-1234", + ) + assert_matches_type(ChatCompletion, completion, path=["response"]) + + @parametrize + async def test_raw_response_create_overload_1(self, client: AsyncOpenAI) -> None: + response = await client.chat.completions.with_raw_response.create( + messages=[ + { + "content": "string", + "role": "system", + } + ], + model="gpt-3.5-turbo", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + completion = response.parse() + assert_matches_type(ChatCompletion, completion, path=["response"]) + + @parametrize + async def test_method_create_overload_2(self, client: AsyncOpenAI) -> None: + await client.chat.completions.create( + messages=[ + { + "content": "string", + "role": "system", + } + ], + model="gpt-3.5-turbo", + stream=True, + ) + + @parametrize + async def test_method_create_with_all_params_overload_2(self, client: AsyncOpenAI) -> None: + await client.chat.completions.create( + messages=[ + { + "content": "string", + "function_call": { + "arguments": "string", + "name": "string", + }, + "name": "string", + "role": "system", + } + ], + model="gpt-3.5-turbo", + stream=True, + frequency_penalty=-2, + function_call="none", + functions=[ + { + "description": "string", + "name": "string", + "parameters": {"foo": "bar"}, + } + ], + logit_bias={"foo": 0}, + max_tokens=0, + n=1, + presence_penalty=-2, + stop="string", + temperature=1, + top_p=1, + user="user-1234", + ) + + @parametrize + async def test_raw_response_create_overload_2(self, client: AsyncOpenAI) -> None: + response = await client.chat.completions.with_raw_response.create( + messages=[ + { + "content": "string", + "role": "system", + } + ], + model="gpt-3.5-turbo", + stream=True, + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + response.parse() diff --git a/tests/api_resources/fine_tuning/__init__.py b/tests/api_resources/fine_tuning/__init__.py new file mode 100644 index 0000000000..1016754ef3 --- /dev/null +++ b/tests/api_resources/fine_tuning/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. diff --git a/tests/api_resources/fine_tuning/test_jobs.py b/tests/api_resources/fine_tuning/test_jobs.py new file mode 100644 index 0000000000..9defcadab6 --- /dev/null +++ b/tests/api_resources/fine_tuning/test_jobs.py @@ -0,0 +1,240 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import os + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai._client import OpenAI, AsyncOpenAI +from openai.pagination import SyncCursorPage, AsyncCursorPage +from openai.types.fine_tuning import FineTuningJob, FineTuningJobEvent + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") +api_key = "My API Key" + + +class TestJobs: + strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + def test_method_create(self, client: OpenAI) -> None: + job = client.fine_tuning.jobs.create( + model="gpt-3.5-turbo", + training_file="file-abc123", + ) + assert_matches_type(FineTuningJob, job, path=["response"]) + + @parametrize + def test_method_create_with_all_params(self, client: OpenAI) -> None: + job = client.fine_tuning.jobs.create( + model="gpt-3.5-turbo", + training_file="file-abc123", + hyperparameters={"n_epochs": "auto"}, + suffix="x", + validation_file="file-abc123", + ) + assert_matches_type(FineTuningJob, job, path=["response"]) + + @parametrize + def test_raw_response_create(self, client: OpenAI) -> None: + response = client.fine_tuning.jobs.with_raw_response.create( + model="gpt-3.5-turbo", + training_file="file-abc123", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + job = response.parse() + assert_matches_type(FineTuningJob, job, path=["response"]) + + @parametrize + def test_method_retrieve(self, client: OpenAI) -> None: + job = client.fine_tuning.jobs.retrieve( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert_matches_type(FineTuningJob, job, path=["response"]) + + @parametrize + def test_raw_response_retrieve(self, client: OpenAI) -> None: + response = client.fine_tuning.jobs.with_raw_response.retrieve( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + job = response.parse() + assert_matches_type(FineTuningJob, job, path=["response"]) + + @parametrize + def test_method_list(self, client: OpenAI) -> None: + job = client.fine_tuning.jobs.list() + assert_matches_type(SyncCursorPage[FineTuningJob], job, path=["response"]) + + @parametrize + def test_method_list_with_all_params(self, client: OpenAI) -> None: + job = client.fine_tuning.jobs.list( + after="string", + limit=0, + ) + assert_matches_type(SyncCursorPage[FineTuningJob], job, path=["response"]) + + @parametrize + def test_raw_response_list(self, client: OpenAI) -> None: + response = client.fine_tuning.jobs.with_raw_response.list() + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + job = response.parse() + assert_matches_type(SyncCursorPage[FineTuningJob], job, path=["response"]) + + @parametrize + def test_method_cancel(self, client: OpenAI) -> None: + job = client.fine_tuning.jobs.cancel( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert_matches_type(FineTuningJob, job, path=["response"]) + + @parametrize + def test_raw_response_cancel(self, client: OpenAI) -> None: + response = client.fine_tuning.jobs.with_raw_response.cancel( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + job = response.parse() + assert_matches_type(FineTuningJob, job, path=["response"]) + + @parametrize + def test_method_list_events(self, client: OpenAI) -> None: + job = client.fine_tuning.jobs.list_events( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert_matches_type(SyncCursorPage[FineTuningJobEvent], job, path=["response"]) + + @parametrize + def test_method_list_events_with_all_params(self, client: OpenAI) -> None: + job = client.fine_tuning.jobs.list_events( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + after="string", + limit=0, + ) + assert_matches_type(SyncCursorPage[FineTuningJobEvent], job, path=["response"]) + + @parametrize + def test_raw_response_list_events(self, client: OpenAI) -> None: + response = client.fine_tuning.jobs.with_raw_response.list_events( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + job = response.parse() + assert_matches_type(SyncCursorPage[FineTuningJobEvent], job, path=["response"]) + + +class TestAsyncJobs: + strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + async def test_method_create(self, client: AsyncOpenAI) -> None: + job = await client.fine_tuning.jobs.create( + model="gpt-3.5-turbo", + training_file="file-abc123", + ) + assert_matches_type(FineTuningJob, job, path=["response"]) + + @parametrize + async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: + job = await client.fine_tuning.jobs.create( + model="gpt-3.5-turbo", + training_file="file-abc123", + hyperparameters={"n_epochs": "auto"}, + suffix="x", + validation_file="file-abc123", + ) + assert_matches_type(FineTuningJob, job, path=["response"]) + + @parametrize + async def test_raw_response_create(self, client: AsyncOpenAI) -> None: + response = await client.fine_tuning.jobs.with_raw_response.create( + model="gpt-3.5-turbo", + training_file="file-abc123", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + job = response.parse() + assert_matches_type(FineTuningJob, job, path=["response"]) + + @parametrize + async def test_method_retrieve(self, client: AsyncOpenAI) -> None: + job = await client.fine_tuning.jobs.retrieve( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert_matches_type(FineTuningJob, job, path=["response"]) + + @parametrize + async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: + response = await client.fine_tuning.jobs.with_raw_response.retrieve( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + job = response.parse() + assert_matches_type(FineTuningJob, job, path=["response"]) + + @parametrize + async def test_method_list(self, client: AsyncOpenAI) -> None: + job = await client.fine_tuning.jobs.list() + assert_matches_type(AsyncCursorPage[FineTuningJob], job, path=["response"]) + + @parametrize + async def test_method_list_with_all_params(self, client: AsyncOpenAI) -> None: + job = await client.fine_tuning.jobs.list( + after="string", + limit=0, + ) + assert_matches_type(AsyncCursorPage[FineTuningJob], job, path=["response"]) + + @parametrize + async def test_raw_response_list(self, client: AsyncOpenAI) -> None: + response = await client.fine_tuning.jobs.with_raw_response.list() + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + job = response.parse() + assert_matches_type(AsyncCursorPage[FineTuningJob], job, path=["response"]) + + @parametrize + async def test_method_cancel(self, client: AsyncOpenAI) -> None: + job = await client.fine_tuning.jobs.cancel( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert_matches_type(FineTuningJob, job, path=["response"]) + + @parametrize + async def test_raw_response_cancel(self, client: AsyncOpenAI) -> None: + response = await client.fine_tuning.jobs.with_raw_response.cancel( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + job = response.parse() + assert_matches_type(FineTuningJob, job, path=["response"]) + + @parametrize + async def test_method_list_events(self, client: AsyncOpenAI) -> None: + job = await client.fine_tuning.jobs.list_events( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert_matches_type(AsyncCursorPage[FineTuningJobEvent], job, path=["response"]) + + @parametrize + async def test_method_list_events_with_all_params(self, client: AsyncOpenAI) -> None: + job = await client.fine_tuning.jobs.list_events( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + after="string", + limit=0, + ) + assert_matches_type(AsyncCursorPage[FineTuningJobEvent], job, path=["response"]) + + @parametrize + async def test_raw_response_list_events(self, client: AsyncOpenAI) -> None: + response = await client.fine_tuning.jobs.with_raw_response.list_events( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + job = response.parse() + assert_matches_type(AsyncCursorPage[FineTuningJobEvent], job, path=["response"]) diff --git a/tests/api_resources/test_completions.py b/tests/api_resources/test_completions.py new file mode 100644 index 0000000000..7b48e88ed2 --- /dev/null +++ b/tests/api_resources/test_completions.py @@ -0,0 +1,185 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import os + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai.types import Completion +from openai._client import OpenAI, AsyncOpenAI + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") +api_key = "My API Key" + + +class TestCompletions: + strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + def test_method_create_overload_1(self, client: OpenAI) -> None: + completion = client.completions.create( + model="string", + prompt="This is a test.", + ) + assert_matches_type(Completion, completion, path=["response"]) + + @parametrize + def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: + completion = client.completions.create( + model="string", + prompt="This is a test.", + best_of=0, + echo=True, + frequency_penalty=-2, + logit_bias={"foo": 0}, + logprobs=0, + max_tokens=16, + n=1, + presence_penalty=-2, + stop="\n", + stream=False, + suffix="test.", + temperature=1, + top_p=1, + user="user-1234", + ) + assert_matches_type(Completion, completion, path=["response"]) + + @parametrize + def test_raw_response_create_overload_1(self, client: OpenAI) -> None: + response = client.completions.with_raw_response.create( + model="string", + prompt="This is a test.", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + completion = response.parse() + assert_matches_type(Completion, completion, path=["response"]) + + @parametrize + def test_method_create_overload_2(self, client: OpenAI) -> None: + client.completions.create( + model="string", + prompt="This is a test.", + stream=True, + ) + + @parametrize + def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: + client.completions.create( + model="string", + prompt="This is a test.", + stream=True, + best_of=0, + echo=True, + frequency_penalty=-2, + logit_bias={"foo": 0}, + logprobs=0, + max_tokens=16, + n=1, + presence_penalty=-2, + stop="\n", + suffix="test.", + temperature=1, + top_p=1, + user="user-1234", + ) + + @parametrize + def test_raw_response_create_overload_2(self, client: OpenAI) -> None: + response = client.completions.with_raw_response.create( + model="string", + prompt="This is a test.", + stream=True, + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + response.parse() + + +class TestAsyncCompletions: + strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + async def test_method_create_overload_1(self, client: AsyncOpenAI) -> None: + completion = await client.completions.create( + model="string", + prompt="This is a test.", + ) + assert_matches_type(Completion, completion, path=["response"]) + + @parametrize + async def test_method_create_with_all_params_overload_1(self, client: AsyncOpenAI) -> None: + completion = await client.completions.create( + model="string", + prompt="This is a test.", + best_of=0, + echo=True, + frequency_penalty=-2, + logit_bias={"foo": 0}, + logprobs=0, + max_tokens=16, + n=1, + presence_penalty=-2, + stop="\n", + stream=False, + suffix="test.", + temperature=1, + top_p=1, + user="user-1234", + ) + assert_matches_type(Completion, completion, path=["response"]) + + @parametrize + async def test_raw_response_create_overload_1(self, client: AsyncOpenAI) -> None: + response = await client.completions.with_raw_response.create( + model="string", + prompt="This is a test.", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + completion = response.parse() + assert_matches_type(Completion, completion, path=["response"]) + + @parametrize + async def test_method_create_overload_2(self, client: AsyncOpenAI) -> None: + await client.completions.create( + model="string", + prompt="This is a test.", + stream=True, + ) + + @parametrize + async def test_method_create_with_all_params_overload_2(self, client: AsyncOpenAI) -> None: + await client.completions.create( + model="string", + prompt="This is a test.", + stream=True, + best_of=0, + echo=True, + frequency_penalty=-2, + logit_bias={"foo": 0}, + logprobs=0, + max_tokens=16, + n=1, + presence_penalty=-2, + stop="\n", + suffix="test.", + temperature=1, + top_p=1, + user="user-1234", + ) + + @parametrize + async def test_raw_response_create_overload_2(self, client: AsyncOpenAI) -> None: + response = await client.completions.with_raw_response.create( + model="string", + prompt="This is a test.", + stream=True, + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + response.parse() diff --git a/tests/api_resources/test_edits.py b/tests/api_resources/test_edits.py new file mode 100644 index 0000000000..76069d6b83 --- /dev/null +++ b/tests/api_resources/test_edits.py @@ -0,0 +1,95 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import os + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai.types import Edit +from openai._client import OpenAI, AsyncOpenAI + +# pyright: reportDeprecated=false + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") +api_key = "My API Key" + + +class TestEdits: + strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + def test_method_create(self, client: OpenAI) -> None: + with pytest.warns(DeprecationWarning): + edit = client.edits.create( + instruction="Fix the spelling mistakes.", + model="text-davinci-edit-001", + ) + assert_matches_type(Edit, edit, path=["response"]) + + @parametrize + def test_method_create_with_all_params(self, client: OpenAI) -> None: + with pytest.warns(DeprecationWarning): + edit = client.edits.create( + instruction="Fix the spelling mistakes.", + model="text-davinci-edit-001", + input="What day of the wek is it?", + n=1, + temperature=1, + top_p=1, + ) + assert_matches_type(Edit, edit, path=["response"]) + + @parametrize + def test_raw_response_create(self, client: OpenAI) -> None: + with pytest.warns(DeprecationWarning): + response = client.edits.with_raw_response.create( + instruction="Fix the spelling mistakes.", + model="text-davinci-edit-001", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + edit = response.parse() + assert_matches_type(Edit, edit, path=["response"]) + + +class TestAsyncEdits: + strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + async def test_method_create(self, client: AsyncOpenAI) -> None: + with pytest.warns(DeprecationWarning): + edit = await client.edits.create( + instruction="Fix the spelling mistakes.", + model="text-davinci-edit-001", + ) + assert_matches_type(Edit, edit, path=["response"]) + + @parametrize + async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: + with pytest.warns(DeprecationWarning): + edit = await client.edits.create( + instruction="Fix the spelling mistakes.", + model="text-davinci-edit-001", + input="What day of the wek is it?", + n=1, + temperature=1, + top_p=1, + ) + assert_matches_type(Edit, edit, path=["response"]) + + @parametrize + async def test_raw_response_create(self, client: AsyncOpenAI) -> None: + with pytest.warns(DeprecationWarning): + response = await client.edits.with_raw_response.create( + instruction="Fix the spelling mistakes.", + model="text-davinci-edit-001", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + edit = response.parse() + assert_matches_type(Edit, edit, path=["response"]) diff --git a/tests/api_resources/test_embeddings.py b/tests/api_resources/test_embeddings.py new file mode 100644 index 0000000000..faf07ffb7c --- /dev/null +++ b/tests/api_resources/test_embeddings.py @@ -0,0 +1,83 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import os + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai.types import CreateEmbeddingResponse +from openai._client import OpenAI, AsyncOpenAI + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") +api_key = "My API Key" + + +class TestEmbeddings: + strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + def test_method_create(self, client: OpenAI) -> None: + embedding = client.embeddings.create( + input="The quick brown fox jumped over the lazy dog", + model="text-embedding-ada-002", + ) + assert_matches_type(CreateEmbeddingResponse, embedding, path=["response"]) + + @parametrize + def test_method_create_with_all_params(self, client: OpenAI) -> None: + embedding = client.embeddings.create( + input="The quick brown fox jumped over the lazy dog", + model="text-embedding-ada-002", + encoding_format="float", + user="user-1234", + ) + assert_matches_type(CreateEmbeddingResponse, embedding, path=["response"]) + + @parametrize + def test_raw_response_create(self, client: OpenAI) -> None: + response = client.embeddings.with_raw_response.create( + input="The quick brown fox jumped over the lazy dog", + model="text-embedding-ada-002", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + embedding = response.parse() + assert_matches_type(CreateEmbeddingResponse, embedding, path=["response"]) + + +class TestAsyncEmbeddings: + strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + async def test_method_create(self, client: AsyncOpenAI) -> None: + embedding = await client.embeddings.create( + input="The quick brown fox jumped over the lazy dog", + model="text-embedding-ada-002", + ) + assert_matches_type(CreateEmbeddingResponse, embedding, path=["response"]) + + @parametrize + async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: + embedding = await client.embeddings.create( + input="The quick brown fox jumped over the lazy dog", + model="text-embedding-ada-002", + encoding_format="float", + user="user-1234", + ) + assert_matches_type(CreateEmbeddingResponse, embedding, path=["response"]) + + @parametrize + async def test_raw_response_create(self, client: AsyncOpenAI) -> None: + response = await client.embeddings.with_raw_response.create( + input="The quick brown fox jumped over the lazy dog", + model="text-embedding-ada-002", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + embedding = response.parse() + assert_matches_type(CreateEmbeddingResponse, embedding, path=["response"]) diff --git a/tests/api_resources/test_files.py b/tests/api_resources/test_files.py new file mode 100644 index 0000000000..389763586e --- /dev/null +++ b/tests/api_resources/test_files.py @@ -0,0 +1,184 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import os + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai.types import FileObject, FileDeleted +from openai._client import OpenAI, AsyncOpenAI +from openai.pagination import SyncPage, AsyncPage + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") +api_key = "My API Key" + + +class TestFiles: + strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + def test_method_create(self, client: OpenAI) -> None: + file = client.files.create( + file=b"raw file contents", + purpose="string", + ) + assert_matches_type(FileObject, file, path=["response"]) + + @parametrize + def test_raw_response_create(self, client: OpenAI) -> None: + response = client.files.with_raw_response.create( + file=b"raw file contents", + purpose="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(FileObject, file, path=["response"]) + + @parametrize + def test_method_retrieve(self, client: OpenAI) -> None: + file = client.files.retrieve( + "string", + ) + assert_matches_type(FileObject, file, path=["response"]) + + @parametrize + def test_raw_response_retrieve(self, client: OpenAI) -> None: + response = client.files.with_raw_response.retrieve( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(FileObject, file, path=["response"]) + + @parametrize + def test_method_list(self, client: OpenAI) -> None: + file = client.files.list() + assert_matches_type(SyncPage[FileObject], file, path=["response"]) + + @parametrize + def test_raw_response_list(self, client: OpenAI) -> None: + response = client.files.with_raw_response.list() + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(SyncPage[FileObject], file, path=["response"]) + + @parametrize + def test_method_delete(self, client: OpenAI) -> None: + file = client.files.delete( + "string", + ) + assert_matches_type(FileDeleted, file, path=["response"]) + + @parametrize + def test_raw_response_delete(self, client: OpenAI) -> None: + response = client.files.with_raw_response.delete( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(FileDeleted, file, path=["response"]) + + @parametrize + def test_method_retrieve_content(self, client: OpenAI) -> None: + file = client.files.retrieve_content( + "string", + ) + assert_matches_type(str, file, path=["response"]) + + @parametrize + def test_raw_response_retrieve_content(self, client: OpenAI) -> None: + response = client.files.with_raw_response.retrieve_content( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(str, file, path=["response"]) + + +class TestAsyncFiles: + strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + async def test_method_create(self, client: AsyncOpenAI) -> None: + file = await client.files.create( + file=b"raw file contents", + purpose="string", + ) + assert_matches_type(FileObject, file, path=["response"]) + + @parametrize + async def test_raw_response_create(self, client: AsyncOpenAI) -> None: + response = await client.files.with_raw_response.create( + file=b"raw file contents", + purpose="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(FileObject, file, path=["response"]) + + @parametrize + async def test_method_retrieve(self, client: AsyncOpenAI) -> None: + file = await client.files.retrieve( + "string", + ) + assert_matches_type(FileObject, file, path=["response"]) + + @parametrize + async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: + response = await client.files.with_raw_response.retrieve( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(FileObject, file, path=["response"]) + + @parametrize + async def test_method_list(self, client: AsyncOpenAI) -> None: + file = await client.files.list() + assert_matches_type(AsyncPage[FileObject], file, path=["response"]) + + @parametrize + async def test_raw_response_list(self, client: AsyncOpenAI) -> None: + response = await client.files.with_raw_response.list() + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(AsyncPage[FileObject], file, path=["response"]) + + @parametrize + async def test_method_delete(self, client: AsyncOpenAI) -> None: + file = await client.files.delete( + "string", + ) + assert_matches_type(FileDeleted, file, path=["response"]) + + @parametrize + async def test_raw_response_delete(self, client: AsyncOpenAI) -> None: + response = await client.files.with_raw_response.delete( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(FileDeleted, file, path=["response"]) + + @parametrize + async def test_method_retrieve_content(self, client: AsyncOpenAI) -> None: + file = await client.files.retrieve_content( + "string", + ) + assert_matches_type(str, file, path=["response"]) + + @parametrize + async def test_raw_response_retrieve_content(self, client: AsyncOpenAI) -> None: + response = await client.files.with_raw_response.retrieve_content( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(str, file, path=["response"]) diff --git a/tests/api_resources/test_fine_tunes.py b/tests/api_resources/test_fine_tunes.py new file mode 100644 index 0000000000..edaf784848 --- /dev/null +++ b/tests/api_resources/test_fine_tunes.py @@ -0,0 +1,274 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import os + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai.types import FineTune, FineTuneEventsListResponse +from openai._client import OpenAI, AsyncOpenAI +from openai.pagination import SyncPage, AsyncPage + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") +api_key = "My API Key" + + +class TestFineTunes: + strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + def test_method_create(self, client: OpenAI) -> None: + fine_tune = client.fine_tunes.create( + training_file="file-abc123", + ) + assert_matches_type(FineTune, fine_tune, path=["response"]) + + @parametrize + def test_method_create_with_all_params(self, client: OpenAI) -> None: + fine_tune = client.fine_tunes.create( + training_file="file-abc123", + batch_size=0, + classification_betas=[0.6, 1, 1.5, 2], + classification_n_classes=0, + classification_positive_class="string", + compute_classification_metrics=True, + hyperparameters={"n_epochs": "auto"}, + learning_rate_multiplier=0, + model="curie", + prompt_loss_weight=0, + suffix="x", + validation_file="file-abc123", + ) + assert_matches_type(FineTune, fine_tune, path=["response"]) + + @parametrize + def test_raw_response_create(self, client: OpenAI) -> None: + response = client.fine_tunes.with_raw_response.create( + training_file="file-abc123", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + fine_tune = response.parse() + assert_matches_type(FineTune, fine_tune, path=["response"]) + + @parametrize + def test_method_retrieve(self, client: OpenAI) -> None: + fine_tune = client.fine_tunes.retrieve( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert_matches_type(FineTune, fine_tune, path=["response"]) + + @parametrize + def test_raw_response_retrieve(self, client: OpenAI) -> None: + response = client.fine_tunes.with_raw_response.retrieve( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + fine_tune = response.parse() + assert_matches_type(FineTune, fine_tune, path=["response"]) + + @parametrize + def test_method_list(self, client: OpenAI) -> None: + fine_tune = client.fine_tunes.list() + assert_matches_type(SyncPage[FineTune], fine_tune, path=["response"]) + + @parametrize + def test_raw_response_list(self, client: OpenAI) -> None: + response = client.fine_tunes.with_raw_response.list() + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + fine_tune = response.parse() + assert_matches_type(SyncPage[FineTune], fine_tune, path=["response"]) + + @parametrize + def test_method_cancel(self, client: OpenAI) -> None: + fine_tune = client.fine_tunes.cancel( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert_matches_type(FineTune, fine_tune, path=["response"]) + + @parametrize + def test_raw_response_cancel(self, client: OpenAI) -> None: + response = client.fine_tunes.with_raw_response.cancel( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + fine_tune = response.parse() + assert_matches_type(FineTune, fine_tune, path=["response"]) + + @pytest.mark.skip(reason="Prism chokes on this") + @parametrize + def test_method_list_events_overload_1(self, client: OpenAI) -> None: + fine_tune = client.fine_tunes.list_events( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert_matches_type(FineTuneEventsListResponse, fine_tune, path=["response"]) + + @pytest.mark.skip(reason="Prism chokes on this") + @parametrize + def test_method_list_events_with_all_params_overload_1(self, client: OpenAI) -> None: + fine_tune = client.fine_tunes.list_events( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + stream=False, + ) + assert_matches_type(FineTuneEventsListResponse, fine_tune, path=["response"]) + + @pytest.mark.skip(reason="Prism chokes on this") + @parametrize + def test_raw_response_list_events_overload_1(self, client: OpenAI) -> None: + response = client.fine_tunes.with_raw_response.list_events( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + fine_tune = response.parse() + assert_matches_type(FineTuneEventsListResponse, fine_tune, path=["response"]) + + @pytest.mark.skip(reason="Prism chokes on this") + @parametrize + def test_method_list_events_overload_2(self, client: OpenAI) -> None: + client.fine_tunes.list_events( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + stream=True, + ) + + @pytest.mark.skip(reason="Prism chokes on this") + @parametrize + def test_raw_response_list_events_overload_2(self, client: OpenAI) -> None: + response = client.fine_tunes.with_raw_response.list_events( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + stream=True, + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + response.parse() + + +class TestAsyncFineTunes: + strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + async def test_method_create(self, client: AsyncOpenAI) -> None: + fine_tune = await client.fine_tunes.create( + training_file="file-abc123", + ) + assert_matches_type(FineTune, fine_tune, path=["response"]) + + @parametrize + async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: + fine_tune = await client.fine_tunes.create( + training_file="file-abc123", + batch_size=0, + classification_betas=[0.6, 1, 1.5, 2], + classification_n_classes=0, + classification_positive_class="string", + compute_classification_metrics=True, + hyperparameters={"n_epochs": "auto"}, + learning_rate_multiplier=0, + model="curie", + prompt_loss_weight=0, + suffix="x", + validation_file="file-abc123", + ) + assert_matches_type(FineTune, fine_tune, path=["response"]) + + @parametrize + async def test_raw_response_create(self, client: AsyncOpenAI) -> None: + response = await client.fine_tunes.with_raw_response.create( + training_file="file-abc123", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + fine_tune = response.parse() + assert_matches_type(FineTune, fine_tune, path=["response"]) + + @parametrize + async def test_method_retrieve(self, client: AsyncOpenAI) -> None: + fine_tune = await client.fine_tunes.retrieve( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert_matches_type(FineTune, fine_tune, path=["response"]) + + @parametrize + async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: + response = await client.fine_tunes.with_raw_response.retrieve( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + fine_tune = response.parse() + assert_matches_type(FineTune, fine_tune, path=["response"]) + + @parametrize + async def test_method_list(self, client: AsyncOpenAI) -> None: + fine_tune = await client.fine_tunes.list() + assert_matches_type(AsyncPage[FineTune], fine_tune, path=["response"]) + + @parametrize + async def test_raw_response_list(self, client: AsyncOpenAI) -> None: + response = await client.fine_tunes.with_raw_response.list() + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + fine_tune = response.parse() + assert_matches_type(AsyncPage[FineTune], fine_tune, path=["response"]) + + @parametrize + async def test_method_cancel(self, client: AsyncOpenAI) -> None: + fine_tune = await client.fine_tunes.cancel( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert_matches_type(FineTune, fine_tune, path=["response"]) + + @parametrize + async def test_raw_response_cancel(self, client: AsyncOpenAI) -> None: + response = await client.fine_tunes.with_raw_response.cancel( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + fine_tune = response.parse() + assert_matches_type(FineTune, fine_tune, path=["response"]) + + @pytest.mark.skip(reason="Prism chokes on this") + @parametrize + async def test_method_list_events_overload_1(self, client: AsyncOpenAI) -> None: + fine_tune = await client.fine_tunes.list_events( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert_matches_type(FineTuneEventsListResponse, fine_tune, path=["response"]) + + @pytest.mark.skip(reason="Prism chokes on this") + @parametrize + async def test_method_list_events_with_all_params_overload_1(self, client: AsyncOpenAI) -> None: + fine_tune = await client.fine_tunes.list_events( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + stream=False, + ) + assert_matches_type(FineTuneEventsListResponse, fine_tune, path=["response"]) + + @pytest.mark.skip(reason="Prism chokes on this") + @parametrize + async def test_raw_response_list_events_overload_1(self, client: AsyncOpenAI) -> None: + response = await client.fine_tunes.with_raw_response.list_events( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + fine_tune = response.parse() + assert_matches_type(FineTuneEventsListResponse, fine_tune, path=["response"]) + + @pytest.mark.skip(reason="Prism chokes on this") + @parametrize + async def test_method_list_events_overload_2(self, client: AsyncOpenAI) -> None: + await client.fine_tunes.list_events( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + stream=True, + ) + + @pytest.mark.skip(reason="Prism chokes on this") + @parametrize + async def test_raw_response_list_events_overload_2(self, client: AsyncOpenAI) -> None: + response = await client.fine_tunes.with_raw_response.list_events( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + stream=True, + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + response.parse() diff --git a/tests/api_resources/test_images.py b/tests/api_resources/test_images.py new file mode 100644 index 0000000000..fa7fb6d533 --- /dev/null +++ b/tests/api_resources/test_images.py @@ -0,0 +1,197 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import os + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai.types import ImagesResponse +from openai._client import OpenAI, AsyncOpenAI + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") +api_key = "My API Key" + + +class TestImages: + strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + def test_method_create_variation(self, client: OpenAI) -> None: + image = client.images.create_variation( + image=b"raw file contents", + ) + assert_matches_type(ImagesResponse, image, path=["response"]) + + @parametrize + def test_method_create_variation_with_all_params(self, client: OpenAI) -> None: + image = client.images.create_variation( + image=b"raw file contents", + n=1, + response_format="url", + size="1024x1024", + user="user-1234", + ) + assert_matches_type(ImagesResponse, image, path=["response"]) + + @parametrize + def test_raw_response_create_variation(self, client: OpenAI) -> None: + response = client.images.with_raw_response.create_variation( + image=b"raw file contents", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + image = response.parse() + assert_matches_type(ImagesResponse, image, path=["response"]) + + @parametrize + def test_method_edit(self, client: OpenAI) -> None: + image = client.images.edit( + image=b"raw file contents", + prompt="A cute baby sea otter wearing a beret", + ) + assert_matches_type(ImagesResponse, image, path=["response"]) + + @parametrize + def test_method_edit_with_all_params(self, client: OpenAI) -> None: + image = client.images.edit( + image=b"raw file contents", + prompt="A cute baby sea otter wearing a beret", + mask=b"raw file contents", + n=1, + response_format="url", + size="1024x1024", + user="user-1234", + ) + assert_matches_type(ImagesResponse, image, path=["response"]) + + @parametrize + def test_raw_response_edit(self, client: OpenAI) -> None: + response = client.images.with_raw_response.edit( + image=b"raw file contents", + prompt="A cute baby sea otter wearing a beret", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + image = response.parse() + assert_matches_type(ImagesResponse, image, path=["response"]) + + @parametrize + def test_method_generate(self, client: OpenAI) -> None: + image = client.images.generate( + prompt="A cute baby sea otter", + ) + assert_matches_type(ImagesResponse, image, path=["response"]) + + @parametrize + def test_method_generate_with_all_params(self, client: OpenAI) -> None: + image = client.images.generate( + prompt="A cute baby sea otter", + n=1, + response_format="url", + size="1024x1024", + user="user-1234", + ) + assert_matches_type(ImagesResponse, image, path=["response"]) + + @parametrize + def test_raw_response_generate(self, client: OpenAI) -> None: + response = client.images.with_raw_response.generate( + prompt="A cute baby sea otter", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + image = response.parse() + assert_matches_type(ImagesResponse, image, path=["response"]) + + +class TestAsyncImages: + strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + async def test_method_create_variation(self, client: AsyncOpenAI) -> None: + image = await client.images.create_variation( + image=b"raw file contents", + ) + assert_matches_type(ImagesResponse, image, path=["response"]) + + @parametrize + async def test_method_create_variation_with_all_params(self, client: AsyncOpenAI) -> None: + image = await client.images.create_variation( + image=b"raw file contents", + n=1, + response_format="url", + size="1024x1024", + user="user-1234", + ) + assert_matches_type(ImagesResponse, image, path=["response"]) + + @parametrize + async def test_raw_response_create_variation(self, client: AsyncOpenAI) -> None: + response = await client.images.with_raw_response.create_variation( + image=b"raw file contents", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + image = response.parse() + assert_matches_type(ImagesResponse, image, path=["response"]) + + @parametrize + async def test_method_edit(self, client: AsyncOpenAI) -> None: + image = await client.images.edit( + image=b"raw file contents", + prompt="A cute baby sea otter wearing a beret", + ) + assert_matches_type(ImagesResponse, image, path=["response"]) + + @parametrize + async def test_method_edit_with_all_params(self, client: AsyncOpenAI) -> None: + image = await client.images.edit( + image=b"raw file contents", + prompt="A cute baby sea otter wearing a beret", + mask=b"raw file contents", + n=1, + response_format="url", + size="1024x1024", + user="user-1234", + ) + assert_matches_type(ImagesResponse, image, path=["response"]) + + @parametrize + async def test_raw_response_edit(self, client: AsyncOpenAI) -> None: + response = await client.images.with_raw_response.edit( + image=b"raw file contents", + prompt="A cute baby sea otter wearing a beret", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + image = response.parse() + assert_matches_type(ImagesResponse, image, path=["response"]) + + @parametrize + async def test_method_generate(self, client: AsyncOpenAI) -> None: + image = await client.images.generate( + prompt="A cute baby sea otter", + ) + assert_matches_type(ImagesResponse, image, path=["response"]) + + @parametrize + async def test_method_generate_with_all_params(self, client: AsyncOpenAI) -> None: + image = await client.images.generate( + prompt="A cute baby sea otter", + n=1, + response_format="url", + size="1024x1024", + user="user-1234", + ) + assert_matches_type(ImagesResponse, image, path=["response"]) + + @parametrize + async def test_raw_response_generate(self, client: AsyncOpenAI) -> None: + response = await client.images.with_raw_response.generate( + prompt="A cute baby sea otter", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + image = response.parse() + assert_matches_type(ImagesResponse, image, path=["response"]) diff --git a/tests/api_resources/test_models.py b/tests/api_resources/test_models.py new file mode 100644 index 0000000000..3998809610 --- /dev/null +++ b/tests/api_resources/test_models.py @@ -0,0 +1,116 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import os + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai.types import Model, ModelDeleted +from openai._client import OpenAI, AsyncOpenAI +from openai.pagination import SyncPage, AsyncPage + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") +api_key = "My API Key" + + +class TestModels: + strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + def test_method_retrieve(self, client: OpenAI) -> None: + model = client.models.retrieve( + "gpt-3.5-turbo", + ) + assert_matches_type(Model, model, path=["response"]) + + @parametrize + def test_raw_response_retrieve(self, client: OpenAI) -> None: + response = client.models.with_raw_response.retrieve( + "gpt-3.5-turbo", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + model = response.parse() + assert_matches_type(Model, model, path=["response"]) + + @parametrize + def test_method_list(self, client: OpenAI) -> None: + model = client.models.list() + assert_matches_type(SyncPage[Model], model, path=["response"]) + + @parametrize + def test_raw_response_list(self, client: OpenAI) -> None: + response = client.models.with_raw_response.list() + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + model = response.parse() + assert_matches_type(SyncPage[Model], model, path=["response"]) + + @parametrize + def test_method_delete(self, client: OpenAI) -> None: + model = client.models.delete( + "ft:gpt-3.5-turbo:acemeco:suffix:abc123", + ) + assert_matches_type(ModelDeleted, model, path=["response"]) + + @parametrize + def test_raw_response_delete(self, client: OpenAI) -> None: + response = client.models.with_raw_response.delete( + "ft:gpt-3.5-turbo:acemeco:suffix:abc123", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + model = response.parse() + assert_matches_type(ModelDeleted, model, path=["response"]) + + +class TestAsyncModels: + strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + async def test_method_retrieve(self, client: AsyncOpenAI) -> None: + model = await client.models.retrieve( + "gpt-3.5-turbo", + ) + assert_matches_type(Model, model, path=["response"]) + + @parametrize + async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: + response = await client.models.with_raw_response.retrieve( + "gpt-3.5-turbo", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + model = response.parse() + assert_matches_type(Model, model, path=["response"]) + + @parametrize + async def test_method_list(self, client: AsyncOpenAI) -> None: + model = await client.models.list() + assert_matches_type(AsyncPage[Model], model, path=["response"]) + + @parametrize + async def test_raw_response_list(self, client: AsyncOpenAI) -> None: + response = await client.models.with_raw_response.list() + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + model = response.parse() + assert_matches_type(AsyncPage[Model], model, path=["response"]) + + @parametrize + async def test_method_delete(self, client: AsyncOpenAI) -> None: + model = await client.models.delete( + "ft:gpt-3.5-turbo:acemeco:suffix:abc123", + ) + assert_matches_type(ModelDeleted, model, path=["response"]) + + @parametrize + async def test_raw_response_delete(self, client: AsyncOpenAI) -> None: + response = await client.models.with_raw_response.delete( + "ft:gpt-3.5-turbo:acemeco:suffix:abc123", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + model = response.parse() + assert_matches_type(ModelDeleted, model, path=["response"]) diff --git a/tests/api_resources/test_moderations.py b/tests/api_resources/test_moderations.py new file mode 100644 index 0000000000..502030d614 --- /dev/null +++ b/tests/api_resources/test_moderations.py @@ -0,0 +1,75 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import os + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai.types import ModerationCreateResponse +from openai._client import OpenAI, AsyncOpenAI + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") +api_key = "My API Key" + + +class TestModerations: + strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + def test_method_create(self, client: OpenAI) -> None: + moderation = client.moderations.create( + input="I want to kill them.", + ) + assert_matches_type(ModerationCreateResponse, moderation, path=["response"]) + + @parametrize + def test_method_create_with_all_params(self, client: OpenAI) -> None: + moderation = client.moderations.create( + input="I want to kill them.", + model="text-moderation-stable", + ) + assert_matches_type(ModerationCreateResponse, moderation, path=["response"]) + + @parametrize + def test_raw_response_create(self, client: OpenAI) -> None: + response = client.moderations.with_raw_response.create( + input="I want to kill them.", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + moderation = response.parse() + assert_matches_type(ModerationCreateResponse, moderation, path=["response"]) + + +class TestAsyncModerations: + strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + async def test_method_create(self, client: AsyncOpenAI) -> None: + moderation = await client.moderations.create( + input="I want to kill them.", + ) + assert_matches_type(ModerationCreateResponse, moderation, path=["response"]) + + @parametrize + async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: + moderation = await client.moderations.create( + input="I want to kill them.", + model="text-moderation-stable", + ) + assert_matches_type(ModerationCreateResponse, moderation, path=["response"]) + + @parametrize + async def test_raw_response_create(self, client: AsyncOpenAI) -> None: + response = await client.moderations.with_raw_response.create( + input="I want to kill them.", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + moderation = response.parse() + assert_matches_type(ModerationCreateResponse, moderation, path=["response"]) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000000..c3a1efe9df --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,16 @@ +import asyncio +import logging +from typing import Iterator + +import pytest + +pytest.register_assert_rewrite("tests.utils") + +logging.getLogger("openai").setLevel(logging.DEBUG) + + +@pytest.fixture(scope="session") +def event_loop() -> Iterator[asyncio.AbstractEventLoop]: + loop = asyncio.new_event_loop() + yield loop + loop.close() diff --git a/tests/lib/test_azure.py b/tests/lib/test_azure.py new file mode 100644 index 0000000000..b0bd87571b --- /dev/null +++ b/tests/lib/test_azure.py @@ -0,0 +1,36 @@ +from typing import Union + +import pytest + +from openai._models import FinalRequestOptions +from openai.lib.azure import AzureOpenAI, AsyncAzureOpenAI + +Client = Union[AzureOpenAI, AsyncAzureOpenAI] + + +sync_client = AzureOpenAI( + api_version="2023-07-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", +) + +async_client = AsyncAzureOpenAI( + api_version="2023-07-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", +) + + +@pytest.mark.parametrize("client", [sync_client, async_client]) +def test_implicit_deployment_path(client: Client) -> None: + req = client._build_request( + FinalRequestOptions.construct( + method="post", + url="/chat/completions", + json_data={"model": "my-deployment-model"}, + ) + ) + assert ( + req.url + == "https://example-resource.azure.openai.com/openai/deployments/my-deployment-model/chat/completions?api-version=2023-07-01" + ) diff --git a/tests/test_client.py b/tests/test_client.py new file mode 100644 index 0000000000..3b70594ecd --- /dev/null +++ b/tests/test_client.py @@ -0,0 +1,1110 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import os +import json +import asyncio +import inspect +from typing import Any, Dict, Union, cast +from unittest import mock + +import httpx +import pytest +from respx import MockRouter +from pydantic import ValidationError + +from openai import OpenAI, AsyncOpenAI, APIResponseValidationError +from openai._client import OpenAI, AsyncOpenAI +from openai._models import BaseModel, FinalRequestOptions +from openai._streaming import Stream, AsyncStream +from openai._exceptions import APIResponseValidationError +from openai._base_client import ( + DEFAULT_TIMEOUT, + HTTPX_DEFAULT_TIMEOUT, + BaseClient, + make_request_options, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") +api_key = "My API Key" + + +def _get_params(client: BaseClient[Any, Any]) -> dict[str, str]: + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + url = httpx.URL(request.url) + return dict(url.params) + + +class TestOpenAI: + client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + + @pytest.mark.respx(base_url=base_url) + def test_raw_response(self, respx_mock: MockRouter) -> None: + respx_mock.post("/foo").mock(return_value=httpx.Response(200, json='{"foo": "bar"}')) + + response = self.client.post("/foo", cast_to=httpx.Response) + assert response.status_code == 200 + assert isinstance(response, httpx.Response) + assert response.json() == '{"foo": "bar"}' + + @pytest.mark.respx(base_url=base_url) + def test_raw_response_for_binary(self, respx_mock: MockRouter) -> None: + respx_mock.post("/foo").mock( + return_value=httpx.Response(200, headers={"Content-Type": "application/binary"}, content='{"foo": "bar"}') + ) + + response = self.client.post("/foo", cast_to=httpx.Response) + assert response.status_code == 200 + assert isinstance(response, httpx.Response) + assert response.json() == '{"foo": "bar"}' + + def test_copy(self) -> None: + copied = self.client.copy() + assert id(copied) != id(self.client) + + copied = self.client.copy(api_key="another My API Key") + assert copied.api_key == "another My API Key" + assert self.client.api_key == "My API Key" + + def test_copy_default_options(self) -> None: + # options that have a default are overridden correctly + copied = self.client.copy(max_retries=7) + assert copied.max_retries == 7 + assert self.client.max_retries == 2 + + copied2 = copied.copy(max_retries=6) + assert copied2.max_retries == 6 + assert copied.max_retries == 7 + + # timeout + assert isinstance(self.client.timeout, httpx.Timeout) + copied = self.client.copy(timeout=None) + assert copied.timeout is None + assert isinstance(self.client.timeout, httpx.Timeout) + + def test_copy_default_headers(self) -> None: + client = OpenAI( + base_url=base_url, api_key=api_key, _strict_response_validation=True, default_headers={"X-Foo": "bar"} + ) + assert client.default_headers["X-Foo"] == "bar" + + # does not override the already given value when not specified + copied = client.copy() + assert copied.default_headers["X-Foo"] == "bar" + + # merges already given headers + copied = client.copy(default_headers={"X-Bar": "stainless"}) + assert copied.default_headers["X-Foo"] == "bar" + assert copied.default_headers["X-Bar"] == "stainless" + + # uses new values for any already given headers + copied = client.copy(default_headers={"X-Foo": "stainless"}) + assert copied.default_headers["X-Foo"] == "stainless" + + # set_default_headers + + # completely overrides already set values + copied = client.copy(set_default_headers={}) + assert copied.default_headers.get("X-Foo") is None + + copied = client.copy(set_default_headers={"X-Bar": "Robert"}) + assert copied.default_headers["X-Bar"] == "Robert" + + with pytest.raises( + ValueError, + match="`default_headers` and `set_default_headers` arguments are mutually exclusive", + ): + client.copy(set_default_headers={}, default_headers={"X-Foo": "Bar"}) + + def test_copy_default_query(self) -> None: + client = OpenAI( + base_url=base_url, api_key=api_key, _strict_response_validation=True, default_query={"foo": "bar"} + ) + assert _get_params(client)["foo"] == "bar" + + # does not override the already given value when not specified + copied = client.copy() + assert _get_params(copied)["foo"] == "bar" + + # merges already given params + copied = client.copy(default_query={"bar": "stainless"}) + params = _get_params(copied) + assert params["foo"] == "bar" + assert params["bar"] == "stainless" + + # uses new values for any already given headers + copied = client.copy(default_query={"foo": "stainless"}) + assert _get_params(copied)["foo"] == "stainless" + + # set_default_query + + # completely overrides already set values + copied = client.copy(set_default_query={}) + assert _get_params(copied) == {} + + copied = client.copy(set_default_query={"bar": "Robert"}) + assert _get_params(copied)["bar"] == "Robert" + + with pytest.raises( + ValueError, + # TODO: update + match="`default_query` and `set_default_query` arguments are mutually exclusive", + ): + client.copy(set_default_query={}, default_query={"foo": "Bar"}) + + def test_copy_signature(self) -> None: + # ensure the same parameters that can be passed to the client are defined in the `.copy()` method + init_signature = inspect.signature( + # mypy doesn't like that we access the `__init__` property. + self.client.__init__, # type: ignore[misc] + ) + copy_signature = inspect.signature(self.client.copy) + exclude_params = {"transport", "proxies", "_strict_response_validation"} + + for name in init_signature.parameters.keys(): + if name in exclude_params: + continue + + copy_param = copy_signature.parameters.get(name) + assert copy_param is not None, f"copy() signature is missing the {name} param" + + def test_request_timeout(self) -> None: + request = self.client._build_request(FinalRequestOptions(method="get", url="/foo")) + timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore + assert timeout == DEFAULT_TIMEOUT + + request = self.client._build_request( + FinalRequestOptions(method="get", url="/foo", timeout=httpx.Timeout(100.0)) + ) + timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore + assert timeout == httpx.Timeout(100.0) + + def test_client_timeout_option(self) -> None: + client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True, timeout=httpx.Timeout(0)) + + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore + assert timeout == httpx.Timeout(0) + + def test_http_client_timeout_option(self) -> None: + # custom timeout given to the httpx client should be used + with httpx.Client(timeout=None) as http_client: + client = OpenAI( + base_url=base_url, api_key=api_key, _strict_response_validation=True, http_client=http_client + ) + + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore + assert timeout == httpx.Timeout(None) + + # no timeout given to the httpx client should not use the httpx default + with httpx.Client() as http_client: + client = OpenAI( + base_url=base_url, api_key=api_key, _strict_response_validation=True, http_client=http_client + ) + + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore + assert timeout == DEFAULT_TIMEOUT + + # explicitly passing the default timeout currently results in it being ignored + with httpx.Client(timeout=HTTPX_DEFAULT_TIMEOUT) as http_client: + client = OpenAI( + base_url=base_url, api_key=api_key, _strict_response_validation=True, http_client=http_client + ) + + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore + assert timeout == DEFAULT_TIMEOUT # our default + + def test_default_headers_option(self) -> None: + client = OpenAI( + base_url=base_url, api_key=api_key, _strict_response_validation=True, default_headers={"X-Foo": "bar"} + ) + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + assert request.headers.get("x-foo") == "bar" + assert request.headers.get("x-stainless-lang") == "python" + + client2 = OpenAI( + base_url=base_url, + api_key=api_key, + _strict_response_validation=True, + default_headers={ + "X-Foo": "stainless", + "X-Stainless-Lang": "my-overriding-header", + }, + ) + request = client2._build_request(FinalRequestOptions(method="get", url="/foo")) + assert request.headers.get("x-foo") == "stainless" + assert request.headers.get("x-stainless-lang") == "my-overriding-header" + + def test_validate_headers(self) -> None: + client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + assert request.headers.get("Authorization") == f"Bearer {api_key}" + + with pytest.raises(Exception): + client2 = OpenAI(base_url=base_url, api_key=None, _strict_response_validation=True) + _ = client2 + + def test_default_query_option(self) -> None: + client = OpenAI( + base_url=base_url, api_key=api_key, _strict_response_validation=True, default_query={"query_param": "bar"} + ) + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + url = httpx.URL(request.url) + assert dict(url.params) == {"query_param": "bar"} + + request = client._build_request( + FinalRequestOptions( + method="get", + url="/foo", + params={"foo": "baz", "query_param": "overriden"}, + ) + ) + url = httpx.URL(request.url) + assert dict(url.params) == {"foo": "baz", "query_param": "overriden"} + + def test_request_extra_json(self) -> None: + request = self.client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + json_data={"foo": "bar"}, + extra_json={"baz": False}, + ), + ) + data = json.loads(request.content.decode("utf-8")) + assert data == {"foo": "bar", "baz": False} + + request = self.client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + extra_json={"baz": False}, + ), + ) + data = json.loads(request.content.decode("utf-8")) + assert data == {"baz": False} + + # `extra_json` takes priority over `json_data` when keys clash + request = self.client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + json_data={"foo": "bar", "baz": True}, + extra_json={"baz": None}, + ), + ) + data = json.loads(request.content.decode("utf-8")) + assert data == {"foo": "bar", "baz": None} + + def test_request_extra_headers(self) -> None: + request = self.client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + **make_request_options(extra_headers={"X-Foo": "Foo"}), + ), + ) + assert request.headers.get("X-Foo") == "Foo" + + # `extra_headers` takes priority over `default_headers` when keys clash + request = self.client.with_options(default_headers={"X-Bar": "true"})._build_request( + FinalRequestOptions( + method="post", + url="/foo", + **make_request_options( + extra_headers={"X-Bar": "false"}, + ), + ), + ) + assert request.headers.get("X-Bar") == "false" + + def test_request_extra_query(self) -> None: + request = self.client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + **make_request_options( + extra_query={"my_query_param": "Foo"}, + ), + ), + ) + params = cast(Dict[str, str], dict(request.url.params)) + assert params == {"my_query_param": "Foo"} + + # if both `query` and `extra_query` are given, they are merged + request = self.client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + **make_request_options( + query={"bar": "1"}, + extra_query={"foo": "2"}, + ), + ), + ) + params = cast(Dict[str, str], dict(request.url.params)) + assert params == {"bar": "1", "foo": "2"} + + # `extra_query` takes priority over `query` when keys clash + request = self.client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + **make_request_options( + query={"foo": "1"}, + extra_query={"foo": "2"}, + ), + ), + ) + params = cast(Dict[str, str], dict(request.url.params)) + assert params == {"foo": "2"} + + @pytest.mark.respx(base_url=base_url) + def test_basic_union_response(self, respx_mock: MockRouter) -> None: + class Model1(BaseModel): + name: str + + class Model2(BaseModel): + foo: str + + respx_mock.get("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + + response = self.client.get("/foo", cast_to=cast(Any, Union[Model1, Model2])) + assert isinstance(response, Model2) + assert response.foo == "bar" + + @pytest.mark.respx(base_url=base_url) + def test_union_response_different_types(self, respx_mock: MockRouter) -> None: + """Union of objects with the same field name using a different type""" + + class Model1(BaseModel): + foo: int + + class Model2(BaseModel): + foo: str + + respx_mock.get("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + + response = self.client.get("/foo", cast_to=cast(Any, Union[Model1, Model2])) + assert isinstance(response, Model2) + assert response.foo == "bar" + + respx_mock.get("/foo").mock(return_value=httpx.Response(200, json={"foo": 1})) + + response = self.client.get("/foo", cast_to=cast(Any, Union[Model1, Model2])) + assert isinstance(response, Model1) + assert response.foo == 1 + + @pytest.mark.parametrize( + "client", + [ + OpenAI(base_url="http://localhost:5000/custom/path/", api_key=api_key, _strict_response_validation=True), + OpenAI( + base_url="http://localhost:5000/custom/path/", + api_key=api_key, + _strict_response_validation=True, + http_client=httpx.Client(), + ), + ], + ids=["standard", "custom http client"], + ) + def test_base_url_trailing_slash(self, client: OpenAI) -> None: + request = client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + json_data={"foo": "bar"}, + ), + ) + assert request.url == "http://localhost:5000/custom/path/foo" + + @pytest.mark.parametrize( + "client", + [ + OpenAI(base_url="http://localhost:5000/custom/path/", api_key=api_key, _strict_response_validation=True), + OpenAI( + base_url="http://localhost:5000/custom/path/", + api_key=api_key, + _strict_response_validation=True, + http_client=httpx.Client(), + ), + ], + ids=["standard", "custom http client"], + ) + def test_base_url_no_trailing_slash(self, client: OpenAI) -> None: + request = client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + json_data={"foo": "bar"}, + ), + ) + assert request.url == "http://localhost:5000/custom/path/foo" + + @pytest.mark.parametrize( + "client", + [ + OpenAI(base_url="http://localhost:5000/custom/path/", api_key=api_key, _strict_response_validation=True), + OpenAI( + base_url="http://localhost:5000/custom/path/", + api_key=api_key, + _strict_response_validation=True, + http_client=httpx.Client(), + ), + ], + ids=["standard", "custom http client"], + ) + def test_absolute_request_url(http://github.com/self,%20client:%20OpenAI) -> None: + request = client._build_request( + FinalRequestOptions( + method="post", + url="https://myapi.com/foo", + json_data={"foo": "bar"}, + ), + ) + assert request.url == "https://myapi.com/foo" + + def test_client_del(self) -> None: + client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + assert not client.is_closed() + + client.__del__() + + assert client.is_closed() + + def test_copied_client_does_not_close_http(self) -> None: + client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + assert not client.is_closed() + + copied = client.copy() + assert copied is not client + + copied.__del__() + + assert not copied.is_closed() + assert not client.is_closed() + + def test_client_context_manager(self) -> None: + client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + with client as c2: + assert c2 is client + assert not c2.is_closed() + assert not client.is_closed() + assert client.is_closed() + + @pytest.mark.respx(base_url=base_url) + def test_client_response_validation_error(self, respx_mock: MockRouter) -> None: + class Model(BaseModel): + foo: str + + respx_mock.get("/foo").mock(return_value=httpx.Response(200, json={"foo": {"invalid": True}})) + + with pytest.raises(APIResponseValidationError) as exc: + self.client.get("/foo", cast_to=Model) + + assert isinstance(exc.value.__cause__, ValidationError) + + @pytest.mark.respx(base_url=base_url) + def test_default_stream_cls(self, respx_mock: MockRouter) -> None: + class Model(BaseModel): + name: str + + respx_mock.post("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + + response = self.client.post("/foo", cast_to=Model, stream=True) + assert isinstance(response, Stream) + + @pytest.mark.respx(base_url=base_url) + def test_received_text_for_expected_json(self, respx_mock: MockRouter) -> None: + class Model(BaseModel): + name: str + + respx_mock.get("/foo").mock(return_value=httpx.Response(200, text="my-custom-format")) + + strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + + with pytest.raises(APIResponseValidationError): + strict_client.get("/foo", cast_to=Model) + + client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + + response = client.get("/foo", cast_to=Model) + assert isinstance(response, str) # type: ignore[unreachable] + + @pytest.mark.parametrize( + "remaining_retries,retry_after,timeout", + [ + [3, "20", 20], + [3, "0", 0.5], + [3, "-10", 0.5], + [3, "60", 60], + [3, "61", 0.5], + [3, "Fri, 29 Sep 2023 16:26:57 GMT", 20], + [3, "Fri, 29 Sep 2023 16:26:37 GMT", 0.5], + [3, "Fri, 29 Sep 2023 16:26:27 GMT", 0.5], + [3, "Fri, 29 Sep 2023 16:27:37 GMT", 60], + [3, "Fri, 29 Sep 2023 16:27:38 GMT", 0.5], + [3, "99999999999999999999999999999999999", 0.5], + [3, "Zun, 29 Sep 2023 16:26:27 GMT", 0.5], + [3, "", 0.5], + [2, "", 0.5 * 2.0], + [1, "", 0.5 * 4.0], + ], + ) + @mock.patch("time.time", mock.MagicMock(return_value=1696004797)) + def test_parse_retry_after_header(self, remaining_retries: int, retry_after: str, timeout: float) -> None: + client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + + headers = httpx.Headers({"retry-after": retry_after}) + options = FinalRequestOptions(method="get", url="/foo", max_retries=3) + calculated = client._calculate_retry_timeout(remaining_retries, options, headers) + assert calculated == pytest.approx(timeout, 0.5 * 0.875) # pyright: ignore[reportUnknownMemberType] + + +class TestAsyncOpenAI: + client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + + @pytest.mark.respx(base_url=base_url) + @pytest.mark.asyncio + async def test_raw_response(self, respx_mock: MockRouter) -> None: + respx_mock.post("/foo").mock(return_value=httpx.Response(200, json='{"foo": "bar"}')) + + response = await self.client.post("/foo", cast_to=httpx.Response) + assert response.status_code == 200 + assert isinstance(response, httpx.Response) + assert response.json() == '{"foo": "bar"}' + + @pytest.mark.respx(base_url=base_url) + @pytest.mark.asyncio + async def test_raw_response_for_binary(self, respx_mock: MockRouter) -> None: + respx_mock.post("/foo").mock( + return_value=httpx.Response(200, headers={"Content-Type": "application/binary"}, content='{"foo": "bar"}') + ) + + response = await self.client.post("/foo", cast_to=httpx.Response) + assert response.status_code == 200 + assert isinstance(response, httpx.Response) + assert response.json() == '{"foo": "bar"}' + + def test_copy(self) -> None: + copied = self.client.copy() + assert id(copied) != id(self.client) + + copied = self.client.copy(api_key="another My API Key") + assert copied.api_key == "another My API Key" + assert self.client.api_key == "My API Key" + + def test_copy_default_options(self) -> None: + # options that have a default are overridden correctly + copied = self.client.copy(max_retries=7) + assert copied.max_retries == 7 + assert self.client.max_retries == 2 + + copied2 = copied.copy(max_retries=6) + assert copied2.max_retries == 6 + assert copied.max_retries == 7 + + # timeout + assert isinstance(self.client.timeout, httpx.Timeout) + copied = self.client.copy(timeout=None) + assert copied.timeout is None + assert isinstance(self.client.timeout, httpx.Timeout) + + def test_copy_default_headers(self) -> None: + client = AsyncOpenAI( + base_url=base_url, api_key=api_key, _strict_response_validation=True, default_headers={"X-Foo": "bar"} + ) + assert client.default_headers["X-Foo"] == "bar" + + # does not override the already given value when not specified + copied = client.copy() + assert copied.default_headers["X-Foo"] == "bar" + + # merges already given headers + copied = client.copy(default_headers={"X-Bar": "stainless"}) + assert copied.default_headers["X-Foo"] == "bar" + assert copied.default_headers["X-Bar"] == "stainless" + + # uses new values for any already given headers + copied = client.copy(default_headers={"X-Foo": "stainless"}) + assert copied.default_headers["X-Foo"] == "stainless" + + # set_default_headers + + # completely overrides already set values + copied = client.copy(set_default_headers={}) + assert copied.default_headers.get("X-Foo") is None + + copied = client.copy(set_default_headers={"X-Bar": "Robert"}) + assert copied.default_headers["X-Bar"] == "Robert" + + with pytest.raises( + ValueError, + match="`default_headers` and `set_default_headers` arguments are mutually exclusive", + ): + client.copy(set_default_headers={}, default_headers={"X-Foo": "Bar"}) + + def test_copy_default_query(self) -> None: + client = AsyncOpenAI( + base_url=base_url, api_key=api_key, _strict_response_validation=True, default_query={"foo": "bar"} + ) + assert _get_params(client)["foo"] == "bar" + + # does not override the already given value when not specified + copied = client.copy() + assert _get_params(copied)["foo"] == "bar" + + # merges already given params + copied = client.copy(default_query={"bar": "stainless"}) + params = _get_params(copied) + assert params["foo"] == "bar" + assert params["bar"] == "stainless" + + # uses new values for any already given headers + copied = client.copy(default_query={"foo": "stainless"}) + assert _get_params(copied)["foo"] == "stainless" + + # set_default_query + + # completely overrides already set values + copied = client.copy(set_default_query={}) + assert _get_params(copied) == {} + + copied = client.copy(set_default_query={"bar": "Robert"}) + assert _get_params(copied)["bar"] == "Robert" + + with pytest.raises( + ValueError, + # TODO: update + match="`default_query` and `set_default_query` arguments are mutually exclusive", + ): + client.copy(set_default_query={}, default_query={"foo": "Bar"}) + + def test_copy_signature(self) -> None: + # ensure the same parameters that can be passed to the client are defined in the `.copy()` method + init_signature = inspect.signature( + # mypy doesn't like that we access the `__init__` property. + self.client.__init__, # type: ignore[misc] + ) + copy_signature = inspect.signature(self.client.copy) + exclude_params = {"transport", "proxies", "_strict_response_validation"} + + for name in init_signature.parameters.keys(): + if name in exclude_params: + continue + + copy_param = copy_signature.parameters.get(name) + assert copy_param is not None, f"copy() signature is missing the {name} param" + + async def test_request_timeout(self) -> None: + request = self.client._build_request(FinalRequestOptions(method="get", url="/foo")) + timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore + assert timeout == DEFAULT_TIMEOUT + + request = self.client._build_request( + FinalRequestOptions(method="get", url="/foo", timeout=httpx.Timeout(100.0)) + ) + timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore + assert timeout == httpx.Timeout(100.0) + + async def test_client_timeout_option(self) -> None: + client = AsyncOpenAI( + base_url=base_url, api_key=api_key, _strict_response_validation=True, timeout=httpx.Timeout(0) + ) + + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore + assert timeout == httpx.Timeout(0) + + async def test_http_client_timeout_option(self) -> None: + # custom timeout given to the httpx client should be used + async with httpx.AsyncClient(timeout=None) as http_client: + client = AsyncOpenAI( + base_url=base_url, api_key=api_key, _strict_response_validation=True, http_client=http_client + ) + + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore + assert timeout == httpx.Timeout(None) + + # no timeout given to the httpx client should not use the httpx default + async with httpx.AsyncClient() as http_client: + client = AsyncOpenAI( + base_url=base_url, api_key=api_key, _strict_response_validation=True, http_client=http_client + ) + + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore + assert timeout == DEFAULT_TIMEOUT + + # explicitly passing the default timeout currently results in it being ignored + async with httpx.AsyncClient(timeout=HTTPX_DEFAULT_TIMEOUT) as http_client: + client = AsyncOpenAI( + base_url=base_url, api_key=api_key, _strict_response_validation=True, http_client=http_client + ) + + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore + assert timeout == DEFAULT_TIMEOUT # our default + + def test_default_headers_option(self) -> None: + client = AsyncOpenAI( + base_url=base_url, api_key=api_key, _strict_response_validation=True, default_headers={"X-Foo": "bar"} + ) + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + assert request.headers.get("x-foo") == "bar" + assert request.headers.get("x-stainless-lang") == "python" + + client2 = AsyncOpenAI( + base_url=base_url, + api_key=api_key, + _strict_response_validation=True, + default_headers={ + "X-Foo": "stainless", + "X-Stainless-Lang": "my-overriding-header", + }, + ) + request = client2._build_request(FinalRequestOptions(method="get", url="/foo")) + assert request.headers.get("x-foo") == "stainless" + assert request.headers.get("x-stainless-lang") == "my-overriding-header" + + def test_validate_headers(self) -> None: + client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + assert request.headers.get("Authorization") == f"Bearer {api_key}" + + with pytest.raises(Exception): + client2 = AsyncOpenAI(base_url=base_url, api_key=None, _strict_response_validation=True) + _ = client2 + + def test_default_query_option(self) -> None: + client = AsyncOpenAI( + base_url=base_url, api_key=api_key, _strict_response_validation=True, default_query={"query_param": "bar"} + ) + request = client._build_request(FinalRequestOptions(method="get", url="/foo")) + url = httpx.URL(request.url) + assert dict(url.params) == {"query_param": "bar"} + + request = client._build_request( + FinalRequestOptions( + method="get", + url="/foo", + params={"foo": "baz", "query_param": "overriden"}, + ) + ) + url = httpx.URL(request.url) + assert dict(url.params) == {"foo": "baz", "query_param": "overriden"} + + def test_request_extra_json(self) -> None: + request = self.client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + json_data={"foo": "bar"}, + extra_json={"baz": False}, + ), + ) + data = json.loads(request.content.decode("utf-8")) + assert data == {"foo": "bar", "baz": False} + + request = self.client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + extra_json={"baz": False}, + ), + ) + data = json.loads(request.content.decode("utf-8")) + assert data == {"baz": False} + + # `extra_json` takes priority over `json_data` when keys clash + request = self.client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + json_data={"foo": "bar", "baz": True}, + extra_json={"baz": None}, + ), + ) + data = json.loads(request.content.decode("utf-8")) + assert data == {"foo": "bar", "baz": None} + + def test_request_extra_headers(self) -> None: + request = self.client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + **make_request_options(extra_headers={"X-Foo": "Foo"}), + ), + ) + assert request.headers.get("X-Foo") == "Foo" + + # `extra_headers` takes priority over `default_headers` when keys clash + request = self.client.with_options(default_headers={"X-Bar": "true"})._build_request( + FinalRequestOptions( + method="post", + url="/foo", + **make_request_options( + extra_headers={"X-Bar": "false"}, + ), + ), + ) + assert request.headers.get("X-Bar") == "false" + + def test_request_extra_query(self) -> None: + request = self.client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + **make_request_options( + extra_query={"my_query_param": "Foo"}, + ), + ), + ) + params = cast(Dict[str, str], dict(request.url.params)) + assert params == {"my_query_param": "Foo"} + + # if both `query` and `extra_query` are given, they are merged + request = self.client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + **make_request_options( + query={"bar": "1"}, + extra_query={"foo": "2"}, + ), + ), + ) + params = cast(Dict[str, str], dict(request.url.params)) + assert params == {"bar": "1", "foo": "2"} + + # `extra_query` takes priority over `query` when keys clash + request = self.client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + **make_request_options( + query={"foo": "1"}, + extra_query={"foo": "2"}, + ), + ), + ) + params = cast(Dict[str, str], dict(request.url.params)) + assert params == {"foo": "2"} + + @pytest.mark.respx(base_url=base_url) + async def test_basic_union_response(self, respx_mock: MockRouter) -> None: + class Model1(BaseModel): + name: str + + class Model2(BaseModel): + foo: str + + respx_mock.get("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + + response = await self.client.get("/foo", cast_to=cast(Any, Union[Model1, Model2])) + assert isinstance(response, Model2) + assert response.foo == "bar" + + @pytest.mark.respx(base_url=base_url) + async def test_union_response_different_types(self, respx_mock: MockRouter) -> None: + """Union of objects with the same field name using a different type""" + + class Model1(BaseModel): + foo: int + + class Model2(BaseModel): + foo: str + + respx_mock.get("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + + response = await self.client.get("/foo", cast_to=cast(Any, Union[Model1, Model2])) + assert isinstance(response, Model2) + assert response.foo == "bar" + + respx_mock.get("/foo").mock(return_value=httpx.Response(200, json={"foo": 1})) + + response = await self.client.get("/foo", cast_to=cast(Any, Union[Model1, Model2])) + assert isinstance(response, Model1) + assert response.foo == 1 + + @pytest.mark.parametrize( + "client", + [ + AsyncOpenAI( + base_url="http://localhost:5000/custom/path/", api_key=api_key, _strict_response_validation=True + ), + AsyncOpenAI( + base_url="http://localhost:5000/custom/path/", + api_key=api_key, + _strict_response_validation=True, + http_client=httpx.AsyncClient(), + ), + ], + ids=["standard", "custom http client"], + ) + def test_base_url_trailing_slash(self, client: AsyncOpenAI) -> None: + request = client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + json_data={"foo": "bar"}, + ), + ) + assert request.url == "http://localhost:5000/custom/path/foo" + + @pytest.mark.parametrize( + "client", + [ + AsyncOpenAI( + base_url="http://localhost:5000/custom/path/", api_key=api_key, _strict_response_validation=True + ), + AsyncOpenAI( + base_url="http://localhost:5000/custom/path/", + api_key=api_key, + _strict_response_validation=True, + http_client=httpx.AsyncClient(), + ), + ], + ids=["standard", "custom http client"], + ) + def test_base_url_no_trailing_slash(self, client: AsyncOpenAI) -> None: + request = client._build_request( + FinalRequestOptions( + method="post", + url="/foo", + json_data={"foo": "bar"}, + ), + ) + assert request.url == "http://localhost:5000/custom/path/foo" + + @pytest.mark.parametrize( + "client", + [ + AsyncOpenAI( + base_url="http://localhost:5000/custom/path/", api_key=api_key, _strict_response_validation=True + ), + AsyncOpenAI( + base_url="http://localhost:5000/custom/path/", + api_key=api_key, + _strict_response_validation=True, + http_client=httpx.AsyncClient(), + ), + ], + ids=["standard", "custom http client"], + ) + def test_absolute_request_url(http://github.com/self,%20client:%20AsyncOpenAI) -> None: + request = client._build_request( + FinalRequestOptions( + method="post", + url="https://myapi.com/foo", + json_data={"foo": "bar"}, + ), + ) + assert request.url == "https://myapi.com/foo" + + async def test_client_del(self) -> None: + client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + assert not client.is_closed() + + client.__del__() + + await asyncio.sleep(0.2) + assert client.is_closed() + + async def test_copied_client_does_not_close_http(self) -> None: + client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + assert not client.is_closed() + + copied = client.copy() + assert copied is not client + + copied.__del__() + + await asyncio.sleep(0.2) + assert not copied.is_closed() + assert not client.is_closed() + + async def test_client_context_manager(self) -> None: + client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + async with client as c2: + assert c2 is client + assert not c2.is_closed() + assert not client.is_closed() + assert client.is_closed() + + @pytest.mark.respx(base_url=base_url) + @pytest.mark.asyncio + async def test_client_response_validation_error(self, respx_mock: MockRouter) -> None: + class Model(BaseModel): + foo: str + + respx_mock.get("/foo").mock(return_value=httpx.Response(200, json={"foo": {"invalid": True}})) + + with pytest.raises(APIResponseValidationError) as exc: + await self.client.get("/foo", cast_to=Model) + + assert isinstance(exc.value.__cause__, ValidationError) + + @pytest.mark.respx(base_url=base_url) + @pytest.mark.asyncio + async def test_default_stream_cls(self, respx_mock: MockRouter) -> None: + class Model(BaseModel): + name: str + + respx_mock.post("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + + response = await self.client.post("/foo", cast_to=Model, stream=True) + assert isinstance(response, AsyncStream) + + @pytest.mark.respx(base_url=base_url) + @pytest.mark.asyncio + async def test_received_text_for_expected_json(self, respx_mock: MockRouter) -> None: + class Model(BaseModel): + name: str + + respx_mock.get("/foo").mock(return_value=httpx.Response(200, text="my-custom-format")) + + strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + + with pytest.raises(APIResponseValidationError): + await strict_client.get("/foo", cast_to=Model) + + client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + + response = await client.get("/foo", cast_to=Model) + assert isinstance(response, str) # type: ignore[unreachable] + + @pytest.mark.parametrize( + "remaining_retries,retry_after,timeout", + [ + [3, "20", 20], + [3, "0", 0.5], + [3, "-10", 0.5], + [3, "60", 60], + [3, "61", 0.5], + [3, "Fri, 29 Sep 2023 16:26:57 GMT", 20], + [3, "Fri, 29 Sep 2023 16:26:37 GMT", 0.5], + [3, "Fri, 29 Sep 2023 16:26:27 GMT", 0.5], + [3, "Fri, 29 Sep 2023 16:27:37 GMT", 60], + [3, "Fri, 29 Sep 2023 16:27:38 GMT", 0.5], + [3, "99999999999999999999999999999999999", 0.5], + [3, "Zun, 29 Sep 2023 16:26:27 GMT", 0.5], + [3, "", 0.5], + [2, "", 0.5 * 2.0], + [1, "", 0.5 * 4.0], + ], + ) + @mock.patch("time.time", mock.MagicMock(return_value=1696004797)) + @pytest.mark.asyncio + async def test_parse_retry_after_header(self, remaining_retries: int, retry_after: str, timeout: float) -> None: + client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + + headers = httpx.Headers({"retry-after": retry_after}) + options = FinalRequestOptions(method="get", url="/foo", max_retries=3) + calculated = client._calculate_retry_timeout(remaining_retries, options, headers) + assert calculated == pytest.approx(timeout, 0.5 * 0.875) # pyright: ignore[reportUnknownMemberType] diff --git a/tests/test_deepcopy.py b/tests/test_deepcopy.py new file mode 100644 index 0000000000..8cf65ce94e --- /dev/null +++ b/tests/test_deepcopy.py @@ -0,0 +1,59 @@ +from openai._utils import deepcopy_minimal + + +def assert_different_identities(obj1: object, obj2: object) -> None: + assert obj1 == obj2 + assert id(obj1) != id(obj2) + + +def test_simple_dict() -> None: + obj1 = {"foo": "bar"} + obj2 = deepcopy_minimal(obj1) + assert_different_identities(obj1, obj2) + + +def test_nested_dict() -> None: + obj1 = {"foo": {"bar": True}} + obj2 = deepcopy_minimal(obj1) + assert_different_identities(obj1, obj2) + assert_different_identities(obj1["foo"], obj2["foo"]) + + +def test_complex_nested_dict() -> None: + obj1 = {"foo": {"bar": [{"hello": "world"}]}} + obj2 = deepcopy_minimal(obj1) + assert_different_identities(obj1, obj2) + assert_different_identities(obj1["foo"], obj2["foo"]) + assert_different_identities(obj1["foo"]["bar"], obj2["foo"]["bar"]) + assert_different_identities(obj1["foo"]["bar"][0], obj2["foo"]["bar"][0]) + + +def test_simple_list() -> None: + obj1 = ["a", "b", "c"] + obj2 = deepcopy_minimal(obj1) + assert_different_identities(obj1, obj2) + + +def test_nested_list() -> None: + obj1 = ["a", [1, 2, 3]] + obj2 = deepcopy_minimal(obj1) + assert_different_identities(obj1, obj2) + assert_different_identities(obj1[1], obj2[1]) + + +class MyObject: + ... + + +def test_ignores_other_types() -> None: + # custom classes + my_obj = MyObject() + obj1 = {"foo": my_obj} + obj2 = deepcopy_minimal(obj1) + assert_different_identities(obj1, obj2) + assert obj1["foo"] is my_obj + + # tuples + obj3 = ("a", "b") + obj4 = deepcopy_minimal(obj3) + assert obj3 is obj4 diff --git a/tests/test_extract_files.py b/tests/test_extract_files.py new file mode 100644 index 0000000000..554487da42 --- /dev/null +++ b/tests/test_extract_files.py @@ -0,0 +1,64 @@ +from __future__ import annotations + +from typing import Sequence + +import pytest + +from openai._types import FileTypes +from openai._utils import extract_files + + +def test_removes_files_from_input() -> None: + query = {"foo": "bar"} + assert extract_files(query, paths=[]) == [] + assert query == {"foo": "bar"} + + query2 = {"foo": b"Bar", "hello": "world"} + assert extract_files(query2, paths=[["foo"]]) == [("foo", b"Bar")] + assert query2 == {"hello": "world"} + + query3 = {"foo": {"foo": {"bar": b"Bar"}}, "hello": "world"} + assert extract_files(query3, paths=[["foo", "foo", "bar"]]) == [("foo[foo][bar]", b"Bar")] + assert query3 == {"foo": {"foo": {}}, "hello": "world"} + + query4 = {"foo": {"bar": b"Bar", "baz": "foo"}, "hello": "world"} + assert extract_files(query4, paths=[["foo", "bar"]]) == [("foo[bar]", b"Bar")] + assert query4 == {"hello": "world", "foo": {"baz": "foo"}} + + +def test_multiple_files() -> None: + query = {"documents": [{"file": b"My first file"}, {"file": b"My second file"}]} + assert extract_files(query, paths=[["documents", "", "file"]]) == [ + ("documents[][file]", b"My first file"), + ("documents[][file]", b"My second file"), + ] + assert query == {"documents": [{}, {}]} + + +@pytest.mark.parametrize( + "query,paths,expected", + [ + [ + {"foo": {"bar": "baz"}}, + [["foo", "", "bar"]], + [], + ], + [ + {"foo": ["bar", "baz"]}, + [["foo", "bar"]], + [], + ], + [ + {"foo": {"bar": "baz"}}, + [["foo", "foo"]], + [], + ], + ], + ids=["dict expecting array", "arraye expecting dict", "unknown keys"], +) +def test_ignores_incorrect_paths( + query: dict[str, object], + paths: Sequence[Sequence[str]], + expected: list[tuple[str, FileTypes]], +) -> None: + assert extract_files(query, paths=paths) == expected diff --git a/tests/test_files.py b/tests/test_files.py new file mode 100644 index 0000000000..15d5c6a811 --- /dev/null +++ b/tests/test_files.py @@ -0,0 +1,51 @@ +from pathlib import Path + +import anyio +import pytest +from dirty_equals import IsDict, IsList, IsBytes, IsTuple + +from openai._files import to_httpx_files, async_to_httpx_files + +readme_path = Path(__file__).parent.parent.joinpath("README.md") + + +def test_pathlib_includes_file_name() -> None: + result = to_httpx_files({"file": readme_path}) + print(result) + assert result == IsDict({"file": IsTuple("README.md", IsBytes())}) + + +def test_tuple_input() -> None: + result = to_httpx_files([("file", readme_path)]) + print(result) + assert result == IsList(IsTuple("file", IsTuple("README.md", IsBytes()))) + + +@pytest.mark.asyncio +async def test_async_pathlib_includes_file_name() -> None: + result = await async_to_httpx_files({"file": readme_path}) + print(result) + assert result == IsDict({"file": IsTuple("README.md", IsBytes())}) + + +@pytest.mark.asyncio +async def test_async_supports_anyio_path() -> None: + result = await async_to_httpx_files({"file": anyio.Path(readme_path)}) + print(result) + assert result == IsDict({"file": IsTuple("README.md", IsBytes())}) + + +@pytest.mark.asyncio +async def test_async_tuple_input() -> None: + result = await async_to_httpx_files([("file", readme_path)]) + print(result) + assert result == IsList(IsTuple("file", IsTuple("README.md", IsBytes()))) + + +def test_string_not_allowed() -> None: + with pytest.raises(TypeError, match="Expected file types input to be a FileContent type or to be a tuple"): + to_httpx_files( + { + "file": "foo", # type: ignore + } + ) diff --git a/tests/test_models.py b/tests/test_models.py new file mode 100644 index 0000000000..713bd2cb1b --- /dev/null +++ b/tests/test_models.py @@ -0,0 +1,573 @@ +import json +from typing import Any, Dict, List, Union, Optional, cast +from datetime import datetime, timezone +from typing_extensions import Literal + +import pytest +import pydantic +from pydantic import Field + +from openai._compat import PYDANTIC_V2, parse_obj, model_dump, model_json +from openai._models import BaseModel + + +class BasicModel(BaseModel): + foo: str + + +@pytest.mark.parametrize("value", ["hello", 1], ids=["correct type", "mismatched"]) +def test_basic(value: object) -> None: + m = BasicModel.construct(foo=value) + assert m.foo == value + + +def test_directly_nested_model() -> None: + class NestedModel(BaseModel): + nested: BasicModel + + m = NestedModel.construct(nested={"foo": "Foo!"}) + assert m.nested.foo == "Foo!" + + # mismatched types + m = NestedModel.construct(nested="hello!") + assert m.nested == "hello!" + + +def test_optional_nested_model() -> None: + class NestedModel(BaseModel): + nested: Optional[BasicModel] + + m1 = NestedModel.construct(nested=None) + assert m1.nested is None + + m2 = NestedModel.construct(nested={"foo": "bar"}) + assert m2.nested is not None + assert m2.nested.foo == "bar" + + # mismatched types + m3 = NestedModel.construct(nested={"foo"}) + assert isinstance(cast(Any, m3.nested), set) + assert m3.nested == {"foo"} + + +def test_list_nested_model() -> None: + class NestedModel(BaseModel): + nested: List[BasicModel] + + m = NestedModel.construct(nested=[{"foo": "bar"}, {"foo": "2"}]) + assert m.nested is not None + assert isinstance(m.nested, list) + assert len(m.nested) == 2 + assert m.nested[0].foo == "bar" + assert m.nested[1].foo == "2" + + # mismatched types + m = NestedModel.construct(nested=True) + assert cast(Any, m.nested) is True + + m = NestedModel.construct(nested=[False]) + assert cast(Any, m.nested) == [False] + + +def test_optional_list_nested_model() -> None: + class NestedModel(BaseModel): + nested: Optional[List[BasicModel]] + + m1 = NestedModel.construct(nested=[{"foo": "bar"}, {"foo": "2"}]) + assert m1.nested is not None + assert isinstance(m1.nested, list) + assert len(m1.nested) == 2 + assert m1.nested[0].foo == "bar" + assert m1.nested[1].foo == "2" + + m2 = NestedModel.construct(nested=None) + assert m2.nested is None + + # mismatched types + m3 = NestedModel.construct(nested={1}) + assert cast(Any, m3.nested) == {1} + + m4 = NestedModel.construct(nested=[False]) + assert cast(Any, m4.nested) == [False] + + +def test_list_optional_items_nested_model() -> None: + class NestedModel(BaseModel): + nested: List[Optional[BasicModel]] + + m = NestedModel.construct(nested=[None, {"foo": "bar"}]) + assert m.nested is not None + assert isinstance(m.nested, list) + assert len(m.nested) == 2 + assert m.nested[0] is None + assert m.nested[1] is not None + assert m.nested[1].foo == "bar" + + # mismatched types + m3 = NestedModel.construct(nested="foo") + assert cast(Any, m3.nested) == "foo" + + m4 = NestedModel.construct(nested=[False]) + assert cast(Any, m4.nested) == [False] + + +def test_list_mismatched_type() -> None: + class NestedModel(BaseModel): + nested: List[str] + + m = NestedModel.construct(nested=False) + assert cast(Any, m.nested) is False + + +def test_raw_dictionary() -> None: + class NestedModel(BaseModel): + nested: Dict[str, str] + + m = NestedModel.construct(nested={"hello": "world"}) + assert m.nested == {"hello": "world"} + + # mismatched types + m = NestedModel.construct(nested=False) + assert cast(Any, m.nested) is False + + +def test_nested_dictionary_model() -> None: + class NestedModel(BaseModel): + nested: Dict[str, BasicModel] + + m = NestedModel.construct(nested={"hello": {"foo": "bar"}}) + assert isinstance(m.nested, dict) + assert m.nested["hello"].foo == "bar" + + # mismatched types + m = NestedModel.construct(nested={"hello": False}) + assert cast(Any, m.nested["hello"]) is False + + +def test_unknown_fields() -> None: + m1 = BasicModel.construct(foo="foo", unknown=1) + assert m1.foo == "foo" + assert cast(Any, m1).unknown == 1 + + m2 = BasicModel.construct(foo="foo", unknown={"foo_bar": True}) + assert m2.foo == "foo" + assert cast(Any, m2).unknown == {"foo_bar": True} + + assert model_dump(m2) == {"foo": "foo", "unknown": {"foo_bar": True}} + + +def test_strict_validation_unknown_fields() -> None: + class Model(BaseModel): + foo: str + + model = parse_obj(Model, dict(foo="hello!", user="Robert")) + assert model.foo == "hello!" + assert cast(Any, model).user == "Robert" + + assert model_dump(model) == {"foo": "hello!", "user": "Robert"} + + +def test_aliases() -> None: + class Model(BaseModel): + my_field: int = Field(alias="myField") + + m = Model.construct(myField=1) + assert m.my_field == 1 + + # mismatched types + m = Model.construct(myField={"hello": False}) + assert cast(Any, m.my_field) == {"hello": False} + + +def test_repr() -> None: + model = BasicModel(foo="bar") + assert str(model) == "BasicModel(foo='bar')" + assert repr(model) == "BasicModel(foo='bar')" + + +def test_repr_nested_model() -> None: + class Child(BaseModel): + name: str + age: int + + class Parent(BaseModel): + name: str + child: Child + + model = Parent(name="Robert", child=Child(name="Foo", age=5)) + assert str(model) == "Parent(name='Robert', child=Child(name='Foo', age=5))" + assert repr(model) == "Parent(name='Robert', child=Child(name='Foo', age=5))" + + +def test_optional_list() -> None: + class Submodel(BaseModel): + name: str + + class Model(BaseModel): + items: Optional[List[Submodel]] + + m = Model.construct(items=None) + assert m.items is None + + m = Model.construct(items=[]) + assert m.items == [] + + m = Model.construct(items=[{"name": "Robert"}]) + assert m.items is not None + assert len(m.items) == 1 + assert m.items[0].name == "Robert" + + +def test_nested_union_of_models() -> None: + class Submodel1(BaseModel): + bar: bool + + class Submodel2(BaseModel): + thing: str + + class Model(BaseModel): + foo: Union[Submodel1, Submodel2] + + m = Model.construct(foo={"thing": "hello"}) + assert isinstance(m.foo, Submodel2) + assert m.foo.thing == "hello" + + +def test_nested_union_of_mixed_types() -> None: + class Submodel1(BaseModel): + bar: bool + + class Model(BaseModel): + foo: Union[Submodel1, Literal[True], Literal["CARD_HOLDER"]] + + m = Model.construct(foo=True) + assert m.foo is True + + m = Model.construct(foo="CARD_HOLDER") + assert m.foo is "CARD_HOLDER" + + m = Model.construct(foo={"bar": False}) + assert isinstance(m.foo, Submodel1) + assert m.foo.bar is False + + +def test_nested_union_multiple_variants() -> None: + class Submodel1(BaseModel): + bar: bool + + class Submodel2(BaseModel): + thing: str + + class Submodel3(BaseModel): + foo: int + + class Model(BaseModel): + foo: Union[Submodel1, Submodel2, None, Submodel3] + + m = Model.construct(foo={"thing": "hello"}) + assert isinstance(m.foo, Submodel2) + assert m.foo.thing == "hello" + + m = Model.construct(foo=None) + assert m.foo is None + + m = Model.construct() + assert m.foo is None + + m = Model.construct(foo={"foo": "1"}) + assert isinstance(m.foo, Submodel3) + assert m.foo.foo == 1 + + +def test_nested_union_invalid_data() -> None: + class Submodel1(BaseModel): + level: int + + class Submodel2(BaseModel): + name: str + + class Model(BaseModel): + foo: Union[Submodel1, Submodel2] + + m = Model.construct(foo=True) + assert cast(bool, m.foo) is True + + m = Model.construct(foo={"name": 3}) + if PYDANTIC_V2: + assert isinstance(m.foo, Submodel1) + assert m.foo.name == 3 # type: ignore + else: + assert isinstance(m.foo, Submodel2) + assert m.foo.name == "3" + + +def test_list_of_unions() -> None: + class Submodel1(BaseModel): + level: int + + class Submodel2(BaseModel): + name: str + + class Model(BaseModel): + items: List[Union[Submodel1, Submodel2]] + + m = Model.construct(items=[{"level": 1}, {"name": "Robert"}]) + assert len(m.items) == 2 + assert isinstance(m.items[0], Submodel1) + assert m.items[0].level == 1 + assert isinstance(m.items[1], Submodel2) + assert m.items[1].name == "Robert" + + m = Model.construct(items=[{"level": -1}, 156]) + assert len(m.items) == 2 + assert isinstance(m.items[0], Submodel1) + assert m.items[0].level == -1 + assert m.items[1] == 156 + + +def test_union_of_lists() -> None: + class SubModel1(BaseModel): + level: int + + class SubModel2(BaseModel): + name: str + + class Model(BaseModel): + items: Union[List[SubModel1], List[SubModel2]] + + # with one valid entry + m = Model.construct(items=[{"name": "Robert"}]) + assert len(m.items) == 1 + assert isinstance(m.items[0], SubModel2) + assert m.items[0].name == "Robert" + + # with two entries pointing to different types + m = Model.construct(items=[{"level": 1}, {"name": "Robert"}]) + assert len(m.items) == 2 + assert isinstance(m.items[0], SubModel1) + assert m.items[0].level == 1 + assert isinstance(m.items[1], SubModel1) + assert cast(Any, m.items[1]).name == "Robert" + + # with two entries pointing to *completely* different types + m = Model.construct(items=[{"level": -1}, 156]) + assert len(m.items) == 2 + assert isinstance(m.items[0], SubModel1) + assert m.items[0].level == -1 + assert m.items[1] == 156 + + +def test_dict_of_union() -> None: + class SubModel1(BaseModel): + name: str + + class SubModel2(BaseModel): + foo: str + + class Model(BaseModel): + data: Dict[str, Union[SubModel1, SubModel2]] + + m = Model.construct(data={"hello": {"name": "there"}, "foo": {"foo": "bar"}}) + assert len(list(m.data.keys())) == 2 + assert isinstance(m.data["hello"], SubModel1) + assert m.data["hello"].name == "there" + assert isinstance(m.data["foo"], SubModel2) + assert m.data["foo"].foo == "bar" + + # TODO: test mismatched type + + +def test_double_nested_union() -> None: + class SubModel1(BaseModel): + name: str + + class SubModel2(BaseModel): + bar: str + + class Model(BaseModel): + data: Dict[str, List[Union[SubModel1, SubModel2]]] + + m = Model.construct(data={"foo": [{"bar": "baz"}, {"name": "Robert"}]}) + assert len(m.data["foo"]) == 2 + + entry1 = m.data["foo"][0] + assert isinstance(entry1, SubModel2) + assert entry1.bar == "baz" + + entry2 = m.data["foo"][1] + assert isinstance(entry2, SubModel1) + assert entry2.name == "Robert" + + # TODO: test mismatched type + + +def test_union_of_dict() -> None: + class SubModel1(BaseModel): + name: str + + class SubModel2(BaseModel): + foo: str + + class Model(BaseModel): + data: Union[Dict[str, SubModel1], Dict[str, SubModel2]] + + m = Model.construct(data={"hello": {"name": "there"}, "foo": {"foo": "bar"}}) + assert len(list(m.data.keys())) == 2 + assert isinstance(m.data["hello"], SubModel1) + assert m.data["hello"].name == "there" + assert isinstance(m.data["foo"], SubModel1) + assert cast(Any, m.data["foo"]).foo == "bar" + + +def test_iso8601_datetime() -> None: + class Model(BaseModel): + created_at: datetime + + expected = datetime(2019, 12, 27, 18, 11, 19, 117000, tzinfo=timezone.utc) + + if PYDANTIC_V2: + expected_json = '{"created_at":"2019-12-27T18:11:19.117000Z"}' + else: + expected_json = '{"created_at": "2019-12-27T18:11:19.117000+00:00"}' + + model = Model.construct(created_at="2019-12-27T18:11:19.117Z") + assert model.created_at == expected + assert model_json(model) == expected_json + + model = parse_obj(Model, dict(created_at="2019-12-27T18:11:19.117Z")) + assert model.created_at == expected + assert model_json(model) == expected_json + + +def test_does_not_coerce_int() -> None: + class Model(BaseModel): + bar: int + + assert Model.construct(bar=1).bar == 1 + assert Model.construct(bar=10.9).bar == 10.9 + assert Model.construct(bar="19").bar == "19" # type: ignore[comparison-overlap] + assert Model.construct(bar=False).bar is False + + +def test_int_to_float_safe_conversion() -> None: + class Model(BaseModel): + float_field: float + + m = Model.construct(float_field=10) + assert m.float_field == 10.0 + assert isinstance(m.float_field, float) + + m = Model.construct(float_field=10.12) + assert m.float_field == 10.12 + assert isinstance(m.float_field, float) + + # number too big + m = Model.construct(float_field=2**53 + 1) + assert m.float_field == 2**53 + 1 + assert isinstance(m.float_field, int) + + +def test_deprecated_alias() -> None: + class Model(BaseModel): + resource_id: str = Field(alias="model_id") + + @property + def model_id(self) -> str: + return self.resource_id + + m = Model.construct(model_id="id") + assert m.model_id == "id" + assert m.resource_id == "id" + assert m.resource_id is m.model_id + + m = parse_obj(Model, {"model_id": "id"}) + assert m.model_id == "id" + assert m.resource_id == "id" + assert m.resource_id is m.model_id + + +def test_omitted_fields() -> None: + class Model(BaseModel): + resource_id: Optional[str] = None + + m = Model.construct() + assert "resource_id" not in m.model_fields_set + + m = Model.construct(resource_id=None) + assert "resource_id" in m.model_fields_set + + m = Model.construct(resource_id="foo") + assert "resource_id" in m.model_fields_set + + +def test_forwards_compat_model_dump_method() -> None: + class Model(BaseModel): + foo: Optional[str] = Field(alias="FOO", default=None) + + m = Model(FOO="hello") + assert m.model_dump() == {"foo": "hello"} + assert m.model_dump(include={"bar"}) == {} + assert m.model_dump(exclude={"foo"}) == {} + assert m.model_dump(by_alias=True) == {"FOO": "hello"} + + m2 = Model() + assert m2.model_dump() == {"foo": None} + assert m2.model_dump(exclude_unset=True) == {} + assert m2.model_dump(exclude_none=True) == {} + assert m2.model_dump(exclude_defaults=True) == {} + + m3 = Model(FOO=None) + assert m3.model_dump() == {"foo": None} + assert m3.model_dump(exclude_none=True) == {} + + if not PYDANTIC_V2: + with pytest.raises(ValueError, match="mode is only supported in Pydantic v2"): + m.model_dump(mode="json") + + with pytest.raises(ValueError, match="round_trip is only supported in Pydantic v2"): + m.model_dump(round_trip=True) + + with pytest.raises(ValueError, match="warnings is only supported in Pydantic v2"): + m.model_dump(warnings=False) + + +def test_forwards_compat_model_dump_json_method() -> None: + class Model(BaseModel): + foo: Optional[str] = Field(alias="FOO", default=None) + + m = Model(FOO="hello") + assert json.loads(m.model_dump_json()) == {"foo": "hello"} + assert json.loads(m.model_dump_json(include={"bar"})) == {} + assert json.loads(m.model_dump_json(include={"foo"})) == {"foo": "hello"} + assert json.loads(m.model_dump_json(by_alias=True)) == {"FOO": "hello"} + + assert m.model_dump_json(indent=2) == '{\n "foo": "hello"\n}' + + m2 = Model() + assert json.loads(m2.model_dump_json()) == {"foo": None} + assert json.loads(m2.model_dump_json(exclude_unset=True)) == {} + assert json.loads(m2.model_dump_json(exclude_none=True)) == {} + assert json.loads(m2.model_dump_json(exclude_defaults=True)) == {} + + m3 = Model(FOO=None) + assert json.loads(m3.model_dump_json()) == {"foo": None} + assert json.loads(m3.model_dump_json(exclude_none=True)) == {} + + if not PYDANTIC_V2: + with pytest.raises(ValueError, match="round_trip is only supported in Pydantic v2"): + m.model_dump_json(round_trip=True) + + with pytest.raises(ValueError, match="warnings is only supported in Pydantic v2"): + m.model_dump_json(warnings=False) + + +def test_type_compat() -> None: + # our model type can be assigned to Pydantic's model type + + def takes_pydantic(model: pydantic.BaseModel) -> None: # noqa: ARG001 + ... + + class OurModel(BaseModel): + foo: Optional[str] = None + + takes_pydantic(OurModel()) diff --git a/tests/test_module_client.py b/tests/test_module_client.py new file mode 100644 index 0000000000..0beca37f61 --- /dev/null +++ b/tests/test_module_client.py @@ -0,0 +1,179 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import os as _os + +import httpx +import pytest +from httpx import URL + +import openai +from openai import DEFAULT_TIMEOUT, DEFAULT_MAX_RETRIES + + +def reset_state() -> None: + openai._reset_client() + openai.api_key = None or "My API Key" + openai.organization = None + openai.base_url = None + openai.timeout = DEFAULT_TIMEOUT + openai.max_retries = DEFAULT_MAX_RETRIES + openai.default_headers = None + openai.default_query = None + openai.http_client = None + openai.api_type = _os.environ.get("OPENAI_API_TYPE") # type: ignore + openai.api_version = None + openai.azure_endpoint = None + openai.azure_ad_token = None + openai.azure_ad_token_provider = None + + +@pytest.fixture(autouse=True) +def reset_state_fixture() -> None: + reset_state() + + +def test_base_url_option() -> None: + assert openai.base_url is None + assert openai.completions._client.base_url == URL("https://api.openai.com/v1/") + + openai.base_url = "http://foo.com/" + + assert openai.base_url == URL("http://foo.com/") + assert openai.completions._client.base_url == URL("http://foo.com/") + + +def test_timeout_option() -> None: + assert openai.timeout == openai.DEFAULT_TIMEOUT + assert openai.completions._client.timeout == openai.DEFAULT_TIMEOUT + + openai.timeout = 3 + + assert openai.timeout == 3 + assert openai.completions._client.timeout == 3 + + +def test_max_retries_option() -> None: + assert openai.max_retries == openai.DEFAULT_MAX_RETRIES + assert openai.completions._client.max_retries == openai.DEFAULT_MAX_RETRIES + + openai.max_retries = 1 + + assert openai.max_retries == 1 + assert openai.completions._client.max_retries == 1 + + +def test_default_headers_option() -> None: + assert openai.default_headers == None + + openai.default_headers = {"Foo": "Bar"} + + assert openai.default_headers["Foo"] == "Bar" + assert openai.completions._client.default_headers["Foo"] == "Bar" + + +def test_default_query_option() -> None: + assert openai.default_query is None + assert openai.completions._client._custom_query == {} + + openai.default_query = {"Foo": {"nested": 1}} + + assert openai.default_query["Foo"] == {"nested": 1} + assert openai.completions._client._custom_query["Foo"] == {"nested": 1} + + +def test_http_client_option() -> None: + assert openai.http_client is None + + original_http_client = openai.completions._client._client + assert original_http_client is not None + + new_client = httpx.Client() + openai.http_client = new_client + + assert openai.completions._client._client is new_client + + +import contextlib +from typing import Iterator + +from openai.lib.azure import AzureOpenAI + + +@contextlib.contextmanager +def fresh_env() -> Iterator[None]: + old = _os.environ.copy() + + try: + _os.environ.clear() + yield + finally: + _os.environ.update(old) + + +def test_only_api_key_results_in_openai_api() -> None: + with fresh_env(): + openai.api_type = None + openai.api_key = "example API key" + + assert type(openai.completions._client).__name__ == "_ModuleClient" + + +def test_azure_api_key_env_without_api_version() -> None: + with fresh_env(): + openai.api_type = None + _os.environ["AZURE_OPENAI_API_KEY"] = "example API key" + + with pytest.raises(ValueError, match=r"Expected `api_version` to be given for the Azure client"): + openai.completions._client + + +def test_azure_api_key_and_version_env() -> None: + with fresh_env(): + openai.api_type = None + _os.environ["AZURE_OPENAI_API_KEY"] = "example API key" + _os.environ["OPENAI_API_VERSION"] = "example-version" + + with pytest.raises( + ValueError, + match=r"Must provide one of the `base_url` or `azure_endpoint` arguments, or the `OPENAI_BASE_URL`", + ): + openai.completions._client + + +def test_azure_api_key_version_and_endpoint_env() -> None: + with fresh_env(): + openai.api_type = None + _os.environ["AZURE_OPENAI_API_KEY"] = "example API key" + _os.environ["OPENAI_API_VERSION"] = "example-version" + _os.environ["AZURE_OPENAI_ENDPOINT"] = "https://www.example/" + + openai.completions._client + + assert openai.api_type == "azure" + + +def test_azure_azure_ad_token_version_and_endpoint_env() -> None: + with fresh_env(): + openai.api_type = None + _os.environ["AZURE_OPENAI_AD_TOKEN"] = "example AD token" + _os.environ["OPENAI_API_VERSION"] = "example-version" + _os.environ["AZURE_OPENAI_ENDPOINT"] = "https://www.example/" + + client = openai.completions._client + assert isinstance(client, AzureOpenAI) + assert client._azure_ad_token == "example AD token" + + +def test_azure_azure_ad_token_provider_version_and_endpoint_env() -> None: + with fresh_env(): + openai.api_type = None + _os.environ["OPENAI_API_VERSION"] = "example-version" + _os.environ["AZURE_OPENAI_ENDPOINT"] = "https://www.example/" + openai.azure_ad_token_provider = lambda: "token" + + client = openai.completions._client + assert isinstance(client, AzureOpenAI) + assert client._azure_ad_token_provider is not None + assert client._azure_ad_token_provider() == "token" diff --git a/tests/test_qs.py b/tests/test_qs.py new file mode 100644 index 0000000000..697b8a95ec --- /dev/null +++ b/tests/test_qs.py @@ -0,0 +1,78 @@ +from typing import Any, cast +from functools import partial +from urllib.parse import unquote + +import pytest + +from openai._qs import Querystring, stringify + + +def test_empty() -> None: + assert stringify({}) == "" + assert stringify({"a": {}}) == "" + assert stringify({"a": {"b": {"c": {}}}}) == "" + + +def test_basic() -> None: + assert stringify({"a": 1}) == "a=1" + assert stringify({"a": "b"}) == "a=b" + assert stringify({"a": True}) == "a=true" + assert stringify({"a": False}) == "a=false" + assert stringify({"a": 1.23456}) == "a=1.23456" + assert stringify({"a": None}) == "" + + +@pytest.mark.parametrize("method", ["class", "function"]) +def test_nested_dotted(method: str) -> None: + if method == "class": + serialise = Querystring(nested_format="dots").stringify + else: + serialise = partial(stringify, nested_format="dots") + + assert unquote(serialise({"a": {"b": "c"}})) == "a.b=c" + assert unquote(serialise({"a": {"b": "c", "d": "e", "f": "g"}})) == "a.b=c&a.d=e&a.f=g" + assert unquote(serialise({"a": {"b": {"c": {"d": "e"}}}})) == "a.b.c.d=e" + assert unquote(serialise({"a": {"b": True}})) == "a.b=true" + + +def test_nested_brackets() -> None: + assert unquote(stringify({"a": {"b": "c"}})) == "a[b]=c" + assert unquote(stringify({"a": {"b": "c", "d": "e", "f": "g"}})) == "a[b]=c&a[d]=e&a[f]=g" + assert unquote(stringify({"a": {"b": {"c": {"d": "e"}}}})) == "a[b][c][d]=e" + assert unquote(stringify({"a": {"b": True}})) == "a[b]=true" + + +@pytest.mark.parametrize("method", ["class", "function"]) +def test_array_comma(method: str) -> None: + if method == "class": + serialise = Querystring(array_format="comma").stringify + else: + serialise = partial(stringify, array_format="comma") + + assert unquote(serialise({"in": ["foo", "bar"]})) == "in=foo,bar" + assert unquote(serialise({"a": {"b": [True, False]}})) == "a[b]=true,false" + assert unquote(serialise({"a": {"b": [True, False, None, True]}})) == "a[b]=true,false,true" + + +def test_array_repeat() -> None: + assert unquote(stringify({"in": ["foo", "bar"]})) == "in=foo&in=bar" + assert unquote(stringify({"a": {"b": [True, False]}})) == "a[b]=true&a[b]=false" + assert unquote(stringify({"a": {"b": [True, False, None, True]}})) == "a[b]=true&a[b]=false&a[b]=true" + assert unquote(stringify({"in": ["foo", {"b": {"c": ["d", "e"]}}]})) == "in=foo&in[b][c]=d&in[b][c]=e" + + +@pytest.mark.parametrize("method", ["class", "function"]) +def test_array_brackets(method: str) -> None: + if method == "class": + serialise = Querystring(array_format="brackets").stringify + else: + serialise = partial(stringify, array_format="brackets") + + assert unquote(serialise({"in": ["foo", "bar"]})) == "in[]=foo&in[]=bar" + assert unquote(serialise({"a": {"b": [True, False]}})) == "a[b][]=true&a[b][]=false" + assert unquote(serialise({"a": {"b": [True, False, None, True]}})) == "a[b][]=true&a[b][]=false&a[b][]=true" + + +def test_unknown_array_format() -> None: + with pytest.raises(NotImplementedError, match="Unknown array_format value: foo, choose from comma, repeat"): + stringify({"a": ["foo", "bar"]}, array_format=cast(Any, "foo")) diff --git a/tests/test_required_args.py b/tests/test_required_args.py new file mode 100644 index 0000000000..1de017db24 --- /dev/null +++ b/tests/test_required_args.py @@ -0,0 +1,111 @@ +from __future__ import annotations + +import pytest + +from openai._utils import required_args + + +def test_too_many_positional_params() -> None: + @required_args(["a"]) + def foo(a: str | None = None) -> str | None: + return a + + with pytest.raises(TypeError, match=r"foo\(\) takes 1 argument\(s\) but 2 were given"): + foo("a", "b") # type: ignore + + +def test_positional_param() -> None: + @required_args(["a"]) + def foo(a: str | None = None) -> str | None: + return a + + assert foo("a") == "a" + assert foo(None) is None + assert foo(a="b") == "b" + + with pytest.raises(TypeError, match="Missing required argument: 'a'"): + foo() + + +def test_keyword_only_param() -> None: + @required_args(["a"]) + def foo(*, a: str | None = None) -> str | None: + return a + + assert foo(a="a") == "a" + assert foo(a=None) is None + assert foo(a="b") == "b" + + with pytest.raises(TypeError, match="Missing required argument: 'a'"): + foo() + + +def test_multiple_params() -> None: + @required_args(["a", "b", "c"]) + def foo(a: str = "", *, b: str = "", c: str = "") -> str | None: + return a + " " + b + " " + c + + assert foo(a="a", b="b", c="c") == "a b c" + + error_message = r"Missing required arguments.*" + + with pytest.raises(TypeError, match=error_message): + foo() + + with pytest.raises(TypeError, match=error_message): + foo(a="a") + + with pytest.raises(TypeError, match=error_message): + foo(b="b") + + with pytest.raises(TypeError, match=error_message): + foo(c="c") + + with pytest.raises(TypeError, match=r"Missing required argument: 'a'"): + foo(b="a", c="c") + + with pytest.raises(TypeError, match=r"Missing required argument: 'b'"): + foo("a", c="c") + + +def test_multiple_variants() -> None: + @required_args(["a"], ["b"]) + def foo(*, a: str | None = None, b: str | None = None) -> str | None: + return a if a is not None else b + + assert foo(a="foo") == "foo" + assert foo(b="bar") == "bar" + assert foo(a=None) is None + assert foo(b=None) is None + + # TODO: this error message could probably be improved + with pytest.raises( + TypeError, + match=r"Missing required arguments; Expected either \('a'\) or \('b'\) arguments to be given", + ): + foo() + + +def test_multiple_params_multiple_variants() -> None: + @required_args(["a", "b"], ["c"]) + def foo(*, a: str | None = None, b: str | None = None, c: str | None = None) -> str | None: + if a is not None: + return a + if b is not None: + return b + return c + + error_message = r"Missing required arguments; Expected either \('a' and 'b'\) or \('c'\) arguments to be given" + + with pytest.raises(TypeError, match=error_message): + foo(a="foo") + + with pytest.raises(TypeError, match=error_message): + foo(b="bar") + + with pytest.raises(TypeError, match=error_message): + foo() + + assert foo(a=None, b="bar") == "bar" + assert foo(c=None) is None + assert foo(c="foo") == "foo" diff --git a/tests/test_streaming.py b/tests/test_streaming.py new file mode 100644 index 0000000000..75e4ca2699 --- /dev/null +++ b/tests/test_streaming.py @@ -0,0 +1,104 @@ +from typing import Iterator, AsyncIterator + +import pytest + +from openai._streaming import SSEDecoder + + +@pytest.mark.asyncio +async def test_basic_async() -> None: + async def body() -> AsyncIterator[str]: + yield "event: completion" + yield 'data: {"foo":true}' + yield "" + + async for sse in SSEDecoder().aiter(body()): + assert sse.event == "completion" + assert sse.json() == {"foo": True} + + +def test_basic() -> None: + def body() -> Iterator[str]: + yield "event: completion" + yield 'data: {"foo":true}' + yield "" + + it = SSEDecoder().iter(body()) + sse = next(it) + assert sse.event == "completion" + assert sse.json() == {"foo": True} + + with pytest.raises(StopIteration): + next(it) + + +def test_data_missing_event() -> None: + def body() -> Iterator[str]: + yield 'data: {"foo":true}' + yield "" + + it = SSEDecoder().iter(body()) + sse = next(it) + assert sse.event is None + assert sse.json() == {"foo": True} + + with pytest.raises(StopIteration): + next(it) + + +def test_event_missing_data() -> None: + def body() -> Iterator[str]: + yield "event: ping" + yield "" + + it = SSEDecoder().iter(body()) + sse = next(it) + assert sse.event == "ping" + assert sse.data == "" + + with pytest.raises(StopIteration): + next(it) + + +def test_multiple_events() -> None: + def body() -> Iterator[str]: + yield "event: ping" + yield "" + yield "event: completion" + yield "" + + it = SSEDecoder().iter(body()) + + sse = next(it) + assert sse.event == "ping" + assert sse.data == "" + + sse = next(it) + assert sse.event == "completion" + assert sse.data == "" + + with pytest.raises(StopIteration): + next(it) + + +def test_multiple_events_with_data() -> None: + def body() -> Iterator[str]: + yield "event: ping" + yield 'data: {"foo":true}' + yield "" + yield "event: completion" + yield 'data: {"bar":false}' + yield "" + + it = SSEDecoder().iter(body()) + + sse = next(it) + assert sse.event == "ping" + assert sse.json() == {"foo": True} + + sse = next(it) + assert sse.event == "completion" + assert sse.json() == {"bar": False} + + with pytest.raises(StopIteration): + next(it) diff --git a/tests/test_transform.py b/tests/test_transform.py new file mode 100644 index 0000000000..3fc89bb093 --- /dev/null +++ b/tests/test_transform.py @@ -0,0 +1,232 @@ +from __future__ import annotations + +from typing import Any, List, Union, Optional +from datetime import date, datetime +from typing_extensions import Required, Annotated, TypedDict + +import pytest + +from openai._utils import PropertyInfo, transform, parse_datetime +from openai._models import BaseModel + + +class Foo1(TypedDict): + foo_bar: Annotated[str, PropertyInfo(alias="fooBar")] + + +def test_top_level_alias() -> None: + assert transform({"foo_bar": "hello"}, expected_type=Foo1) == {"fooBar": "hello"} + + +class Foo2(TypedDict): + bar: Bar2 + + +class Bar2(TypedDict): + this_thing: Annotated[int, PropertyInfo(alias="this__thing")] + baz: Annotated[Baz2, PropertyInfo(alias="Baz")] + + +class Baz2(TypedDict): + my_baz: Annotated[str, PropertyInfo(alias="myBaz")] + + +def test_recursive_typeddict() -> None: + assert transform({"bar": {"this_thing": 1}}, Foo2) == {"bar": {"this__thing": 1}} + assert transform({"bar": {"baz": {"my_baz": "foo"}}}, Foo2) == {"bar": {"Baz": {"myBaz": "foo"}}} + + +class Foo3(TypedDict): + things: List[Bar3] + + +class Bar3(TypedDict): + my_field: Annotated[str, PropertyInfo(alias="myField")] + + +def test_list_of_typeddict() -> None: + result = transform({"things": [{"my_field": "foo"}, {"my_field": "foo2"}]}, expected_type=Foo3) + assert result == {"things": [{"myField": "foo"}, {"myField": "foo2"}]} + + +class Foo4(TypedDict): + foo: Union[Bar4, Baz4] + + +class Bar4(TypedDict): + foo_bar: Annotated[str, PropertyInfo(alias="fooBar")] + + +class Baz4(TypedDict): + foo_baz: Annotated[str, PropertyInfo(alias="fooBaz")] + + +def test_union_of_typeddict() -> None: + assert transform({"foo": {"foo_bar": "bar"}}, Foo4) == {"foo": {"fooBar": "bar"}} + assert transform({"foo": {"foo_baz": "baz"}}, Foo4) == {"foo": {"fooBaz": "baz"}} + assert transform({"foo": {"foo_baz": "baz", "foo_bar": "bar"}}, Foo4) == {"foo": {"fooBaz": "baz", "fooBar": "bar"}} + + +class Foo5(TypedDict): + foo: Annotated[Union[Bar4, List[Baz4]], PropertyInfo(alias="FOO")] + + +class Bar5(TypedDict): + foo_bar: Annotated[str, PropertyInfo(alias="fooBar")] + + +class Baz5(TypedDict): + foo_baz: Annotated[str, PropertyInfo(alias="fooBaz")] + + +def test_union_of_list() -> None: + assert transform({"foo": {"foo_bar": "bar"}}, Foo5) == {"FOO": {"fooBar": "bar"}} + assert transform( + { + "foo": [ + {"foo_baz": "baz"}, + {"foo_baz": "baz"}, + ] + }, + Foo5, + ) == {"FOO": [{"fooBaz": "baz"}, {"fooBaz": "baz"}]} + + +class Foo6(TypedDict): + bar: Annotated[str, PropertyInfo(alias="Bar")] + + +def test_includes_unknown_keys() -> None: + assert transform({"bar": "bar", "baz_": {"FOO": 1}}, Foo6) == { + "Bar": "bar", + "baz_": {"FOO": 1}, + } + + +class Foo7(TypedDict): + bar: Annotated[List[Bar7], PropertyInfo(alias="bAr")] + foo: Bar7 + + +class Bar7(TypedDict): + foo: str + + +def test_ignores_invalid_input() -> None: + assert transform({"bar": ""}, Foo7) == {"bAr": ""} + assert transform({"foo": ""}, Foo7) == {"foo": ""} + + +class DatetimeDict(TypedDict, total=False): + foo: Annotated[datetime, PropertyInfo(format="iso8601")] + + bar: Annotated[Optional[datetime], PropertyInfo(format="iso8601")] + + required: Required[Annotated[Optional[datetime], PropertyInfo(format="iso8601")]] + + list_: Required[Annotated[Optional[List[datetime]], PropertyInfo(format="iso8601")]] + + union: Annotated[Union[int, datetime], PropertyInfo(format="iso8601")] + + +class DateDict(TypedDict, total=False): + foo: Annotated[date, PropertyInfo(format="iso8601")] + + +def test_iso8601_format() -> None: + dt = datetime.fromisoformat("2023-02-23T14:16:36.337692+00:00") + assert transform({"foo": dt}, DatetimeDict) == {"foo": "2023-02-23T14:16:36.337692+00:00"} # type: ignore[comparison-overlap] + + dt = dt.replace(tzinfo=None) + assert transform({"foo": dt}, DatetimeDict) == {"foo": "2023-02-23T14:16:36.337692"} # type: ignore[comparison-overlap] + + assert transform({"foo": None}, DateDict) == {"foo": None} # type: ignore[comparison-overlap] + assert transform({"foo": date.fromisoformat("2023-02-23")}, DateDict) == {"foo": "2023-02-23"} # type: ignore[comparison-overlap] + + +def test_optional_iso8601_format() -> None: + dt = datetime.fromisoformat("2023-02-23T14:16:36.337692+00:00") + assert transform({"bar": dt}, DatetimeDict) == {"bar": "2023-02-23T14:16:36.337692+00:00"} # type: ignore[comparison-overlap] + + assert transform({"bar": None}, DatetimeDict) == {"bar": None} + + +def test_required_iso8601_format() -> None: + dt = datetime.fromisoformat("2023-02-23T14:16:36.337692+00:00") + assert transform({"required": dt}, DatetimeDict) == {"required": "2023-02-23T14:16:36.337692+00:00"} # type: ignore[comparison-overlap] + + assert transform({"required": None}, DatetimeDict) == {"required": None} + + +def test_union_datetime() -> None: + dt = datetime.fromisoformat("2023-02-23T14:16:36.337692+00:00") + assert transform({"union": dt}, DatetimeDict) == { # type: ignore[comparison-overlap] + "union": "2023-02-23T14:16:36.337692+00:00" + } + + assert transform({"union": "foo"}, DatetimeDict) == {"union": "foo"} + + +def test_nested_list_iso6801_format() -> None: + dt1 = datetime.fromisoformat("2023-02-23T14:16:36.337692+00:00") + dt2 = parse_datetime("2022-01-15T06:34:23Z") + assert transform({"list_": [dt1, dt2]}, DatetimeDict) == { # type: ignore[comparison-overlap] + "list_": ["2023-02-23T14:16:36.337692+00:00", "2022-01-15T06:34:23+00:00"] + } + + +def test_datetime_custom_format() -> None: + dt = parse_datetime("2022-01-15T06:34:23Z") + + result = transform(dt, Annotated[datetime, PropertyInfo(format="custom", format_template="%H")]) + assert result == "06" # type: ignore[comparison-overlap] + + +class DateDictWithRequiredAlias(TypedDict, total=False): + required_prop: Required[Annotated[date, PropertyInfo(format="iso8601", alias="prop")]] + + +def test_datetime_with_alias() -> None: + assert transform({"required_prop": None}, DateDictWithRequiredAlias) == {"prop": None} # type: ignore[comparison-overlap] + assert transform({"required_prop": date.fromisoformat("2023-02-23")}, DateDictWithRequiredAlias) == {"prop": "2023-02-23"} # type: ignore[comparison-overlap] + + +class MyModel(BaseModel): + foo: str + + +def test_pydantic_model_to_dictionary() -> None: + assert transform(MyModel(foo="hi!"), Any) == {"foo": "hi!"} + assert transform(MyModel.construct(foo="hi!"), Any) == {"foo": "hi!"} + + +def test_pydantic_empty_model() -> None: + assert transform(MyModel.construct(), Any) == {} + + +def test_pydantic_unknown_field() -> None: + assert transform(MyModel.construct(my_untyped_field=True), Any) == {"my_untyped_field": True} + + +def test_pydantic_mismatched_types() -> None: + model = MyModel.construct(foo=True) + with pytest.warns(UserWarning): + params = transform(model, Any) + assert params == {"foo": True} + + +def test_pydantic_mismatched_object_type() -> None: + model = MyModel.construct(foo=MyModel.construct(hello="world")) + with pytest.warns(UserWarning): + params = transform(model, Any) + assert params == {"foo": {"hello": "world"}} + + +class ModelNestedObjects(BaseModel): + nested: MyModel + + +def test_pydantic_nested_objects() -> None: + model = ModelNestedObjects.construct(nested={"foo": "stainless"}) + assert isinstance(model.nested, MyModel) + assert transform(model, Any) == {"nested": {"foo": "stainless"}} diff --git a/tests/utils.py b/tests/utils.py new file mode 100644 index 0000000000..3cccab223a --- /dev/null +++ b/tests/utils.py @@ -0,0 +1,105 @@ +from __future__ import annotations + +import traceback +from typing import Any, TypeVar, cast +from datetime import date, datetime +from typing_extensions import Literal, get_args, get_origin, assert_type + +from openai._types import NoneType +from openai._utils import is_dict, is_list, is_list_type, is_union_type +from openai._compat import PYDANTIC_V2, field_outer_type, get_model_fields +from openai._models import BaseModel + +BaseModelT = TypeVar("BaseModelT", bound=BaseModel) + + +def assert_matches_model(model: type[BaseModelT], value: BaseModelT, *, path: list[str]) -> bool: + for name, field in get_model_fields(model).items(): + field_value = getattr(value, name) + if PYDANTIC_V2: + allow_none = False + else: + # in v1 nullability was structured differently + # https://docs.pydantic.dev/2.0/migration/#required-optional-and-nullable-fields + allow_none = getattr(field, "allow_none", False) + + assert_matches_type( + field_outer_type(field), + field_value, + path=[*path, name], + allow_none=allow_none, + ) + + return True + + +# Note: the `path` argument is only used to improve error messages when `--showlocals` is used +def assert_matches_type( + type_: Any, + value: object, + *, + path: list[str], + allow_none: bool = False, +) -> None: + if allow_none and value is None: + return + + if type_ is None or type_ is NoneType: + assert value is None + return + + origin = get_origin(type_) or type_ + + if is_list_type(type_): + return _assert_list_type(type_, value) + + if origin == str: + assert isinstance(value, str) + elif origin == int: + assert isinstance(value, int) + elif origin == bool: + assert isinstance(value, bool) + elif origin == float: + assert isinstance(value, float) + elif origin == datetime: + assert isinstance(value, datetime) + elif origin == date: + assert isinstance(value, date) + elif origin == object: + # nothing to do here, the expected type is unknown + pass + elif origin == Literal: + assert value in get_args(type_) + elif origin == dict: + assert is_dict(value) + + args = get_args(type_) + key_type = args[0] + items_type = args[1] + + for key, item in value.items(): + assert_matches_type(key_type, key, path=[*path, ""]) + assert_matches_type(items_type, item, path=[*path, ""]) + elif is_union_type(type_): + for i, variant in enumerate(get_args(type_)): + try: + assert_matches_type(variant, value, path=[*path, f"variant {i}"]) + return + except AssertionError: + traceback.print_exc() + continue + + assert False, "Did not match any variants" + elif issubclass(origin, BaseModel): + assert isinstance(value, type_) + assert assert_matches_model(type_, cast(Any, value), path=path) + else: + assert None, f"Unhandled field type: {type_}" + + +def _assert_list_type(type_: type[object], value: object) -> None: + assert is_list(value) + + inner_type = get_args(type_)[0] + for entry in value: + assert_type(inner_type, entry) # type: ignore From 6d21709610a97bd7c8575744998d0cc800e89f0c Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 6 Nov 2023 16:31:09 +0000 Subject: [PATCH 060/816] docs(readme): remove mention of beta version (#678) --- README.md | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/README.md b/README.md index a27375d598..821ecf1ecf 100644 --- a/README.md +++ b/README.md @@ -12,23 +12,10 @@ It is generated from our [OpenAPI specification](https://github.com/openai/opena The API documentation can be found [here](https://platform.openai.com/docs). -## Beta Release - -> [!IMPORTANT] -> We're preparing to release version 1.0 of the OpenAI Python library. - -This new version will be a major release and will include breaking changes. We're releasing this beta version to give you a chance to try out the new features and provide feedback before the official release. You can install the beta version with: - -```sh -pip install --pre openai -``` -And follow along with the [beta release notes](https://github.com/openai/openai-python/discussions/631). - - ## Installation ```sh -pip install --pre openai +pip install openai ``` ## Usage From 26d1a93458f754e6b8d5d1b2507e208393f06bda Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 6 Nov 2023 16:38:04 +0000 Subject: [PATCH 061/816] v1.0.1 (#679) --- pyproject.toml | 2 +- src/openai/_version.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 7f6e3123d4..8c83f4260d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.0.0" +version = "1.0.1" description = "Client library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index e9a3efc55c..f6f3a35c07 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.0.0" +__version__ = "1.0.1" From baa9f07f5b503017ea6dae8f047d3cfc1ee22c37 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 6 Nov 2023 20:35:10 +0000 Subject: [PATCH 062/816] feat(api): releases from DevDay; assistants, multimodality, tools, dall-e-3, tts, and more (#682) * feat(api): releases from DevDay; assistants, multimodality, tools, dall-e-3, tts, and more * docs(api): improve docstrings * v1.1.0 --- .stats.yml | 2 +- api.md | 140 +++- examples/async_demo.py | 0 examples/azure.py | 0 examples/azure_ad.py | 0 examples/demo.py | 0 examples/module_client.py | 0 pyproject.toml | 2 +- src/openai/__init__.py | 1 + src/openai/_client.py | 6 + src/openai/_module_client.py | 7 + src/openai/_version.py | 2 +- src/openai/cli/_api/chat/completions.py | 6 +- src/openai/cli/_api/files.py | 9 +- src/openai/pagination.py | 6 +- src/openai/resources/__init__.py | 5 + src/openai/resources/audio/__init__.py | 10 + src/openai/resources/audio/audio.py | 12 + src/openai/resources/audio/speech.py | 166 +++++ src/openai/resources/audio/transcriptions.py | 8 +- src/openai/resources/audio/translations.py | 8 +- src/openai/resources/beta/__init__.py | 30 + .../resources/beta/assistants/__init__.py | 20 + .../resources/beta/assistants/assistants.py | 654 ++++++++++++++++++ src/openai/resources/beta/assistants/files.py | 414 +++++++++++ src/openai/resources/beta/beta.py | 60 ++ src/openai/resources/beta/threads/__init__.py | 30 + .../beta/threads/messages/__init__.py | 20 + .../resources/beta/threads/messages/files.py | 257 +++++++ .../beta/threads/messages/messages.py | 477 +++++++++++++ .../resources/beta/threads/runs/__init__.py | 15 + .../resources/beta/threads/runs/runs.py | 654 ++++++++++++++++++ .../resources/beta/threads/runs/steps.py | 255 +++++++ src/openai/resources/beta/threads/threads.py | 541 +++++++++++++++ src/openai/resources/chat/completions.py | 300 ++++++-- src/openai/resources/completions.py | 64 +- src/openai/resources/files.py | 103 ++- src/openai/resources/images.py | 82 ++- src/openai/types/__init__.py | 1 + src/openai/types/audio/__init__.py | 1 + .../types/audio/speech_create_params.py | 34 + .../audio/transcription_create_params.py | 4 +- .../types/audio/translation_create_params.py | 4 +- src/openai/types/beta/__init__.py | 16 + src/openai/types/beta/assistant.py | 112 +++ .../types/beta/assistant_create_params.py | 109 +++ .../types/beta/assistant_list_params.py | 39 ++ .../types/beta/assistant_update_params.py | 111 +++ src/openai/types/beta/assistants/__init__.py | 8 + .../types/beta/assistants/assistant_file.py | 21 + .../beta/assistants/file_create_params.py | 16 + .../beta/assistants/file_delete_response.py | 15 + .../types/beta/assistants/file_list_params.py | 39 ++ src/openai/types/beta/asssitant_deleted.py | 15 + src/openai/types/beta/chat/__init__.py | 3 + src/openai/types/beta/thread.py | 28 + .../beta/thread_create_and_run_params.py | 148 ++++ src/openai/types/beta/thread_create_params.py | 51 ++ src/openai/types/beta/thread_deleted.py | 15 + src/openai/types/beta/thread_update_params.py | 18 + src/openai/types/beta/threads/__init__.py | 22 + .../threads/message_content_image_file.py | 22 + .../beta/threads/message_content_text.py | 74 ++ .../beta/threads/message_create_params.py | 35 + .../types/beta/threads/message_list_params.py | 39 ++ .../beta/threads/message_update_params.py | 20 + .../types/beta/threads/messages/__init__.py | 6 + .../beta/threads/messages/file_list_params.py | 41 ++ .../beta/threads/messages/message_file.py | 25 + .../required_action_function_tool_call.py | 34 + src/openai/types/beta/threads/run.py | 182 +++++ .../types/beta/threads/run_create_params.py | 100 +++ .../types/beta/threads/run_list_params.py | 39 ++ .../threads/run_submit_tool_outputs_params.py | 26 + .../types/beta/threads/run_update_params.py | 20 + .../types/beta/threads/runs/__init__.py | 13 + .../types/beta/threads/runs/code_tool_call.py | 67 ++ .../beta/threads/runs/function_tool_call.py | 38 + .../runs/message_creation_step_details.py | 19 + .../beta/threads/runs/retrieval_tool_call.py | 21 + .../types/beta/threads/runs/run_step.py | 93 +++ .../beta/threads/runs/step_list_params.py | 41 ++ .../threads/runs/tool_calls_step_details.py | 25 + .../types/beta/threads/thread_message.py | 65 ++ src/openai/types/chat/__init__.py | 42 ++ src/openai/types/chat/chat_completion.py | 14 +- ...chat_completion_assistant_message_param.py | 41 ++ .../types/chat/chat_completion_chunk.py | 49 +- ...hat_completion_content_part_image_param.py | 22 + .../chat_completion_content_part_param.py | 14 + ...chat_completion_content_part_text_param.py | 15 + ...t_completion_function_call_option_param.py | 12 + .../chat_completion_function_message_param.py | 19 + .../types/chat/chat_completion_message.py | 13 +- .../chat/chat_completion_message_param.py | 63 +- .../chat/chat_completion_message_tool_call.py | 31 + ...chat_completion_message_tool_call_param.py | 31 + ...chat_completion_named_tool_choice_param.py | 19 + src/openai/types/chat/chat_completion_role.py | 2 +- .../chat_completion_system_message_param.py | 16 + ...hat_completion_tool_choice_option_param.py | 12 + .../chat_completion_tool_message_param.py | 19 + .../types/chat/chat_completion_tool_param.py | 42 ++ .../chat_completion_user_message_param.py | 18 + .../types/chat/completion_create_params.py | 90 ++- src/openai/types/completion.py | 10 +- src/openai/types/completion_create_params.py | 12 +- src/openai/types/create_embedding_response.py | 3 +- src/openai/types/edit.py | 2 +- src/openai/types/embedding.py | 3 +- src/openai/types/file_create_params.py | 17 +- src/openai/types/file_deleted.py | 4 +- src/openai/types/file_list_params.py | 12 + src/openai/types/file_object.py | 28 +- src/openai/types/fine_tune.py | 3 +- src/openai/types/fine_tune_event.py | 4 +- .../types/fine_tune_events_list_response.py | 3 +- .../types/fine_tuning/fine_tuning_job.py | 4 +- .../fine_tuning/fine_tuning_job_event.py | 2 +- .../types/fine_tuning/job_create_params.py | 13 + src/openai/types/image.py | 6 + .../types/image_create_variation_params.py | 13 +- src/openai/types/image_edit_params.py | 8 +- src/openai/types/image_generate_params.py | 34 +- src/openai/types/model.py | 4 +- tests/api_resources/audio/test_speech.py | 110 +++ tests/api_resources/beta/__init__.py | 1 + .../api_resources/beta/assistants/__init__.py | 1 + .../beta/assistants/test_files.py | 190 +++++ tests/api_resources/beta/chat/__init__.py | 1 + tests/api_resources/beta/test_assistants.py | 254 +++++++ tests/api_resources/beta/test_threads.py | 318 +++++++++ tests/api_resources/beta/threads/__init__.py | 1 + .../beta/threads/messages/__init__.py | 1 + .../beta/threads/messages/test_files.py | 128 ++++ .../beta/threads/runs/__init__.py | 1 + .../beta/threads/runs/test_steps.py | 128 ++++ .../beta/threads/test_messages.py | 234 +++++++ tests/api_resources/beta/threads/test_runs.py | 308 +++++++++ tests/api_resources/chat/test_completions.py | 136 +++- tests/api_resources/fine_tuning/test_jobs.py | 12 +- tests/api_resources/test_completions.py | 4 + tests/api_resources/test_files.py | 22 +- tests/api_resources/test_images.py | 10 + 144 files changed, 8618 insertions(+), 252 deletions(-) mode change 100644 => 100755 examples/async_demo.py mode change 100644 => 100755 examples/azure.py mode change 100644 => 100755 examples/azure_ad.py mode change 100644 => 100755 examples/demo.py mode change 100644 => 100755 examples/module_client.py create mode 100644 src/openai/resources/audio/speech.py create mode 100644 src/openai/resources/beta/__init__.py create mode 100644 src/openai/resources/beta/assistants/__init__.py create mode 100644 src/openai/resources/beta/assistants/assistants.py create mode 100644 src/openai/resources/beta/assistants/files.py create mode 100644 src/openai/resources/beta/beta.py create mode 100644 src/openai/resources/beta/threads/__init__.py create mode 100644 src/openai/resources/beta/threads/messages/__init__.py create mode 100644 src/openai/resources/beta/threads/messages/files.py create mode 100644 src/openai/resources/beta/threads/messages/messages.py create mode 100644 src/openai/resources/beta/threads/runs/__init__.py create mode 100644 src/openai/resources/beta/threads/runs/runs.py create mode 100644 src/openai/resources/beta/threads/runs/steps.py create mode 100644 src/openai/resources/beta/threads/threads.py create mode 100644 src/openai/types/audio/speech_create_params.py create mode 100644 src/openai/types/beta/__init__.py create mode 100644 src/openai/types/beta/assistant.py create mode 100644 src/openai/types/beta/assistant_create_params.py create mode 100644 src/openai/types/beta/assistant_list_params.py create mode 100644 src/openai/types/beta/assistant_update_params.py create mode 100644 src/openai/types/beta/assistants/__init__.py create mode 100644 src/openai/types/beta/assistants/assistant_file.py create mode 100644 src/openai/types/beta/assistants/file_create_params.py create mode 100644 src/openai/types/beta/assistants/file_delete_response.py create mode 100644 src/openai/types/beta/assistants/file_list_params.py create mode 100644 src/openai/types/beta/asssitant_deleted.py create mode 100644 src/openai/types/beta/chat/__init__.py create mode 100644 src/openai/types/beta/thread.py create mode 100644 src/openai/types/beta/thread_create_and_run_params.py create mode 100644 src/openai/types/beta/thread_create_params.py create mode 100644 src/openai/types/beta/thread_deleted.py create mode 100644 src/openai/types/beta/thread_update_params.py create mode 100644 src/openai/types/beta/threads/__init__.py create mode 100644 src/openai/types/beta/threads/message_content_image_file.py create mode 100644 src/openai/types/beta/threads/message_content_text.py create mode 100644 src/openai/types/beta/threads/message_create_params.py create mode 100644 src/openai/types/beta/threads/message_list_params.py create mode 100644 src/openai/types/beta/threads/message_update_params.py create mode 100644 src/openai/types/beta/threads/messages/__init__.py create mode 100644 src/openai/types/beta/threads/messages/file_list_params.py create mode 100644 src/openai/types/beta/threads/messages/message_file.py create mode 100644 src/openai/types/beta/threads/required_action_function_tool_call.py create mode 100644 src/openai/types/beta/threads/run.py create mode 100644 src/openai/types/beta/threads/run_create_params.py create mode 100644 src/openai/types/beta/threads/run_list_params.py create mode 100644 src/openai/types/beta/threads/run_submit_tool_outputs_params.py create mode 100644 src/openai/types/beta/threads/run_update_params.py create mode 100644 src/openai/types/beta/threads/runs/__init__.py create mode 100644 src/openai/types/beta/threads/runs/code_tool_call.py create mode 100644 src/openai/types/beta/threads/runs/function_tool_call.py create mode 100644 src/openai/types/beta/threads/runs/message_creation_step_details.py create mode 100644 src/openai/types/beta/threads/runs/retrieval_tool_call.py create mode 100644 src/openai/types/beta/threads/runs/run_step.py create mode 100644 src/openai/types/beta/threads/runs/step_list_params.py create mode 100644 src/openai/types/beta/threads/runs/tool_calls_step_details.py create mode 100644 src/openai/types/beta/threads/thread_message.py create mode 100644 src/openai/types/chat/chat_completion_assistant_message_param.py create mode 100644 src/openai/types/chat/chat_completion_content_part_image_param.py create mode 100644 src/openai/types/chat/chat_completion_content_part_param.py create mode 100644 src/openai/types/chat/chat_completion_content_part_text_param.py create mode 100644 src/openai/types/chat/chat_completion_function_call_option_param.py create mode 100644 src/openai/types/chat/chat_completion_function_message_param.py create mode 100644 src/openai/types/chat/chat_completion_message_tool_call.py create mode 100644 src/openai/types/chat/chat_completion_message_tool_call_param.py create mode 100644 src/openai/types/chat/chat_completion_named_tool_choice_param.py create mode 100644 src/openai/types/chat/chat_completion_system_message_param.py create mode 100644 src/openai/types/chat/chat_completion_tool_choice_option_param.py create mode 100644 src/openai/types/chat/chat_completion_tool_message_param.py create mode 100644 src/openai/types/chat/chat_completion_tool_param.py create mode 100644 src/openai/types/chat/chat_completion_user_message_param.py create mode 100644 src/openai/types/file_list_params.py create mode 100644 tests/api_resources/audio/test_speech.py create mode 100644 tests/api_resources/beta/__init__.py create mode 100644 tests/api_resources/beta/assistants/__init__.py create mode 100644 tests/api_resources/beta/assistants/test_files.py create mode 100644 tests/api_resources/beta/chat/__init__.py create mode 100644 tests/api_resources/beta/test_assistants.py create mode 100644 tests/api_resources/beta/test_threads.py create mode 100644 tests/api_resources/beta/threads/__init__.py create mode 100644 tests/api_resources/beta/threads/messages/__init__.py create mode 100644 tests/api_resources/beta/threads/messages/test_files.py create mode 100644 tests/api_resources/beta/threads/runs/__init__.py create mode 100644 tests/api_resources/beta/threads/runs/test_steps.py create mode 100644 tests/api_resources/beta/threads/test_messages.py create mode 100644 tests/api_resources/beta/threads/test_runs.py diff --git a/.stats.yml b/.stats.yml index f21eb8fef0..03b0268ffa 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1 +1 @@ -configured_endpoints: 28 +configured_endpoints: 57 diff --git a/api.md b/api.md index 915a05479a..818ae73b31 100644 --- a/api.md +++ b/api.md @@ -19,10 +19,23 @@ Types: ```python from openai.types.chat import ( ChatCompletion, + ChatCompletionAssistantMessageParam, ChatCompletionChunk, + ChatCompletionContentPart, + ChatCompletionContentPartImage, + ChatCompletionContentPartText, + ChatCompletionFunctionCallOption, + ChatCompletionFunctionMessageParam, ChatCompletionMessage, ChatCompletionMessageParam, + ChatCompletionMessageToolCall, + ChatCompletionNamedToolChoice, ChatCompletionRole, + ChatCompletionSystemMessageParam, + ChatCompletionTool, + ChatCompletionToolChoiceOption, + ChatCompletionToolMessageParam, + ChatCompletionUserMessageParam, ) ``` @@ -66,7 +79,7 @@ Methods: - client.files.create(\*\*params) -> FileObject - client.files.retrieve(file_id) -> FileObject -- client.files.list() -> SyncPage[FileObject] +- client.files.list(\*\*params) -> SyncPage[FileObject] - client.files.delete(file_id) -> FileDeleted - client.files.retrieve_content(file_id) -> str - client.files.wait_for_processing(\*args) -> FileObject @@ -111,6 +124,12 @@ Methods: - client.audio.translations.create(\*\*params) -> Translation +## Speech + +Methods: + +- client.audio.speech.create(\*\*params) -> HttpxBinaryResponseContent + # Moderations Types: @@ -170,3 +189,122 @@ Methods: - client.fine_tunes.list() -> SyncPage[FineTune] - client.fine_tunes.cancel(fine_tune_id) -> FineTune - client.fine_tunes.list_events(fine_tune_id, \*\*params) -> FineTuneEventsListResponse + +# Beta + +## Assistants + +Types: + +```python +from openai.types.beta import Assistant, AsssitantDeleted +``` + +Methods: + +- client.beta.assistants.create(\*\*params) -> Assistant +- client.beta.assistants.retrieve(assistant_id) -> Assistant +- client.beta.assistants.update(assistant_id, \*\*params) -> Assistant +- client.beta.assistants.list(\*\*params) -> SyncCursorPage[Assistant] +- client.beta.assistants.delete(assistant_id) -> AsssitantDeleted + +### Files + +Types: + +```python +from openai.types.beta.assistants import AssistantFile, FileDeleteResponse +``` + +Methods: + +- client.beta.assistants.files.create(assistant_id, \*\*params) -> AssistantFile +- client.beta.assistants.files.retrieve(file_id, \*, assistant_id) -> AssistantFile +- client.beta.assistants.files.list(assistant_id, \*\*params) -> SyncCursorPage[AssistantFile] +- client.beta.assistants.files.delete(file_id, \*, assistant_id) -> FileDeleteResponse + +## Threads + +Types: + +```python +from openai.types.beta import Thread, ThreadDeleted +``` + +Methods: + +- client.beta.threads.create(\*\*params) -> Thread +- client.beta.threads.retrieve(thread_id) -> Thread +- client.beta.threads.update(thread_id, \*\*params) -> Thread +- client.beta.threads.delete(thread_id) -> ThreadDeleted +- client.beta.threads.create_and_run(\*\*params) -> Run + +### Runs + +Types: + +```python +from openai.types.beta.threads import RequiredActionFunctionToolCall, Run +``` + +Methods: + +- client.beta.threads.runs.create(thread_id, \*\*params) -> Run +- client.beta.threads.runs.retrieve(run_id, \*, thread_id) -> Run +- client.beta.threads.runs.update(run_id, \*, thread_id, \*\*params) -> Run +- client.beta.threads.runs.list(thread_id, \*\*params) -> SyncCursorPage[Run] +- client.beta.threads.runs.cancel(run_id, \*, thread_id) -> Run +- client.beta.threads.runs.submit_tool_outputs(run_id, \*, thread_id, \*\*params) -> Run + +#### Steps + +Types: + +```python +from openai.types.beta.threads.runs import ( + CodeToolCall, + FunctionToolCall, + MessageCreationStepDetails, + RetrievalToolCall, + RunStep, + ToolCallsStepDetails, +) +``` + +Methods: + +- client.beta.threads.runs.steps.retrieve(step_id, \*, thread_id, run_id) -> RunStep +- client.beta.threads.runs.steps.list(run_id, \*, thread_id, \*\*params) -> SyncCursorPage[RunStep] + +### Messages + +Types: + +```python +from openai.types.beta.threads import ( + MessageContentImageFile, + MessageContentText, + ThreadMessage, + ThreadMessageDeleted, +) +``` + +Methods: + +- client.beta.threads.messages.create(thread_id, \*\*params) -> ThreadMessage +- client.beta.threads.messages.retrieve(message_id, \*, thread_id) -> ThreadMessage +- client.beta.threads.messages.update(message_id, \*, thread_id, \*\*params) -> ThreadMessage +- client.beta.threads.messages.list(thread_id, \*\*params) -> SyncCursorPage[ThreadMessage] + +#### Files + +Types: + +```python +from openai.types.beta.threads.messages import MessageFile +``` + +Methods: + +- client.beta.threads.messages.files.retrieve(file_id, \*, thread_id, message_id) -> MessageFile +- client.beta.threads.messages.files.list(message_id, \*, thread_id, \*\*params) -> SyncCursorPage[MessageFile] diff --git a/examples/async_demo.py b/examples/async_demo.py old mode 100644 new mode 100755 diff --git a/examples/azure.py b/examples/azure.py old mode 100644 new mode 100755 diff --git a/examples/azure_ad.py b/examples/azure_ad.py old mode 100644 new mode 100755 diff --git a/examples/demo.py b/examples/demo.py old mode 100644 new mode 100755 diff --git a/examples/module_client.py b/examples/module_client.py old mode 100644 new mode 100755 diff --git a/pyproject.toml b/pyproject.toml index 8c83f4260d..9ab62e23fc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.0.1" +version = "1.1.0" description = "Client library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/__init__.py b/src/openai/__init__.py index f033d8f26c..da1157a767 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -329,6 +329,7 @@ def _reset_client() -> None: # type: ignore[reportUnusedFunction] _client = None +from ._module_client import beta as beta from ._module_client import chat as chat from ._module_client import audio as audio from ._module_client import edits as edits diff --git a/src/openai/_client.py b/src/openai/_client.py index 9df7eabf9a..6476d2b1a8 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -52,6 +52,7 @@ class OpenAI(SyncAPIClient): models: resources.Models fine_tuning: resources.FineTuning fine_tunes: resources.FineTunes + beta: resources.Beta with_raw_response: OpenAIWithRawResponse # client options @@ -125,6 +126,7 @@ def __init__( self.models = resources.Models(self) self.fine_tuning = resources.FineTuning(self) self.fine_tunes = resources.FineTunes(self) + self.beta = resources.Beta(self) self.with_raw_response = OpenAIWithRawResponse(self) @property @@ -257,6 +259,7 @@ class AsyncOpenAI(AsyncAPIClient): models: resources.AsyncModels fine_tuning: resources.AsyncFineTuning fine_tunes: resources.AsyncFineTunes + beta: resources.AsyncBeta with_raw_response: AsyncOpenAIWithRawResponse # client options @@ -330,6 +333,7 @@ def __init__( self.models = resources.AsyncModels(self) self.fine_tuning = resources.AsyncFineTuning(self) self.fine_tunes = resources.AsyncFineTunes(self) + self.beta = resources.AsyncBeta(self) self.with_raw_response = AsyncOpenAIWithRawResponse(self) @property @@ -466,6 +470,7 @@ def __init__(self, client: OpenAI) -> None: self.models = resources.ModelsWithRawResponse(client.models) self.fine_tuning = resources.FineTuningWithRawResponse(client.fine_tuning) self.fine_tunes = resources.FineTunesWithRawResponse(client.fine_tunes) + self.beta = resources.BetaWithRawResponse(client.beta) class AsyncOpenAIWithRawResponse: @@ -481,6 +486,7 @@ def __init__(self, client: AsyncOpenAI) -> None: self.models = resources.AsyncModelsWithRawResponse(client.models) self.fine_tuning = resources.AsyncFineTuningWithRawResponse(client.fine_tuning) self.fine_tunes = resources.AsyncFineTunesWithRawResponse(client.fine_tunes) + self.beta = resources.AsyncBetaWithRawResponse(client.beta) Client = OpenAI diff --git a/src/openai/_module_client.py b/src/openai/_module_client.py index ca80468e88..fe8e0a2139 100644 --- a/src/openai/_module_client.py +++ b/src/openai/_module_client.py @@ -12,6 +12,12 @@ def __load__(self) -> resources.Chat: return _load_client().chat +class BetaProxy(LazyProxy[resources.Beta]): + @override + def __load__(self) -> resources.Beta: + return _load_client().beta + + class EditsProxy(LazyProxy[resources.Edits]): @override def __load__(self) -> resources.Edits: @@ -73,6 +79,7 @@ def __load__(self) -> resources.FineTuning: chat: resources.Chat = ChatProxy().__as_proxied__() +beta: resources.Beta = BetaProxy().__as_proxied__() edits: resources.Edits = EditsProxy().__as_proxied__() files: resources.Files = FilesProxy().__as_proxied__() audio: resources.Audio = AudioProxy().__as_proxied__() diff --git a/src/openai/_version.py b/src/openai/_version.py index f6f3a35c07..57548ed376 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.0.1" +__version__ = "1.1.0" diff --git a/src/openai/cli/_api/chat/completions.py b/src/openai/cli/_api/chat/completions.py index e7566b143d..c299741fe0 100644 --- a/src/openai/cli/_api/chat/completions.py +++ b/src/openai/cli/_api/chat/completions.py @@ -3,7 +3,7 @@ import sys from typing import TYPE_CHECKING, List, Optional, cast from argparse import ArgumentParser -from typing_extensions import NamedTuple +from typing_extensions import Literal, NamedTuple from ..._utils import get_client from ..._models import BaseModel @@ -97,7 +97,9 @@ class CLIChatCompletion: def create(args: CLIChatCompletionCreateArgs) -> None: params: CompletionCreateParams = { "model": args.model, - "messages": [{"role": message.role, "content": message.content} for message in args.message], + "messages": [ + {"role": cast(Literal["user"], message.role), "content": message.content} for message in args.message + ], "n": args.n, "temperature": args.temperature, "top_p": args.top_p, diff --git a/src/openai/cli/_api/files.py b/src/openai/cli/_api/files.py index ae6dadf0f1..5f3631b284 100644 --- a/src/openai/cli/_api/files.py +++ b/src/openai/cli/_api/files.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any, cast from argparse import ArgumentParser from .._utils import get_client, print_model @@ -55,7 +55,12 @@ def create(args: CLIFileCreateArgs) -> None: with open(args.file, "rb") as file_reader: buffer_reader = BufferReader(file_reader.read(), desc="Upload progress") - file = get_client().files.create(file=(args.file, buffer_reader), purpose=args.purpose) + file = get_client().files.create( + file=(args.file, buffer_reader), + # casts required because the API is typed for enums + # but we don't want to validate that here for forwards-compat + purpose=cast(Any, args.purpose), + ) print_model(file) @staticmethod diff --git a/src/openai/pagination.py b/src/openai/pagination.py index ff45f39517..4ec300f2d1 100644 --- a/src/openai/pagination.py +++ b/src/openai/pagination.py @@ -1,7 +1,7 @@ # File generated from our OpenAPI spec by Stainless. from typing import Any, List, Generic, TypeVar, Optional, cast -from typing_extensions import Protocol, override, runtime_checkable +from typing_extensions import Literal, Protocol, override, runtime_checkable from ._types import ModelT from ._models import BaseModel @@ -21,7 +21,7 @@ class SyncPage(BaseSyncPage[ModelT], BasePage[ModelT], Generic[ModelT]): """Note: no pagination actually occurs yet, this is for forwards-compatibility.""" data: List[ModelT] - object: str + object: Literal["list"] @override def _get_page_items(self) -> List[ModelT]: @@ -40,7 +40,7 @@ class AsyncPage(BaseAsyncPage[ModelT], BasePage[ModelT], Generic[ModelT]): """Note: no pagination actually occurs yet, this is for forwards-compatibility.""" data: List[ModelT] - object: str + object: Literal["list"] @override def _get_page_items(self) -> List[ModelT]: diff --git a/src/openai/resources/__init__.py b/src/openai/resources/__init__.py index e0a26c72d2..e0f4f08d5c 100644 --- a/src/openai/resources/__init__.py +++ b/src/openai/resources/__init__.py @@ -1,5 +1,6 @@ # File generated from our OpenAPI spec by Stainless. +from .beta import Beta, AsyncBeta, BetaWithRawResponse, AsyncBetaWithRawResponse from .chat import Chat, AsyncChat, ChatWithRawResponse, AsyncChatWithRawResponse from .audio import Audio, AsyncAudio, AudioWithRawResponse, AsyncAudioWithRawResponse from .edits import Edits, AsyncEdits, EditsWithRawResponse, AsyncEditsWithRawResponse @@ -92,4 +93,8 @@ "AsyncFineTunes", "FineTunesWithRawResponse", "AsyncFineTunesWithRawResponse", + "Beta", + "AsyncBeta", + "BetaWithRawResponse", + "AsyncBetaWithRawResponse", ] diff --git a/src/openai/resources/audio/__init__.py b/src/openai/resources/audio/__init__.py index 771bfe9da2..76547b5f34 100644 --- a/src/openai/resources/audio/__init__.py +++ b/src/openai/resources/audio/__init__.py @@ -1,6 +1,12 @@ # File generated from our OpenAPI spec by Stainless. from .audio import Audio, AsyncAudio, AudioWithRawResponse, AsyncAudioWithRawResponse +from .speech import ( + Speech, + AsyncSpeech, + SpeechWithRawResponse, + AsyncSpeechWithRawResponse, +) from .translations import ( Translations, AsyncTranslations, @@ -23,6 +29,10 @@ "AsyncTranslations", "TranslationsWithRawResponse", "AsyncTranslationsWithRawResponse", + "Speech", + "AsyncSpeech", + "SpeechWithRawResponse", + "AsyncSpeechWithRawResponse", "Audio", "AsyncAudio", "AudioWithRawResponse", diff --git a/src/openai/resources/audio/audio.py b/src/openai/resources/audio/audio.py index 8e8872c5b5..6f7226ee59 100644 --- a/src/openai/resources/audio/audio.py +++ b/src/openai/resources/audio/audio.py @@ -4,6 +4,12 @@ from typing import TYPE_CHECKING +from .speech import ( + Speech, + AsyncSpeech, + SpeechWithRawResponse, + AsyncSpeechWithRawResponse, +) from ..._resource import SyncAPIResource, AsyncAPIResource from .translations import ( Translations, @@ -27,24 +33,28 @@ class Audio(SyncAPIResource): transcriptions: Transcriptions translations: Translations + speech: Speech with_raw_response: AudioWithRawResponse def __init__(self, client: OpenAI) -> None: super().__init__(client) self.transcriptions = Transcriptions(client) self.translations = Translations(client) + self.speech = Speech(client) self.with_raw_response = AudioWithRawResponse(self) class AsyncAudio(AsyncAPIResource): transcriptions: AsyncTranscriptions translations: AsyncTranslations + speech: AsyncSpeech with_raw_response: AsyncAudioWithRawResponse def __init__(self, client: AsyncOpenAI) -> None: super().__init__(client) self.transcriptions = AsyncTranscriptions(client) self.translations = AsyncTranslations(client) + self.speech = AsyncSpeech(client) self.with_raw_response = AsyncAudioWithRawResponse(self) @@ -52,9 +62,11 @@ class AudioWithRawResponse: def __init__(self, audio: Audio) -> None: self.transcriptions = TranscriptionsWithRawResponse(audio.transcriptions) self.translations = TranslationsWithRawResponse(audio.translations) + self.speech = SpeechWithRawResponse(audio.speech) class AsyncAudioWithRawResponse: def __init__(self, audio: AsyncAudio) -> None: self.transcriptions = AsyncTranscriptionsWithRawResponse(audio.transcriptions) self.translations = AsyncTranslationsWithRawResponse(audio.translations) + self.speech = AsyncSpeechWithRawResponse(audio.speech) diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py new file mode 100644 index 0000000000..7318e3a2e4 --- /dev/null +++ b/src/openai/resources/audio/speech.py @@ -0,0 +1,166 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import TYPE_CHECKING, Union +from typing_extensions import Literal + +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ..._utils import maybe_transform +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from ...types.audio import speech_create_params +from ..._base_client import HttpxBinaryResponseContent, make_request_options + +if TYPE_CHECKING: + from ..._client import OpenAI, AsyncOpenAI + +__all__ = ["Speech", "AsyncSpeech"] + + +class Speech(SyncAPIResource): + with_raw_response: SpeechWithRawResponse + + def __init__(self, client: OpenAI) -> None: + super().__init__(client) + self.with_raw_response = SpeechWithRawResponse(self) + + def create( + self, + *, + input: str, + model: Union[str, Literal["tts-1", "tts-1-hd"]], + voice: Literal["alloy", "echo", "fable", "onyx", "nova", "shimmer"], + response_format: Literal["mp3", "opus", "aac", "flac"] | NotGiven = NOT_GIVEN, + speed: float | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> HttpxBinaryResponseContent: + """ + Generates audio from the input text. + + Args: + input: The text to generate audio for. The maximum length is 4096 characters. + + model: + One of the available [TTS models](https://platform.openai.com/docs/models/tts): + `tts-1` or `tts-1-hd` + + voice: The voice to use when generating the audio. Supported voices are `alloy`, + `echo`, `fable`, `onyx`, `nova`, and `shimmer`. + + response_format: The format to audio in. Supported formats are `mp3`, `opus`, `aac`, and `flac`. + + speed: The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is + the default. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._post( + "/audio/speech", + body=maybe_transform( + { + "input": input, + "model": model, + "voice": voice, + "response_format": response_format, + "speed": speed, + }, + speech_create_params.SpeechCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=HttpxBinaryResponseContent, + ) + + +class AsyncSpeech(AsyncAPIResource): + with_raw_response: AsyncSpeechWithRawResponse + + def __init__(self, client: AsyncOpenAI) -> None: + super().__init__(client) + self.with_raw_response = AsyncSpeechWithRawResponse(self) + + async def create( + self, + *, + input: str, + model: Union[str, Literal["tts-1", "tts-1-hd"]], + voice: Literal["alloy", "echo", "fable", "onyx", "nova", "shimmer"], + response_format: Literal["mp3", "opus", "aac", "flac"] | NotGiven = NOT_GIVEN, + speed: float | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> HttpxBinaryResponseContent: + """ + Generates audio from the input text. + + Args: + input: The text to generate audio for. The maximum length is 4096 characters. + + model: + One of the available [TTS models](https://platform.openai.com/docs/models/tts): + `tts-1` or `tts-1-hd` + + voice: The voice to use when generating the audio. Supported voices are `alloy`, + `echo`, `fable`, `onyx`, `nova`, and `shimmer`. + + response_format: The format to audio in. Supported formats are `mp3`, `opus`, `aac`, and `flac`. + + speed: The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is + the default. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._post( + "/audio/speech", + body=maybe_transform( + { + "input": input, + "model": model, + "voice": voice, + "response_format": response_format, + "speed": speed, + }, + speech_create_params.SpeechCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=HttpxBinaryResponseContent, + ) + + +class SpeechWithRawResponse: + def __init__(self, speech: Speech) -> None: + self.create = to_raw_response_wrapper( + speech.create, + ) + + +class AsyncSpeechWithRawResponse: + def __init__(self, speech: AsyncSpeech) -> None: + self.create = async_to_raw_response_wrapper( + speech.create, + ) diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index ca61f8bd42..44d973d0af 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -60,8 +60,8 @@ def create( [prompt](https://platform.openai.com/docs/guides/speech-to-text/prompting) should match the audio language. - response_format: The format of the transcript output, in one of these options: json, text, srt, - verbose_json, or vtt. + response_format: The format of the transcript output, in one of these options: `json`, `text`, + `srt`, `verbose_json`, or `vtt`. temperature: The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and @@ -147,8 +147,8 @@ async def create( [prompt](https://platform.openai.com/docs/guides/speech-to-text/prompting) should match the audio language. - response_format: The format of the transcript output, in one of these options: json, text, srt, - verbose_json, or vtt. + response_format: The format of the transcript output, in one of these options: `json`, `text`, + `srt`, `verbose_json`, or `vtt`. temperature: The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index 0b499b9865..bb37c691fc 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -54,8 +54,8 @@ def create( [prompt](https://platform.openai.com/docs/guides/speech-to-text/prompting) should be in English. - response_format: The format of the transcript output, in one of these options: json, text, srt, - verbose_json, or vtt. + response_format: The format of the transcript output, in one of these options: `json`, `text`, + `srt`, `verbose_json`, or `vtt`. temperature: The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and @@ -134,8 +134,8 @@ async def create( [prompt](https://platform.openai.com/docs/guides/speech-to-text/prompting) should be in English. - response_format: The format of the transcript output, in one of these options: json, text, srt, - verbose_json, or vtt. + response_format: The format of the transcript output, in one of these options: `json`, `text`, + `srt`, `verbose_json`, or `vtt`. temperature: The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and diff --git a/src/openai/resources/beta/__init__.py b/src/openai/resources/beta/__init__.py new file mode 100644 index 0000000000..55ad243cca --- /dev/null +++ b/src/openai/resources/beta/__init__.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. + +from .beta import Beta, AsyncBeta, BetaWithRawResponse, AsyncBetaWithRawResponse +from .threads import ( + Threads, + AsyncThreads, + ThreadsWithRawResponse, + AsyncThreadsWithRawResponse, +) +from .assistants import ( + Assistants, + AsyncAssistants, + AssistantsWithRawResponse, + AsyncAssistantsWithRawResponse, +) + +__all__ = [ + "Assistants", + "AsyncAssistants", + "AssistantsWithRawResponse", + "AsyncAssistantsWithRawResponse", + "Threads", + "AsyncThreads", + "ThreadsWithRawResponse", + "AsyncThreadsWithRawResponse", + "Beta", + "AsyncBeta", + "BetaWithRawResponse", + "AsyncBetaWithRawResponse", +] diff --git a/src/openai/resources/beta/assistants/__init__.py b/src/openai/resources/beta/assistants/__init__.py new file mode 100644 index 0000000000..6efb0b21ec --- /dev/null +++ b/src/openai/resources/beta/assistants/__init__.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. + +from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse +from .assistants import ( + Assistants, + AsyncAssistants, + AssistantsWithRawResponse, + AsyncAssistantsWithRawResponse, +) + +__all__ = [ + "Files", + "AsyncFiles", + "FilesWithRawResponse", + "AsyncFilesWithRawResponse", + "Assistants", + "AsyncAssistants", + "AssistantsWithRawResponse", + "AsyncAssistantsWithRawResponse", +] diff --git a/src/openai/resources/beta/assistants/assistants.py b/src/openai/resources/beta/assistants/assistants.py new file mode 100644 index 0000000000..03f2759fc2 --- /dev/null +++ b/src/openai/resources/beta/assistants/assistants.py @@ -0,0 +1,654 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import TYPE_CHECKING, List, Optional +from typing_extensions import Literal + +from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ...._utils import maybe_transform +from ...._resource import SyncAPIResource, AsyncAPIResource +from ...._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from ....pagination import SyncCursorPage, AsyncCursorPage +from ....types.beta import ( + Assistant, + AsssitantDeleted, + assistant_list_params, + assistant_create_params, + assistant_update_params, +) +from ...._base_client import AsyncPaginator, make_request_options + +if TYPE_CHECKING: + from ...._client import OpenAI, AsyncOpenAI + +__all__ = ["Assistants", "AsyncAssistants"] + + +class Assistants(SyncAPIResource): + files: Files + with_raw_response: AssistantsWithRawResponse + + def __init__(self, client: OpenAI) -> None: + super().__init__(client) + self.files = Files(client) + self.with_raw_response = AssistantsWithRawResponse(self) + + def create( + self, + *, + model: str, + description: Optional[str] | NotGiven = NOT_GIVEN, + file_ids: List[str] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + name: Optional[str] | NotGiven = NOT_GIVEN, + tools: List[assistant_create_params.Tool] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Assistant: + """ + Create an assistant with a model and instructions. + + Args: + model: ID of the model to use. You can use the + [List models](https://platform.openai.com/docs/api-reference/models/list) API to + see all of your available models, or see our + [Model overview](https://platform.openai.com/docs/models/overview) for + descriptions of them. + + description: The description of the assistant. The maximum length is 512 characters. + + file_ids: A list of [file](https://platform.openai.com/docs/api-reference/files) IDs + attached to this assistant. There can be a maximum of 20 files attached to the + assistant. Files are ordered by their creation date in ascending order. + + instructions: The system instructions that the assistant uses. The maximum length is 32768 + characters. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + name: The name of the assistant. The maximum length is 256 characters. + + tools: A list of tool enabled on the assistant. There can be a maximum of 128 tools per + assistant. Tools can be of types `code_interpreter`, `retrieval`, or `function`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._post( + "/assistants", + body=maybe_transform( + { + "model": model, + "description": description, + "file_ids": file_ids, + "instructions": instructions, + "metadata": metadata, + "name": name, + "tools": tools, + }, + assistant_create_params.AssistantCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Assistant, + ) + + def retrieve( + self, + assistant_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Assistant: + """ + Retrieves an assistant. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._get( + f"/assistants/{assistant_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Assistant, + ) + + def update( + self, + assistant_id: str, + *, + description: Optional[str] | NotGiven = NOT_GIVEN, + file_ids: List[str] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: str | NotGiven = NOT_GIVEN, + name: Optional[str] | NotGiven = NOT_GIVEN, + tools: List[assistant_update_params.Tool] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Assistant: + """Modifies an assistant. + + Args: + description: The description of the assistant. + + The maximum length is 512 characters. + + file_ids: A list of [File](https://platform.openai.com/docs/api-reference/files) IDs + attached to this assistant. There can be a maximum of 20 files attached to the + assistant. Files are ordered by their creation date in ascending order. If a + file was previosuly attached to the list but does not show up in the list, it + will be deleted from the assistant. + + instructions: The system instructions that the assistant uses. The maximum length is 32768 + characters. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + model: ID of the model to use. You can use the + [List models](https://platform.openai.com/docs/api-reference/models/list) API to + see all of your available models, or see our + [Model overview](https://platform.openai.com/docs/models/overview) for + descriptions of them. + + name: The name of the assistant. The maximum length is 256 characters. + + tools: A list of tool enabled on the assistant. There can be a maximum of 128 tools per + assistant. Tools can be of types `code_interpreter`, `retrieval`, or `function`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._post( + f"/assistants/{assistant_id}", + body=maybe_transform( + { + "description": description, + "file_ids": file_ids, + "instructions": instructions, + "metadata": metadata, + "model": model, + "name": name, + "tools": tools, + }, + assistant_update_params.AssistantUpdateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Assistant, + ) + + def list( + self, + *, + after: str | NotGiven = NOT_GIVEN, + before: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> SyncCursorPage[Assistant]: + """Returns a list of assistants. + + Args: + after: A cursor for use in pagination. + + `after` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include after=obj_foo in order to + fetch the next page of the list. + + before: A cursor for use in pagination. `before` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include before=obj_foo in order to + fetch the previous page of the list. + + limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the default is 20. + + order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending + order and `desc` for descending order. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._get_api_list( + "/assistants", + page=SyncCursorPage[Assistant], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "before": before, + "limit": limit, + "order": order, + }, + assistant_list_params.AssistantListParams, + ), + ), + model=Assistant, + ) + + def delete( + self, + assistant_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> AsssitantDeleted: + """ + Delete an assistant. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._delete( + f"/assistants/{assistant_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=AsssitantDeleted, + ) + + +class AsyncAssistants(AsyncAPIResource): + files: AsyncFiles + with_raw_response: AsyncAssistantsWithRawResponse + + def __init__(self, client: AsyncOpenAI) -> None: + super().__init__(client) + self.files = AsyncFiles(client) + self.with_raw_response = AsyncAssistantsWithRawResponse(self) + + async def create( + self, + *, + model: str, + description: Optional[str] | NotGiven = NOT_GIVEN, + file_ids: List[str] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + name: Optional[str] | NotGiven = NOT_GIVEN, + tools: List[assistant_create_params.Tool] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Assistant: + """ + Create an assistant with a model and instructions. + + Args: + model: ID of the model to use. You can use the + [List models](https://platform.openai.com/docs/api-reference/models/list) API to + see all of your available models, or see our + [Model overview](https://platform.openai.com/docs/models/overview) for + descriptions of them. + + description: The description of the assistant. The maximum length is 512 characters. + + file_ids: A list of [file](https://platform.openai.com/docs/api-reference/files) IDs + attached to this assistant. There can be a maximum of 20 files attached to the + assistant. Files are ordered by their creation date in ascending order. + + instructions: The system instructions that the assistant uses. The maximum length is 32768 + characters. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + name: The name of the assistant. The maximum length is 256 characters. + + tools: A list of tool enabled on the assistant. There can be a maximum of 128 tools per + assistant. Tools can be of types `code_interpreter`, `retrieval`, or `function`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return await self._post( + "/assistants", + body=maybe_transform( + { + "model": model, + "description": description, + "file_ids": file_ids, + "instructions": instructions, + "metadata": metadata, + "name": name, + "tools": tools, + }, + assistant_create_params.AssistantCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Assistant, + ) + + async def retrieve( + self, + assistant_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Assistant: + """ + Retrieves an assistant. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return await self._get( + f"/assistants/{assistant_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Assistant, + ) + + async def update( + self, + assistant_id: str, + *, + description: Optional[str] | NotGiven = NOT_GIVEN, + file_ids: List[str] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: str | NotGiven = NOT_GIVEN, + name: Optional[str] | NotGiven = NOT_GIVEN, + tools: List[assistant_update_params.Tool] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Assistant: + """Modifies an assistant. + + Args: + description: The description of the assistant. + + The maximum length is 512 characters. + + file_ids: A list of [File](https://platform.openai.com/docs/api-reference/files) IDs + attached to this assistant. There can be a maximum of 20 files attached to the + assistant. Files are ordered by their creation date in ascending order. If a + file was previosuly attached to the list but does not show up in the list, it + will be deleted from the assistant. + + instructions: The system instructions that the assistant uses. The maximum length is 32768 + characters. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + model: ID of the model to use. You can use the + [List models](https://platform.openai.com/docs/api-reference/models/list) API to + see all of your available models, or see our + [Model overview](https://platform.openai.com/docs/models/overview) for + descriptions of them. + + name: The name of the assistant. The maximum length is 256 characters. + + tools: A list of tool enabled on the assistant. There can be a maximum of 128 tools per + assistant. Tools can be of types `code_interpreter`, `retrieval`, or `function`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return await self._post( + f"/assistants/{assistant_id}", + body=maybe_transform( + { + "description": description, + "file_ids": file_ids, + "instructions": instructions, + "metadata": metadata, + "model": model, + "name": name, + "tools": tools, + }, + assistant_update_params.AssistantUpdateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Assistant, + ) + + def list( + self, + *, + after: str | NotGiven = NOT_GIVEN, + before: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> AsyncPaginator[Assistant, AsyncCursorPage[Assistant]]: + """Returns a list of assistants. + + Args: + after: A cursor for use in pagination. + + `after` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include after=obj_foo in order to + fetch the next page of the list. + + before: A cursor for use in pagination. `before` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include before=obj_foo in order to + fetch the previous page of the list. + + limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the default is 20. + + order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending + order and `desc` for descending order. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._get_api_list( + "/assistants", + page=AsyncCursorPage[Assistant], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "before": before, + "limit": limit, + "order": order, + }, + assistant_list_params.AssistantListParams, + ), + ), + model=Assistant, + ) + + async def delete( + self, + assistant_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> AsssitantDeleted: + """ + Delete an assistant. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return await self._delete( + f"/assistants/{assistant_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=AsssitantDeleted, + ) + + +class AssistantsWithRawResponse: + def __init__(self, assistants: Assistants) -> None: + self.files = FilesWithRawResponse(assistants.files) + + self.create = to_raw_response_wrapper( + assistants.create, + ) + self.retrieve = to_raw_response_wrapper( + assistants.retrieve, + ) + self.update = to_raw_response_wrapper( + assistants.update, + ) + self.list = to_raw_response_wrapper( + assistants.list, + ) + self.delete = to_raw_response_wrapper( + assistants.delete, + ) + + +class AsyncAssistantsWithRawResponse: + def __init__(self, assistants: AsyncAssistants) -> None: + self.files = AsyncFilesWithRawResponse(assistants.files) + + self.create = async_to_raw_response_wrapper( + assistants.create, + ) + self.retrieve = async_to_raw_response_wrapper( + assistants.retrieve, + ) + self.update = async_to_raw_response_wrapper( + assistants.update, + ) + self.list = async_to_raw_response_wrapper( + assistants.list, + ) + self.delete = async_to_raw_response_wrapper( + assistants.delete, + ) diff --git a/src/openai/resources/beta/assistants/files.py b/src/openai/resources/beta/assistants/files.py new file mode 100644 index 0000000000..b1953525e8 --- /dev/null +++ b/src/openai/resources/beta/assistants/files.py @@ -0,0 +1,414 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import TYPE_CHECKING +from typing_extensions import Literal + +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ...._utils import maybe_transform +from ...._resource import SyncAPIResource, AsyncAPIResource +from ...._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from ....pagination import SyncCursorPage, AsyncCursorPage +from ...._base_client import AsyncPaginator, make_request_options +from ....types.beta.assistants import ( + AssistantFile, + FileDeleteResponse, + file_list_params, + file_create_params, +) + +if TYPE_CHECKING: + from ...._client import OpenAI, AsyncOpenAI + +__all__ = ["Files", "AsyncFiles"] + + +class Files(SyncAPIResource): + with_raw_response: FilesWithRawResponse + + def __init__(self, client: OpenAI) -> None: + super().__init__(client) + self.with_raw_response = FilesWithRawResponse(self) + + def create( + self, + assistant_id: str, + *, + file_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> AssistantFile: + """ + Create an assistant file by attaching a + [File](https://platform.openai.com/docs/api-reference/files) to an + [assistant](https://platform.openai.com/docs/api-reference/assistants). + + Args: + file_id: A [File](https://platform.openai.com/docs/api-reference/files) ID (with + `purpose="assistants"`) that the assistant should use. Useful for tools like + `retrieval` and `code_interpreter` that can access files. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._post( + f"/assistants/{assistant_id}/files", + body=maybe_transform({"file_id": file_id}, file_create_params.FileCreateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=AssistantFile, + ) + + def retrieve( + self, + file_id: str, + *, + assistant_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> AssistantFile: + """ + Retrieves an AssistantFile. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._get( + f"/assistants/{assistant_id}/files/{file_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=AssistantFile, + ) + + def list( + self, + assistant_id: str, + *, + after: str | NotGiven = NOT_GIVEN, + before: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> SyncCursorPage[AssistantFile]: + """ + Returns a list of assistant files. + + Args: + after: A cursor for use in pagination. `after` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include after=obj_foo in order to + fetch the next page of the list. + + before: A cursor for use in pagination. `before` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include before=obj_foo in order to + fetch the previous page of the list. + + limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the default is 20. + + order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending + order and `desc` for descending order. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._get_api_list( + f"/assistants/{assistant_id}/files", + page=SyncCursorPage[AssistantFile], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "before": before, + "limit": limit, + "order": order, + }, + file_list_params.FileListParams, + ), + ), + model=AssistantFile, + ) + + def delete( + self, + file_id: str, + *, + assistant_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> FileDeleteResponse: + """ + Delete an assistant file. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._delete( + f"/assistants/{assistant_id}/files/{file_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=FileDeleteResponse, + ) + + +class AsyncFiles(AsyncAPIResource): + with_raw_response: AsyncFilesWithRawResponse + + def __init__(self, client: AsyncOpenAI) -> None: + super().__init__(client) + self.with_raw_response = AsyncFilesWithRawResponse(self) + + async def create( + self, + assistant_id: str, + *, + file_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> AssistantFile: + """ + Create an assistant file by attaching a + [File](https://platform.openai.com/docs/api-reference/files) to an + [assistant](https://platform.openai.com/docs/api-reference/assistants). + + Args: + file_id: A [File](https://platform.openai.com/docs/api-reference/files) ID (with + `purpose="assistants"`) that the assistant should use. Useful for tools like + `retrieval` and `code_interpreter` that can access files. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return await self._post( + f"/assistants/{assistant_id}/files", + body=maybe_transform({"file_id": file_id}, file_create_params.FileCreateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=AssistantFile, + ) + + async def retrieve( + self, + file_id: str, + *, + assistant_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> AssistantFile: + """ + Retrieves an AssistantFile. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return await self._get( + f"/assistants/{assistant_id}/files/{file_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=AssistantFile, + ) + + def list( + self, + assistant_id: str, + *, + after: str | NotGiven = NOT_GIVEN, + before: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> AsyncPaginator[AssistantFile, AsyncCursorPage[AssistantFile]]: + """ + Returns a list of assistant files. + + Args: + after: A cursor for use in pagination. `after` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include after=obj_foo in order to + fetch the next page of the list. + + before: A cursor for use in pagination. `before` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include before=obj_foo in order to + fetch the previous page of the list. + + limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the default is 20. + + order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending + order and `desc` for descending order. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._get_api_list( + f"/assistants/{assistant_id}/files", + page=AsyncCursorPage[AssistantFile], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "before": before, + "limit": limit, + "order": order, + }, + file_list_params.FileListParams, + ), + ), + model=AssistantFile, + ) + + async def delete( + self, + file_id: str, + *, + assistant_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> FileDeleteResponse: + """ + Delete an assistant file. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return await self._delete( + f"/assistants/{assistant_id}/files/{file_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=FileDeleteResponse, + ) + + +class FilesWithRawResponse: + def __init__(self, files: Files) -> None: + self.create = to_raw_response_wrapper( + files.create, + ) + self.retrieve = to_raw_response_wrapper( + files.retrieve, + ) + self.list = to_raw_response_wrapper( + files.list, + ) + self.delete = to_raw_response_wrapper( + files.delete, + ) + + +class AsyncFilesWithRawResponse: + def __init__(self, files: AsyncFiles) -> None: + self.create = async_to_raw_response_wrapper( + files.create, + ) + self.retrieve = async_to_raw_response_wrapper( + files.retrieve, + ) + self.list = async_to_raw_response_wrapper( + files.list, + ) + self.delete = async_to_raw_response_wrapper( + files.delete, + ) diff --git a/src/openai/resources/beta/beta.py b/src/openai/resources/beta/beta.py new file mode 100644 index 0000000000..b552561763 --- /dev/null +++ b/src/openai/resources/beta/beta.py @@ -0,0 +1,60 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from .threads import ( + Threads, + AsyncThreads, + ThreadsWithRawResponse, + AsyncThreadsWithRawResponse, +) +from .assistants import ( + Assistants, + AsyncAssistants, + AssistantsWithRawResponse, + AsyncAssistantsWithRawResponse, +) +from ..._resource import SyncAPIResource, AsyncAPIResource + +if TYPE_CHECKING: + from ..._client import OpenAI, AsyncOpenAI + +__all__ = ["Beta", "AsyncBeta"] + + +class Beta(SyncAPIResource): + assistants: Assistants + threads: Threads + with_raw_response: BetaWithRawResponse + + def __init__(self, client: OpenAI) -> None: + super().__init__(client) + self.assistants = Assistants(client) + self.threads = Threads(client) + self.with_raw_response = BetaWithRawResponse(self) + + +class AsyncBeta(AsyncAPIResource): + assistants: AsyncAssistants + threads: AsyncThreads + with_raw_response: AsyncBetaWithRawResponse + + def __init__(self, client: AsyncOpenAI) -> None: + super().__init__(client) + self.assistants = AsyncAssistants(client) + self.threads = AsyncThreads(client) + self.with_raw_response = AsyncBetaWithRawResponse(self) + + +class BetaWithRawResponse: + def __init__(self, beta: Beta) -> None: + self.assistants = AssistantsWithRawResponse(beta.assistants) + self.threads = ThreadsWithRawResponse(beta.threads) + + +class AsyncBetaWithRawResponse: + def __init__(self, beta: AsyncBeta) -> None: + self.assistants = AsyncAssistantsWithRawResponse(beta.assistants) + self.threads = AsyncThreadsWithRawResponse(beta.threads) diff --git a/src/openai/resources/beta/threads/__init__.py b/src/openai/resources/beta/threads/__init__.py new file mode 100644 index 0000000000..b9aaada465 --- /dev/null +++ b/src/openai/resources/beta/threads/__init__.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. + +from .runs import Runs, AsyncRuns, RunsWithRawResponse, AsyncRunsWithRawResponse +from .threads import ( + Threads, + AsyncThreads, + ThreadsWithRawResponse, + AsyncThreadsWithRawResponse, +) +from .messages import ( + Messages, + AsyncMessages, + MessagesWithRawResponse, + AsyncMessagesWithRawResponse, +) + +__all__ = [ + "Runs", + "AsyncRuns", + "RunsWithRawResponse", + "AsyncRunsWithRawResponse", + "Messages", + "AsyncMessages", + "MessagesWithRawResponse", + "AsyncMessagesWithRawResponse", + "Threads", + "AsyncThreads", + "ThreadsWithRawResponse", + "AsyncThreadsWithRawResponse", +] diff --git a/src/openai/resources/beta/threads/messages/__init__.py b/src/openai/resources/beta/threads/messages/__init__.py new file mode 100644 index 0000000000..d8d4ce448c --- /dev/null +++ b/src/openai/resources/beta/threads/messages/__init__.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. + +from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse +from .messages import ( + Messages, + AsyncMessages, + MessagesWithRawResponse, + AsyncMessagesWithRawResponse, +) + +__all__ = [ + "Files", + "AsyncFiles", + "FilesWithRawResponse", + "AsyncFilesWithRawResponse", + "Messages", + "AsyncMessages", + "MessagesWithRawResponse", + "AsyncMessagesWithRawResponse", +] diff --git a/src/openai/resources/beta/threads/messages/files.py b/src/openai/resources/beta/threads/messages/files.py new file mode 100644 index 0000000000..70166eb7b2 --- /dev/null +++ b/src/openai/resources/beta/threads/messages/files.py @@ -0,0 +1,257 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import TYPE_CHECKING +from typing_extensions import Literal + +from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ....._utils import maybe_transform +from ....._resource import SyncAPIResource, AsyncAPIResource +from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from .....pagination import SyncCursorPage, AsyncCursorPage +from ....._base_client import AsyncPaginator, make_request_options +from .....types.beta.threads.messages import MessageFile, file_list_params + +if TYPE_CHECKING: + from ....._client import OpenAI, AsyncOpenAI + +__all__ = ["Files", "AsyncFiles"] + + +class Files(SyncAPIResource): + with_raw_response: FilesWithRawResponse + + def __init__(self, client: OpenAI) -> None: + super().__init__(client) + self.with_raw_response = FilesWithRawResponse(self) + + def retrieve( + self, + file_id: str, + *, + thread_id: str, + message_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> MessageFile: + """ + Retrieves a message file. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._get( + f"/threads/{thread_id}/messages/{message_id}/files/{file_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=MessageFile, + ) + + def list( + self, + message_id: str, + *, + thread_id: str, + after: str | NotGiven = NOT_GIVEN, + before: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> SyncCursorPage[MessageFile]: + """Returns a list of message files. + + Args: + after: A cursor for use in pagination. + + `after` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include after=obj_foo in order to + fetch the next page of the list. + + before: A cursor for use in pagination. `before` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include before=obj_foo in order to + fetch the previous page of the list. + + limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the default is 20. + + order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending + order and `desc` for descending order. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._get_api_list( + f"/threads/{thread_id}/messages/{message_id}/files", + page=SyncCursorPage[MessageFile], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "before": before, + "limit": limit, + "order": order, + }, + file_list_params.FileListParams, + ), + ), + model=MessageFile, + ) + + +class AsyncFiles(AsyncAPIResource): + with_raw_response: AsyncFilesWithRawResponse + + def __init__(self, client: AsyncOpenAI) -> None: + super().__init__(client) + self.with_raw_response = AsyncFilesWithRawResponse(self) + + async def retrieve( + self, + file_id: str, + *, + thread_id: str, + message_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> MessageFile: + """ + Retrieves a message file. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return await self._get( + f"/threads/{thread_id}/messages/{message_id}/files/{file_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=MessageFile, + ) + + def list( + self, + message_id: str, + *, + thread_id: str, + after: str | NotGiven = NOT_GIVEN, + before: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> AsyncPaginator[MessageFile, AsyncCursorPage[MessageFile]]: + """Returns a list of message files. + + Args: + after: A cursor for use in pagination. + + `after` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include after=obj_foo in order to + fetch the next page of the list. + + before: A cursor for use in pagination. `before` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include before=obj_foo in order to + fetch the previous page of the list. + + limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the default is 20. + + order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending + order and `desc` for descending order. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._get_api_list( + f"/threads/{thread_id}/messages/{message_id}/files", + page=AsyncCursorPage[MessageFile], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "before": before, + "limit": limit, + "order": order, + }, + file_list_params.FileListParams, + ), + ), + model=MessageFile, + ) + + +class FilesWithRawResponse: + def __init__(self, files: Files) -> None: + self.retrieve = to_raw_response_wrapper( + files.retrieve, + ) + self.list = to_raw_response_wrapper( + files.list, + ) + + +class AsyncFilesWithRawResponse: + def __init__(self, files: AsyncFiles) -> None: + self.retrieve = async_to_raw_response_wrapper( + files.retrieve, + ) + self.list = async_to_raw_response_wrapper( + files.list, + ) diff --git a/src/openai/resources/beta/threads/messages/messages.py b/src/openai/resources/beta/threads/messages/messages.py new file mode 100644 index 0000000000..caec03f484 --- /dev/null +++ b/src/openai/resources/beta/threads/messages/messages.py @@ -0,0 +1,477 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import TYPE_CHECKING, List, Optional +from typing_extensions import Literal + +from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse +from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ....._utils import maybe_transform +from ....._resource import SyncAPIResource, AsyncAPIResource +from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from .....pagination import SyncCursorPage, AsyncCursorPage +from ....._base_client import AsyncPaginator, make_request_options +from .....types.beta.threads import ( + ThreadMessage, + message_list_params, + message_create_params, + message_update_params, +) + +if TYPE_CHECKING: + from ....._client import OpenAI, AsyncOpenAI + +__all__ = ["Messages", "AsyncMessages"] + + +class Messages(SyncAPIResource): + files: Files + with_raw_response: MessagesWithRawResponse + + def __init__(self, client: OpenAI) -> None: + super().__init__(client) + self.files = Files(client) + self.with_raw_response = MessagesWithRawResponse(self) + + def create( + self, + thread_id: str, + *, + content: str, + role: Literal["user"], + file_ids: List[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> ThreadMessage: + """ + Create a message. + + Args: + content: The content of the message. + + role: The role of the entity that is creating the message. Currently only `user` is + supported. + + file_ids: A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + the message should use. There can be a maximum of 10 files attached to a + message. Useful for tools like `retrieval` and `code_interpreter` that can + access and use files. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._post( + f"/threads/{thread_id}/messages", + body=maybe_transform( + { + "content": content, + "role": role, + "file_ids": file_ids, + "metadata": metadata, + }, + message_create_params.MessageCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ThreadMessage, + ) + + def retrieve( + self, + message_id: str, + *, + thread_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> ThreadMessage: + """ + Retrieve a message. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._get( + f"/threads/{thread_id}/messages/{message_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ThreadMessage, + ) + + def update( + self, + message_id: str, + *, + thread_id: str, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> ThreadMessage: + """ + Modifies a message. + + Args: + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._post( + f"/threads/{thread_id}/messages/{message_id}", + body=maybe_transform({"metadata": metadata}, message_update_params.MessageUpdateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ThreadMessage, + ) + + def list( + self, + thread_id: str, + *, + after: str | NotGiven = NOT_GIVEN, + before: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> SyncCursorPage[ThreadMessage]: + """ + Returns a list of messages for a given thread. + + Args: + after: A cursor for use in pagination. `after` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include after=obj_foo in order to + fetch the next page of the list. + + before: A cursor for use in pagination. `before` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include before=obj_foo in order to + fetch the previous page of the list. + + limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the default is 20. + + order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending + order and `desc` for descending order. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._get_api_list( + f"/threads/{thread_id}/messages", + page=SyncCursorPage[ThreadMessage], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "before": before, + "limit": limit, + "order": order, + }, + message_list_params.MessageListParams, + ), + ), + model=ThreadMessage, + ) + + +class AsyncMessages(AsyncAPIResource): + files: AsyncFiles + with_raw_response: AsyncMessagesWithRawResponse + + def __init__(self, client: AsyncOpenAI) -> None: + super().__init__(client) + self.files = AsyncFiles(client) + self.with_raw_response = AsyncMessagesWithRawResponse(self) + + async def create( + self, + thread_id: str, + *, + content: str, + role: Literal["user"], + file_ids: List[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> ThreadMessage: + """ + Create a message. + + Args: + content: The content of the message. + + role: The role of the entity that is creating the message. Currently only `user` is + supported. + + file_ids: A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + the message should use. There can be a maximum of 10 files attached to a + message. Useful for tools like `retrieval` and `code_interpreter` that can + access and use files. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return await self._post( + f"/threads/{thread_id}/messages", + body=maybe_transform( + { + "content": content, + "role": role, + "file_ids": file_ids, + "metadata": metadata, + }, + message_create_params.MessageCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ThreadMessage, + ) + + async def retrieve( + self, + message_id: str, + *, + thread_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> ThreadMessage: + """ + Retrieve a message. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return await self._get( + f"/threads/{thread_id}/messages/{message_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ThreadMessage, + ) + + async def update( + self, + message_id: str, + *, + thread_id: str, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> ThreadMessage: + """ + Modifies a message. + + Args: + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return await self._post( + f"/threads/{thread_id}/messages/{message_id}", + body=maybe_transform({"metadata": metadata}, message_update_params.MessageUpdateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ThreadMessage, + ) + + def list( + self, + thread_id: str, + *, + after: str | NotGiven = NOT_GIVEN, + before: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> AsyncPaginator[ThreadMessage, AsyncCursorPage[ThreadMessage]]: + """ + Returns a list of messages for a given thread. + + Args: + after: A cursor for use in pagination. `after` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include after=obj_foo in order to + fetch the next page of the list. + + before: A cursor for use in pagination. `before` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include before=obj_foo in order to + fetch the previous page of the list. + + limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the default is 20. + + order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending + order and `desc` for descending order. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._get_api_list( + f"/threads/{thread_id}/messages", + page=AsyncCursorPage[ThreadMessage], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "before": before, + "limit": limit, + "order": order, + }, + message_list_params.MessageListParams, + ), + ), + model=ThreadMessage, + ) + + +class MessagesWithRawResponse: + def __init__(self, messages: Messages) -> None: + self.files = FilesWithRawResponse(messages.files) + + self.create = to_raw_response_wrapper( + messages.create, + ) + self.retrieve = to_raw_response_wrapper( + messages.retrieve, + ) + self.update = to_raw_response_wrapper( + messages.update, + ) + self.list = to_raw_response_wrapper( + messages.list, + ) + + +class AsyncMessagesWithRawResponse: + def __init__(self, messages: AsyncMessages) -> None: + self.files = AsyncFilesWithRawResponse(messages.files) + + self.create = async_to_raw_response_wrapper( + messages.create, + ) + self.retrieve = async_to_raw_response_wrapper( + messages.retrieve, + ) + self.update = async_to_raw_response_wrapper( + messages.update, + ) + self.list = async_to_raw_response_wrapper( + messages.list, + ) diff --git a/src/openai/resources/beta/threads/runs/__init__.py b/src/openai/resources/beta/threads/runs/__init__.py new file mode 100644 index 0000000000..6b61813974 --- /dev/null +++ b/src/openai/resources/beta/threads/runs/__init__.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. + +from .runs import Runs, AsyncRuns, RunsWithRawResponse, AsyncRunsWithRawResponse +from .steps import Steps, AsyncSteps, StepsWithRawResponse, AsyncStepsWithRawResponse + +__all__ = [ + "Steps", + "AsyncSteps", + "StepsWithRawResponse", + "AsyncStepsWithRawResponse", + "Runs", + "AsyncRuns", + "RunsWithRawResponse", + "AsyncRunsWithRawResponse", +] diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py new file mode 100644 index 0000000000..370056cbf4 --- /dev/null +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -0,0 +1,654 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import TYPE_CHECKING, List, Optional +from typing_extensions import Literal + +from .steps import Steps, AsyncSteps, StepsWithRawResponse, AsyncStepsWithRawResponse +from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ....._utils import maybe_transform +from ....._resource import SyncAPIResource, AsyncAPIResource +from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from .....pagination import SyncCursorPage, AsyncCursorPage +from ....._base_client import AsyncPaginator, make_request_options +from .....types.beta.threads import ( + Run, + run_list_params, + run_create_params, + run_update_params, + run_submit_tool_outputs_params, +) + +if TYPE_CHECKING: + from ....._client import OpenAI, AsyncOpenAI + +__all__ = ["Runs", "AsyncRuns"] + + +class Runs(SyncAPIResource): + steps: Steps + with_raw_response: RunsWithRawResponse + + def __init__(self, client: OpenAI) -> None: + super().__init__(client) + self.steps = Steps(client) + self.with_raw_response = RunsWithRawResponse(self) + + def create( + self, + thread_id: str, + *, + assistant_id: str, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + tools: Optional[List[run_create_params.Tool]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Run: + """ + Create a run. + + Args: + assistant_id: The ID of the + [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + execute this run. + + instructions: Override the default system message of the assistant. This is useful for + modifying the behavior on a per-run basis. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + be used to execute this run. If a value is provided here, it will override the + model associated with the assistant. If not, the model associated with the + assistant will be used. + + tools: Override the tools the assistant can use for this run. This is useful for + modifying the behavior on a per-run basis. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._post( + f"/threads/{thread_id}/runs", + body=maybe_transform( + { + "assistant_id": assistant_id, + "instructions": instructions, + "metadata": metadata, + "model": model, + "tools": tools, + }, + run_create_params.RunCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Run, + ) + + def retrieve( + self, + run_id: str, + *, + thread_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Run: + """ + Retrieves a run. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._get( + f"/threads/{thread_id}/runs/{run_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Run, + ) + + def update( + self, + run_id: str, + *, + thread_id: str, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Run: + """ + Modifies a run. + + Args: + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._post( + f"/threads/{thread_id}/runs/{run_id}", + body=maybe_transform({"metadata": metadata}, run_update_params.RunUpdateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Run, + ) + + def list( + self, + thread_id: str, + *, + after: str | NotGiven = NOT_GIVEN, + before: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> SyncCursorPage[Run]: + """ + Returns a list of runs belonging to a thread. + + Args: + after: A cursor for use in pagination. `after` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include after=obj_foo in order to + fetch the next page of the list. + + before: A cursor for use in pagination. `before` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include before=obj_foo in order to + fetch the previous page of the list. + + limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the default is 20. + + order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending + order and `desc` for descending order. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._get_api_list( + f"/threads/{thread_id}/runs", + page=SyncCursorPage[Run], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "before": before, + "limit": limit, + "order": order, + }, + run_list_params.RunListParams, + ), + ), + model=Run, + ) + + def cancel( + self, + run_id: str, + *, + thread_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Run: + """ + Cancels a run that is `in_progress`. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._post( + f"/threads/{thread_id}/runs/{run_id}/cancel", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Run, + ) + + def submit_tool_outputs( + self, + run_id: str, + *, + thread_id: str, + tool_outputs: List[run_submit_tool_outputs_params.ToolOutput], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Run: + """ + When a run has the `status: "requires_action"` and `required_action.type` is + `submit_tool_outputs`, this endpoint can be used to submit the outputs from the + tool calls once they're all completed. All outputs must be submitted in a single + request. + + Args: + tool_outputs: A list of tools for which the outputs are being submitted. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._post( + f"/threads/{thread_id}/runs/{run_id}/submit_tool_outputs", + body=maybe_transform( + {"tool_outputs": tool_outputs}, run_submit_tool_outputs_params.RunSubmitToolOutputsParams + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Run, + ) + + +class AsyncRuns(AsyncAPIResource): + steps: AsyncSteps + with_raw_response: AsyncRunsWithRawResponse + + def __init__(self, client: AsyncOpenAI) -> None: + super().__init__(client) + self.steps = AsyncSteps(client) + self.with_raw_response = AsyncRunsWithRawResponse(self) + + async def create( + self, + thread_id: str, + *, + assistant_id: str, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + tools: Optional[List[run_create_params.Tool]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Run: + """ + Create a run. + + Args: + assistant_id: The ID of the + [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + execute this run. + + instructions: Override the default system message of the assistant. This is useful for + modifying the behavior on a per-run basis. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + be used to execute this run. If a value is provided here, it will override the + model associated with the assistant. If not, the model associated with the + assistant will be used. + + tools: Override the tools the assistant can use for this run. This is useful for + modifying the behavior on a per-run basis. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return await self._post( + f"/threads/{thread_id}/runs", + body=maybe_transform( + { + "assistant_id": assistant_id, + "instructions": instructions, + "metadata": metadata, + "model": model, + "tools": tools, + }, + run_create_params.RunCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Run, + ) + + async def retrieve( + self, + run_id: str, + *, + thread_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Run: + """ + Retrieves a run. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return await self._get( + f"/threads/{thread_id}/runs/{run_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Run, + ) + + async def update( + self, + run_id: str, + *, + thread_id: str, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Run: + """ + Modifies a run. + + Args: + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return await self._post( + f"/threads/{thread_id}/runs/{run_id}", + body=maybe_transform({"metadata": metadata}, run_update_params.RunUpdateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Run, + ) + + def list( + self, + thread_id: str, + *, + after: str | NotGiven = NOT_GIVEN, + before: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> AsyncPaginator[Run, AsyncCursorPage[Run]]: + """ + Returns a list of runs belonging to a thread. + + Args: + after: A cursor for use in pagination. `after` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include after=obj_foo in order to + fetch the next page of the list. + + before: A cursor for use in pagination. `before` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include before=obj_foo in order to + fetch the previous page of the list. + + limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the default is 20. + + order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending + order and `desc` for descending order. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._get_api_list( + f"/threads/{thread_id}/runs", + page=AsyncCursorPage[Run], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "before": before, + "limit": limit, + "order": order, + }, + run_list_params.RunListParams, + ), + ), + model=Run, + ) + + async def cancel( + self, + run_id: str, + *, + thread_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Run: + """ + Cancels a run that is `in_progress`. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return await self._post( + f"/threads/{thread_id}/runs/{run_id}/cancel", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Run, + ) + + async def submit_tool_outputs( + self, + run_id: str, + *, + thread_id: str, + tool_outputs: List[run_submit_tool_outputs_params.ToolOutput], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Run: + """ + When a run has the `status: "requires_action"` and `required_action.type` is + `submit_tool_outputs`, this endpoint can be used to submit the outputs from the + tool calls once they're all completed. All outputs must be submitted in a single + request. + + Args: + tool_outputs: A list of tools for which the outputs are being submitted. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return await self._post( + f"/threads/{thread_id}/runs/{run_id}/submit_tool_outputs", + body=maybe_transform( + {"tool_outputs": tool_outputs}, run_submit_tool_outputs_params.RunSubmitToolOutputsParams + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Run, + ) + + +class RunsWithRawResponse: + def __init__(self, runs: Runs) -> None: + self.steps = StepsWithRawResponse(runs.steps) + + self.create = to_raw_response_wrapper( + runs.create, + ) + self.retrieve = to_raw_response_wrapper( + runs.retrieve, + ) + self.update = to_raw_response_wrapper( + runs.update, + ) + self.list = to_raw_response_wrapper( + runs.list, + ) + self.cancel = to_raw_response_wrapper( + runs.cancel, + ) + self.submit_tool_outputs = to_raw_response_wrapper( + runs.submit_tool_outputs, + ) + + +class AsyncRunsWithRawResponse: + def __init__(self, runs: AsyncRuns) -> None: + self.steps = AsyncStepsWithRawResponse(runs.steps) + + self.create = async_to_raw_response_wrapper( + runs.create, + ) + self.retrieve = async_to_raw_response_wrapper( + runs.retrieve, + ) + self.update = async_to_raw_response_wrapper( + runs.update, + ) + self.list = async_to_raw_response_wrapper( + runs.list, + ) + self.cancel = async_to_raw_response_wrapper( + runs.cancel, + ) + self.submit_tool_outputs = async_to_raw_response_wrapper( + runs.submit_tool_outputs, + ) diff --git a/src/openai/resources/beta/threads/runs/steps.py b/src/openai/resources/beta/threads/runs/steps.py new file mode 100644 index 0000000000..bc6fd7fdc9 --- /dev/null +++ b/src/openai/resources/beta/threads/runs/steps.py @@ -0,0 +1,255 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import TYPE_CHECKING +from typing_extensions import Literal + +from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ....._utils import maybe_transform +from ....._resource import SyncAPIResource, AsyncAPIResource +from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from .....pagination import SyncCursorPage, AsyncCursorPage +from ....._base_client import AsyncPaginator, make_request_options +from .....types.beta.threads.runs import RunStep, step_list_params + +if TYPE_CHECKING: + from ....._client import OpenAI, AsyncOpenAI + +__all__ = ["Steps", "AsyncSteps"] + + +class Steps(SyncAPIResource): + with_raw_response: StepsWithRawResponse + + def __init__(self, client: OpenAI) -> None: + super().__init__(client) + self.with_raw_response = StepsWithRawResponse(self) + + def retrieve( + self, + step_id: str, + *, + thread_id: str, + run_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> RunStep: + """ + Retrieves a run step. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._get( + f"/threads/{thread_id}/runs/{run_id}/steps/{step_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=RunStep, + ) + + def list( + self, + run_id: str, + *, + thread_id: str, + after: str | NotGiven = NOT_GIVEN, + before: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> SyncCursorPage[RunStep]: + """ + Returns a list of run steps belonging to a run. + + Args: + after: A cursor for use in pagination. `after` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include after=obj_foo in order to + fetch the next page of the list. + + before: A cursor for use in pagination. `before` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include before=obj_foo in order to + fetch the previous page of the list. + + limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the default is 20. + + order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending + order and `desc` for descending order. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._get_api_list( + f"/threads/{thread_id}/runs/{run_id}/steps", + page=SyncCursorPage[RunStep], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "before": before, + "limit": limit, + "order": order, + }, + step_list_params.StepListParams, + ), + ), + model=RunStep, + ) + + +class AsyncSteps(AsyncAPIResource): + with_raw_response: AsyncStepsWithRawResponse + + def __init__(self, client: AsyncOpenAI) -> None: + super().__init__(client) + self.with_raw_response = AsyncStepsWithRawResponse(self) + + async def retrieve( + self, + step_id: str, + *, + thread_id: str, + run_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> RunStep: + """ + Retrieves a run step. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return await self._get( + f"/threads/{thread_id}/runs/{run_id}/steps/{step_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=RunStep, + ) + + def list( + self, + run_id: str, + *, + thread_id: str, + after: str | NotGiven = NOT_GIVEN, + before: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> AsyncPaginator[RunStep, AsyncCursorPage[RunStep]]: + """ + Returns a list of run steps belonging to a run. + + Args: + after: A cursor for use in pagination. `after` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include after=obj_foo in order to + fetch the next page of the list. + + before: A cursor for use in pagination. `before` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include before=obj_foo in order to + fetch the previous page of the list. + + limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the default is 20. + + order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending + order and `desc` for descending order. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._get_api_list( + f"/threads/{thread_id}/runs/{run_id}/steps", + page=AsyncCursorPage[RunStep], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "before": before, + "limit": limit, + "order": order, + }, + step_list_params.StepListParams, + ), + ), + model=RunStep, + ) + + +class StepsWithRawResponse: + def __init__(self, steps: Steps) -> None: + self.retrieve = to_raw_response_wrapper( + steps.retrieve, + ) + self.list = to_raw_response_wrapper( + steps.list, + ) + + +class AsyncStepsWithRawResponse: + def __init__(self, steps: AsyncSteps) -> None: + self.retrieve = async_to_raw_response_wrapper( + steps.retrieve, + ) + self.list = async_to_raw_response_wrapper( + steps.list, + ) diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py new file mode 100644 index 0000000000..286630d81c --- /dev/null +++ b/src/openai/resources/beta/threads/threads.py @@ -0,0 +1,541 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import TYPE_CHECKING, List, Optional + +from .runs import Runs, AsyncRuns, RunsWithRawResponse, AsyncRunsWithRawResponse +from .messages import ( + Messages, + AsyncMessages, + MessagesWithRawResponse, + AsyncMessagesWithRawResponse, +) +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ...._utils import maybe_transform +from ...._resource import SyncAPIResource, AsyncAPIResource +from ...._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from ....types.beta import ( + Thread, + ThreadDeleted, + thread_create_params, + thread_update_params, + thread_create_and_run_params, +) +from ...._base_client import make_request_options +from ....types.beta.threads import Run + +if TYPE_CHECKING: + from ...._client import OpenAI, AsyncOpenAI + +__all__ = ["Threads", "AsyncThreads"] + + +class Threads(SyncAPIResource): + runs: Runs + messages: Messages + with_raw_response: ThreadsWithRawResponse + + def __init__(self, client: OpenAI) -> None: + super().__init__(client) + self.runs = Runs(client) + self.messages = Messages(client) + self.with_raw_response = ThreadsWithRawResponse(self) + + def create( + self, + *, + messages: List[thread_create_params.Message] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Thread: + """ + Create a thread. + + Args: + messages: A list of [messages](https://platform.openai.com/docs/api-reference/messages) to + start the thread with. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._post( + "/threads", + body=maybe_transform( + { + "messages": messages, + "metadata": metadata, + }, + thread_create_params.ThreadCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Thread, + ) + + def retrieve( + self, + thread_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Thread: + """ + Retrieves a thread. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._get( + f"/threads/{thread_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Thread, + ) + + def update( + self, + thread_id: str, + *, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Thread: + """ + Modifies a thread. + + Args: + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._post( + f"/threads/{thread_id}", + body=maybe_transform({"metadata": metadata}, thread_update_params.ThreadUpdateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Thread, + ) + + def delete( + self, + thread_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> ThreadDeleted: + """ + Delete a thread. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._delete( + f"/threads/{thread_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ThreadDeleted, + ) + + def create_and_run( + self, + *, + assistant_id: str, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tools: Optional[List[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Run: + """ + Create a thread and run it in one request. + + Args: + assistant_id: The ID of the + [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + execute this run. + + instructions: Override the default system message of the assistant. This is useful for + modifying the behavior on a per-run basis. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + be used to execute this run. If a value is provided here, it will override the + model associated with the assistant. If not, the model associated with the + assistant will be used. + + thread: If no thread is provided, an empty thread will be created. + + tools: Override the tools the assistant can use for this run. This is useful for + modifying the behavior on a per-run basis. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._post( + "/threads/runs", + body=maybe_transform( + { + "assistant_id": assistant_id, + "instructions": instructions, + "metadata": metadata, + "model": model, + "thread": thread, + "tools": tools, + }, + thread_create_and_run_params.ThreadCreateAndRunParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Run, + ) + + +class AsyncThreads(AsyncAPIResource): + runs: AsyncRuns + messages: AsyncMessages + with_raw_response: AsyncThreadsWithRawResponse + + def __init__(self, client: AsyncOpenAI) -> None: + super().__init__(client) + self.runs = AsyncRuns(client) + self.messages = AsyncMessages(client) + self.with_raw_response = AsyncThreadsWithRawResponse(self) + + async def create( + self, + *, + messages: List[thread_create_params.Message] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Thread: + """ + Create a thread. + + Args: + messages: A list of [messages](https://platform.openai.com/docs/api-reference/messages) to + start the thread with. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return await self._post( + "/threads", + body=maybe_transform( + { + "messages": messages, + "metadata": metadata, + }, + thread_create_params.ThreadCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Thread, + ) + + async def retrieve( + self, + thread_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Thread: + """ + Retrieves a thread. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return await self._get( + f"/threads/{thread_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Thread, + ) + + async def update( + self, + thread_id: str, + *, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Thread: + """ + Modifies a thread. + + Args: + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return await self._post( + f"/threads/{thread_id}", + body=maybe_transform({"metadata": metadata}, thread_update_params.ThreadUpdateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Thread, + ) + + async def delete( + self, + thread_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> ThreadDeleted: + """ + Delete a thread. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return await self._delete( + f"/threads/{thread_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ThreadDeleted, + ) + + async def create_and_run( + self, + *, + assistant_id: str, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tools: Optional[List[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | None | NotGiven = NOT_GIVEN, + ) -> Run: + """ + Create a thread and run it in one request. + + Args: + assistant_id: The ID of the + [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + execute this run. + + instructions: Override the default system message of the assistant. This is useful for + modifying the behavior on a per-run basis. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + be used to execute this run. If a value is provided here, it will override the + model associated with the assistant. If not, the model associated with the + assistant will be used. + + thread: If no thread is provided, an empty thread will be created. + + tools: Override the tools the assistant can use for this run. This is useful for + modifying the behavior on a per-run basis. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return await self._post( + "/threads/runs", + body=maybe_transform( + { + "assistant_id": assistant_id, + "instructions": instructions, + "metadata": metadata, + "model": model, + "thread": thread, + "tools": tools, + }, + thread_create_and_run_params.ThreadCreateAndRunParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Run, + ) + + +class ThreadsWithRawResponse: + def __init__(self, threads: Threads) -> None: + self.runs = RunsWithRawResponse(threads.runs) + self.messages = MessagesWithRawResponse(threads.messages) + + self.create = to_raw_response_wrapper( + threads.create, + ) + self.retrieve = to_raw_response_wrapper( + threads.retrieve, + ) + self.update = to_raw_response_wrapper( + threads.update, + ) + self.delete = to_raw_response_wrapper( + threads.delete, + ) + self.create_and_run = to_raw_response_wrapper( + threads.create_and_run, + ) + + +class AsyncThreadsWithRawResponse: + def __init__(self, threads: AsyncThreads) -> None: + self.runs = AsyncRunsWithRawResponse(threads.runs) + self.messages = AsyncMessagesWithRawResponse(threads.messages) + + self.create = async_to_raw_response_wrapper( + threads.create, + ) + self.retrieve = async_to_raw_response_wrapper( + threads.retrieve, + ) + self.update = async_to_raw_response_wrapper( + threads.update, + ) + self.delete = async_to_raw_response_wrapper( + threads.delete, + ) + self.create_and_run = async_to_raw_response_wrapper( + threads.create_and_run, + ) diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index e6e6ce52b8..2ecde23ce1 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -13,7 +13,9 @@ from ...types.chat import ( ChatCompletion, ChatCompletionChunk, + ChatCompletionToolParam, ChatCompletionMessageParam, + ChatCompletionToolChoiceOptionParam, completion_create_params, ) from ..._base_client import make_request_options @@ -59,9 +61,13 @@ def create( max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, + seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, + tools: List[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -88,18 +94,24 @@ def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) - function_call: Controls how the model calls functions. "none" means the model will not call a - function and instead generates a message. "auto" means the model can pick - between generating a message or calling a function. Specifying a particular - function via `{"name": "my_function"}` forces the model to call that function. - "none" is the default when no functions are present. "auto" is the default if + function_call: Deprecated in favor of `tool_choice`. + + Controls which (if any) function is called by the model. `none` means the model + will not call a function and instead generates a message. `auto` means the model + can pick between generating a message or calling a function. Specifying a + particular function via `{"name": "my_function"}` forces the model to call that + function. + + `none` is the default when no functions are present. `auto`` is the default if functions are present. - functions: A list of functions the model may generate JSON inputs for. + functions: Deprecated in favor of `tools`. + + A list of functions the model may generate JSON inputs for. logit_bias: Modify the likelihood of specified tokens appearing in the completion. - Accepts a json object that maps tokens (specified by their token ID in the + Accepts a JSON object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or @@ -121,6 +133,15 @@ def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + response_format: An object specifying the format that the model must output. Used to enable JSON + mode. + + seed: This feature is in Beta. If specified, our system will make a best effort to + sample deterministically, such that repeated requests with the same `seed` and + parameters should return the same result. Determinism is not guaranteed, and you + should refer to the `system_fingerprint` response parameter to monitor changes + in the backend. + stop: Up to 4 sequences where the API will stop generating further tokens. stream: If set, partial message deltas will be sent, like in ChatGPT. Tokens will be @@ -136,6 +157,20 @@ def create( We generally recommend altering this or `top_p` but not both. + tool_choice: Controls which (if any) function is called by the model. `none` means the model + will not call a function and instead generates a message. `auto` means the model + can pick between generating a message or calling a function. Specifying a + particular function via + `{"type: "function", "function": {"name": "my_function"}}` forces the model to + call that function. + + `none` is the default when no functions are present. `auto` is the default if + functions are present. + + tools: A list of tools the model may call. Currently, only functions are supported as a + tool. Use this to provide a list of functions the model may generate JSON inputs + for. + top_p: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. @@ -185,8 +220,12 @@ def create( max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, + seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, + tools: List[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -220,18 +259,24 @@ def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) - function_call: Controls how the model calls functions. "none" means the model will not call a - function and instead generates a message. "auto" means the model can pick - between generating a message or calling a function. Specifying a particular - function via `{"name": "my_function"}` forces the model to call that function. - "none" is the default when no functions are present. "auto" is the default if + function_call: Deprecated in favor of `tool_choice`. + + Controls which (if any) function is called by the model. `none` means the model + will not call a function and instead generates a message. `auto` means the model + can pick between generating a message or calling a function. Specifying a + particular function via `{"name": "my_function"}` forces the model to call that + function. + + `none` is the default when no functions are present. `auto`` is the default if functions are present. - functions: A list of functions the model may generate JSON inputs for. + functions: Deprecated in favor of `tools`. + + A list of functions the model may generate JSON inputs for. logit_bias: Modify the likelihood of specified tokens appearing in the completion. - Accepts a json object that maps tokens (specified by their token ID in the + Accepts a JSON object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or @@ -253,6 +298,15 @@ def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + response_format: An object specifying the format that the model must output. Used to enable JSON + mode. + + seed: This feature is in Beta. If specified, our system will make a best effort to + sample deterministically, such that repeated requests with the same `seed` and + parameters should return the same result. Determinism is not guaranteed, and you + should refer to the `system_fingerprint` response parameter to monitor changes + in the backend. + stop: Up to 4 sequences where the API will stop generating further tokens. temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will @@ -261,6 +315,20 @@ def create( We generally recommend altering this or `top_p` but not both. + tool_choice: Controls which (if any) function is called by the model. `none` means the model + will not call a function and instead generates a message. `auto` means the model + can pick between generating a message or calling a function. Specifying a + particular function via + `{"type: "function", "function": {"name": "my_function"}}` forces the model to + call that function. + + `none` is the default when no functions are present. `auto` is the default if + functions are present. + + tools: A list of tools the model may call. Currently, only functions are supported as a + tool. Use this to provide a list of functions the model may generate JSON inputs + for. + top_p: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. @@ -310,8 +378,12 @@ def create( max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, + seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, + tools: List[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -345,18 +417,24 @@ def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) - function_call: Controls how the model calls functions. "none" means the model will not call a - function and instead generates a message. "auto" means the model can pick - between generating a message or calling a function. Specifying a particular - function via `{"name": "my_function"}` forces the model to call that function. - "none" is the default when no functions are present. "auto" is the default if + function_call: Deprecated in favor of `tool_choice`. + + Controls which (if any) function is called by the model. `none` means the model + will not call a function and instead generates a message. `auto` means the model + can pick between generating a message or calling a function. Specifying a + particular function via `{"name": "my_function"}` forces the model to call that + function. + + `none` is the default when no functions are present. `auto`` is the default if functions are present. - functions: A list of functions the model may generate JSON inputs for. + functions: Deprecated in favor of `tools`. + + A list of functions the model may generate JSON inputs for. logit_bias: Modify the likelihood of specified tokens appearing in the completion. - Accepts a json object that maps tokens (specified by their token ID in the + Accepts a JSON object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or @@ -378,6 +456,15 @@ def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + response_format: An object specifying the format that the model must output. Used to enable JSON + mode. + + seed: This feature is in Beta. If specified, our system will make a best effort to + sample deterministically, such that repeated requests with the same `seed` and + parameters should return the same result. Determinism is not guaranteed, and you + should refer to the `system_fingerprint` response parameter to monitor changes + in the backend. + stop: Up to 4 sequences where the API will stop generating further tokens. temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will @@ -386,6 +473,20 @@ def create( We generally recommend altering this or `top_p` but not both. + tool_choice: Controls which (if any) function is called by the model. `none` means the model + will not call a function and instead generates a message. `auto` means the model + can pick between generating a message or calling a function. Specifying a + particular function via + `{"type: "function", "function": {"name": "my_function"}}` forces the model to + call that function. + + `none` is the default when no functions are present. `auto` is the default if + functions are present. + + tools: A list of tools the model may call. Currently, only functions are supported as a + tool. Use this to provide a list of functions the model may generate JSON inputs + for. + top_p: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. @@ -434,9 +535,13 @@ def create( max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, + seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, + tools: List[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -459,9 +564,13 @@ def create( "max_tokens": max_tokens, "n": n, "presence_penalty": presence_penalty, + "response_format": response_format, + "seed": seed, "stop": stop, "stream": stream, "temperature": temperature, + "tool_choice": tool_choice, + "tools": tools, "top_p": top_p, "user": user, }, @@ -511,9 +620,13 @@ async def create( max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, + seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, + tools: List[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -540,18 +653,24 @@ async def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) - function_call: Controls how the model calls functions. "none" means the model will not call a - function and instead generates a message. "auto" means the model can pick - between generating a message or calling a function. Specifying a particular - function via `{"name": "my_function"}` forces the model to call that function. - "none" is the default when no functions are present. "auto" is the default if + function_call: Deprecated in favor of `tool_choice`. + + Controls which (if any) function is called by the model. `none` means the model + will not call a function and instead generates a message. `auto` means the model + can pick between generating a message or calling a function. Specifying a + particular function via `{"name": "my_function"}` forces the model to call that + function. + + `none` is the default when no functions are present. `auto`` is the default if functions are present. - functions: A list of functions the model may generate JSON inputs for. + functions: Deprecated in favor of `tools`. + + A list of functions the model may generate JSON inputs for. logit_bias: Modify the likelihood of specified tokens appearing in the completion. - Accepts a json object that maps tokens (specified by their token ID in the + Accepts a JSON object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or @@ -573,6 +692,15 @@ async def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + response_format: An object specifying the format that the model must output. Used to enable JSON + mode. + + seed: This feature is in Beta. If specified, our system will make a best effort to + sample deterministically, such that repeated requests with the same `seed` and + parameters should return the same result. Determinism is not guaranteed, and you + should refer to the `system_fingerprint` response parameter to monitor changes + in the backend. + stop: Up to 4 sequences where the API will stop generating further tokens. stream: If set, partial message deltas will be sent, like in ChatGPT. Tokens will be @@ -588,6 +716,20 @@ async def create( We generally recommend altering this or `top_p` but not both. + tool_choice: Controls which (if any) function is called by the model. `none` means the model + will not call a function and instead generates a message. `auto` means the model + can pick between generating a message or calling a function. Specifying a + particular function via + `{"type: "function", "function": {"name": "my_function"}}` forces the model to + call that function. + + `none` is the default when no functions are present. `auto` is the default if + functions are present. + + tools: A list of tools the model may call. Currently, only functions are supported as a + tool. Use this to provide a list of functions the model may generate JSON inputs + for. + top_p: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. @@ -637,8 +779,12 @@ async def create( max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, + seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, + tools: List[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -672,18 +818,24 @@ async def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) - function_call: Controls how the model calls functions. "none" means the model will not call a - function and instead generates a message. "auto" means the model can pick - between generating a message or calling a function. Specifying a particular - function via `{"name": "my_function"}` forces the model to call that function. - "none" is the default when no functions are present. "auto" is the default if + function_call: Deprecated in favor of `tool_choice`. + + Controls which (if any) function is called by the model. `none` means the model + will not call a function and instead generates a message. `auto` means the model + can pick between generating a message or calling a function. Specifying a + particular function via `{"name": "my_function"}` forces the model to call that + function. + + `none` is the default when no functions are present. `auto`` is the default if functions are present. - functions: A list of functions the model may generate JSON inputs for. + functions: Deprecated in favor of `tools`. + + A list of functions the model may generate JSON inputs for. logit_bias: Modify the likelihood of specified tokens appearing in the completion. - Accepts a json object that maps tokens (specified by their token ID in the + Accepts a JSON object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or @@ -705,6 +857,15 @@ async def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + response_format: An object specifying the format that the model must output. Used to enable JSON + mode. + + seed: This feature is in Beta. If specified, our system will make a best effort to + sample deterministically, such that repeated requests with the same `seed` and + parameters should return the same result. Determinism is not guaranteed, and you + should refer to the `system_fingerprint` response parameter to monitor changes + in the backend. + stop: Up to 4 sequences where the API will stop generating further tokens. temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will @@ -713,6 +874,20 @@ async def create( We generally recommend altering this or `top_p` but not both. + tool_choice: Controls which (if any) function is called by the model. `none` means the model + will not call a function and instead generates a message. `auto` means the model + can pick between generating a message or calling a function. Specifying a + particular function via + `{"type: "function", "function": {"name": "my_function"}}` forces the model to + call that function. + + `none` is the default when no functions are present. `auto` is the default if + functions are present. + + tools: A list of tools the model may call. Currently, only functions are supported as a + tool. Use this to provide a list of functions the model may generate JSON inputs + for. + top_p: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. @@ -762,8 +937,12 @@ async def create( max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, + seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, + tools: List[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -797,18 +976,24 @@ async def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) - function_call: Controls how the model calls functions. "none" means the model will not call a - function and instead generates a message. "auto" means the model can pick - between generating a message or calling a function. Specifying a particular - function via `{"name": "my_function"}` forces the model to call that function. - "none" is the default when no functions are present. "auto" is the default if + function_call: Deprecated in favor of `tool_choice`. + + Controls which (if any) function is called by the model. `none` means the model + will not call a function and instead generates a message. `auto` means the model + can pick between generating a message or calling a function. Specifying a + particular function via `{"name": "my_function"}` forces the model to call that + function. + + `none` is the default when no functions are present. `auto`` is the default if functions are present. - functions: A list of functions the model may generate JSON inputs for. + functions: Deprecated in favor of `tools`. + + A list of functions the model may generate JSON inputs for. logit_bias: Modify the likelihood of specified tokens appearing in the completion. - Accepts a json object that maps tokens (specified by their token ID in the + Accepts a JSON object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or @@ -830,6 +1015,15 @@ async def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + response_format: An object specifying the format that the model must output. Used to enable JSON + mode. + + seed: This feature is in Beta. If specified, our system will make a best effort to + sample deterministically, such that repeated requests with the same `seed` and + parameters should return the same result. Determinism is not guaranteed, and you + should refer to the `system_fingerprint` response parameter to monitor changes + in the backend. + stop: Up to 4 sequences where the API will stop generating further tokens. temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will @@ -838,6 +1032,20 @@ async def create( We generally recommend altering this or `top_p` but not both. + tool_choice: Controls which (if any) function is called by the model. `none` means the model + will not call a function and instead generates a message. `auto` means the model + can pick between generating a message or calling a function. Specifying a + particular function via + `{"type: "function", "function": {"name": "my_function"}}` forces the model to + call that function. + + `none` is the default when no functions are present. `auto` is the default if + functions are present. + + tools: A list of tools the model may call. Currently, only functions are supported as a + tool. Use this to provide a list of functions the model may generate JSON inputs + for. + top_p: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. @@ -886,9 +1094,13 @@ async def create( max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, + seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, + tools: List[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -911,9 +1123,13 @@ async def create( "max_tokens": max_tokens, "n": n, "presence_penalty": presence_penalty, + "response_format": response_format, + "seed": seed, "stop": stop, "stream": stream, "temperature": temperature, + "tool_choice": tool_choice, + "tools": tools, "top_p": top_p, "user": user, }, diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index 26a34524c6..f1a938ba9a 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -54,6 +54,7 @@ def create( max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, suffix: Optional[str] | NotGiven = NOT_GIVEN, @@ -104,7 +105,7 @@ def create( logit_bias: Modify the likelihood of specified tokens appearing in the completion. - Accepts a json object that maps tokens (specified by their token ID in the GPT + Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this [tokenizer tool](/tokenizer?view=bpe) (which works for both GPT-2 and GPT-3) to convert text to token IDs. Mathematically, the bias is added to the logits @@ -142,6 +143,13 @@ def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + seed: If specified, our system will make a best effort to sample deterministically, + such that repeated requests with the same `seed` and parameters should return + the same result. + + Determinism is not guaranteed, and you should refer to the `system_fingerprint` + response parameter to monitor changes in the backend. + stop: Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. @@ -209,6 +217,7 @@ def create( max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, suffix: Optional[str] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -265,7 +274,7 @@ def create( logit_bias: Modify the likelihood of specified tokens appearing in the completion. - Accepts a json object that maps tokens (specified by their token ID in the GPT + Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this [tokenizer tool](/tokenizer?view=bpe) (which works for both GPT-2 and GPT-3) to convert text to token IDs. Mathematically, the bias is added to the logits @@ -303,6 +312,13 @@ def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + seed: If specified, our system will make a best effort to sample deterministically, + such that repeated requests with the same `seed` and parameters should return + the same result. + + Determinism is not guaranteed, and you should refer to the `system_fingerprint` + response parameter to monitor changes in the backend. + stop: Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. @@ -363,6 +379,7 @@ def create( max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, suffix: Optional[str] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -419,7 +436,7 @@ def create( logit_bias: Modify the likelihood of specified tokens appearing in the completion. - Accepts a json object that maps tokens (specified by their token ID in the GPT + Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this [tokenizer tool](/tokenizer?view=bpe) (which works for both GPT-2 and GPT-3) to convert text to token IDs. Mathematically, the bias is added to the logits @@ -457,6 +474,13 @@ def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + seed: If specified, our system will make a best effort to sample deterministically, + such that repeated requests with the same `seed` and parameters should return + the same result. + + Determinism is not guaranteed, and you should refer to the `system_fingerprint` + response parameter to monitor changes in the backend. + stop: Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. @@ -516,6 +540,7 @@ def create( max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, suffix: Optional[str] | NotGiven = NOT_GIVEN, @@ -543,6 +568,7 @@ def create( "max_tokens": max_tokens, "n": n, "presence_penalty": presence_penalty, + "seed": seed, "stop": stop, "stream": stream, "suffix": suffix, @@ -596,6 +622,7 @@ async def create( max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, suffix: Optional[str] | NotGiven = NOT_GIVEN, @@ -646,7 +673,7 @@ async def create( logit_bias: Modify the likelihood of specified tokens appearing in the completion. - Accepts a json object that maps tokens (specified by their token ID in the GPT + Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this [tokenizer tool](/tokenizer?view=bpe) (which works for both GPT-2 and GPT-3) to convert text to token IDs. Mathematically, the bias is added to the logits @@ -684,6 +711,13 @@ async def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + seed: If specified, our system will make a best effort to sample deterministically, + such that repeated requests with the same `seed` and parameters should return + the same result. + + Determinism is not guaranteed, and you should refer to the `system_fingerprint` + response parameter to monitor changes in the backend. + stop: Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. @@ -751,6 +785,7 @@ async def create( max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, suffix: Optional[str] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -807,7 +842,7 @@ async def create( logit_bias: Modify the likelihood of specified tokens appearing in the completion. - Accepts a json object that maps tokens (specified by their token ID in the GPT + Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this [tokenizer tool](/tokenizer?view=bpe) (which works for both GPT-2 and GPT-3) to convert text to token IDs. Mathematically, the bias is added to the logits @@ -845,6 +880,13 @@ async def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + seed: If specified, our system will make a best effort to sample deterministically, + such that repeated requests with the same `seed` and parameters should return + the same result. + + Determinism is not guaranteed, and you should refer to the `system_fingerprint` + response parameter to monitor changes in the backend. + stop: Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. @@ -905,6 +947,7 @@ async def create( max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, suffix: Optional[str] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -961,7 +1004,7 @@ async def create( logit_bias: Modify the likelihood of specified tokens appearing in the completion. - Accepts a json object that maps tokens (specified by their token ID in the GPT + Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this [tokenizer tool](/tokenizer?view=bpe) (which works for both GPT-2 and GPT-3) to convert text to token IDs. Mathematically, the bias is added to the logits @@ -999,6 +1042,13 @@ async def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + seed: If specified, our system will make a best effort to sample deterministically, + such that repeated requests with the same `seed` and parameters should return + the same result. + + Determinism is not guaranteed, and you should refer to the `system_fingerprint` + response parameter to monitor changes in the backend. + stop: Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. @@ -1058,6 +1108,7 @@ async def create( max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, suffix: Optional[str] | NotGiven = NOT_GIVEN, @@ -1085,6 +1136,7 @@ async def create( "max_tokens": max_tokens, "n": n, "presence_penalty": presence_penalty, + "seed": seed, "stop": stop, "stream": stream, "suffix": suffix, diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index d2e674c942..16d3944a12 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -4,8 +4,9 @@ import time from typing import TYPE_CHECKING, Mapping, cast +from typing_extensions import Literal -from ..types import FileObject, FileDeleted, file_create_params +from ..types import FileObject, FileDeleted, file_list_params, file_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from .._utils import extract_files, maybe_transform, deepcopy_minimal from .._resource import SyncAPIResource, AsyncAPIResource @@ -30,7 +31,7 @@ def create( self, *, file: FileTypes, - purpose: str, + purpose: Literal["fine-tune", "assistants"], # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -40,22 +41,28 @@ def create( ) -> FileObject: """Upload a file that can be used across various endpoints/features. - Currently, the - size of all the files uploaded by one organization can be up to 1 GB. Please - [contact us](https://help.openai.com/) if you need to increase the storage - limit. + The size of + all the files uploaded by one organization can be up to 100 GB. - Args: - file: The file object (not file name) to be uploaded. + The size of individual files for can be a maximum of 512MB. See the + [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) to + learn more about the types of files supported. The Fine-tuning API only supports + `.jsonl` files. + + Please [contact us](https://help.openai.com/) if you need to increase these + storage limits. - If the `purpose` is set to "fine-tune", the file will be used for fine-tuning. + Args: + file: The File object (not file name) to be uploaded. purpose: The intended purpose of the uploaded file. Use "fine-tune" for - [fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning). This - allows us to validate the format of the uploaded file is correct for - fine-tuning. + [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning) and + "assistants" for + [Assistants](https://platform.openai.com/docs/api-reference/assistants) and + [Messages](https://platform.openai.com/docs/api-reference/messages). This allows + us to validate the format of the uploaded file is correct for fine-tuning. extra_headers: Send extra headers @@ -122,6 +129,7 @@ def retrieve( def list( self, *, + purpose: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -129,12 +137,29 @@ def list( extra_body: Body | None = None, timeout: float | None | NotGiven = NOT_GIVEN, ) -> SyncPage[FileObject]: - """Returns a list of files that belong to the user's organization.""" + """ + Returns a list of files that belong to the user's organization. + + Args: + purpose: Only return files with the given purpose. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ return self._get_api_list( "/files", page=SyncPage[FileObject], options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform({"purpose": purpose}, file_list_params.FileListParams), ), model=FileObject, ) @@ -237,7 +262,7 @@ async def create( self, *, file: FileTypes, - purpose: str, + purpose: Literal["fine-tune", "assistants"], # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -247,22 +272,28 @@ async def create( ) -> FileObject: """Upload a file that can be used across various endpoints/features. - Currently, the - size of all the files uploaded by one organization can be up to 1 GB. Please - [contact us](https://help.openai.com/) if you need to increase the storage - limit. + The size of + all the files uploaded by one organization can be up to 100 GB. - Args: - file: The file object (not file name) to be uploaded. + The size of individual files for can be a maximum of 512MB. See the + [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) to + learn more about the types of files supported. The Fine-tuning API only supports + `.jsonl` files. + + Please [contact us](https://help.openai.com/) if you need to increase these + storage limits. - If the `purpose` is set to "fine-tune", the file will be used for fine-tuning. + Args: + file: The File object (not file name) to be uploaded. purpose: The intended purpose of the uploaded file. Use "fine-tune" for - [fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning). This - allows us to validate the format of the uploaded file is correct for - fine-tuning. + [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning) and + "assistants" for + [Assistants](https://platform.openai.com/docs/api-reference/assistants) and + [Messages](https://platform.openai.com/docs/api-reference/messages). This allows + us to validate the format of the uploaded file is correct for fine-tuning. extra_headers: Send extra headers @@ -329,6 +360,7 @@ async def retrieve( def list( self, *, + purpose: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -336,12 +368,29 @@ def list( extra_body: Body | None = None, timeout: float | None | NotGiven = NOT_GIVEN, ) -> AsyncPaginator[FileObject, AsyncPage[FileObject]]: - """Returns a list of files that belong to the user's organization.""" + """ + Returns a list of files that belong to the user's organization. + + Args: + purpose: Only return files with the given purpose. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ return self._get_api_list( "/files", page=AsyncPage[FileObject], options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform({"purpose": purpose}, file_list_params.FileListParams), ), model=FileObject, ) diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py index 1fd39b43a6..9d4ae9936a 100644 --- a/src/openai/resources/images.py +++ b/src/openai/resources/images.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Mapping, Optional, cast +from typing import TYPE_CHECKING, Union, Mapping, Optional, cast from typing_extensions import Literal from ..types import ( @@ -34,6 +34,7 @@ def create_variation( self, *, image: FileTypes, + model: Union[str, Literal["dall-e-2"], None] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN, size: Optional[Literal["256x256", "512x512", "1024x1024"]] | NotGiven = NOT_GIVEN, @@ -52,7 +53,11 @@ def create_variation( image: The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square. - n: The number of images to generate. Must be between 1 and 10. + model: The model to use for image generation. Only `dall-e-2` is supported at this + time. + + n: The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only + `n=1` is supported. response_format: The format in which the generated images are returned. Must be one of `url` or `b64_json`. @@ -75,6 +80,7 @@ def create_variation( body = deepcopy_minimal( { "image": image, + "model": model, "n": n, "response_format": response_format, "size": size, @@ -104,6 +110,7 @@ def edit( image: FileTypes, prompt: str, mask: FileTypes | NotGiven = NOT_GIVEN, + model: Union[str, Literal["dall-e-2"], None] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN, size: Optional[Literal["256x256", "512x512", "1024x1024"]] | NotGiven = NOT_GIVEN, @@ -129,6 +136,9 @@ def edit( indicate where `image` should be edited. Must be a valid PNG file, less than 4MB, and have the same dimensions as `image`. + model: The model to use for image generation. Only `dall-e-2` is supported at this + time. + n: The number of images to generate. Must be between 1 and 10. response_format: The format in which the generated images are returned. Must be one of `url` or @@ -154,6 +164,7 @@ def edit( "image": image, "prompt": prompt, "mask": mask, + "model": model, "n": n, "response_format": response_format, "size": size, @@ -181,9 +192,12 @@ def generate( self, *, prompt: str, + model: Union[str, Literal["dall-e-2", "dall-e-3"], None] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, + quality: Literal["standard", "hd"] | NotGiven = NOT_GIVEN, response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN, - size: Optional[Literal["256x256", "512x512", "1024x1024"]] | NotGiven = NOT_GIVEN, + size: Optional[Literal["256x256", "512x512", "1024x1024", "1792x1024", "1024x1792"]] | NotGiven = NOT_GIVEN, + style: Optional[Literal["vivid", "natural"]] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -197,15 +211,28 @@ def generate( Args: prompt: A text description of the desired image(s). The maximum length is 1000 - characters. + characters for `dall-e-2` and 4000 characters for `dall-e-3`. - n: The number of images to generate. Must be between 1 and 10. + model: The model to use for image generation. + + n: The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only + `n=1` is supported. + + quality: The quality of the image that will be generated. `hd` creates images with finer + details and greater consistency across the image. This param is only supported + for `dall-e-3`. response_format: The format in which the generated images are returned. Must be one of `url` or `b64_json`. size: The size of the generated images. Must be one of `256x256`, `512x512`, or - `1024x1024`. + `1024x1024` for `dall-e-2`. Must be one of `1024x1024`, `1792x1024`, or + `1024x1792` for `dall-e-3` models. + + style: The style of the generated images. Must be one of `vivid` or `natural`. Vivid + causes the model to lean towards generating hyper-real and dramatic images. + Natural causes the model to produce more natural, less hyper-real looking + images. This param is only supported for `dall-e-3`. user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. @@ -224,9 +251,12 @@ def generate( body=maybe_transform( { "prompt": prompt, + "model": model, "n": n, + "quality": quality, "response_format": response_format, "size": size, + "style": style, "user": user, }, image_generate_params.ImageGenerateParams, @@ -249,6 +279,7 @@ async def create_variation( self, *, image: FileTypes, + model: Union[str, Literal["dall-e-2"], None] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN, size: Optional[Literal["256x256", "512x512", "1024x1024"]] | NotGiven = NOT_GIVEN, @@ -267,7 +298,11 @@ async def create_variation( image: The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square. - n: The number of images to generate. Must be between 1 and 10. + model: The model to use for image generation. Only `dall-e-2` is supported at this + time. + + n: The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only + `n=1` is supported. response_format: The format in which the generated images are returned. Must be one of `url` or `b64_json`. @@ -290,6 +325,7 @@ async def create_variation( body = deepcopy_minimal( { "image": image, + "model": model, "n": n, "response_format": response_format, "size": size, @@ -319,6 +355,7 @@ async def edit( image: FileTypes, prompt: str, mask: FileTypes | NotGiven = NOT_GIVEN, + model: Union[str, Literal["dall-e-2"], None] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN, size: Optional[Literal["256x256", "512x512", "1024x1024"]] | NotGiven = NOT_GIVEN, @@ -344,6 +381,9 @@ async def edit( indicate where `image` should be edited. Must be a valid PNG file, less than 4MB, and have the same dimensions as `image`. + model: The model to use for image generation. Only `dall-e-2` is supported at this + time. + n: The number of images to generate. Must be between 1 and 10. response_format: The format in which the generated images are returned. Must be one of `url` or @@ -369,6 +409,7 @@ async def edit( "image": image, "prompt": prompt, "mask": mask, + "model": model, "n": n, "response_format": response_format, "size": size, @@ -396,9 +437,12 @@ async def generate( self, *, prompt: str, + model: Union[str, Literal["dall-e-2", "dall-e-3"], None] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, + quality: Literal["standard", "hd"] | NotGiven = NOT_GIVEN, response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN, - size: Optional[Literal["256x256", "512x512", "1024x1024"]] | NotGiven = NOT_GIVEN, + size: Optional[Literal["256x256", "512x512", "1024x1024", "1792x1024", "1024x1792"]] | NotGiven = NOT_GIVEN, + style: Optional[Literal["vivid", "natural"]] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -412,15 +456,28 @@ async def generate( Args: prompt: A text description of the desired image(s). The maximum length is 1000 - characters. + characters for `dall-e-2` and 4000 characters for `dall-e-3`. - n: The number of images to generate. Must be between 1 and 10. + model: The model to use for image generation. + + n: The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only + `n=1` is supported. + + quality: The quality of the image that will be generated. `hd` creates images with finer + details and greater consistency across the image. This param is only supported + for `dall-e-3`. response_format: The format in which the generated images are returned. Must be one of `url` or `b64_json`. size: The size of the generated images. Must be one of `256x256`, `512x512`, or - `1024x1024`. + `1024x1024` for `dall-e-2`. Must be one of `1024x1024`, `1792x1024`, or + `1024x1792` for `dall-e-3` models. + + style: The style of the generated images. Must be one of `vivid` or `natural`. Vivid + causes the model to lean towards generating hyper-real and dramatic images. + Natural causes the model to produce more natural, less hyper-real looking + images. This param is only supported for `dall-e-3`. user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. @@ -439,9 +496,12 @@ async def generate( body=maybe_transform( { "prompt": prompt, + "model": model, "n": n, + "quality": quality, "response_format": response_format, "size": size, + "style": style, "user": user, }, image_generate_params.ImageGenerateParams, diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index defaf13446..8f21480d5e 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -16,6 +16,7 @@ from .fine_tune_event import FineTuneEvent as FineTuneEvent from .images_response import ImagesResponse as ImagesResponse from .completion_usage import CompletionUsage as CompletionUsage +from .file_list_params import FileListParams as FileListParams from .completion_choice import CompletionChoice as CompletionChoice from .image_edit_params import ImageEditParams as ImageEditParams from .edit_create_params import EditCreateParams as EditCreateParams diff --git a/src/openai/types/audio/__init__.py b/src/openai/types/audio/__init__.py index 469bc6f25b..83afa060f8 100644 --- a/src/openai/types/audio/__init__.py +++ b/src/openai/types/audio/__init__.py @@ -4,6 +4,7 @@ from .translation import Translation as Translation from .transcription import Transcription as Transcription +from .speech_create_params import SpeechCreateParams as SpeechCreateParams from .translation_create_params import ( TranslationCreateParams as TranslationCreateParams, ) diff --git a/src/openai/types/audio/speech_create_params.py b/src/openai/types/audio/speech_create_params.py new file mode 100644 index 0000000000..06bea01746 --- /dev/null +++ b/src/openai/types/audio/speech_create_params.py @@ -0,0 +1,34 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["SpeechCreateParams"] + + +class SpeechCreateParams(TypedDict, total=False): + input: Required[str] + """The text to generate audio for. The maximum length is 4096 characters.""" + + model: Required[Union[str, Literal["tts-1", "tts-1-hd"]]] + """ + One of the available [TTS models](https://platform.openai.com/docs/models/tts): + `tts-1` or `tts-1-hd` + """ + + voice: Required[Literal["alloy", "echo", "fable", "onyx", "nova", "shimmer"]] + """The voice to use when generating the audio. + + Supported voices are `alloy`, `echo`, `fable`, `onyx`, `nova`, and `shimmer`. + """ + + response_format: Literal["mp3", "opus", "aac", "flac"] + """The format to audio in. Supported formats are `mp3`, `opus`, `aac`, and `flac`.""" + + speed: float + """The speed of the generated audio. + + Select a value from `0.25` to `4.0`. `1.0` is the default. + """ diff --git a/src/openai/types/audio/transcription_create_params.py b/src/openai/types/audio/transcription_create_params.py index f8f193484a..7bd70d7b48 100644 --- a/src/openai/types/audio/transcription_create_params.py +++ b/src/openai/types/audio/transcription_create_params.py @@ -38,8 +38,8 @@ class TranscriptionCreateParams(TypedDict, total=False): response_format: Literal["json", "text", "srt", "verbose_json", "vtt"] """ - The format of the transcript output, in one of these options: json, text, srt, - verbose_json, or vtt. + The format of the transcript output, in one of these options: `json`, `text`, + `srt`, `verbose_json`, or `vtt`. """ temperature: float diff --git a/src/openai/types/audio/translation_create_params.py b/src/openai/types/audio/translation_create_params.py index bfa5fc56d2..d3cb4b9e63 100644 --- a/src/openai/types/audio/translation_create_params.py +++ b/src/openai/types/audio/translation_create_params.py @@ -30,8 +30,8 @@ class TranslationCreateParams(TypedDict, total=False): response_format: str """ - The format of the transcript output, in one of these options: json, text, srt, - verbose_json, or vtt. + The format of the transcript output, in one of these options: `json`, `text`, + `srt`, `verbose_json`, or `vtt`. """ temperature: float diff --git a/src/openai/types/beta/__init__.py b/src/openai/types/beta/__init__.py new file mode 100644 index 0000000000..8b834f286d --- /dev/null +++ b/src/openai/types/beta/__init__.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from .thread import Thread as Thread +from .assistant import Assistant as Assistant +from .thread_deleted import ThreadDeleted as ThreadDeleted +from .asssitant_deleted import AsssitantDeleted as AsssitantDeleted +from .thread_create_params import ThreadCreateParams as ThreadCreateParams +from .thread_update_params import ThreadUpdateParams as ThreadUpdateParams +from .assistant_list_params import AssistantListParams as AssistantListParams +from .assistant_create_params import AssistantCreateParams as AssistantCreateParams +from .assistant_update_params import AssistantUpdateParams as AssistantUpdateParams +from .thread_create_and_run_params import ( + ThreadCreateAndRunParams as ThreadCreateAndRunParams, +) diff --git a/src/openai/types/beta/assistant.py b/src/openai/types/beta/assistant.py new file mode 100644 index 0000000000..9130b60363 --- /dev/null +++ b/src/openai/types/beta/assistant.py @@ -0,0 +1,112 @@ +# File generated from our OpenAPI spec by Stainless. + +import builtins +from typing import Dict, List, Union, Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["Assistant", "Tool", "ToolCodeInterpreter", "ToolRetreival", "ToolFunction", "ToolFunctionFunction"] + + +class ToolCodeInterpreter(BaseModel): + type: Literal["code_interpreter"] + """The type of tool being defined: `code_interpreter`""" + + +class ToolRetreival(BaseModel): + type: Literal["retreival"] + """The type of tool being defined: `retreival`""" + + +class ToolFunctionFunction(BaseModel): + description: str + """ + A description of what the function does, used by the model to choose when and + how to call the function. + """ + + name: str + """The name of the function to be called. + + Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length + of 64. + """ + + parameters: Dict[str, builtins.object] + """The parameters the functions accepts, described as a JSON Schema object. + + See the [guide](https://platform.openai.com/docs/guides/gpt/function-calling) + for examples, and the + [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for + documentation about the format. + + To describe a function that accepts no parameters, provide the value + `{"type": "object", "properties": {}}`. + """ + + +class ToolFunction(BaseModel): + function: ToolFunctionFunction + """The function definition.""" + + type: Literal["function"] + """The type of tool being defined: `function`""" + + +Tool = Union[ToolCodeInterpreter, ToolRetreival, ToolFunction] + + +class Assistant(BaseModel): + id: str + """The identifier, which can be referenced in API endpoints.""" + + created_at: int + """The Unix timestamp (in seconds) for when the assistant was created.""" + + description: Optional[str] + """The description of the assistant. The maximum length is 512 characters.""" + + file_ids: List[str] + """ + A list of [file](https://platform.openai.com/docs/api-reference/files) IDs + attached to this assistant. There can be a maximum of 20 files attached to the + assistant. Files are ordered by their creation date in ascending order. + """ + + instructions: Optional[str] + """The system instructions that the assistant uses. + + The maximum length is 32768 characters. + """ + + metadata: Optional[builtins.object] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format. Keys can be a maximum of 64 characters long and values can be + a maxium of 512 characters long. + """ + + model: str + """ID of the model to use. + + You can use the + [List models](https://platform.openai.com/docs/api-reference/models/list) API to + see all of your available models, or see our + [Model overview](https://platform.openai.com/docs/models/overview) for + descriptions of them. + """ + + name: Optional[str] + """The name of the assistant. The maximum length is 256 characters.""" + + object: Literal["assistant"] + """The object type, which is always `assistant`.""" + + tools: List[Tool] + """A list of tool enabled on the assistant. + + There can be a maximum of 128 tools per assistant. Tools can be of types + `code_interpreter`, `retrieval`, or `function`. + """ diff --git a/src/openai/types/beta/assistant_create_params.py b/src/openai/types/beta/assistant_create_params.py new file mode 100644 index 0000000000..8b8f025c39 --- /dev/null +++ b/src/openai/types/beta/assistant_create_params.py @@ -0,0 +1,109 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Dict, List, Union, Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = [ + "AssistantCreateParams", + "Tool", + "ToolAssistantToolsCode", + "ToolAssistantToolsRetrieval", + "ToolAssistantToolsFunction", + "ToolAssistantToolsFunctionFunction", +] + + +class AssistantCreateParams(TypedDict, total=False): + model: Required[str] + """ID of the model to use. + + You can use the + [List models](https://platform.openai.com/docs/api-reference/models/list) API to + see all of your available models, or see our + [Model overview](https://platform.openai.com/docs/models/overview) for + descriptions of them. + """ + + description: Optional[str] + """The description of the assistant. The maximum length is 512 characters.""" + + file_ids: List[str] + """ + A list of [file](https://platform.openai.com/docs/api-reference/files) IDs + attached to this assistant. There can be a maximum of 20 files attached to the + assistant. Files are ordered by their creation date in ascending order. + """ + + instructions: Optional[str] + """The system instructions that the assistant uses. + + The maximum length is 32768 characters. + """ + + metadata: Optional[object] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format. Keys can be a maximum of 64 characters long and values can be + a maxium of 512 characters long. + """ + + name: Optional[str] + """The name of the assistant. The maximum length is 256 characters.""" + + tools: List[Tool] + """A list of tool enabled on the assistant. + + There can be a maximum of 128 tools per assistant. Tools can be of types + `code_interpreter`, `retrieval`, or `function`. + """ + + +class ToolAssistantToolsCode(TypedDict, total=False): + type: Required[Literal["code_interpreter"]] + """The type of tool being defined: `code_interpreter`""" + + +class ToolAssistantToolsRetrieval(TypedDict, total=False): + type: Required[Literal["retreival"]] + """The type of tool being defined: `retreival`""" + + +class ToolAssistantToolsFunctionFunction(TypedDict, total=False): + description: Required[str] + """ + A description of what the function does, used by the model to choose when and + how to call the function. + """ + + name: Required[str] + """The name of the function to be called. + + Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length + of 64. + """ + + parameters: Required[Dict[str, object]] + """The parameters the functions accepts, described as a JSON Schema object. + + See the [guide](https://platform.openai.com/docs/guides/gpt/function-calling) + for examples, and the + [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for + documentation about the format. + + To describe a function that accepts no parameters, provide the value + `{"type": "object", "properties": {}}`. + """ + + +class ToolAssistantToolsFunction(TypedDict, total=False): + function: Required[ToolAssistantToolsFunctionFunction] + """The function definition.""" + + type: Required[Literal["function"]] + """The type of tool being defined: `function`""" + + +Tool = Union[ToolAssistantToolsCode, ToolAssistantToolsRetrieval, ToolAssistantToolsFunction] diff --git a/src/openai/types/beta/assistant_list_params.py b/src/openai/types/beta/assistant_list_params.py new file mode 100644 index 0000000000..b2d794a43a --- /dev/null +++ b/src/openai/types/beta/assistant_list_params.py @@ -0,0 +1,39 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing_extensions import Literal, TypedDict + +__all__ = ["AssistantListParams"] + + +class AssistantListParams(TypedDict, total=False): + after: str + """A cursor for use in pagination. + + `after` is an object ID that defines your place in the list. For instance, if + you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include after=obj_foo in order to fetch the next page of the + list. + """ + + before: str + """A cursor for use in pagination. + + `before` is an object ID that defines your place in the list. For instance, if + you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page + of the list. + """ + + limit: int + """A limit on the number of objects to be returned. + + Limit can range between 1 and 100, and the default is 20. + """ + + order: Literal["asc", "desc"] + """Sort order by the `created_at` timestamp of the objects. + + `asc` for ascending order and `desc` for descending order. + """ diff --git a/src/openai/types/beta/assistant_update_params.py b/src/openai/types/beta/assistant_update_params.py new file mode 100644 index 0000000000..fa838f51e3 --- /dev/null +++ b/src/openai/types/beta/assistant_update_params.py @@ -0,0 +1,111 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Dict, List, Union, Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = [ + "AssistantUpdateParams", + "Tool", + "ToolAssistantToolsCode", + "ToolAssistantToolsRetrieval", + "ToolAssistantToolsFunction", + "ToolAssistantToolsFunctionFunction", +] + + +class AssistantUpdateParams(TypedDict, total=False): + description: Optional[str] + """The description of the assistant. The maximum length is 512 characters.""" + + file_ids: List[str] + """ + A list of [File](https://platform.openai.com/docs/api-reference/files) IDs + attached to this assistant. There can be a maximum of 20 files attached to the + assistant. Files are ordered by their creation date in ascending order. If a + file was previosuly attached to the list but does not show up in the list, it + will be deleted from the assistant. + """ + + instructions: Optional[str] + """The system instructions that the assistant uses. + + The maximum length is 32768 characters. + """ + + metadata: Optional[object] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format. Keys can be a maximum of 64 characters long and values can be + a maxium of 512 characters long. + """ + + model: str + """ID of the model to use. + + You can use the + [List models](https://platform.openai.com/docs/api-reference/models/list) API to + see all of your available models, or see our + [Model overview](https://platform.openai.com/docs/models/overview) for + descriptions of them. + """ + + name: Optional[str] + """The name of the assistant. The maximum length is 256 characters.""" + + tools: List[Tool] + """A list of tool enabled on the assistant. + + There can be a maximum of 128 tools per assistant. Tools can be of types + `code_interpreter`, `retrieval`, or `function`. + """ + + +class ToolAssistantToolsCode(TypedDict, total=False): + type: Required[Literal["code_interpreter"]] + """The type of tool being defined: `code_interpreter`""" + + +class ToolAssistantToolsRetrieval(TypedDict, total=False): + type: Required[Literal["retreival"]] + """The type of tool being defined: `retreival`""" + + +class ToolAssistantToolsFunctionFunction(TypedDict, total=False): + description: Required[str] + """ + A description of what the function does, used by the model to choose when and + how to call the function. + """ + + name: Required[str] + """The name of the function to be called. + + Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length + of 64. + """ + + parameters: Required[Dict[str, object]] + """The parameters the functions accepts, described as a JSON Schema object. + + See the [guide](https://platform.openai.com/docs/guides/gpt/function-calling) + for examples, and the + [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for + documentation about the format. + + To describe a function that accepts no parameters, provide the value + `{"type": "object", "properties": {}}`. + """ + + +class ToolAssistantToolsFunction(TypedDict, total=False): + function: Required[ToolAssistantToolsFunctionFunction] + """The function definition.""" + + type: Required[Literal["function"]] + """The type of tool being defined: `function`""" + + +Tool = Union[ToolAssistantToolsCode, ToolAssistantToolsRetrieval, ToolAssistantToolsFunction] diff --git a/src/openai/types/beta/assistants/__init__.py b/src/openai/types/beta/assistants/__init__.py new file mode 100644 index 0000000000..9dbb3e2b8b --- /dev/null +++ b/src/openai/types/beta/assistants/__init__.py @@ -0,0 +1,8 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from .assistant_file import AssistantFile as AssistantFile +from .file_list_params import FileListParams as FileListParams +from .file_create_params import FileCreateParams as FileCreateParams +from .file_delete_response import FileDeleteResponse as FileDeleteResponse diff --git a/src/openai/types/beta/assistants/assistant_file.py b/src/openai/types/beta/assistants/assistant_file.py new file mode 100644 index 0000000000..1d1573ac0f --- /dev/null +++ b/src/openai/types/beta/assistants/assistant_file.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["AssistantFile"] + + +class AssistantFile(BaseModel): + id: str + """The identifier, which can be referenced in API endpoints.""" + + assistant_id: str + """The assistant ID that the file is attached to.""" + + created_at: int + """The Unix timestamp (in seconds) for when the assistant file was created.""" + + object: Literal["assistant.file"] + """The object type, which is always `assistant.file`.""" diff --git a/src/openai/types/beta/assistants/file_create_params.py b/src/openai/types/beta/assistants/file_create_params.py new file mode 100644 index 0000000000..f70f96fc1b --- /dev/null +++ b/src/openai/types/beta/assistants/file_create_params.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +__all__ = ["FileCreateParams"] + + +class FileCreateParams(TypedDict, total=False): + file_id: Required[str] + """ + A [File](https://platform.openai.com/docs/api-reference/files) ID (with + `purpose="assistants"`) that the assistant should use. Useful for tools like + `retrieval` and `code_interpreter` that can access files. + """ diff --git a/src/openai/types/beta/assistants/file_delete_response.py b/src/openai/types/beta/assistants/file_delete_response.py new file mode 100644 index 0000000000..52c138feda --- /dev/null +++ b/src/openai/types/beta/assistants/file_delete_response.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["FileDeleteResponse"] + + +class FileDeleteResponse(BaseModel): + id: str + + deleted: bool + + object: Literal["assistant.file.deleted"] diff --git a/src/openai/types/beta/assistants/file_list_params.py b/src/openai/types/beta/assistants/file_list_params.py new file mode 100644 index 0000000000..397e35a0d1 --- /dev/null +++ b/src/openai/types/beta/assistants/file_list_params.py @@ -0,0 +1,39 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing_extensions import Literal, TypedDict + +__all__ = ["FileListParams"] + + +class FileListParams(TypedDict, total=False): + after: str + """A cursor for use in pagination. + + `after` is an object ID that defines your place in the list. For instance, if + you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include after=obj_foo in order to fetch the next page of the + list. + """ + + before: str + """A cursor for use in pagination. + + `before` is an object ID that defines your place in the list. For instance, if + you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page + of the list. + """ + + limit: int + """A limit on the number of objects to be returned. + + Limit can range between 1 and 100, and the default is 20. + """ + + order: Literal["asc", "desc"] + """Sort order by the `created_at` timestamp of the objects. + + `asc` for ascending order and `desc` for descending order. + """ diff --git a/src/openai/types/beta/asssitant_deleted.py b/src/openai/types/beta/asssitant_deleted.py new file mode 100644 index 0000000000..258210e7fe --- /dev/null +++ b/src/openai/types/beta/asssitant_deleted.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["AsssitantDeleted"] + + +class AsssitantDeleted(BaseModel): + id: str + + deleted: bool + + object: Literal["assistant.deleted"] diff --git a/src/openai/types/beta/chat/__init__.py b/src/openai/types/beta/chat/__init__.py new file mode 100644 index 0000000000..b2f53e3525 --- /dev/null +++ b/src/openai/types/beta/chat/__init__.py @@ -0,0 +1,3 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations diff --git a/src/openai/types/beta/thread.py b/src/openai/types/beta/thread.py new file mode 100644 index 0000000000..a340bffd60 --- /dev/null +++ b/src/openai/types/beta/thread.py @@ -0,0 +1,28 @@ +# File generated from our OpenAPI spec by Stainless. + +import builtins +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["Thread"] + + +class Thread(BaseModel): + id: str + """The identifier, which can be referenced in API endpoints.""" + + created_at: int + """The Unix timestamp (in seconds) for when the thread was created.""" + + metadata: Optional[builtins.object] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format. Keys can be a maximum of 64 characters long and values can be + a maxium of 512 characters long. + """ + + object: Literal["thread"] + """The object type, which is always `thread`.""" diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py new file mode 100644 index 0000000000..2955343ec0 --- /dev/null +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -0,0 +1,148 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Dict, List, Union, Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = [ + "ThreadCreateAndRunParams", + "Thread", + "ThreadMessage", + "Tool", + "ToolAssistantToolsCode", + "ToolAssistantToolsRetrieval", + "ToolAssistantToolsFunction", + "ToolAssistantToolsFunctionFunction", +] + + +class ThreadCreateAndRunParams(TypedDict, total=False): + assistant_id: Required[str] + """ + The ID of the + [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + execute this run. + """ + + instructions: Optional[str] + """Override the default system message of the assistant. + + This is useful for modifying the behavior on a per-run basis. + """ + + metadata: Optional[object] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format. Keys can be a maximum of 64 characters long and values can be + a maxium of 512 characters long. + """ + + model: Optional[str] + """ + The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + be used to execute this run. If a value is provided here, it will override the + model associated with the assistant. If not, the model associated with the + assistant will be used. + """ + + thread: Thread + """If no thread is provided, an empty thread will be created.""" + + tools: Optional[List[Tool]] + """Override the tools the assistant can use for this run. + + This is useful for modifying the behavior on a per-run basis. + """ + + +class ThreadMessage(TypedDict, total=False): + content: Required[str] + """The content of the message.""" + + role: Required[Literal["user"]] + """The role of the entity that is creating the message. + + Currently only `user` is supported. + """ + + file_ids: List[str] + """ + A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + the message should use. There can be a maximum of 10 files attached to a + message. Useful for tools like `retrieval` and `code_interpreter` that can + access and use files. + """ + + metadata: Optional[object] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format. Keys can be a maximum of 64 characters long and values can be + a maxium of 512 characters long. + """ + + +class Thread(TypedDict, total=False): + messages: List[ThreadMessage] + """ + A list of [messages](https://platform.openai.com/docs/api-reference/messages) to + start the thread with. + """ + + metadata: Optional[object] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format. Keys can be a maximum of 64 characters long and values can be + a maxium of 512 characters long. + """ + + +class ToolAssistantToolsCode(TypedDict, total=False): + type: Required[Literal["code_interpreter"]] + """The type of tool being defined: `code_interpreter`""" + + +class ToolAssistantToolsRetrieval(TypedDict, total=False): + type: Required[Literal["retreival"]] + """The type of tool being defined: `retreival`""" + + +class ToolAssistantToolsFunctionFunction(TypedDict, total=False): + description: Required[str] + """ + A description of what the function does, used by the model to choose when and + how to call the function. + """ + + name: Required[str] + """The name of the function to be called. + + Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length + of 64. + """ + + parameters: Required[Dict[str, object]] + """The parameters the functions accepts, described as a JSON Schema object. + + See the [guide](https://platform.openai.com/docs/guides/gpt/function-calling) + for examples, and the + [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for + documentation about the format. + + To describe a function that accepts no parameters, provide the value + `{"type": "object", "properties": {}}`. + """ + + +class ToolAssistantToolsFunction(TypedDict, total=False): + function: Required[ToolAssistantToolsFunctionFunction] + """The function definition.""" + + type: Required[Literal["function"]] + """The type of tool being defined: `function`""" + + +Tool = Union[ToolAssistantToolsCode, ToolAssistantToolsRetrieval, ToolAssistantToolsFunction] diff --git a/src/openai/types/beta/thread_create_params.py b/src/openai/types/beta/thread_create_params.py new file mode 100644 index 0000000000..d2ec78bbc3 --- /dev/null +++ b/src/openai/types/beta/thread_create_params.py @@ -0,0 +1,51 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ThreadCreateParams", "Message"] + + +class ThreadCreateParams(TypedDict, total=False): + messages: List[Message] + """ + A list of [messages](https://platform.openai.com/docs/api-reference/messages) to + start the thread with. + """ + + metadata: Optional[object] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format. Keys can be a maximum of 64 characters long and values can be + a maxium of 512 characters long. + """ + + +class Message(TypedDict, total=False): + content: Required[str] + """The content of the message.""" + + role: Required[Literal["user"]] + """The role of the entity that is creating the message. + + Currently only `user` is supported. + """ + + file_ids: List[str] + """ + A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + the message should use. There can be a maximum of 10 files attached to a + message. Useful for tools like `retrieval` and `code_interpreter` that can + access and use files. + """ + + metadata: Optional[object] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format. Keys can be a maximum of 64 characters long and values can be + a maxium of 512 characters long. + """ diff --git a/src/openai/types/beta/thread_deleted.py b/src/openai/types/beta/thread_deleted.py new file mode 100644 index 0000000000..410ac1aea0 --- /dev/null +++ b/src/openai/types/beta/thread_deleted.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ThreadDeleted"] + + +class ThreadDeleted(BaseModel): + id: str + + deleted: bool + + object: Literal["thread.deleted"] diff --git a/src/openai/types/beta/thread_update_params.py b/src/openai/types/beta/thread_update_params.py new file mode 100644 index 0000000000..6c1d32fc57 --- /dev/null +++ b/src/openai/types/beta/thread_update_params.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +__all__ = ["ThreadUpdateParams"] + + +class ThreadUpdateParams(TypedDict, total=False): + metadata: Optional[object] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format. Keys can be a maximum of 64 characters long and values can be + a maxium of 512 characters long. + """ diff --git a/src/openai/types/beta/threads/__init__.py b/src/openai/types/beta/threads/__init__.py new file mode 100644 index 0000000000..0cb557a514 --- /dev/null +++ b/src/openai/types/beta/threads/__init__.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from .run import Run as Run +from .thread_message import ThreadMessage as ThreadMessage +from .run_list_params import RunListParams as RunListParams +from .run_create_params import RunCreateParams as RunCreateParams +from .run_update_params import RunUpdateParams as RunUpdateParams +from .message_list_params import MessageListParams as MessageListParams +from .message_content_text import MessageContentText as MessageContentText +from .message_create_params import MessageCreateParams as MessageCreateParams +from .message_update_params import MessageUpdateParams as MessageUpdateParams +from .message_content_image_file import ( + MessageContentImageFile as MessageContentImageFile, +) +from .run_submit_tool_outputs_params import ( + RunSubmitToolOutputsParams as RunSubmitToolOutputsParams, +) +from .required_action_function_tool_call import ( + RequiredActionFunctionToolCall as RequiredActionFunctionToolCall, +) diff --git a/src/openai/types/beta/threads/message_content_image_file.py b/src/openai/types/beta/threads/message_content_image_file.py new file mode 100644 index 0000000000..eeba5a633c --- /dev/null +++ b/src/openai/types/beta/threads/message_content_image_file.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["MessageContentImageFile", "ImageFile"] + + +class ImageFile(BaseModel): + file_id: str + """ + The [File](https://platform.openai.com/docs/api-reference/files) ID of the image + in the message content. + """ + + +class MessageContentImageFile(BaseModel): + image_file: ImageFile + + type: Literal["image_file"] + """Always `image_file`.""" diff --git a/src/openai/types/beta/threads/message_content_text.py b/src/openai/types/beta/threads/message_content_text.py new file mode 100644 index 0000000000..b529a384c6 --- /dev/null +++ b/src/openai/types/beta/threads/message_content_text.py @@ -0,0 +1,74 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import List, Union +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = [ + "MessageContentText", + "Text", + "TextAnnotation", + "TextAnnotationFileCitation", + "TextAnnotationFileCitationFileCitation", + "TextAnnotationFilePath", + "TextAnnotationFilePathFilePath", +] + + +class TextAnnotationFileCitationFileCitation(BaseModel): + file_id: str + """The ID of the specific File the citation is from.""" + + quote: str + """The specific quote in the file.""" + + +class TextAnnotationFileCitation(BaseModel): + end_index: int + + file_citation: TextAnnotationFileCitationFileCitation + + start_index: int + + text: str + """The text in the message content that needs to be replaced.""" + + type: Literal["file_citation"] + """Always `file_citation`.""" + + +class TextAnnotationFilePathFilePath(BaseModel): + file_id: str + """The ID of the file that was generated.""" + + +class TextAnnotationFilePath(BaseModel): + end_index: int + + file_path: TextAnnotationFilePathFilePath + + start_index: int + + text: str + """The text in the message content that needs to be replaced.""" + + type: Literal["file_path"] + """Always `file_path`.""" + + +TextAnnotation = Union[TextAnnotationFileCitation, TextAnnotationFilePath] + + +class Text(BaseModel): + annotations: List[TextAnnotation] + + value: str + """The data that makes up the text.""" + + +class MessageContentText(BaseModel): + text: Text + + type: Literal["text"] + """Always `text`.""" diff --git a/src/openai/types/beta/threads/message_create_params.py b/src/openai/types/beta/threads/message_create_params.py new file mode 100644 index 0000000000..8733f10b8a --- /dev/null +++ b/src/openai/types/beta/threads/message_create_params.py @@ -0,0 +1,35 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["MessageCreateParams"] + + +class MessageCreateParams(TypedDict, total=False): + content: Required[str] + """The content of the message.""" + + role: Required[Literal["user"]] + """The role of the entity that is creating the message. + + Currently only `user` is supported. + """ + + file_ids: List[str] + """ + A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + the message should use. There can be a maximum of 10 files attached to a + message. Useful for tools like `retrieval` and `code_interpreter` that can + access and use files. + """ + + metadata: Optional[object] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format. Keys can be a maximum of 64 characters long and values can be + a maxium of 512 characters long. + """ diff --git a/src/openai/types/beta/threads/message_list_params.py b/src/openai/types/beta/threads/message_list_params.py new file mode 100644 index 0000000000..31e407bb22 --- /dev/null +++ b/src/openai/types/beta/threads/message_list_params.py @@ -0,0 +1,39 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing_extensions import Literal, TypedDict + +__all__ = ["MessageListParams"] + + +class MessageListParams(TypedDict, total=False): + after: str + """A cursor for use in pagination. + + `after` is an object ID that defines your place in the list. For instance, if + you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include after=obj_foo in order to fetch the next page of the + list. + """ + + before: str + """A cursor for use in pagination. + + `before` is an object ID that defines your place in the list. For instance, if + you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page + of the list. + """ + + limit: int + """A limit on the number of objects to be returned. + + Limit can range between 1 and 100, and the default is 20. + """ + + order: Literal["asc", "desc"] + """Sort order by the `created_at` timestamp of the objects. + + `asc` for ascending order and `desc` for descending order. + """ diff --git a/src/openai/types/beta/threads/message_update_params.py b/src/openai/types/beta/threads/message_update_params.py new file mode 100644 index 0000000000..2e3e1b4b1a --- /dev/null +++ b/src/openai/types/beta/threads/message_update_params.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Required, TypedDict + +__all__ = ["MessageUpdateParams"] + + +class MessageUpdateParams(TypedDict, total=False): + thread_id: Required[str] + + metadata: Optional[object] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format. Keys can be a maximum of 64 characters long and values can be + a maxium of 512 characters long. + """ diff --git a/src/openai/types/beta/threads/messages/__init__.py b/src/openai/types/beta/threads/messages/__init__.py new file mode 100644 index 0000000000..6046f68204 --- /dev/null +++ b/src/openai/types/beta/threads/messages/__init__.py @@ -0,0 +1,6 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from .message_file import MessageFile as MessageFile +from .file_list_params import FileListParams as FileListParams diff --git a/src/openai/types/beta/threads/messages/file_list_params.py b/src/openai/types/beta/threads/messages/file_list_params.py new file mode 100644 index 0000000000..3640b8508b --- /dev/null +++ b/src/openai/types/beta/threads/messages/file_list_params.py @@ -0,0 +1,41 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["FileListParams"] + + +class FileListParams(TypedDict, total=False): + thread_id: Required[str] + + after: str + """A cursor for use in pagination. + + `after` is an object ID that defines your place in the list. For instance, if + you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include after=obj_foo in order to fetch the next page of the + list. + """ + + before: str + """A cursor for use in pagination. + + `before` is an object ID that defines your place in the list. For instance, if + you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page + of the list. + """ + + limit: int + """A limit on the number of objects to be returned. + + Limit can range between 1 and 100, and the default is 20. + """ + + order: Literal["asc", "desc"] + """Sort order by the `created_at` timestamp of the objects. + + `asc` for ascending order and `desc` for descending order. + """ diff --git a/src/openai/types/beta/threads/messages/message_file.py b/src/openai/types/beta/threads/messages/message_file.py new file mode 100644 index 0000000000..5332dee962 --- /dev/null +++ b/src/openai/types/beta/threads/messages/message_file.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing_extensions import Literal + +from ....._models import BaseModel + +__all__ = ["MessageFile"] + + +class MessageFile(BaseModel): + id: str + """The identifier, which can be referenced in API endpoints.""" + + created_at: int + """The Unix timestamp (in seconds) for when the message file was created.""" + + message_id: str + """ + The ID of the [message](https://platform.openai.com/docs/api-reference/messages) + that the [File](https://platform.openai.com/docs/api-reference/files) is + attached to. + """ + + object: Literal["thread.message.file"] + """The object type, which is always `thread.message.file`.""" diff --git a/src/openai/types/beta/threads/required_action_function_tool_call.py b/src/openai/types/beta/threads/required_action_function_tool_call.py new file mode 100644 index 0000000000..0284d0f188 --- /dev/null +++ b/src/openai/types/beta/threads/required_action_function_tool_call.py @@ -0,0 +1,34 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["RequiredActionFunctionToolCall", "Function"] + + +class Function(BaseModel): + arguments: str + """The arguments that the model expects you to pass to the function.""" + + name: str + """The name of the function.""" + + +class RequiredActionFunctionToolCall(BaseModel): + id: str + """The ID of the tool call. + + This ID must be referenced when you submit the tool outputs in using the + [Submit tool outputs to run](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) + endpoint. + """ + + function: Function + """The function definition.""" + + type: Literal["function"] + """The type of tool call the output is required for. + + For now, this is always `function`. + """ diff --git a/src/openai/types/beta/threads/run.py b/src/openai/types/beta/threads/run.py new file mode 100644 index 0000000000..d06152fa5b --- /dev/null +++ b/src/openai/types/beta/threads/run.py @@ -0,0 +1,182 @@ +# File generated from our OpenAPI spec by Stainless. + +import builtins +from typing import Dict, List, Union, Optional +from typing_extensions import Literal + +from ...._models import BaseModel +from .required_action_function_tool_call import RequiredActionFunctionToolCall + +__all__ = [ + "Run", + "LastError", + "RequiredAction", + "RequiredActionSubmitToolOutputs", + "Tool", + "ToolAssistantToolsCode", + "ToolAssistantToolsRetrieval", + "ToolAssistantToolsFunction", + "ToolAssistantToolsFunctionFunction", +] + + +class LastError(BaseModel): + code: Literal["server_error", "rate_limit_exceeded"] + """One of `server_error` or `rate_limit_exceeded`.""" + + message: str + """A human-readable description of the error.""" + + +class RequiredActionSubmitToolOutputs(BaseModel): + tool_calls: List[RequiredActionFunctionToolCall] + """A list of the relevant tool calls.""" + + +class RequiredAction(BaseModel): + submit_tool_outputs: RequiredActionSubmitToolOutputs + """Details on the tool outputs needed for this run to continue.""" + + type: Literal["submit_tool_outputs"] + """For now, this is always `submit_tool_outputs`.""" + + +class ToolAssistantToolsCode(BaseModel): + type: Literal["code_interpreter"] + """The type of tool being defined: `code_interpreter`""" + + +class ToolAssistantToolsRetrieval(BaseModel): + type: Literal["retreival"] + """The type of tool being defined: `retreival`""" + + +class ToolAssistantToolsFunctionFunction(BaseModel): + description: str + """ + A description of what the function does, used by the model to choose when and + how to call the function. + """ + + name: str + """The name of the function to be called. + + Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length + of 64. + """ + + parameters: Dict[str, builtins.object] + """The parameters the functions accepts, described as a JSON Schema object. + + See the [guide](https://platform.openai.com/docs/guides/gpt/function-calling) + for examples, and the + [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for + documentation about the format. + + To describe a function that accepts no parameters, provide the value + `{"type": "object", "properties": {}}`. + """ + + +class ToolAssistantToolsFunction(BaseModel): + function: ToolAssistantToolsFunctionFunction + """The function definition.""" + + type: Literal["function"] + """The type of tool being defined: `function`""" + + +Tool = Union[ToolAssistantToolsCode, ToolAssistantToolsRetrieval, ToolAssistantToolsFunction] + + +class Run(BaseModel): + id: str + """The identifier, which can be referenced in API endpoints.""" + + assistant_id: str + """ + The ID of the + [assistant](https://platform.openai.com/docs/api-reference/assistants) used for + execution of this run. + """ + + cancelled_at: Optional[int] + """The Unix timestamp (in seconds) for when the run was cancelled.""" + + completed_at: Optional[int] + """The Unix timestamp (in seconds) for when the run was completed.""" + + created_at: int + """The Unix timestamp (in seconds) for when the run was created.""" + + expires_at: int + """The Unix timestamp (in seconds) for when the run will expire.""" + + failed_at: Optional[int] + """The Unix timestamp (in seconds) for when the run failed.""" + + file_ids: List[str] + """ + The list of [File](https://platform.openai.com/docs/api-reference/files) IDs the + [assistant](https://platform.openai.com/docs/api-reference/assistants) used for + this run. + """ + + instructions: str + """ + The instructions that the + [assistant](https://platform.openai.com/docs/api-reference/assistants) used for + this run. + """ + + last_error: Optional[LastError] + """The last error associated with this run. Will be `null` if there are no errors.""" + + metadata: Optional[builtins.object] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format. Keys can be a maximum of 64 characters long and values can be + a maxium of 512 characters long. + """ + + model: str + """ + The model that the + [assistant](https://platform.openai.com/docs/api-reference/assistants) used for + this run. + """ + + object: Literal["assistant.run"] + """The object type, which is always `assistant.run`.""" + + required_action: Optional[RequiredAction] + """Details on the action required to continue the run. + + Will be `null` if no action is required. + """ + + started_at: Optional[int] + """The Unix timestamp (in seconds) for when the run was started.""" + + status: Literal[ + "queued", "in_progress", "requires_action", "cancelling", "cancelled", "failed", "completed", "expired" + ] + """ + The status of the run, which can be either `queued`, `in_progress`, + `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, or + `expired`. + """ + + thread_id: str + """ + The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) + that was executed on as a part of this run. + """ + + tools: List[Tool] + """ + The list of tools that the + [assistant](https://platform.openai.com/docs/api-reference/assistants) used for + this run. + """ diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py new file mode 100644 index 0000000000..41d2eeea03 --- /dev/null +++ b/src/openai/types/beta/threads/run_create_params.py @@ -0,0 +1,100 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Dict, List, Union, Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = [ + "RunCreateParams", + "Tool", + "ToolAssistantToolsCode", + "ToolAssistantToolsRetrieval", + "ToolAssistantToolsFunction", + "ToolAssistantToolsFunctionFunction", +] + + +class RunCreateParams(TypedDict, total=False): + assistant_id: Required[str] + """ + The ID of the + [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + execute this run. + """ + + instructions: Optional[str] + """Override the default system message of the assistant. + + This is useful for modifying the behavior on a per-run basis. + """ + + metadata: Optional[object] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format. Keys can be a maximum of 64 characters long and values can be + a maxium of 512 characters long. + """ + + model: Optional[str] + """ + The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + be used to execute this run. If a value is provided here, it will override the + model associated with the assistant. If not, the model associated with the + assistant will be used. + """ + + tools: Optional[List[Tool]] + """Override the tools the assistant can use for this run. + + This is useful for modifying the behavior on a per-run basis. + """ + + +class ToolAssistantToolsCode(TypedDict, total=False): + type: Required[Literal["code_interpreter"]] + """The type of tool being defined: `code_interpreter`""" + + +class ToolAssistantToolsRetrieval(TypedDict, total=False): + type: Required[Literal["retreival"]] + """The type of tool being defined: `retreival`""" + + +class ToolAssistantToolsFunctionFunction(TypedDict, total=False): + description: Required[str] + """ + A description of what the function does, used by the model to choose when and + how to call the function. + """ + + name: Required[str] + """The name of the function to be called. + + Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length + of 64. + """ + + parameters: Required[Dict[str, object]] + """The parameters the functions accepts, described as a JSON Schema object. + + See the [guide](https://platform.openai.com/docs/guides/gpt/function-calling) + for examples, and the + [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for + documentation about the format. + + To describe a function that accepts no parameters, provide the value + `{"type": "object", "properties": {}}`. + """ + + +class ToolAssistantToolsFunction(TypedDict, total=False): + function: Required[ToolAssistantToolsFunctionFunction] + """The function definition.""" + + type: Required[Literal["function"]] + """The type of tool being defined: `function`""" + + +Tool = Union[ToolAssistantToolsCode, ToolAssistantToolsRetrieval, ToolAssistantToolsFunction] diff --git a/src/openai/types/beta/threads/run_list_params.py b/src/openai/types/beta/threads/run_list_params.py new file mode 100644 index 0000000000..5f41347718 --- /dev/null +++ b/src/openai/types/beta/threads/run_list_params.py @@ -0,0 +1,39 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing_extensions import Literal, TypedDict + +__all__ = ["RunListParams"] + + +class RunListParams(TypedDict, total=False): + after: str + """A cursor for use in pagination. + + `after` is an object ID that defines your place in the list. For instance, if + you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include after=obj_foo in order to fetch the next page of the + list. + """ + + before: str + """A cursor for use in pagination. + + `before` is an object ID that defines your place in the list. For instance, if + you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page + of the list. + """ + + limit: int + """A limit on the number of objects to be returned. + + Limit can range between 1 and 100, and the default is 20. + """ + + order: Literal["asc", "desc"] + """Sort order by the `created_at` timestamp of the objects. + + `asc` for ascending order and `desc` for descending order. + """ diff --git a/src/openai/types/beta/threads/run_submit_tool_outputs_params.py b/src/openai/types/beta/threads/run_submit_tool_outputs_params.py new file mode 100644 index 0000000000..a960f0f06f --- /dev/null +++ b/src/openai/types/beta/threads/run_submit_tool_outputs_params.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import List +from typing_extensions import Required, TypedDict + +__all__ = ["RunSubmitToolOutputsParams", "ToolOutput"] + + +class RunSubmitToolOutputsParams(TypedDict, total=False): + thread_id: Required[str] + + tool_outputs: Required[List[ToolOutput]] + """A list of tools for which the outputs are being submitted.""" + + +class ToolOutput(TypedDict, total=False): + output: str + """The output of the tool call to be submitted to continue the run.""" + + tool_call_id: str + """ + The ID of the tool call in the `required_action` object within the run object + the output is being submitted for. + """ diff --git a/src/openai/types/beta/threads/run_update_params.py b/src/openai/types/beta/threads/run_update_params.py new file mode 100644 index 0000000000..09f81aa003 --- /dev/null +++ b/src/openai/types/beta/threads/run_update_params.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Required, TypedDict + +__all__ = ["RunUpdateParams"] + + +class RunUpdateParams(TypedDict, total=False): + thread_id: Required[str] + + metadata: Optional[object] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format. Keys can be a maximum of 64 characters long and values can be + a maxium of 512 characters long. + """ diff --git a/src/openai/types/beta/threads/runs/__init__.py b/src/openai/types/beta/threads/runs/__init__.py new file mode 100644 index 0000000000..72b972a986 --- /dev/null +++ b/src/openai/types/beta/threads/runs/__init__.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from .run_step import RunStep as RunStep +from .code_tool_call import CodeToolCall as CodeToolCall +from .step_list_params import StepListParams as StepListParams +from .function_tool_call import FunctionToolCall as FunctionToolCall +from .retrieval_tool_call import RetrievalToolCall as RetrievalToolCall +from .tool_calls_step_details import ToolCallsStepDetails as ToolCallsStepDetails +from .message_creation_step_details import ( + MessageCreationStepDetails as MessageCreationStepDetails, +) diff --git a/src/openai/types/beta/threads/runs/code_tool_call.py b/src/openai/types/beta/threads/runs/code_tool_call.py new file mode 100644 index 0000000000..f808005ecb --- /dev/null +++ b/src/openai/types/beta/threads/runs/code_tool_call.py @@ -0,0 +1,67 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import List, Union +from typing_extensions import Literal + +from ....._models import BaseModel + +__all__ = [ + "CodeToolCall", + "CodeInterpreter", + "CodeInterpreterOutput", + "CodeInterpreterOutputLogs", + "CodeInterpreterOutputImage", + "CodeInterpreterOutputImageImage", +] + + +class CodeInterpreterOutputLogs(BaseModel): + logs: str + """The text output from the Code Interpreter tool call.""" + + type: Literal["logs"] + """Always `logs`.""" + + +class CodeInterpreterOutputImageImage(BaseModel): + file_id: str + """ + The [file](https://platform.openai.com/docs/api-reference/files) ID of the + image. + """ + + +class CodeInterpreterOutputImage(BaseModel): + image: CodeInterpreterOutputImageImage + + type: Literal["image"] + """Always `image`.""" + + +CodeInterpreterOutput = Union[CodeInterpreterOutputLogs, CodeInterpreterOutputImage] + + +class CodeInterpreter(BaseModel): + input: str + """The input to the Code Interpreter tool call.""" + + outputs: List[CodeInterpreterOutput] + """The outputs from the Code Interpreter tool call. + + Code Interpreter can output one or more items, including text (`logs`) or images + (`image`). Each of these are represented by a different object type. + """ + + +class CodeToolCall(BaseModel): + id: str + """The ID of the tool call.""" + + code_interpreter: CodeInterpreter + """The Code Interpreter tool call definition.""" + + type: Literal["code_interpreter"] + """The type of tool call. + + This is always going to be `code_interpreter` for this type of tool call. + """ diff --git a/src/openai/types/beta/threads/runs/function_tool_call.py b/src/openai/types/beta/threads/runs/function_tool_call.py new file mode 100644 index 0000000000..f4cf8bbdd0 --- /dev/null +++ b/src/openai/types/beta/threads/runs/function_tool_call.py @@ -0,0 +1,38 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Optional +from typing_extensions import Literal + +from ....._models import BaseModel + +__all__ = ["FunctionToolCall", "Function"] + + +class Function(BaseModel): + arguments: str + """The arguments passed to the function.""" + + name: str + """The name of the function.""" + + output: Optional[str] + """The output of the function. + + This will be `null` if the outputs have not been + [submitted](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) + yet. + """ + + +class FunctionToolCall(BaseModel): + id: str + """The ID of the tool call object.""" + + function: Function + """The definition of the function that was called.""" + + type: Literal["function"] + """The type of tool call. + + This is always going to be `function` for this type of tool call. + """ diff --git a/src/openai/types/beta/threads/runs/message_creation_step_details.py b/src/openai/types/beta/threads/runs/message_creation_step_details.py new file mode 100644 index 0000000000..29f9106ec0 --- /dev/null +++ b/src/openai/types/beta/threads/runs/message_creation_step_details.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing_extensions import Literal + +from ....._models import BaseModel + +__all__ = ["MessageCreationStepDetails", "MessageCreation"] + + +class MessageCreation(BaseModel): + message_id: str + """The ID of the message that was created by this run step.""" + + +class MessageCreationStepDetails(BaseModel): + message_creation: MessageCreation + + type: Literal["message_creation"] + """Always `message_creation``.""" diff --git a/src/openai/types/beta/threads/runs/retrieval_tool_call.py b/src/openai/types/beta/threads/runs/retrieval_tool_call.py new file mode 100644 index 0000000000..6cdbcdd93f --- /dev/null +++ b/src/openai/types/beta/threads/runs/retrieval_tool_call.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing_extensions import Literal + +from ....._models import BaseModel + +__all__ = ["RetrievalToolCall"] + + +class RetrievalToolCall(BaseModel): + id: str + """The ID of the tool call object.""" + + retrieval: object + """For now, this is always going to be an empty object.""" + + type: Literal["retrieval"] + """The type of tool call. + + This is always going to be `retrieval` for this type of tool call. + """ diff --git a/src/openai/types/beta/threads/runs/run_step.py b/src/openai/types/beta/threads/runs/run_step.py new file mode 100644 index 0000000000..17a567dc0e --- /dev/null +++ b/src/openai/types/beta/threads/runs/run_step.py @@ -0,0 +1,93 @@ +# File generated from our OpenAPI spec by Stainless. + +import builtins +from typing import Union, Optional +from typing_extensions import Literal + +from ....._models import BaseModel +from .tool_calls_step_details import ToolCallsStepDetails +from .message_creation_step_details import MessageCreationStepDetails + +__all__ = ["RunStep", "LastError", "StepDetails"] + + +class LastError(BaseModel): + code: Literal["server_error", "rate_limit_exceeded"] + """One of `server_error` or `rate_limit_exceeded`.""" + + message: str + """A human-readable description of the error.""" + + +StepDetails = Union[MessageCreationStepDetails, ToolCallsStepDetails] + + +class RunStep(BaseModel): + id: str + """The identifier of the run step, which can be referenced in API endpoints.""" + + assistant_id: str + """ + The ID of the + [assistant](https://platform.openai.com/docs/api-reference/assistants) + associated with the run step. + """ + + cancelled_at: Optional[int] + """The Unix timestamp (in seconds) for when the run step was cancelled.""" + + completed_at: Optional[int] + """The Unix timestamp (in seconds) for when the run step completed.""" + + created_at: int + """The Unix timestamp (in seconds) for when the run step was created.""" + + expired_at: Optional[int] + """The Unix timestamp (in seconds) for when the run step expired. + + A step is considered expired if the parent run is expired. + """ + + failed_at: Optional[int] + """The Unix timestamp (in seconds) for when the run step failed.""" + + last_error: Optional[LastError] + """The last error associated with this run step. + + Will be `null` if there are no errors. + """ + + metadata: Optional[builtins.object] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format. Keys can be a maximum of 64 characters long and values can be + a maxium of 512 characters long. + """ + + object: Literal["assistant.run.step"] + """The object type, which is always `assistant.run.step``.""" + + run_id: str + """ + The ID of the [run](https://platform.openai.com/docs/api-reference/runs) that + this run step is a part of. + """ + + status: Literal["in_progress", "cancelled", "failed", "completed", "expired"] + """ + The status of the run, which can be either `in_progress`, `cancelled`, `failed`, + `completed`, or `expired`. + """ + + step_details: StepDetails + """The details of the run step.""" + + thread_id: str + """ + The ID of the [thread](https://platform.openai.com/docs/api-reference/threads) + that was run. + """ + + type: Literal["message_creation", "tool_calls"] + """The type of run step, which can be either `message_creation` or `tool_calls`.""" diff --git a/src/openai/types/beta/threads/runs/step_list_params.py b/src/openai/types/beta/threads/runs/step_list_params.py new file mode 100644 index 0000000000..9c7b6c64d0 --- /dev/null +++ b/src/openai/types/beta/threads/runs/step_list_params.py @@ -0,0 +1,41 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["StepListParams"] + + +class StepListParams(TypedDict, total=False): + thread_id: Required[str] + + after: str + """A cursor for use in pagination. + + `after` is an object ID that defines your place in the list. For instance, if + you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include after=obj_foo in order to fetch the next page of the + list. + """ + + before: str + """A cursor for use in pagination. + + `before` is an object ID that defines your place in the list. For instance, if + you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page + of the list. + """ + + limit: int + """A limit on the number of objects to be returned. + + Limit can range between 1 and 100, and the default is 20. + """ + + order: Literal["asc", "desc"] + """Sort order by the `created_at` timestamp of the objects. + + `asc` for ascending order and `desc` for descending order. + """ diff --git a/src/openai/types/beta/threads/runs/tool_calls_step_details.py b/src/openai/types/beta/threads/runs/tool_calls_step_details.py new file mode 100644 index 0000000000..80eb90bf66 --- /dev/null +++ b/src/openai/types/beta/threads/runs/tool_calls_step_details.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import List, Union +from typing_extensions import Literal + +from ....._models import BaseModel +from .code_tool_call import CodeToolCall +from .function_tool_call import FunctionToolCall +from .retrieval_tool_call import RetrievalToolCall + +__all__ = ["ToolCallsStepDetails", "ToolCall"] + +ToolCall = Union[CodeToolCall, RetrievalToolCall, FunctionToolCall] + + +class ToolCallsStepDetails(BaseModel): + tool_calls: List[ToolCall] + """An array of tool calls the run step was involved in. + + These can be associated with one of three types of tools: `code_interpreter`, + `retrieval`, or `function`. + """ + + type: Literal["tool_calls"] + """Always `tool_calls`.""" diff --git a/src/openai/types/beta/threads/thread_message.py b/src/openai/types/beta/threads/thread_message.py new file mode 100644 index 0000000000..0f782ef845 --- /dev/null +++ b/src/openai/types/beta/threads/thread_message.py @@ -0,0 +1,65 @@ +# File generated from our OpenAPI spec by Stainless. + +import builtins +from typing import List, Union, Optional +from typing_extensions import Literal + +from ...._models import BaseModel +from .message_content_text import MessageContentText +from .message_content_image_file import MessageContentImageFile + +__all__ = ["ThreadMessage", "Content"] + +Content = Union[MessageContentImageFile, MessageContentText] + + +class ThreadMessage(BaseModel): + id: str + """The identifier, which can be referenced in API endpoints.""" + + assistant_id: Optional[str] + """ + If applicable, the ID of the + [assistant](https://platform.openai.com/docs/api-reference/assistants) that + authored this message. + """ + + content: List[Content] + """The content of the message in array of text and/or images.""" + + created_at: int + """The Unix timestamp (in seconds) for when the message was created.""" + + file_ids: List[str] + """ + A list of [file](https://platform.openai.com/docs/api-reference/files) IDs that + the assistant should use. Useful for tools like retrieval and code_interpreter + that can access files. A maximum of 10 files can be attached to a message. + """ + + metadata: Optional[builtins.object] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format. Keys can be a maximum of 64 characters long and values can be + a maxium of 512 characters long. + """ + + object: Literal["thread.message"] + """The object type, which is always `thread.message`.""" + + role: Literal["user", "assistant"] + """The entity that produced the message. One of `user` or `assistant`.""" + + run_id: Optional[str] + """ + If applicable, the ID of the + [run](https://platform.openai.com/docs/api-reference/runs) associated with the + authoring of this message. + """ + + thread_id: str + """ + The [thread](https://platform.openai.com/docs/api-reference/threads) ID that + this message belongs to. + """ diff --git a/src/openai/types/chat/__init__.py b/src/openai/types/chat/__init__.py index 2f23cf3ca4..5fe182f41e 100644 --- a/src/openai/types/chat/__init__.py +++ b/src/openai/types/chat/__init__.py @@ -7,6 +7,48 @@ from .chat_completion_chunk import ChatCompletionChunk as ChatCompletionChunk from .chat_completion_message import ChatCompletionMessage as ChatCompletionMessage from .completion_create_params import CompletionCreateParams as CompletionCreateParams +from .chat_completion_tool_param import ( + ChatCompletionToolParam as ChatCompletionToolParam, +) from .chat_completion_message_param import ( ChatCompletionMessageParam as ChatCompletionMessageParam, ) +from .chat_completion_message_tool_call import ( + ChatCompletionMessageToolCall as ChatCompletionMessageToolCall, +) +from .chat_completion_content_part_param import ( + ChatCompletionContentPartParam as ChatCompletionContentPartParam, +) +from .chat_completion_tool_message_param import ( + ChatCompletionToolMessageParam as ChatCompletionToolMessageParam, +) +from .chat_completion_user_message_param import ( + ChatCompletionUserMessageParam as ChatCompletionUserMessageParam, +) +from .chat_completion_system_message_param import ( + ChatCompletionSystemMessageParam as ChatCompletionSystemMessageParam, +) +from .chat_completion_function_message_param import ( + ChatCompletionFunctionMessageParam as ChatCompletionFunctionMessageParam, +) +from .chat_completion_assistant_message_param import ( + ChatCompletionAssistantMessageParam as ChatCompletionAssistantMessageParam, +) +from .chat_completion_content_part_text_param import ( + ChatCompletionContentPartTextParam as ChatCompletionContentPartTextParam, +) +from .chat_completion_message_tool_call_param import ( + ChatCompletionMessageToolCallParam as ChatCompletionMessageToolCallParam, +) +from .chat_completion_named_tool_choice_param import ( + ChatCompletionNamedToolChoiceParam as ChatCompletionNamedToolChoiceParam, +) +from .chat_completion_content_part_image_param import ( + ChatCompletionContentPartImageParam as ChatCompletionContentPartImageParam, +) +from .chat_completion_tool_choice_option_param import ( + ChatCompletionToolChoiceOptionParam as ChatCompletionToolChoiceOptionParam, +) +from .chat_completion_function_call_option_param import ( + ChatCompletionFunctionCallOptionParam as ChatCompletionFunctionCallOptionParam, +) diff --git a/src/openai/types/chat/chat_completion.py b/src/openai/types/chat/chat_completion.py index 8d7a0b9716..da12ee7c07 100644 --- a/src/openai/types/chat/chat_completion.py +++ b/src/openai/types/chat/chat_completion.py @@ -11,13 +11,14 @@ class Choice(BaseModel): - finish_reason: Literal["stop", "length", "function_call", "content_filter"] + finish_reason: Literal["stop", "length", "tool_calls", "content_filter", "function_call"] """The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, `length` if the maximum number of tokens specified in the request was reached, `content_filter` if content was omitted due to a flag from our content - filters, or `function_call` if the model called a function. + filters, `tool_calls` if the model called a tool, or `function_call` + (deprecated) if the model called a function. """ index: int @@ -43,8 +44,15 @@ class ChatCompletion(BaseModel): model: str """The model used for the chat completion.""" - object: str + object: Literal["chat.completion"] """The object type, which is always `chat.completion`.""" + system_fingerprint: Optional[str] = None + """This fingerprint represents the backend configuration that the model runs with. + + Can be used in conjunction with the `seed` request parameter to understand when + backend changes have been made that might impact determinism. + """ + usage: Optional[CompletionUsage] = None """Usage statistics for the completion request.""" diff --git a/src/openai/types/chat/chat_completion_assistant_message_param.py b/src/openai/types/chat/chat_completion_assistant_message_param.py new file mode 100644 index 0000000000..abdd87c991 --- /dev/null +++ b/src/openai/types/chat/chat_completion_assistant_message_param.py @@ -0,0 +1,41 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Literal, Required, TypedDict + +from .chat_completion_message_tool_call_param import ChatCompletionMessageToolCallParam + +__all__ = ["ChatCompletionAssistantMessageParam", "FunctionCall"] + + +class FunctionCall(TypedDict, total=False): + arguments: Required[str] + """ + The arguments to call the function with, as generated by the model in JSON + format. Note that the model does not always generate valid JSON, and may + hallucinate parameters not defined by your function schema. Validate the + arguments in your code before calling your function. + """ + + name: Required[str] + """The name of the function to call.""" + + +class ChatCompletionAssistantMessageParam(TypedDict, total=False): + content: Required[Optional[str]] + """The contents of the assistant message.""" + + role: Required[Literal["assistant"]] + """The role of the messages author, in this case `assistant`.""" + + function_call: FunctionCall + """Deprecated and replaced by `tool_calls`. + + The name and arguments of a function that should be called, as generated by the + model. + """ + + tool_calls: List[ChatCompletionMessageToolCallParam] + """The tool calls generated by the model, such as function calls.""" diff --git a/src/openai/types/chat/chat_completion_chunk.py b/src/openai/types/chat/chat_completion_chunk.py index 66610898b4..bbc46a37bb 100644 --- a/src/openai/types/chat/chat_completion_chunk.py +++ b/src/openai/types/chat/chat_completion_chunk.py @@ -4,9 +4,15 @@ from typing_extensions import Literal from ..._models import BaseModel -from .chat_completion_role import ChatCompletionRole -__all__ = ["ChatCompletionChunk", "Choice", "ChoiceDelta", "ChoiceDeltaFunctionCall"] +__all__ = [ + "ChatCompletionChunk", + "Choice", + "ChoiceDelta", + "ChoiceDeltaFunctionCall", + "ChoiceDeltaToolCall", + "ChoiceDeltaToolCallFunction", +] class ChoiceDeltaFunctionCall(BaseModel): @@ -22,31 +28,60 @@ class ChoiceDeltaFunctionCall(BaseModel): """The name of the function to call.""" +class ChoiceDeltaToolCallFunction(BaseModel): + arguments: Optional[str] = None + """ + The arguments to call the function with, as generated by the model in JSON + format. Note that the model does not always generate valid JSON, and may + hallucinate parameters not defined by your function schema. Validate the + arguments in your code before calling your function. + """ + + name: Optional[str] = None + """The name of the function to call.""" + + +class ChoiceDeltaToolCall(BaseModel): + index: int + + id: Optional[str] = None + """The ID of the tool call.""" + + function: Optional[ChoiceDeltaToolCallFunction] = None + + type: Optional[Literal["function"]] = None + """The type of the tool. Currently, only `function` is supported.""" + + class ChoiceDelta(BaseModel): content: Optional[str] = None """The contents of the chunk message.""" function_call: Optional[ChoiceDeltaFunctionCall] = None - """ + """Deprecated and replaced by `tool_calls`. + The name and arguments of a function that should be called, as generated by the model. """ - role: Optional[ChatCompletionRole] = None + role: Optional[Literal["system", "user", "assistant", "tool"]] = None """The role of the author of this message.""" + tool_calls: Optional[List[ChoiceDeltaToolCall]] = None + class Choice(BaseModel): delta: ChoiceDelta """A chat completion delta generated by streamed model responses.""" - finish_reason: Optional[Literal["stop", "length", "function_call", "content_filter"]] + finish_reason: Optional[Literal["stop", "length", "tool_calls", "content_filter", "function_call"]] """The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence, `length` if the maximum number of tokens specified in the request was reached, `content_filter` if content was omitted due to a flag from our content - filters, or `function_call` if the model called a function. + filters, `tool_calls` if the model called a tool, or `function_call` + (deprecated) if the model called a function. """ index: int @@ -72,5 +107,5 @@ class ChatCompletionChunk(BaseModel): model: str """The model to generate the completion.""" - object: str + object: Literal["chat.completion.chunk"] """The object type, which is always `chat.completion.chunk`.""" diff --git a/src/openai/types/chat/chat_completion_content_part_image_param.py b/src/openai/types/chat/chat_completion_content_part_image_param.py new file mode 100644 index 0000000000..2051786562 --- /dev/null +++ b/src/openai/types/chat/chat_completion_content_part_image_param.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ChatCompletionContentPartImageParam", "ImageURL"] + + +class ImageURL(TypedDict, total=False): + detail: Literal["auto", "low", "high"] + """Specifies the detail level of the image.""" + + url: str + """Either a URL of the image or the base64 encoded image data.""" + + +class ChatCompletionContentPartImageParam(TypedDict, total=False): + image_url: Required[ImageURL] + + type: Required[Literal["image_url"]] + """The type of the content part.""" diff --git a/src/openai/types/chat/chat_completion_content_part_param.py b/src/openai/types/chat/chat_completion_content_part_param.py new file mode 100644 index 0000000000..587578e2ef --- /dev/null +++ b/src/openai/types/chat/chat_completion_content_part_param.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Union + +from .chat_completion_content_part_text_param import ChatCompletionContentPartTextParam +from .chat_completion_content_part_image_param import ( + ChatCompletionContentPartImageParam, +) + +__all__ = ["ChatCompletionContentPartParam"] + +ChatCompletionContentPartParam = Union[ChatCompletionContentPartTextParam, ChatCompletionContentPartImageParam] diff --git a/src/openai/types/chat/chat_completion_content_part_text_param.py b/src/openai/types/chat/chat_completion_content_part_text_param.py new file mode 100644 index 0000000000..38edcf054e --- /dev/null +++ b/src/openai/types/chat/chat_completion_content_part_text_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ChatCompletionContentPartTextParam"] + + +class ChatCompletionContentPartTextParam(TypedDict, total=False): + text: Required[str] + """The text content.""" + + type: Required[Literal["text"]] + """The type of the content part.""" diff --git a/src/openai/types/chat/chat_completion_function_call_option_param.py b/src/openai/types/chat/chat_completion_function_call_option_param.py new file mode 100644 index 0000000000..72d41d908c --- /dev/null +++ b/src/openai/types/chat/chat_completion_function_call_option_param.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +__all__ = ["ChatCompletionFunctionCallOptionParam"] + + +class ChatCompletionFunctionCallOptionParam(TypedDict, total=False): + name: Required[str] + """The name of the function to call.""" diff --git a/src/openai/types/chat/chat_completion_function_message_param.py b/src/openai/types/chat/chat_completion_function_message_param.py new file mode 100644 index 0000000000..1a16c5f5eb --- /dev/null +++ b/src/openai/types/chat/chat_completion_function_message_param.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ChatCompletionFunctionMessageParam"] + + +class ChatCompletionFunctionMessageParam(TypedDict, total=False): + content: Required[Optional[str]] + """The return value from the function call, to return to the model.""" + + name: Required[str] + """The name of the function to call.""" + + role: Required[Literal["function"]] + """The role of the messages author, in this case `function`.""" diff --git a/src/openai/types/chat/chat_completion_message.py b/src/openai/types/chat/chat_completion_message.py index 531eb3d43c..4749798a33 100644 --- a/src/openai/types/chat/chat_completion_message.py +++ b/src/openai/types/chat/chat_completion_message.py @@ -1,9 +1,10 @@ # File generated from our OpenAPI spec by Stainless. -from typing import Optional +from typing import List, Optional +from typing_extensions import Literal from ..._models import BaseModel -from .chat_completion_role import ChatCompletionRole +from .chat_completion_message_tool_call import ChatCompletionMessageToolCall __all__ = ["ChatCompletionMessage", "FunctionCall"] @@ -25,11 +26,15 @@ class ChatCompletionMessage(BaseModel): content: Optional[str] """The contents of the message.""" - role: ChatCompletionRole + role: Literal["assistant"] """The role of the author of this message.""" function_call: Optional[FunctionCall] = None - """ + """Deprecated and replaced by `tool_calls`. + The name and arguments of a function that should be called, as generated by the model. """ + + tool_calls: Optional[List[ChatCompletionMessageToolCall]] = None + """The tool calls generated by the model, such as function calls.""" diff --git a/src/openai/types/chat/chat_completion_message_param.py b/src/openai/types/chat/chat_completion_message_param.py index 29b8882573..7ec3d6a7b7 100644 --- a/src/openai/types/chat/chat_completion_message_param.py +++ b/src/openai/types/chat/chat_completion_message_param.py @@ -2,49 +2,20 @@ from __future__ import annotations -from typing import Optional -from typing_extensions import Literal, Required, TypedDict - -__all__ = ["ChatCompletionMessageParam", "FunctionCall"] - - -class FunctionCall(TypedDict, total=False): - arguments: Required[str] - """ - The arguments to call the function with, as generated by the model in JSON - format. Note that the model does not always generate valid JSON, and may - hallucinate parameters not defined by your function schema. Validate the - arguments in your code before calling your function. - """ - - name: Required[str] - """The name of the function to call.""" - - -class ChatCompletionMessageParam(TypedDict, total=False): - content: Required[Optional[str]] - """The contents of the message. - - `content` is required for all messages, and may be null for assistant messages - with function calls. - """ - - role: Required[Literal["system", "user", "assistant", "function"]] - """The role of the messages author. - - One of `system`, `user`, `assistant`, or `function`. - """ - - function_call: FunctionCall - """ - The name and arguments of a function that should be called, as generated by the - model. - """ - - name: str - """The name of the author of this message. - - `name` is required if role is `function`, and it should be the name of the - function whose response is in the `content`. May contain a-z, A-Z, 0-9, and - underscores, with a maximum length of 64 characters. - """ +from typing import Union + +from .chat_completion_tool_message_param import ChatCompletionToolMessageParam +from .chat_completion_user_message_param import ChatCompletionUserMessageParam +from .chat_completion_system_message_param import ChatCompletionSystemMessageParam +from .chat_completion_function_message_param import ChatCompletionFunctionMessageParam +from .chat_completion_assistant_message_param import ChatCompletionAssistantMessageParam + +__all__ = ["ChatCompletionMessageParam"] + +ChatCompletionMessageParam = Union[ + ChatCompletionSystemMessageParam, + ChatCompletionUserMessageParam, + ChatCompletionAssistantMessageParam, + ChatCompletionToolMessageParam, + ChatCompletionFunctionMessageParam, +] diff --git a/src/openai/types/chat/chat_completion_message_tool_call.py b/src/openai/types/chat/chat_completion_message_tool_call.py new file mode 100644 index 0000000000..63c72fcdca --- /dev/null +++ b/src/openai/types/chat/chat_completion_message_tool_call.py @@ -0,0 +1,31 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ChatCompletionMessageToolCall", "Function"] + + +class Function(BaseModel): + arguments: str + """ + The arguments to call the function with, as generated by the model in JSON + format. Note that the model does not always generate valid JSON, and may + hallucinate parameters not defined by your function schema. Validate the + arguments in your code before calling your function. + """ + + name: str + """The name of the function to call.""" + + +class ChatCompletionMessageToolCall(BaseModel): + id: str + """The ID of the tool call.""" + + function: Function + """The function that the model called.""" + + type: Literal["function"] + """The type of the tool. Currently, only `function` is supported.""" diff --git a/src/openai/types/chat/chat_completion_message_tool_call_param.py b/src/openai/types/chat/chat_completion_message_tool_call_param.py new file mode 100644 index 0000000000..a700f02c4f --- /dev/null +++ b/src/openai/types/chat/chat_completion_message_tool_call_param.py @@ -0,0 +1,31 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ChatCompletionMessageToolCallParam", "Function"] + + +class Function(TypedDict, total=False): + arguments: Required[str] + """ + The arguments to call the function with, as generated by the model in JSON + format. Note that the model does not always generate valid JSON, and may + hallucinate parameters not defined by your function schema. Validate the + arguments in your code before calling your function. + """ + + name: Required[str] + """The name of the function to call.""" + + +class ChatCompletionMessageToolCallParam(TypedDict, total=False): + id: Required[str] + """The ID of the tool call.""" + + function: Required[Function] + """The function that the model called.""" + + type: Required[Literal["function"]] + """The type of the tool. Currently, only `function` is supported.""" diff --git a/src/openai/types/chat/chat_completion_named_tool_choice_param.py b/src/openai/types/chat/chat_completion_named_tool_choice_param.py new file mode 100644 index 0000000000..4c6f20d2f1 --- /dev/null +++ b/src/openai/types/chat/chat_completion_named_tool_choice_param.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ChatCompletionNamedToolChoiceParam", "Function"] + + +class Function(TypedDict, total=False): + name: Required[str] + """The name of the function to call.""" + + +class ChatCompletionNamedToolChoiceParam(TypedDict, total=False): + function: Function + + type: Literal["function"] + """The type of the tool. Currently, only `function` is supported.""" diff --git a/src/openai/types/chat/chat_completion_role.py b/src/openai/types/chat/chat_completion_role.py index da8896a072..9fa2acb4bb 100644 --- a/src/openai/types/chat/chat_completion_role.py +++ b/src/openai/types/chat/chat_completion_role.py @@ -4,4 +4,4 @@ __all__ = ["ChatCompletionRole"] -ChatCompletionRole = Literal["system", "user", "assistant", "function"] +ChatCompletionRole = Literal["system", "user", "assistant", "tool", "function"] diff --git a/src/openai/types/chat/chat_completion_system_message_param.py b/src/openai/types/chat/chat_completion_system_message_param.py new file mode 100644 index 0000000000..ec08e00350 --- /dev/null +++ b/src/openai/types/chat/chat_completion_system_message_param.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ChatCompletionSystemMessageParam"] + + +class ChatCompletionSystemMessageParam(TypedDict, total=False): + content: Required[Optional[str]] + """The contents of the system message.""" + + role: Required[Literal["system"]] + """The role of the messages author, in this case `system`.""" diff --git a/src/openai/types/chat/chat_completion_tool_choice_option_param.py b/src/openai/types/chat/chat_completion_tool_choice_option_param.py new file mode 100644 index 0000000000..8104b26acb --- /dev/null +++ b/src/openai/types/chat/chat_completion_tool_choice_option_param.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal + +from .chat_completion_named_tool_choice_param import ChatCompletionNamedToolChoiceParam + +__all__ = ["ChatCompletionToolChoiceOptionParam"] + +ChatCompletionToolChoiceOptionParam = Union[Literal["none", "auto"], ChatCompletionNamedToolChoiceParam] diff --git a/src/openai/types/chat/chat_completion_tool_message_param.py b/src/openai/types/chat/chat_completion_tool_message_param.py new file mode 100644 index 0000000000..51759a9a99 --- /dev/null +++ b/src/openai/types/chat/chat_completion_tool_message_param.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ChatCompletionToolMessageParam"] + + +class ChatCompletionToolMessageParam(TypedDict, total=False): + content: Required[Optional[str]] + """The contents of the tool message.""" + + role: Required[Literal["tool"]] + """The role of the messages author, in this case `tool`.""" + + tool_call_id: Required[str] + """Tool call that this message is responding to.""" diff --git a/src/openai/types/chat/chat_completion_tool_param.py b/src/openai/types/chat/chat_completion_tool_param.py new file mode 100644 index 0000000000..4b7e6238c7 --- /dev/null +++ b/src/openai/types/chat/chat_completion_tool_param.py @@ -0,0 +1,42 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Dict +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ChatCompletionToolParam", "Function"] + + +class Function(TypedDict, total=False): + name: Required[str] + """The name of the function to be called. + + Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length + of 64. + """ + + parameters: Required[Dict[str, object]] + """The parameters the functions accepts, described as a JSON Schema object. + + See the [guide](https://platform.openai.com/docs/guides/gpt/function-calling) + for examples, and the + [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for + documentation about the format. + + To describe a function that accepts no parameters, provide the value + `{"type": "object", "properties": {}}`. + """ + + description: str + """ + A description of what the function does, used by the model to choose when and + how to call the function. + """ + + +class ChatCompletionToolParam(TypedDict, total=False): + function: Required[Function] + + type: Required[Literal["function"]] + """The type of the tool. Currently, only `function` is supported.""" diff --git a/src/openai/types/chat/chat_completion_user_message_param.py b/src/openai/types/chat/chat_completion_user_message_param.py new file mode 100644 index 0000000000..6f0cf34623 --- /dev/null +++ b/src/openai/types/chat/chat_completion_user_message_param.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import List, Union +from typing_extensions import Literal, Required, TypedDict + +from .chat_completion_content_part_param import ChatCompletionContentPartParam + +__all__ = ["ChatCompletionUserMessageParam"] + + +class ChatCompletionUserMessageParam(TypedDict, total=False): + content: Required[Union[str, List[ChatCompletionContentPartParam], None]] + """The contents of the user message.""" + + role: Required[Literal["user"]] + """The role of the messages author, in this case `user`.""" diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index d681a90cd6..44b1abe576 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -5,13 +5,20 @@ from typing import Dict, List, Union, Optional from typing_extensions import Literal, Required, TypedDict +from .chat_completion_tool_param import ChatCompletionToolParam from .chat_completion_message_param import ChatCompletionMessageParam +from .chat_completion_tool_choice_option_param import ( + ChatCompletionToolChoiceOptionParam, +) +from .chat_completion_function_call_option_param import ( + ChatCompletionFunctionCallOptionParam, +) __all__ = [ "CompletionCreateParamsBase", "FunctionCall", - "FunctionCallFunctionCallOption", "Function", + "ResponseFormat", "CompletionCreateParamsNonStreaming", "CompletionCreateParamsStreaming", ] @@ -59,22 +66,28 @@ class CompletionCreateParamsBase(TypedDict, total=False): """ function_call: FunctionCall - """Controls how the model calls functions. + """Deprecated in favor of `tool_choice`. - "none" means the model will not call a function and instead generates a message. - "auto" means the model can pick between generating a message or calling a - function. Specifying a particular function via `{"name": "my_function"}` forces - the model to call that function. "none" is the default when no functions are - present. "auto" is the default if functions are present. + Controls which (if any) function is called by the model. `none` means the model + will not call a function and instead generates a message. `auto` means the model + can pick between generating a message or calling a function. Specifying a + particular function via `{"name": "my_function"}` forces the model to call that + function. + + `none` is the default when no functions are present. `auto`` is the default if + functions are present. """ functions: List[Function] - """A list of functions the model may generate JSON inputs for.""" + """Deprecated in favor of `tools`. + + A list of functions the model may generate JSON inputs for. + """ logit_bias: Optional[Dict[str, int]] """Modify the likelihood of specified tokens appearing in the completion. - Accepts a json object that maps tokens (specified by their token ID in the + Accepts a JSON object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or @@ -103,6 +116,21 @@ class CompletionCreateParamsBase(TypedDict, total=False): [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) """ + response_format: ResponseFormat + """An object specifying the format that the model must output. + + Used to enable JSON mode. + """ + + seed: Optional[int] + """This feature is in Beta. + + If specified, our system will make a best effort to sample deterministically, + such that repeated requests with the same `seed` and parameters should return + the same result. Determinism is not guaranteed, and you should refer to the + `system_fingerprint` response parameter to monitor changes in the backend. + """ + stop: Union[Optional[str], List[str]] """Up to 4 sequences where the API will stop generating further tokens.""" @@ -115,6 +143,26 @@ class CompletionCreateParamsBase(TypedDict, total=False): We generally recommend altering this or `top_p` but not both. """ + tool_choice: ChatCompletionToolChoiceOptionParam + """ + Controls which (if any) function is called by the model. `none` means the model + will not call a function and instead generates a message. `auto` means the model + can pick between generating a message or calling a function. Specifying a + particular function via + `{"type: "function", "function": {"name": "my_function"}}` forces the model to + call that function. + + `none` is the default when no functions are present. `auto` is the default if + functions are present. + """ + + tools: List[ChatCompletionToolParam] + """A list of tools the model may call. + + Currently, only functions are supported as a tool. Use this to provide a list of + functions the model may generate JSON inputs for. + """ + top_p: Optional[float] """ An alternative to sampling with temperature, called nucleus sampling, where the @@ -132,12 +180,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): """ -class FunctionCallFunctionCallOption(TypedDict, total=False): - name: Required[str] - """The name of the function to call.""" - - -FunctionCall = Union[Literal["none", "auto"], FunctionCallFunctionCallOption] +FunctionCall = Union[Literal["none", "auto"], ChatCompletionFunctionCallOptionParam] class Function(TypedDict, total=False): @@ -167,6 +210,23 @@ class Function(TypedDict, total=False): """ +class ResponseFormat(TypedDict, total=False): + type: Literal["text", "json_object"] + """Setting to `json_object` enables JSON mode. + + This guarantees that the message the model generates is valid JSON. + + Note that your system prompt must still instruct the model to produce JSON, and + to help ensure you don't forget, the API will throw an error if the string + `JSON` does not appear in your system message. Also note that the message + content may be partial (i.e. cut off) if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. + + Must be one of `text` or `json_object`. + """ + + class CompletionCreateParamsNonStreaming(CompletionCreateParamsBase): stream: Optional[Literal[False]] """If set, partial message deltas will be sent, like in ChatGPT. diff --git a/src/openai/types/completion.py b/src/openai/types/completion.py index 0a90838fd4..cd80498b16 100644 --- a/src/openai/types/completion.py +++ b/src/openai/types/completion.py @@ -1,6 +1,7 @@ # File generated from our OpenAPI spec by Stainless. from typing import List, Optional +from typing_extensions import Literal from .._models import BaseModel from .completion_usage import CompletionUsage @@ -22,8 +23,15 @@ class Completion(BaseModel): model: str """The model used for completion.""" - object: str + object: Literal["text_completion"] """The object type, which is always "text_completion" """ + system_fingerprint: Optional[str] = None + """This fingerprint represents the backend configuration that the model runs with. + + Can be used in conjunction with the `seed` request parameter to understand when + backend changes have been made that might impact determinism. + """ + usage: Optional[CompletionUsage] = None """Usage statistics for the completion request.""" diff --git a/src/openai/types/completion_create_params.py b/src/openai/types/completion_create_params.py index 023c087d5f..3e56d4f7bf 100644 --- a/src/openai/types/completion_create_params.py +++ b/src/openai/types/completion_create_params.py @@ -73,7 +73,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): logit_bias: Optional[Dict[str, int]] """Modify the likelihood of specified tokens appearing in the completion. - Accepts a json object that maps tokens (specified by their token ID in the GPT + Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this [tokenizer tool](/tokenizer?view=bpe) (which works for both GPT-2 and GPT-3) to convert text to token IDs. Mathematically, the bias is added to the logits @@ -122,6 +122,16 @@ class CompletionCreateParamsBase(TypedDict, total=False): [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) """ + seed: Optional[int] + """ + If specified, our system will make a best effort to sample deterministically, + such that repeated requests with the same `seed` and parameters should return + the same result. + + Determinism is not guaranteed, and you should refer to the `system_fingerprint` + response parameter to monitor changes in the backend. + """ + stop: Union[Optional[str], List[str], None] """Up to 4 sequences where the API will stop generating further tokens. diff --git a/src/openai/types/create_embedding_response.py b/src/openai/types/create_embedding_response.py index eccd148d3c..7382bed6b9 100644 --- a/src/openai/types/create_embedding_response.py +++ b/src/openai/types/create_embedding_response.py @@ -1,6 +1,7 @@ # File generated from our OpenAPI spec by Stainless. from typing import List +from typing_extensions import Literal from .._models import BaseModel from .embedding import Embedding @@ -23,7 +24,7 @@ class CreateEmbeddingResponse(BaseModel): model: str """The name of the model used to generate the embedding.""" - object: str + object: Literal["embedding"] """The object type, which is always "embedding".""" usage: Usage diff --git a/src/openai/types/edit.py b/src/openai/types/edit.py index 41b327534e..48bca2987b 100644 --- a/src/openai/types/edit.py +++ b/src/openai/types/edit.py @@ -33,7 +33,7 @@ class Edit(BaseModel): created: int """The Unix timestamp (in seconds) of when the edit was created.""" - object: str + object: Literal["edit"] """The object type, which is always `edit`.""" usage: CompletionUsage diff --git a/src/openai/types/embedding.py b/src/openai/types/embedding.py index 4579b9bb57..9c53704d5d 100644 --- a/src/openai/types/embedding.py +++ b/src/openai/types/embedding.py @@ -1,6 +1,7 @@ # File generated from our OpenAPI spec by Stainless. from typing import List +from typing_extensions import Literal from .._models import BaseModel @@ -18,5 +19,5 @@ class Embedding(BaseModel): index: int """The index of the embedding in the list of embeddings.""" - object: str + object: Literal["embedding"] """The object type, which is always "embedding".""" diff --git a/src/openai/types/file_create_params.py b/src/openai/types/file_create_params.py index 07b068c5c6..a59ddb2817 100644 --- a/src/openai/types/file_create_params.py +++ b/src/openai/types/file_create_params.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing_extensions import Required, TypedDict +from typing_extensions import Literal, Required, TypedDict from .._types import FileTypes @@ -11,16 +11,15 @@ class FileCreateParams(TypedDict, total=False): file: Required[FileTypes] - """The file object (not file name) to be uploaded. + """The File object (not file name) to be uploaded.""" - If the `purpose` is set to "fine-tune", the file will be used for fine-tuning. - """ - - purpose: Required[str] + purpose: Required[Literal["fine-tune", "assistants"]] """The intended purpose of the uploaded file. Use "fine-tune" for - [fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning). This - allows us to validate the format of the uploaded file is correct for - fine-tuning. + [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning) and + "assistants" for + [Assistants](https://platform.openai.com/docs/api-reference/assistants) and + [Messages](https://platform.openai.com/docs/api-reference/messages). This allows + us to validate the format of the uploaded file is correct for fine-tuning. """ diff --git a/src/openai/types/file_deleted.py b/src/openai/types/file_deleted.py index a526b2b986..3ac8592ff6 100644 --- a/src/openai/types/file_deleted.py +++ b/src/openai/types/file_deleted.py @@ -1,5 +1,7 @@ # File generated from our OpenAPI spec by Stainless. +from typing_extensions import Literal + from .._models import BaseModel __all__ = ["FileDeleted"] @@ -10,4 +12,4 @@ class FileDeleted(BaseModel): deleted: bool - object: str + object: Literal["file"] diff --git a/src/openai/types/file_list_params.py b/src/openai/types/file_list_params.py new file mode 100644 index 0000000000..a962dd239c --- /dev/null +++ b/src/openai/types/file_list_params.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["FileListParams"] + + +class FileListParams(TypedDict, total=False): + purpose: str + """Only return files with the given purpose.""" diff --git a/src/openai/types/file_object.py b/src/openai/types/file_object.py index dac24a88c5..4ae91b754e 100644 --- a/src/openai/types/file_object.py +++ b/src/openai/types/file_object.py @@ -1,6 +1,7 @@ # File generated from our OpenAPI spec by Stainless. from typing import Optional +from typing_extensions import Literal from .._models import BaseModel @@ -12,7 +13,7 @@ class FileObject(BaseModel): """The file identifier, which can be referenced in the API endpoints.""" bytes: int - """The size of the file in bytes.""" + """The size of the file, in bytes.""" created_at: int """The Unix timestamp (in seconds) for when the file was created.""" @@ -20,21 +21,26 @@ class FileObject(BaseModel): filename: str """The name of the file.""" - object: str - """The object type, which is always "file".""" + object: Literal["file"] + """The object type, which is always `file`.""" - purpose: str - """The intended purpose of the file. Currently, only "fine-tune" is supported.""" + purpose: Literal["fine-tune", "fine-tune-results", "assistants", "assistants_output"] + """The intended purpose of the file. - status: Optional[str] = None + Supported values are `fine-tune`, `fine-tune-results`, `assistants`, and + `assistants_output`. """ - The current status of the file, which can be either `uploaded`, `processed`, - `pending`, `error`, `deleting` or `deleted`. + + status: Literal["uploaded", "processed", "error"] + """Deprecated. + + The current status of the file, which can be either `uploaded`, `processed`, or + `error`. """ status_details: Optional[str] = None - """Additional details about the status of the file. + """Deprecated. - If the file is in the `error` state, this will include a message describing the - error. + For details on why a fine-tuning training file failed validation, see the + `error` field on `fine_tuning.job`. """ diff --git a/src/openai/types/fine_tune.py b/src/openai/types/fine_tune.py index 4124def2f5..de1e097ee4 100644 --- a/src/openai/types/fine_tune.py +++ b/src/openai/types/fine_tune.py @@ -1,6 +1,7 @@ # File generated from our OpenAPI spec by Stainless. from typing import List, Optional +from typing_extensions import Literal from .._models import BaseModel from .file_object import FileObject @@ -63,7 +64,7 @@ class FineTune(BaseModel): model: str """The base model that is being fine-tuned.""" - object: str + object: Literal["fine-tune"] """The object type, which is always "fine-tune".""" organization_id: str diff --git a/src/openai/types/fine_tune_event.py b/src/openai/types/fine_tune_event.py index 6499def98d..299f0de24b 100644 --- a/src/openai/types/fine_tune_event.py +++ b/src/openai/types/fine_tune_event.py @@ -1,5 +1,7 @@ # File generated from our OpenAPI spec by Stainless. +from typing_extensions import Literal + from .._models import BaseModel __all__ = ["FineTuneEvent"] @@ -12,4 +14,4 @@ class FineTuneEvent(BaseModel): message: str - object: str + object: Literal["fine-tune-event"] diff --git a/src/openai/types/fine_tune_events_list_response.py b/src/openai/types/fine_tune_events_list_response.py index ca159d8772..c69746104d 100644 --- a/src/openai/types/fine_tune_events_list_response.py +++ b/src/openai/types/fine_tune_events_list_response.py @@ -1,6 +1,7 @@ # File generated from our OpenAPI spec by Stainless. from typing import List +from typing_extensions import Literal from .._models import BaseModel from .fine_tune_event import FineTuneEvent @@ -11,4 +12,4 @@ class FineTuneEventsListResponse(BaseModel): data: List[FineTuneEvent] - object: str + object: Literal["list"] diff --git a/src/openai/types/fine_tuning/fine_tuning_job.py b/src/openai/types/fine_tuning/fine_tuning_job.py index 2ae1cbb473..3897176a47 100644 --- a/src/openai/types/fine_tuning/fine_tuning_job.py +++ b/src/openai/types/fine_tuning/fine_tuning_job.py @@ -67,7 +67,7 @@ class FineTuningJob(BaseModel): model: str """The base model that is being fine-tuned.""" - object: str + object: Literal["fine_tuning.job"] """The object type, which is always "fine_tuning.job".""" organization_id: str @@ -80,7 +80,7 @@ class FineTuningJob(BaseModel): [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). """ - status: str + status: Literal["validating_files", "queued", "running", "succeeded", "failed", "cancelled"] """ The current status of the fine-tuning job, which can be either `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`. diff --git a/src/openai/types/fine_tuning/fine_tuning_job_event.py b/src/openai/types/fine_tuning/fine_tuning_job_event.py index c21a0503ab..62f268868b 100644 --- a/src/openai/types/fine_tuning/fine_tuning_job_event.py +++ b/src/openai/types/fine_tuning/fine_tuning_job_event.py @@ -16,4 +16,4 @@ class FineTuningJobEvent(BaseModel): message: str - object: str + object: Literal["fine_tuning.job.event"] diff --git a/src/openai/types/fine_tuning/job_create_params.py b/src/openai/types/fine_tuning/job_create_params.py index 2a67b81817..da750ffc19 100644 --- a/src/openai/types/fine_tuning/job_create_params.py +++ b/src/openai/types/fine_tuning/job_create_params.py @@ -58,6 +58,19 @@ class JobCreateParams(TypedDict, total=False): class Hyperparameters(TypedDict, total=False): + batch_size: Union[Literal["auto"], int] + """Number of examples in each batch. + + A larger batch size means that model parameters are updated less frequently, but + with lower variance. + """ + + learning_rate_multiplier: Union[Literal["auto"], float] + """Scaling factor for the learning rate. + + A smaller learning rate may be useful to avoid overfitting. + """ + n_epochs: Union[Literal["auto"], int] """The number of epochs to train the model for. diff --git a/src/openai/types/image.py b/src/openai/types/image.py index 4b8d1aaf18..a040caf7b6 100644 --- a/src/openai/types/image.py +++ b/src/openai/types/image.py @@ -14,5 +14,11 @@ class Image(BaseModel): `b64_json`. """ + revised_prompt: Optional[str] = None + """ + The prompt that was used to generate the image, if there was any revision to the + prompt. + """ + url: Optional[str] = None """The URL of the generated image, if `response_format` is `url` (default).""" diff --git a/src/openai/types/image_create_variation_params.py b/src/openai/types/image_create_variation_params.py index d3b439070e..7b015fc176 100644 --- a/src/openai/types/image_create_variation_params.py +++ b/src/openai/types/image_create_variation_params.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Optional +from typing import Union, Optional from typing_extensions import Literal, Required, TypedDict from .._types import FileTypes @@ -17,8 +17,17 @@ class ImageCreateVariationParams(TypedDict, total=False): Must be a valid PNG file, less than 4MB, and square. """ + model: Union[str, Literal["dall-e-2"], None] + """The model to use for image generation. + + Only `dall-e-2` is supported at this time. + """ + n: Optional[int] - """The number of images to generate. Must be between 1 and 10.""" + """The number of images to generate. + + Must be between 1 and 10. For `dall-e-3`, only `n=1` is supported. + """ response_format: Optional[Literal["url", "b64_json"]] """The format in which the generated images are returned. diff --git a/src/openai/types/image_edit_params.py b/src/openai/types/image_edit_params.py index ce07a9cb30..043885cc38 100644 --- a/src/openai/types/image_edit_params.py +++ b/src/openai/types/image_edit_params.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Optional +from typing import Union, Optional from typing_extensions import Literal, Required, TypedDict from .._types import FileTypes @@ -31,6 +31,12 @@ class ImageEditParams(TypedDict, total=False): PNG file, less than 4MB, and have the same dimensions as `image`. """ + model: Union[str, Literal["dall-e-2"], None] + """The model to use for image generation. + + Only `dall-e-2` is supported at this time. + """ + n: Optional[int] """The number of images to generate. Must be between 1 and 10.""" diff --git a/src/openai/types/image_generate_params.py b/src/openai/types/image_generate_params.py index 4999ed958d..7eca29a7ba 100644 --- a/src/openai/types/image_generate_params.py +++ b/src/openai/types/image_generate_params.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Optional +from typing import Union, Optional from typing_extensions import Literal, Required, TypedDict __all__ = ["ImageGenerateParams"] @@ -12,11 +12,25 @@ class ImageGenerateParams(TypedDict, total=False): prompt: Required[str] """A text description of the desired image(s). - The maximum length is 1000 characters. + The maximum length is 1000 characters for `dall-e-2` and 4000 characters for + `dall-e-3`. """ + model: Union[str, Literal["dall-e-2", "dall-e-3"], None] + """The model to use for image generation.""" + n: Optional[int] - """The number of images to generate. Must be between 1 and 10.""" + """The number of images to generate. + + Must be between 1 and 10. For `dall-e-3`, only `n=1` is supported. + """ + + quality: Literal["standard", "hd"] + """The quality of the image that will be generated. + + `hd` creates images with finer details and greater consistency across the image. + This param is only supported for `dall-e-3`. + """ response_format: Optional[Literal["url", "b64_json"]] """The format in which the generated images are returned. @@ -24,10 +38,20 @@ class ImageGenerateParams(TypedDict, total=False): Must be one of `url` or `b64_json`. """ - size: Optional[Literal["256x256", "512x512", "1024x1024"]] + size: Optional[Literal["256x256", "512x512", "1024x1024", "1792x1024", "1024x1792"]] """The size of the generated images. - Must be one of `256x256`, `512x512`, or `1024x1024`. + Must be one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`. Must be one + of `1024x1024`, `1792x1024`, or `1024x1792` for `dall-e-3` models. + """ + + style: Optional[Literal["vivid", "natural"]] + """The style of the generated images. + + Must be one of `vivid` or `natural`. Vivid causes the model to lean towards + generating hyper-real and dramatic images. Natural causes the model to produce + more natural, less hyper-real looking images. This param is only supported for + `dall-e-3`. """ user: str diff --git a/src/openai/types/model.py b/src/openai/types/model.py index 29e71b81a0..58f3997f70 100644 --- a/src/openai/types/model.py +++ b/src/openai/types/model.py @@ -1,5 +1,7 @@ # File generated from our OpenAPI spec by Stainless. +from typing_extensions import Literal + from .._models import BaseModel __all__ = ["Model"] @@ -12,7 +14,7 @@ class Model(BaseModel): created: int """The Unix timestamp (in seconds) when the model was created.""" - object: str + object: Literal["model"] """The object type, which is always "model".""" owned_by: str diff --git a/tests/api_resources/audio/test_speech.py b/tests/api_resources/audio/test_speech.py new file mode 100644 index 0000000000..89814c2dd3 --- /dev/null +++ b/tests/api_resources/audio/test_speech.py @@ -0,0 +1,110 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import os + +import httpx +import pytest +from respx import MockRouter + +from openai import OpenAI, AsyncOpenAI +from openai._types import BinaryResponseContent +from openai._client import OpenAI, AsyncOpenAI + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") +api_key = "My API Key" + + +class TestSpeech: + strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + @pytest.mark.respx(base_url=base_url) + def test_method_create(self, client: OpenAI, respx_mock: MockRouter) -> None: + respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + speech = client.audio.speech.create( + input="string", + model="string", + voice="alloy", + ) + assert isinstance(speech, BinaryResponseContent) + assert speech.json() == {"foo": "bar"} + + @parametrize + @pytest.mark.respx(base_url=base_url) + def test_method_create_with_all_params(self, client: OpenAI, respx_mock: MockRouter) -> None: + respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + speech = respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + client.audio.speech.create( + input="string", + model="string", + voice="alloy", + response_format="mp3", + speed=0.25, + ) + assert isinstance(speech, BinaryResponseContent) + assert speech.json() == {"foo": "bar"} + + @parametrize + @pytest.mark.respx(base_url=base_url) + def test_raw_response_create(self, client: OpenAI, respx_mock: MockRouter) -> None: + respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + response = client.audio.speech.with_raw_response.create( + input="string", + model="string", + voice="alloy", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + speech = response.parse() + assert isinstance(speech, BinaryResponseContent) + assert speech.json() == {"foo": "bar"} + + +class TestAsyncSpeech: + strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + @pytest.mark.respx(base_url=base_url) + async def test_method_create(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: + respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + speech = await client.audio.speech.create( + input="string", + model="string", + voice="alloy", + ) + assert isinstance(speech, BinaryResponseContent) + assert speech.json() == {"foo": "bar"} + + @parametrize + @pytest.mark.respx(base_url=base_url) + async def test_method_create_with_all_params(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: + respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + speech = respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + await client.audio.speech.create( + input="string", + model="string", + voice="alloy", + response_format="mp3", + speed=0.25, + ) + assert isinstance(speech, BinaryResponseContent) + assert speech.json() == {"foo": "bar"} + + @parametrize + @pytest.mark.respx(base_url=base_url) + async def test_raw_response_create(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: + respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + response = await client.audio.speech.with_raw_response.create( + input="string", + model="string", + voice="alloy", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + speech = response.parse() + assert isinstance(speech, BinaryResponseContent) + assert speech.json() == {"foo": "bar"} diff --git a/tests/api_resources/beta/__init__.py b/tests/api_resources/beta/__init__.py new file mode 100644 index 0000000000..1016754ef3 --- /dev/null +++ b/tests/api_resources/beta/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. diff --git a/tests/api_resources/beta/assistants/__init__.py b/tests/api_resources/beta/assistants/__init__.py new file mode 100644 index 0000000000..1016754ef3 --- /dev/null +++ b/tests/api_resources/beta/assistants/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. diff --git a/tests/api_resources/beta/assistants/test_files.py b/tests/api_resources/beta/assistants/test_files.py new file mode 100644 index 0000000000..2545640c57 --- /dev/null +++ b/tests/api_resources/beta/assistants/test_files.py @@ -0,0 +1,190 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import os + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai._client import OpenAI, AsyncOpenAI +from openai.pagination import SyncCursorPage, AsyncCursorPage +from openai.types.beta.assistants import AssistantFile, FileDeleteResponse + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") +api_key = "My API Key" + + +class TestFiles: + strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + def test_method_create(self, client: OpenAI) -> None: + file = client.beta.assistants.files.create( + "file-AF1WoRqd3aJAHsqc9NY7iL8F", + file_id="string", + ) + assert_matches_type(AssistantFile, file, path=["response"]) + + @parametrize + def test_raw_response_create(self, client: OpenAI) -> None: + response = client.beta.assistants.files.with_raw_response.create( + "file-AF1WoRqd3aJAHsqc9NY7iL8F", + file_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(AssistantFile, file, path=["response"]) + + @parametrize + def test_method_retrieve(self, client: OpenAI) -> None: + file = client.beta.assistants.files.retrieve( + "string", + assistant_id="string", + ) + assert_matches_type(AssistantFile, file, path=["response"]) + + @parametrize + def test_raw_response_retrieve(self, client: OpenAI) -> None: + response = client.beta.assistants.files.with_raw_response.retrieve( + "string", + assistant_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(AssistantFile, file, path=["response"]) + + @parametrize + def test_method_list(self, client: OpenAI) -> None: + file = client.beta.assistants.files.list( + "string", + ) + assert_matches_type(SyncCursorPage[AssistantFile], file, path=["response"]) + + @parametrize + def test_method_list_with_all_params(self, client: OpenAI) -> None: + file = client.beta.assistants.files.list( + "string", + after="string", + before="string", + limit=0, + order="asc", + ) + assert_matches_type(SyncCursorPage[AssistantFile], file, path=["response"]) + + @parametrize + def test_raw_response_list(self, client: OpenAI) -> None: + response = client.beta.assistants.files.with_raw_response.list( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(SyncCursorPage[AssistantFile], file, path=["response"]) + + @parametrize + def test_method_delete(self, client: OpenAI) -> None: + file = client.beta.assistants.files.delete( + "string", + assistant_id="string", + ) + assert_matches_type(FileDeleteResponse, file, path=["response"]) + + @parametrize + def test_raw_response_delete(self, client: OpenAI) -> None: + response = client.beta.assistants.files.with_raw_response.delete( + "string", + assistant_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(FileDeleteResponse, file, path=["response"]) + + +class TestAsyncFiles: + strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + async def test_method_create(self, client: AsyncOpenAI) -> None: + file = await client.beta.assistants.files.create( + "file-AF1WoRqd3aJAHsqc9NY7iL8F", + file_id="string", + ) + assert_matches_type(AssistantFile, file, path=["response"]) + + @parametrize + async def test_raw_response_create(self, client: AsyncOpenAI) -> None: + response = await client.beta.assistants.files.with_raw_response.create( + "file-AF1WoRqd3aJAHsqc9NY7iL8F", + file_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(AssistantFile, file, path=["response"]) + + @parametrize + async def test_method_retrieve(self, client: AsyncOpenAI) -> None: + file = await client.beta.assistants.files.retrieve( + "string", + assistant_id="string", + ) + assert_matches_type(AssistantFile, file, path=["response"]) + + @parametrize + async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: + response = await client.beta.assistants.files.with_raw_response.retrieve( + "string", + assistant_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(AssistantFile, file, path=["response"]) + + @parametrize + async def test_method_list(self, client: AsyncOpenAI) -> None: + file = await client.beta.assistants.files.list( + "string", + ) + assert_matches_type(AsyncCursorPage[AssistantFile], file, path=["response"]) + + @parametrize + async def test_method_list_with_all_params(self, client: AsyncOpenAI) -> None: + file = await client.beta.assistants.files.list( + "string", + after="string", + before="string", + limit=0, + order="asc", + ) + assert_matches_type(AsyncCursorPage[AssistantFile], file, path=["response"]) + + @parametrize + async def test_raw_response_list(self, client: AsyncOpenAI) -> None: + response = await client.beta.assistants.files.with_raw_response.list( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(AsyncCursorPage[AssistantFile], file, path=["response"]) + + @parametrize + async def test_method_delete(self, client: AsyncOpenAI) -> None: + file = await client.beta.assistants.files.delete( + "string", + assistant_id="string", + ) + assert_matches_type(FileDeleteResponse, file, path=["response"]) + + @parametrize + async def test_raw_response_delete(self, client: AsyncOpenAI) -> None: + response = await client.beta.assistants.files.with_raw_response.delete( + "string", + assistant_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(FileDeleteResponse, file, path=["response"]) diff --git a/tests/api_resources/beta/chat/__init__.py b/tests/api_resources/beta/chat/__init__.py new file mode 100644 index 0000000000..1016754ef3 --- /dev/null +++ b/tests/api_resources/beta/chat/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. diff --git a/tests/api_resources/beta/test_assistants.py b/tests/api_resources/beta/test_assistants.py new file mode 100644 index 0000000000..5bbad1d7dd --- /dev/null +++ b/tests/api_resources/beta/test_assistants.py @@ -0,0 +1,254 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import os + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai._client import OpenAI, AsyncOpenAI +from openai.pagination import SyncCursorPage, AsyncCursorPage +from openai.types.beta import Assistant, AsssitantDeleted + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") +api_key = "My API Key" + + +class TestAssistants: + strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + def test_method_create(self, client: OpenAI) -> None: + assistant = client.beta.assistants.create( + model="string", + ) + assert_matches_type(Assistant, assistant, path=["response"]) + + @parametrize + def test_method_create_with_all_params(self, client: OpenAI) -> None: + assistant = client.beta.assistants.create( + model="string", + description="string", + file_ids=["string", "string", "string"], + instructions="string", + metadata={}, + name="string", + tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + ) + assert_matches_type(Assistant, assistant, path=["response"]) + + @parametrize + def test_raw_response_create(self, client: OpenAI) -> None: + response = client.beta.assistants.with_raw_response.create( + model="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + assistant = response.parse() + assert_matches_type(Assistant, assistant, path=["response"]) + + @parametrize + def test_method_retrieve(self, client: OpenAI) -> None: + assistant = client.beta.assistants.retrieve( + "string", + ) + assert_matches_type(Assistant, assistant, path=["response"]) + + @parametrize + def test_raw_response_retrieve(self, client: OpenAI) -> None: + response = client.beta.assistants.with_raw_response.retrieve( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + assistant = response.parse() + assert_matches_type(Assistant, assistant, path=["response"]) + + @parametrize + def test_method_update(self, client: OpenAI) -> None: + assistant = client.beta.assistants.update( + "string", + ) + assert_matches_type(Assistant, assistant, path=["response"]) + + @parametrize + def test_method_update_with_all_params(self, client: OpenAI) -> None: + assistant = client.beta.assistants.update( + "string", + description="string", + file_ids=["string", "string", "string"], + instructions="string", + metadata={}, + model="string", + name="string", + tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + ) + assert_matches_type(Assistant, assistant, path=["response"]) + + @parametrize + def test_raw_response_update(self, client: OpenAI) -> None: + response = client.beta.assistants.with_raw_response.update( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + assistant = response.parse() + assert_matches_type(Assistant, assistant, path=["response"]) + + @parametrize + def test_method_list(self, client: OpenAI) -> None: + assistant = client.beta.assistants.list() + assert_matches_type(SyncCursorPage[Assistant], assistant, path=["response"]) + + @parametrize + def test_method_list_with_all_params(self, client: OpenAI) -> None: + assistant = client.beta.assistants.list( + after="string", + before="string", + limit=0, + order="asc", + ) + assert_matches_type(SyncCursorPage[Assistant], assistant, path=["response"]) + + @parametrize + def test_raw_response_list(self, client: OpenAI) -> None: + response = client.beta.assistants.with_raw_response.list() + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + assistant = response.parse() + assert_matches_type(SyncCursorPage[Assistant], assistant, path=["response"]) + + @parametrize + def test_method_delete(self, client: OpenAI) -> None: + assistant = client.beta.assistants.delete( + "string", + ) + assert_matches_type(AsssitantDeleted, assistant, path=["response"]) + + @parametrize + def test_raw_response_delete(self, client: OpenAI) -> None: + response = client.beta.assistants.with_raw_response.delete( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + assistant = response.parse() + assert_matches_type(AsssitantDeleted, assistant, path=["response"]) + + +class TestAsyncAssistants: + strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + async def test_method_create(self, client: AsyncOpenAI) -> None: + assistant = await client.beta.assistants.create( + model="string", + ) + assert_matches_type(Assistant, assistant, path=["response"]) + + @parametrize + async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: + assistant = await client.beta.assistants.create( + model="string", + description="string", + file_ids=["string", "string", "string"], + instructions="string", + metadata={}, + name="string", + tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + ) + assert_matches_type(Assistant, assistant, path=["response"]) + + @parametrize + async def test_raw_response_create(self, client: AsyncOpenAI) -> None: + response = await client.beta.assistants.with_raw_response.create( + model="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + assistant = response.parse() + assert_matches_type(Assistant, assistant, path=["response"]) + + @parametrize + async def test_method_retrieve(self, client: AsyncOpenAI) -> None: + assistant = await client.beta.assistants.retrieve( + "string", + ) + assert_matches_type(Assistant, assistant, path=["response"]) + + @parametrize + async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: + response = await client.beta.assistants.with_raw_response.retrieve( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + assistant = response.parse() + assert_matches_type(Assistant, assistant, path=["response"]) + + @parametrize + async def test_method_update(self, client: AsyncOpenAI) -> None: + assistant = await client.beta.assistants.update( + "string", + ) + assert_matches_type(Assistant, assistant, path=["response"]) + + @parametrize + async def test_method_update_with_all_params(self, client: AsyncOpenAI) -> None: + assistant = await client.beta.assistants.update( + "string", + description="string", + file_ids=["string", "string", "string"], + instructions="string", + metadata={}, + model="string", + name="string", + tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + ) + assert_matches_type(Assistant, assistant, path=["response"]) + + @parametrize + async def test_raw_response_update(self, client: AsyncOpenAI) -> None: + response = await client.beta.assistants.with_raw_response.update( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + assistant = response.parse() + assert_matches_type(Assistant, assistant, path=["response"]) + + @parametrize + async def test_method_list(self, client: AsyncOpenAI) -> None: + assistant = await client.beta.assistants.list() + assert_matches_type(AsyncCursorPage[Assistant], assistant, path=["response"]) + + @parametrize + async def test_method_list_with_all_params(self, client: AsyncOpenAI) -> None: + assistant = await client.beta.assistants.list( + after="string", + before="string", + limit=0, + order="asc", + ) + assert_matches_type(AsyncCursorPage[Assistant], assistant, path=["response"]) + + @parametrize + async def test_raw_response_list(self, client: AsyncOpenAI) -> None: + response = await client.beta.assistants.with_raw_response.list() + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + assistant = response.parse() + assert_matches_type(AsyncCursorPage[Assistant], assistant, path=["response"]) + + @parametrize + async def test_method_delete(self, client: AsyncOpenAI) -> None: + assistant = await client.beta.assistants.delete( + "string", + ) + assert_matches_type(AsssitantDeleted, assistant, path=["response"]) + + @parametrize + async def test_raw_response_delete(self, client: AsyncOpenAI) -> None: + response = await client.beta.assistants.with_raw_response.delete( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + assistant = response.parse() + assert_matches_type(AsssitantDeleted, assistant, path=["response"]) diff --git a/tests/api_resources/beta/test_threads.py b/tests/api_resources/beta/test_threads.py new file mode 100644 index 0000000000..8fa1fc20ea --- /dev/null +++ b/tests/api_resources/beta/test_threads.py @@ -0,0 +1,318 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import os + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai._client import OpenAI, AsyncOpenAI +from openai.types.beta import Thread, ThreadDeleted +from openai.types.beta.threads import Run + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") +api_key = "My API Key" + + +class TestThreads: + strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + def test_method_create(self, client: OpenAI) -> None: + thread = client.beta.threads.create() + assert_matches_type(Thread, thread, path=["response"]) + + @parametrize + def test_method_create_with_all_params(self, client: OpenAI) -> None: + thread = client.beta.threads.create( + messages=[ + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + ], + metadata={}, + ) + assert_matches_type(Thread, thread, path=["response"]) + + @parametrize + def test_raw_response_create(self, client: OpenAI) -> None: + response = client.beta.threads.with_raw_response.create() + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + thread = response.parse() + assert_matches_type(Thread, thread, path=["response"]) + + @parametrize + def test_method_retrieve(self, client: OpenAI) -> None: + thread = client.beta.threads.retrieve( + "string", + ) + assert_matches_type(Thread, thread, path=["response"]) + + @parametrize + def test_raw_response_retrieve(self, client: OpenAI) -> None: + response = client.beta.threads.with_raw_response.retrieve( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + thread = response.parse() + assert_matches_type(Thread, thread, path=["response"]) + + @parametrize + def test_method_update(self, client: OpenAI) -> None: + thread = client.beta.threads.update( + "string", + ) + assert_matches_type(Thread, thread, path=["response"]) + + @parametrize + def test_method_update_with_all_params(self, client: OpenAI) -> None: + thread = client.beta.threads.update( + "string", + metadata={}, + ) + assert_matches_type(Thread, thread, path=["response"]) + + @parametrize + def test_raw_response_update(self, client: OpenAI) -> None: + response = client.beta.threads.with_raw_response.update( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + thread = response.parse() + assert_matches_type(Thread, thread, path=["response"]) + + @parametrize + def test_method_delete(self, client: OpenAI) -> None: + thread = client.beta.threads.delete( + "string", + ) + assert_matches_type(ThreadDeleted, thread, path=["response"]) + + @parametrize + def test_raw_response_delete(self, client: OpenAI) -> None: + response = client.beta.threads.with_raw_response.delete( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + thread = response.parse() + assert_matches_type(ThreadDeleted, thread, path=["response"]) + + @parametrize + def test_method_create_and_run(self, client: OpenAI) -> None: + thread = client.beta.threads.create_and_run( + assistant_id="string", + ) + assert_matches_type(Run, thread, path=["response"]) + + @parametrize + def test_method_create_and_run_with_all_params(self, client: OpenAI) -> None: + thread = client.beta.threads.create_and_run( + assistant_id="string", + instructions="string", + metadata={}, + model="string", + thread={ + "messages": [ + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + ], + "metadata": {}, + }, + tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + ) + assert_matches_type(Run, thread, path=["response"]) + + @parametrize + def test_raw_response_create_and_run(self, client: OpenAI) -> None: + response = client.beta.threads.with_raw_response.create_and_run( + assistant_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + thread = response.parse() + assert_matches_type(Run, thread, path=["response"]) + + +class TestAsyncThreads: + strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + async def test_method_create(self, client: AsyncOpenAI) -> None: + thread = await client.beta.threads.create() + assert_matches_type(Thread, thread, path=["response"]) + + @parametrize + async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: + thread = await client.beta.threads.create( + messages=[ + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + ], + metadata={}, + ) + assert_matches_type(Thread, thread, path=["response"]) + + @parametrize + async def test_raw_response_create(self, client: AsyncOpenAI) -> None: + response = await client.beta.threads.with_raw_response.create() + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + thread = response.parse() + assert_matches_type(Thread, thread, path=["response"]) + + @parametrize + async def test_method_retrieve(self, client: AsyncOpenAI) -> None: + thread = await client.beta.threads.retrieve( + "string", + ) + assert_matches_type(Thread, thread, path=["response"]) + + @parametrize + async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: + response = await client.beta.threads.with_raw_response.retrieve( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + thread = response.parse() + assert_matches_type(Thread, thread, path=["response"]) + + @parametrize + async def test_method_update(self, client: AsyncOpenAI) -> None: + thread = await client.beta.threads.update( + "string", + ) + assert_matches_type(Thread, thread, path=["response"]) + + @parametrize + async def test_method_update_with_all_params(self, client: AsyncOpenAI) -> None: + thread = await client.beta.threads.update( + "string", + metadata={}, + ) + assert_matches_type(Thread, thread, path=["response"]) + + @parametrize + async def test_raw_response_update(self, client: AsyncOpenAI) -> None: + response = await client.beta.threads.with_raw_response.update( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + thread = response.parse() + assert_matches_type(Thread, thread, path=["response"]) + + @parametrize + async def test_method_delete(self, client: AsyncOpenAI) -> None: + thread = await client.beta.threads.delete( + "string", + ) + assert_matches_type(ThreadDeleted, thread, path=["response"]) + + @parametrize + async def test_raw_response_delete(self, client: AsyncOpenAI) -> None: + response = await client.beta.threads.with_raw_response.delete( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + thread = response.parse() + assert_matches_type(ThreadDeleted, thread, path=["response"]) + + @parametrize + async def test_method_create_and_run(self, client: AsyncOpenAI) -> None: + thread = await client.beta.threads.create_and_run( + assistant_id="string", + ) + assert_matches_type(Run, thread, path=["response"]) + + @parametrize + async def test_method_create_and_run_with_all_params(self, client: AsyncOpenAI) -> None: + thread = await client.beta.threads.create_and_run( + assistant_id="string", + instructions="string", + metadata={}, + model="string", + thread={ + "messages": [ + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + ], + "metadata": {}, + }, + tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + ) + assert_matches_type(Run, thread, path=["response"]) + + @parametrize + async def test_raw_response_create_and_run(self, client: AsyncOpenAI) -> None: + response = await client.beta.threads.with_raw_response.create_and_run( + assistant_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + thread = response.parse() + assert_matches_type(Run, thread, path=["response"]) diff --git a/tests/api_resources/beta/threads/__init__.py b/tests/api_resources/beta/threads/__init__.py new file mode 100644 index 0000000000..1016754ef3 --- /dev/null +++ b/tests/api_resources/beta/threads/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. diff --git a/tests/api_resources/beta/threads/messages/__init__.py b/tests/api_resources/beta/threads/messages/__init__.py new file mode 100644 index 0000000000..1016754ef3 --- /dev/null +++ b/tests/api_resources/beta/threads/messages/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. diff --git a/tests/api_resources/beta/threads/messages/test_files.py b/tests/api_resources/beta/threads/messages/test_files.py new file mode 100644 index 0000000000..a5b68713e6 --- /dev/null +++ b/tests/api_resources/beta/threads/messages/test_files.py @@ -0,0 +1,128 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import os + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai._client import OpenAI, AsyncOpenAI +from openai.pagination import SyncCursorPage, AsyncCursorPage +from openai.types.beta.threads.messages import MessageFile + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") +api_key = "My API Key" + + +class TestFiles: + strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + def test_method_retrieve(self, client: OpenAI) -> None: + file = client.beta.threads.messages.files.retrieve( + "file-AF1WoRqd3aJAHsqc9NY7iL8F", + thread_id="thread_AF1WoRqd3aJAHsqc9NY7iL8F", + message_id="msg_AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert_matches_type(MessageFile, file, path=["response"]) + + @parametrize + def test_raw_response_retrieve(self, client: OpenAI) -> None: + response = client.beta.threads.messages.files.with_raw_response.retrieve( + "file-AF1WoRqd3aJAHsqc9NY7iL8F", + thread_id="thread_AF1WoRqd3aJAHsqc9NY7iL8F", + message_id="msg_AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(MessageFile, file, path=["response"]) + + @parametrize + def test_method_list(self, client: OpenAI) -> None: + file = client.beta.threads.messages.files.list( + "string", + thread_id="string", + ) + assert_matches_type(SyncCursorPage[MessageFile], file, path=["response"]) + + @parametrize + def test_method_list_with_all_params(self, client: OpenAI) -> None: + file = client.beta.threads.messages.files.list( + "string", + thread_id="string", + after="string", + before="string", + limit=0, + order="asc", + ) + assert_matches_type(SyncCursorPage[MessageFile], file, path=["response"]) + + @parametrize + def test_raw_response_list(self, client: OpenAI) -> None: + response = client.beta.threads.messages.files.with_raw_response.list( + "string", + thread_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(SyncCursorPage[MessageFile], file, path=["response"]) + + +class TestAsyncFiles: + strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + async def test_method_retrieve(self, client: AsyncOpenAI) -> None: + file = await client.beta.threads.messages.files.retrieve( + "file-AF1WoRqd3aJAHsqc9NY7iL8F", + thread_id="thread_AF1WoRqd3aJAHsqc9NY7iL8F", + message_id="msg_AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert_matches_type(MessageFile, file, path=["response"]) + + @parametrize + async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: + response = await client.beta.threads.messages.files.with_raw_response.retrieve( + "file-AF1WoRqd3aJAHsqc9NY7iL8F", + thread_id="thread_AF1WoRqd3aJAHsqc9NY7iL8F", + message_id="msg_AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(MessageFile, file, path=["response"]) + + @parametrize + async def test_method_list(self, client: AsyncOpenAI) -> None: + file = await client.beta.threads.messages.files.list( + "string", + thread_id="string", + ) + assert_matches_type(AsyncCursorPage[MessageFile], file, path=["response"]) + + @parametrize + async def test_method_list_with_all_params(self, client: AsyncOpenAI) -> None: + file = await client.beta.threads.messages.files.list( + "string", + thread_id="string", + after="string", + before="string", + limit=0, + order="asc", + ) + assert_matches_type(AsyncCursorPage[MessageFile], file, path=["response"]) + + @parametrize + async def test_raw_response_list(self, client: AsyncOpenAI) -> None: + response = await client.beta.threads.messages.files.with_raw_response.list( + "string", + thread_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(AsyncCursorPage[MessageFile], file, path=["response"]) diff --git a/tests/api_resources/beta/threads/runs/__init__.py b/tests/api_resources/beta/threads/runs/__init__.py new file mode 100644 index 0000000000..1016754ef3 --- /dev/null +++ b/tests/api_resources/beta/threads/runs/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. diff --git a/tests/api_resources/beta/threads/runs/test_steps.py b/tests/api_resources/beta/threads/runs/test_steps.py new file mode 100644 index 0000000000..3f4f8c1022 --- /dev/null +++ b/tests/api_resources/beta/threads/runs/test_steps.py @@ -0,0 +1,128 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import os + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai._client import OpenAI, AsyncOpenAI +from openai.pagination import SyncCursorPage, AsyncCursorPage +from openai.types.beta.threads.runs import RunStep + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") +api_key = "My API Key" + + +class TestSteps: + strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + def test_method_retrieve(self, client: OpenAI) -> None: + step = client.beta.threads.runs.steps.retrieve( + "string", + thread_id="string", + run_id="string", + ) + assert_matches_type(RunStep, step, path=["response"]) + + @parametrize + def test_raw_response_retrieve(self, client: OpenAI) -> None: + response = client.beta.threads.runs.steps.with_raw_response.retrieve( + "string", + thread_id="string", + run_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + step = response.parse() + assert_matches_type(RunStep, step, path=["response"]) + + @parametrize + def test_method_list(self, client: OpenAI) -> None: + step = client.beta.threads.runs.steps.list( + "string", + thread_id="string", + ) + assert_matches_type(SyncCursorPage[RunStep], step, path=["response"]) + + @parametrize + def test_method_list_with_all_params(self, client: OpenAI) -> None: + step = client.beta.threads.runs.steps.list( + "string", + thread_id="string", + after="string", + before="string", + limit=0, + order="asc", + ) + assert_matches_type(SyncCursorPage[RunStep], step, path=["response"]) + + @parametrize + def test_raw_response_list(self, client: OpenAI) -> None: + response = client.beta.threads.runs.steps.with_raw_response.list( + "string", + thread_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + step = response.parse() + assert_matches_type(SyncCursorPage[RunStep], step, path=["response"]) + + +class TestAsyncSteps: + strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + async def test_method_retrieve(self, client: AsyncOpenAI) -> None: + step = await client.beta.threads.runs.steps.retrieve( + "string", + thread_id="string", + run_id="string", + ) + assert_matches_type(RunStep, step, path=["response"]) + + @parametrize + async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: + response = await client.beta.threads.runs.steps.with_raw_response.retrieve( + "string", + thread_id="string", + run_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + step = response.parse() + assert_matches_type(RunStep, step, path=["response"]) + + @parametrize + async def test_method_list(self, client: AsyncOpenAI) -> None: + step = await client.beta.threads.runs.steps.list( + "string", + thread_id="string", + ) + assert_matches_type(AsyncCursorPage[RunStep], step, path=["response"]) + + @parametrize + async def test_method_list_with_all_params(self, client: AsyncOpenAI) -> None: + step = await client.beta.threads.runs.steps.list( + "string", + thread_id="string", + after="string", + before="string", + limit=0, + order="asc", + ) + assert_matches_type(AsyncCursorPage[RunStep], step, path=["response"]) + + @parametrize + async def test_raw_response_list(self, client: AsyncOpenAI) -> None: + response = await client.beta.threads.runs.steps.with_raw_response.list( + "string", + thread_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + step = response.parse() + assert_matches_type(AsyncCursorPage[RunStep], step, path=["response"]) diff --git a/tests/api_resources/beta/threads/test_messages.py b/tests/api_resources/beta/threads/test_messages.py new file mode 100644 index 0000000000..f3fe7dc2bb --- /dev/null +++ b/tests/api_resources/beta/threads/test_messages.py @@ -0,0 +1,234 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import os + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai._client import OpenAI, AsyncOpenAI +from openai.pagination import SyncCursorPage, AsyncCursorPage +from openai.types.beta.threads import ThreadMessage + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") +api_key = "My API Key" + + +class TestMessages: + strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + def test_method_create(self, client: OpenAI) -> None: + message = client.beta.threads.messages.create( + "string", + content="x", + role="user", + ) + assert_matches_type(ThreadMessage, message, path=["response"]) + + @parametrize + def test_method_create_with_all_params(self, client: OpenAI) -> None: + message = client.beta.threads.messages.create( + "string", + content="x", + role="user", + file_ids=["string"], + metadata={}, + ) + assert_matches_type(ThreadMessage, message, path=["response"]) + + @parametrize + def test_raw_response_create(self, client: OpenAI) -> None: + response = client.beta.threads.messages.with_raw_response.create( + "string", + content="x", + role="user", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + message = response.parse() + assert_matches_type(ThreadMessage, message, path=["response"]) + + @parametrize + def test_method_retrieve(self, client: OpenAI) -> None: + message = client.beta.threads.messages.retrieve( + "string", + thread_id="string", + ) + assert_matches_type(ThreadMessage, message, path=["response"]) + + @parametrize + def test_raw_response_retrieve(self, client: OpenAI) -> None: + response = client.beta.threads.messages.with_raw_response.retrieve( + "string", + thread_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + message = response.parse() + assert_matches_type(ThreadMessage, message, path=["response"]) + + @parametrize + def test_method_update(self, client: OpenAI) -> None: + message = client.beta.threads.messages.update( + "string", + thread_id="string", + ) + assert_matches_type(ThreadMessage, message, path=["response"]) + + @parametrize + def test_method_update_with_all_params(self, client: OpenAI) -> None: + message = client.beta.threads.messages.update( + "string", + thread_id="string", + metadata={}, + ) + assert_matches_type(ThreadMessage, message, path=["response"]) + + @parametrize + def test_raw_response_update(self, client: OpenAI) -> None: + response = client.beta.threads.messages.with_raw_response.update( + "string", + thread_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + message = response.parse() + assert_matches_type(ThreadMessage, message, path=["response"]) + + @parametrize + def test_method_list(self, client: OpenAI) -> None: + message = client.beta.threads.messages.list( + "string", + ) + assert_matches_type(SyncCursorPage[ThreadMessage], message, path=["response"]) + + @parametrize + def test_method_list_with_all_params(self, client: OpenAI) -> None: + message = client.beta.threads.messages.list( + "string", + after="string", + before="string", + limit=0, + order="asc", + ) + assert_matches_type(SyncCursorPage[ThreadMessage], message, path=["response"]) + + @parametrize + def test_raw_response_list(self, client: OpenAI) -> None: + response = client.beta.threads.messages.with_raw_response.list( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + message = response.parse() + assert_matches_type(SyncCursorPage[ThreadMessage], message, path=["response"]) + + +class TestAsyncMessages: + strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + async def test_method_create(self, client: AsyncOpenAI) -> None: + message = await client.beta.threads.messages.create( + "string", + content="x", + role="user", + ) + assert_matches_type(ThreadMessage, message, path=["response"]) + + @parametrize + async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: + message = await client.beta.threads.messages.create( + "string", + content="x", + role="user", + file_ids=["string"], + metadata={}, + ) + assert_matches_type(ThreadMessage, message, path=["response"]) + + @parametrize + async def test_raw_response_create(self, client: AsyncOpenAI) -> None: + response = await client.beta.threads.messages.with_raw_response.create( + "string", + content="x", + role="user", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + message = response.parse() + assert_matches_type(ThreadMessage, message, path=["response"]) + + @parametrize + async def test_method_retrieve(self, client: AsyncOpenAI) -> None: + message = await client.beta.threads.messages.retrieve( + "string", + thread_id="string", + ) + assert_matches_type(ThreadMessage, message, path=["response"]) + + @parametrize + async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: + response = await client.beta.threads.messages.with_raw_response.retrieve( + "string", + thread_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + message = response.parse() + assert_matches_type(ThreadMessage, message, path=["response"]) + + @parametrize + async def test_method_update(self, client: AsyncOpenAI) -> None: + message = await client.beta.threads.messages.update( + "string", + thread_id="string", + ) + assert_matches_type(ThreadMessage, message, path=["response"]) + + @parametrize + async def test_method_update_with_all_params(self, client: AsyncOpenAI) -> None: + message = await client.beta.threads.messages.update( + "string", + thread_id="string", + metadata={}, + ) + assert_matches_type(ThreadMessage, message, path=["response"]) + + @parametrize + async def test_raw_response_update(self, client: AsyncOpenAI) -> None: + response = await client.beta.threads.messages.with_raw_response.update( + "string", + thread_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + message = response.parse() + assert_matches_type(ThreadMessage, message, path=["response"]) + + @parametrize + async def test_method_list(self, client: AsyncOpenAI) -> None: + message = await client.beta.threads.messages.list( + "string", + ) + assert_matches_type(AsyncCursorPage[ThreadMessage], message, path=["response"]) + + @parametrize + async def test_method_list_with_all_params(self, client: AsyncOpenAI) -> None: + message = await client.beta.threads.messages.list( + "string", + after="string", + before="string", + limit=0, + order="asc", + ) + assert_matches_type(AsyncCursorPage[ThreadMessage], message, path=["response"]) + + @parametrize + async def test_raw_response_list(self, client: AsyncOpenAI) -> None: + response = await client.beta.threads.messages.with_raw_response.list( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + message = response.parse() + assert_matches_type(AsyncCursorPage[ThreadMessage], message, path=["response"]) diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py new file mode 100644 index 0000000000..d323dfc354 --- /dev/null +++ b/tests/api_resources/beta/threads/test_runs.py @@ -0,0 +1,308 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +import os + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai._client import OpenAI, AsyncOpenAI +from openai.pagination import SyncCursorPage, AsyncCursorPage +from openai.types.beta.threads import Run + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") +api_key = "My API Key" + + +class TestRuns: + strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + def test_method_create(self, client: OpenAI) -> None: + run = client.beta.threads.runs.create( + "string", + assistant_id="string", + ) + assert_matches_type(Run, run, path=["response"]) + + @parametrize + def test_method_create_with_all_params(self, client: OpenAI) -> None: + run = client.beta.threads.runs.create( + "string", + assistant_id="string", + instructions="string", + metadata={}, + model="string", + tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + ) + assert_matches_type(Run, run, path=["response"]) + + @parametrize + def test_raw_response_create(self, client: OpenAI) -> None: + response = client.beta.threads.runs.with_raw_response.create( + "string", + assistant_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + run = response.parse() + assert_matches_type(Run, run, path=["response"]) + + @parametrize + def test_method_retrieve(self, client: OpenAI) -> None: + run = client.beta.threads.runs.retrieve( + "string", + thread_id="string", + ) + assert_matches_type(Run, run, path=["response"]) + + @parametrize + def test_raw_response_retrieve(self, client: OpenAI) -> None: + response = client.beta.threads.runs.with_raw_response.retrieve( + "string", + thread_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + run = response.parse() + assert_matches_type(Run, run, path=["response"]) + + @parametrize + def test_method_update(self, client: OpenAI) -> None: + run = client.beta.threads.runs.update( + "string", + thread_id="string", + ) + assert_matches_type(Run, run, path=["response"]) + + @parametrize + def test_method_update_with_all_params(self, client: OpenAI) -> None: + run = client.beta.threads.runs.update( + "string", + thread_id="string", + metadata={}, + ) + assert_matches_type(Run, run, path=["response"]) + + @parametrize + def test_raw_response_update(self, client: OpenAI) -> None: + response = client.beta.threads.runs.with_raw_response.update( + "string", + thread_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + run = response.parse() + assert_matches_type(Run, run, path=["response"]) + + @parametrize + def test_method_list(self, client: OpenAI) -> None: + run = client.beta.threads.runs.list( + "string", + ) + assert_matches_type(SyncCursorPage[Run], run, path=["response"]) + + @parametrize + def test_method_list_with_all_params(self, client: OpenAI) -> None: + run = client.beta.threads.runs.list( + "string", + after="string", + before="string", + limit=0, + order="asc", + ) + assert_matches_type(SyncCursorPage[Run], run, path=["response"]) + + @parametrize + def test_raw_response_list(self, client: OpenAI) -> None: + response = client.beta.threads.runs.with_raw_response.list( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + run = response.parse() + assert_matches_type(SyncCursorPage[Run], run, path=["response"]) + + @parametrize + def test_method_cancel(self, client: OpenAI) -> None: + run = client.beta.threads.runs.cancel( + "string", + thread_id="string", + ) + assert_matches_type(Run, run, path=["response"]) + + @parametrize + def test_raw_response_cancel(self, client: OpenAI) -> None: + response = client.beta.threads.runs.with_raw_response.cancel( + "string", + thread_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + run = response.parse() + assert_matches_type(Run, run, path=["response"]) + + @parametrize + def test_method_submit_tool_outputs(self, client: OpenAI) -> None: + run = client.beta.threads.runs.submit_tool_outputs( + "string", + thread_id="string", + tool_outputs=[{}, {}, {}], + ) + assert_matches_type(Run, run, path=["response"]) + + @parametrize + def test_raw_response_submit_tool_outputs(self, client: OpenAI) -> None: + response = client.beta.threads.runs.with_raw_response.submit_tool_outputs( + "string", + thread_id="string", + tool_outputs=[{}, {}, {}], + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + run = response.parse() + assert_matches_type(Run, run, path=["response"]) + + +class TestAsyncRuns: + strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) + loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) + parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + + @parametrize + async def test_method_create(self, client: AsyncOpenAI) -> None: + run = await client.beta.threads.runs.create( + "string", + assistant_id="string", + ) + assert_matches_type(Run, run, path=["response"]) + + @parametrize + async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: + run = await client.beta.threads.runs.create( + "string", + assistant_id="string", + instructions="string", + metadata={}, + model="string", + tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + ) + assert_matches_type(Run, run, path=["response"]) + + @parametrize + async def test_raw_response_create(self, client: AsyncOpenAI) -> None: + response = await client.beta.threads.runs.with_raw_response.create( + "string", + assistant_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + run = response.parse() + assert_matches_type(Run, run, path=["response"]) + + @parametrize + async def test_method_retrieve(self, client: AsyncOpenAI) -> None: + run = await client.beta.threads.runs.retrieve( + "string", + thread_id="string", + ) + assert_matches_type(Run, run, path=["response"]) + + @parametrize + async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: + response = await client.beta.threads.runs.with_raw_response.retrieve( + "string", + thread_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + run = response.parse() + assert_matches_type(Run, run, path=["response"]) + + @parametrize + async def test_method_update(self, client: AsyncOpenAI) -> None: + run = await client.beta.threads.runs.update( + "string", + thread_id="string", + ) + assert_matches_type(Run, run, path=["response"]) + + @parametrize + async def test_method_update_with_all_params(self, client: AsyncOpenAI) -> None: + run = await client.beta.threads.runs.update( + "string", + thread_id="string", + metadata={}, + ) + assert_matches_type(Run, run, path=["response"]) + + @parametrize + async def test_raw_response_update(self, client: AsyncOpenAI) -> None: + response = await client.beta.threads.runs.with_raw_response.update( + "string", + thread_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + run = response.parse() + assert_matches_type(Run, run, path=["response"]) + + @parametrize + async def test_method_list(self, client: AsyncOpenAI) -> None: + run = await client.beta.threads.runs.list( + "string", + ) + assert_matches_type(AsyncCursorPage[Run], run, path=["response"]) + + @parametrize + async def test_method_list_with_all_params(self, client: AsyncOpenAI) -> None: + run = await client.beta.threads.runs.list( + "string", + after="string", + before="string", + limit=0, + order="asc", + ) + assert_matches_type(AsyncCursorPage[Run], run, path=["response"]) + + @parametrize + async def test_raw_response_list(self, client: AsyncOpenAI) -> None: + response = await client.beta.threads.runs.with_raw_response.list( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + run = response.parse() + assert_matches_type(AsyncCursorPage[Run], run, path=["response"]) + + @parametrize + async def test_method_cancel(self, client: AsyncOpenAI) -> None: + run = await client.beta.threads.runs.cancel( + "string", + thread_id="string", + ) + assert_matches_type(Run, run, path=["response"]) + + @parametrize + async def test_raw_response_cancel(self, client: AsyncOpenAI) -> None: + response = await client.beta.threads.runs.with_raw_response.cancel( + "string", + thread_id="string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + run = response.parse() + assert_matches_type(Run, run, path=["response"]) + + @parametrize + async def test_method_submit_tool_outputs(self, client: AsyncOpenAI) -> None: + run = await client.beta.threads.runs.submit_tool_outputs( + "string", + thread_id="string", + tool_outputs=[{}, {}, {}], + ) + assert_matches_type(Run, run, path=["response"]) + + @parametrize + async def test_raw_response_submit_tool_outputs(self, client: AsyncOpenAI) -> None: + response = await client.beta.threads.runs.with_raw_response.submit_tool_outputs( + "string", + thread_id="string", + tool_outputs=[{}, {}, {}], + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + run = response.parse() + assert_matches_type(Run, run, path=["response"]) diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index dacf5d2596..132e00039b 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -39,11 +39,6 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: messages=[ { "content": "string", - "function_call": { - "arguments": "string", - "name": "string", - }, - "name": "string", "role": "system", } ], @@ -61,9 +56,38 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: max_tokens=0, n=1, presence_penalty=-2, + response_format={"type": "json_object"}, + seed=-9223372036854776000, stop="string", stream=False, temperature=1, + tool_choice="none", + tools=[ + { + "type": "function", + "function": { + "description": "string", + "name": "string", + "parameters": {"foo": "bar"}, + }, + }, + { + "type": "function", + "function": { + "description": "string", + "name": "string", + "parameters": {"foo": "bar"}, + }, + }, + { + "type": "function", + "function": { + "description": "string", + "name": "string", + "parameters": {"foo": "bar"}, + }, + }, + ], top_p=1, user="user-1234", ) @@ -103,11 +127,6 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: messages=[ { "content": "string", - "function_call": { - "arguments": "string", - "name": "string", - }, - "name": "string", "role": "system", } ], @@ -126,8 +145,37 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: max_tokens=0, n=1, presence_penalty=-2, + response_format={"type": "json_object"}, + seed=-9223372036854776000, stop="string", temperature=1, + tool_choice="none", + tools=[ + { + "type": "function", + "function": { + "description": "string", + "name": "string", + "parameters": {"foo": "bar"}, + }, + }, + { + "type": "function", + "function": { + "description": "string", + "name": "string", + "parameters": {"foo": "bar"}, + }, + }, + { + "type": "function", + "function": { + "description": "string", + "name": "string", + "parameters": {"foo": "bar"}, + }, + }, + ], top_p=1, user="user-1234", ) @@ -172,11 +220,6 @@ async def test_method_create_with_all_params_overload_1(self, client: AsyncOpenA messages=[ { "content": "string", - "function_call": { - "arguments": "string", - "name": "string", - }, - "name": "string", "role": "system", } ], @@ -194,9 +237,38 @@ async def test_method_create_with_all_params_overload_1(self, client: AsyncOpenA max_tokens=0, n=1, presence_penalty=-2, + response_format={"type": "json_object"}, + seed=-9223372036854776000, stop="string", stream=False, temperature=1, + tool_choice="none", + tools=[ + { + "type": "function", + "function": { + "description": "string", + "name": "string", + "parameters": {"foo": "bar"}, + }, + }, + { + "type": "function", + "function": { + "description": "string", + "name": "string", + "parameters": {"foo": "bar"}, + }, + }, + { + "type": "function", + "function": { + "description": "string", + "name": "string", + "parameters": {"foo": "bar"}, + }, + }, + ], top_p=1, user="user-1234", ) @@ -236,11 +308,6 @@ async def test_method_create_with_all_params_overload_2(self, client: AsyncOpenA messages=[ { "content": "string", - "function_call": { - "arguments": "string", - "name": "string", - }, - "name": "string", "role": "system", } ], @@ -259,8 +326,37 @@ async def test_method_create_with_all_params_overload_2(self, client: AsyncOpenA max_tokens=0, n=1, presence_penalty=-2, + response_format={"type": "json_object"}, + seed=-9223372036854776000, stop="string", temperature=1, + tool_choice="none", + tools=[ + { + "type": "function", + "function": { + "description": "string", + "name": "string", + "parameters": {"foo": "bar"}, + }, + }, + { + "type": "function", + "function": { + "description": "string", + "name": "string", + "parameters": {"foo": "bar"}, + }, + }, + { + "type": "function", + "function": { + "description": "string", + "name": "string", + "parameters": {"foo": "bar"}, + }, + }, + ], top_p=1, user="user-1234", ) diff --git a/tests/api_resources/fine_tuning/test_jobs.py b/tests/api_resources/fine_tuning/test_jobs.py index 9defcadab6..5716a23d54 100644 --- a/tests/api_resources/fine_tuning/test_jobs.py +++ b/tests/api_resources/fine_tuning/test_jobs.py @@ -34,7 +34,11 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: job = client.fine_tuning.jobs.create( model="gpt-3.5-turbo", training_file="file-abc123", - hyperparameters={"n_epochs": "auto"}, + hyperparameters={ + "batch_size": "auto", + "learning_rate_multiplier": "auto", + "n_epochs": "auto", + }, suffix="x", validation_file="file-abc123", ) @@ -146,7 +150,11 @@ async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: job = await client.fine_tuning.jobs.create( model="gpt-3.5-turbo", training_file="file-abc123", - hyperparameters={"n_epochs": "auto"}, + hyperparameters={ + "batch_size": "auto", + "learning_rate_multiplier": "auto", + "n_epochs": "auto", + }, suffix="x", validation_file="file-abc123", ) diff --git a/tests/api_resources/test_completions.py b/tests/api_resources/test_completions.py index 7b48e88ed2..b12fd6401e 100644 --- a/tests/api_resources/test_completions.py +++ b/tests/api_resources/test_completions.py @@ -41,6 +41,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: max_tokens=16, n=1, presence_penalty=-2, + seed=-9223372036854776000, stop="\n", stream=False, suffix="test.", @@ -82,6 +83,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: max_tokens=16, n=1, presence_penalty=-2, + seed=-9223372036854776000, stop="\n", suffix="test.", temperature=1, @@ -126,6 +128,7 @@ async def test_method_create_with_all_params_overload_1(self, client: AsyncOpenA max_tokens=16, n=1, presence_penalty=-2, + seed=-9223372036854776000, stop="\n", stream=False, suffix="test.", @@ -167,6 +170,7 @@ async def test_method_create_with_all_params_overload_2(self, client: AsyncOpenA max_tokens=16, n=1, presence_penalty=-2, + seed=-9223372036854776000, stop="\n", suffix="test.", temperature=1, diff --git a/tests/api_resources/test_files.py b/tests/api_resources/test_files.py index 389763586e..d668c2d0c7 100644 --- a/tests/api_resources/test_files.py +++ b/tests/api_resources/test_files.py @@ -25,7 +25,7 @@ class TestFiles: def test_method_create(self, client: OpenAI) -> None: file = client.files.create( file=b"raw file contents", - purpose="string", + purpose="fine-tune", ) assert_matches_type(FileObject, file, path=["response"]) @@ -33,7 +33,7 @@ def test_method_create(self, client: OpenAI) -> None: def test_raw_response_create(self, client: OpenAI) -> None: response = client.files.with_raw_response.create( file=b"raw file contents", - purpose="string", + purpose="fine-tune", ) assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() @@ -60,6 +60,13 @@ def test_method_list(self, client: OpenAI) -> None: file = client.files.list() assert_matches_type(SyncPage[FileObject], file, path=["response"]) + @parametrize + def test_method_list_with_all_params(self, client: OpenAI) -> None: + file = client.files.list( + purpose="string", + ) + assert_matches_type(SyncPage[FileObject], file, path=["response"]) + @parametrize def test_raw_response_list(self, client: OpenAI) -> None: response = client.files.with_raw_response.list() @@ -109,7 +116,7 @@ class TestAsyncFiles: async def test_method_create(self, client: AsyncOpenAI) -> None: file = await client.files.create( file=b"raw file contents", - purpose="string", + purpose="fine-tune", ) assert_matches_type(FileObject, file, path=["response"]) @@ -117,7 +124,7 @@ async def test_method_create(self, client: AsyncOpenAI) -> None: async def test_raw_response_create(self, client: AsyncOpenAI) -> None: response = await client.files.with_raw_response.create( file=b"raw file contents", - purpose="string", + purpose="fine-tune", ) assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() @@ -144,6 +151,13 @@ async def test_method_list(self, client: AsyncOpenAI) -> None: file = await client.files.list() assert_matches_type(AsyncPage[FileObject], file, path=["response"]) + @parametrize + async def test_method_list_with_all_params(self, client: AsyncOpenAI) -> None: + file = await client.files.list( + purpose="string", + ) + assert_matches_type(AsyncPage[FileObject], file, path=["response"]) + @parametrize async def test_raw_response_list(self, client: AsyncOpenAI) -> None: response = await client.files.with_raw_response.list() diff --git a/tests/api_resources/test_images.py b/tests/api_resources/test_images.py index fa7fb6d533..c7f5e5bcd2 100644 --- a/tests/api_resources/test_images.py +++ b/tests/api_resources/test_images.py @@ -31,6 +31,7 @@ def test_method_create_variation(self, client: OpenAI) -> None: def test_method_create_variation_with_all_params(self, client: OpenAI) -> None: image = client.images.create_variation( image=b"raw file contents", + model="dall-e-2", n=1, response_format="url", size="1024x1024", @@ -61,6 +62,7 @@ def test_method_edit_with_all_params(self, client: OpenAI) -> None: image=b"raw file contents", prompt="A cute baby sea otter wearing a beret", mask=b"raw file contents", + model="dall-e-2", n=1, response_format="url", size="1024x1024", @@ -89,9 +91,12 @@ def test_method_generate(self, client: OpenAI) -> None: def test_method_generate_with_all_params(self, client: OpenAI) -> None: image = client.images.generate( prompt="A cute baby sea otter", + model="dall-e-3", n=1, + quality="standard", response_format="url", size="1024x1024", + style="vivid", user="user-1234", ) assert_matches_type(ImagesResponse, image, path=["response"]) @@ -122,6 +127,7 @@ async def test_method_create_variation(self, client: AsyncOpenAI) -> None: async def test_method_create_variation_with_all_params(self, client: AsyncOpenAI) -> None: image = await client.images.create_variation( image=b"raw file contents", + model="dall-e-2", n=1, response_format="url", size="1024x1024", @@ -152,6 +158,7 @@ async def test_method_edit_with_all_params(self, client: AsyncOpenAI) -> None: image=b"raw file contents", prompt="A cute baby sea otter wearing a beret", mask=b"raw file contents", + model="dall-e-2", n=1, response_format="url", size="1024x1024", @@ -180,9 +187,12 @@ async def test_method_generate(self, client: AsyncOpenAI) -> None: async def test_method_generate_with_all_params(self, client: AsyncOpenAI) -> None: image = await client.images.generate( prompt="A cute baby sea otter", + model="dall-e-3", n=1, + quality="standard", response_format="url", size="1024x1024", + style="vivid", user="user-1234", ) assert_matches_type(ImagesResponse, image, path=["response"]) From 7db6d5644b6ea3ff22ba3c391bbbe05f2b9ebafa Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 6 Nov 2023 21:52:18 +0000 Subject: [PATCH 063/816] v1.1.1 (#689) * feat(client): support passing httpx.Timeout to method timeout argument * fix(api): retreival -> retrieval * fix(docs): use correct branch name in github links * v1.1.1 --- README.md | 2 +- pyproject.toml | 2 +- src/openai/_base_client.py | 2 +- src/openai/_files.py | 2 +- src/openai/_version.py | 2 +- src/openai/resources/audio/speech.py | 6 ++-- src/openai/resources/audio/transcriptions.py | 6 ++-- src/openai/resources/audio/translations.py | 6 ++-- .../resources/beta/assistants/assistants.py | 22 ++++++------ src/openai/resources/beta/assistants/files.py | 18 +++++----- .../resources/beta/threads/messages/files.py | 10 +++--- .../beta/threads/messages/messages.py | 18 +++++----- .../resources/beta/threads/runs/runs.py | 26 +++++++------- .../resources/beta/threads/runs/steps.py | 10 +++--- src/openai/resources/beta/threads/threads.py | 22 ++++++------ src/openai/resources/chat/completions.py | 18 +++++----- src/openai/resources/completions.py | 18 +++++----- src/openai/resources/edits.py | 6 ++-- src/openai/resources/embeddings.py | 6 ++-- src/openai/resources/files.py | 22 ++++++------ src/openai/resources/fine_tunes.py | 34 ++++++++++--------- src/openai/resources/fine_tuning/jobs.py | 22 ++++++------ src/openai/resources/images.py | 14 ++++---- src/openai/resources/models.py | 14 ++++---- src/openai/resources/moderations.py | 6 ++-- src/openai/types/beta/assistant.py | 10 +++--- .../types/beta/assistant_create_params.py | 4 +-- .../types/beta/assistant_update_params.py | 4 +-- .../beta/thread_create_and_run_params.py | 4 +-- src/openai/types/beta/threads/run.py | 4 +-- .../types/beta/threads/run_create_params.py | 4 +-- 31 files changed, 192 insertions(+), 152 deletions(-) diff --git a/README.md b/README.md index 821ecf1ecf..8904d9ed52 100644 --- a/README.md +++ b/README.md @@ -410,7 +410,7 @@ completion = response.parse() # get the object that `chat.completions.create()` print(completion) ``` -These methods return an [`APIResponse`](https://github.com/openai/openai-python/tree/v1/src/openai/_response.py) object. +These methods return an [`APIResponse`](https://github.com/openai/openai-python/src/openai/_response.py) object. ### Configuring the HTTP client diff --git a/pyproject.toml b/pyproject.toml index 9ab62e23fc..c5dd666475 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.1.0" +version = "1.1.1" description = "Client library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 22f90050d7..e37759cdf8 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -1537,7 +1537,7 @@ def make_request_options( extra_query: Query | None = None, extra_body: Body | None = None, idempotency_key: str | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, post_parser: PostParser | NotGiven = NOT_GIVEN, ) -> RequestOptions: """Create a dict of type RequestOptions without keys of NotGiven values.""" diff --git a/src/openai/_files.py b/src/openai/_files.py index 49e3536243..94cd553135 100644 --- a/src/openai/_files.py +++ b/src/openai/_files.py @@ -29,7 +29,7 @@ def assert_is_file_content(obj: object, *, key: str | None = None) -> None: if not is_file_content(obj): prefix = f"Expected entry at `{key}`" if key is not None else f"Expected file input `{obj!r}`" raise RuntimeError( - f"{prefix} to be bytes, an io.IOBase instance, PathLike or a tuple but received {type(obj)} instead. See https://github.com/openai/openai-python/tree/v1#file-uploads" + f"{prefix} to be bytes, an io.IOBase instance, PathLike or a tuple but received {type(obj)} instead. See https://github.com/openai/openai-python#file-uploads" ) from None diff --git a/src/openai/_version.py b/src/openai/_version.py index 57548ed376..b4ed828270 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.1.0" +__version__ = "1.1.1" diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index 7318e3a2e4..458843866f 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -5,6 +5,8 @@ from typing import TYPE_CHECKING, Union from typing_extensions import Literal +import httpx + from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ..._utils import maybe_transform from ..._resource import SyncAPIResource, AsyncAPIResource @@ -38,7 +40,7 @@ def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> HttpxBinaryResponseContent: """ Generates audio from the input text. @@ -105,7 +107,7 @@ async def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> HttpxBinaryResponseContent: """ Generates audio from the input text. diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index 44d973d0af..d2b4452411 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -5,6 +5,8 @@ from typing import TYPE_CHECKING, Union, Mapping, cast from typing_extensions import Literal +import httpx + from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from ..._utils import extract_files, maybe_transform, deepcopy_minimal from ..._resource import SyncAPIResource, AsyncAPIResource @@ -39,7 +41,7 @@ def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Transcription: """ Transcribes audio into the input language. @@ -126,7 +128,7 @@ async def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Transcription: """ Transcribes audio into the input language. diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index bb37c691fc..fe7f7f2a40 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -5,6 +5,8 @@ from typing import TYPE_CHECKING, Union, Mapping, cast from typing_extensions import Literal +import httpx + from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from ..._utils import extract_files, maybe_transform, deepcopy_minimal from ..._resource import SyncAPIResource, AsyncAPIResource @@ -38,7 +40,7 @@ def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Translation: """ Translates audio into English. @@ -118,7 +120,7 @@ async def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Translation: """ Translates audio into English. diff --git a/src/openai/resources/beta/assistants/assistants.py b/src/openai/resources/beta/assistants/assistants.py index 03f2759fc2..6b81dc97f3 100644 --- a/src/openai/resources/beta/assistants/assistants.py +++ b/src/openai/resources/beta/assistants/assistants.py @@ -5,6 +5,8 @@ from typing import TYPE_CHECKING, List, Optional from typing_extensions import Literal +import httpx + from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ...._utils import maybe_transform @@ -50,7 +52,7 @@ def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Assistant: """ Create an assistant with a model and instructions. @@ -119,7 +121,7 @@ def retrieve( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Assistant: """ Retrieves an assistant. @@ -158,7 +160,7 @@ def update( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Assistant: """Modifies an assistant. @@ -233,7 +235,7 @@ def list( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> SyncCursorPage[Assistant]: """Returns a list of assistants. @@ -295,7 +297,7 @@ def delete( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AsssitantDeleted: """ Delete an assistant. @@ -343,7 +345,7 @@ async def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Assistant: """ Create an assistant with a model and instructions. @@ -412,7 +414,7 @@ async def retrieve( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Assistant: """ Retrieves an assistant. @@ -451,7 +453,7 @@ async def update( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Assistant: """Modifies an assistant. @@ -526,7 +528,7 @@ def list( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AsyncPaginator[Assistant, AsyncCursorPage[Assistant]]: """Returns a list of assistants. @@ -588,7 +590,7 @@ async def delete( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AsssitantDeleted: """ Delete an assistant. diff --git a/src/openai/resources/beta/assistants/files.py b/src/openai/resources/beta/assistants/files.py index b1953525e8..5ac5897ca3 100644 --- a/src/openai/resources/beta/assistants/files.py +++ b/src/openai/resources/beta/assistants/files.py @@ -5,6 +5,8 @@ from typing import TYPE_CHECKING from typing_extensions import Literal +import httpx + from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ...._utils import maybe_transform from ...._resource import SyncAPIResource, AsyncAPIResource @@ -41,7 +43,7 @@ def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AssistantFile: """ Create an assistant file by attaching a @@ -81,7 +83,7 @@ def retrieve( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AssistantFile: """ Retrieves an AssistantFile. @@ -117,7 +119,7 @@ def list( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> SyncCursorPage[AssistantFile]: """ Returns a list of assistant files. @@ -179,7 +181,7 @@ def delete( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> FileDeleteResponse: """ Delete an assistant file. @@ -220,7 +222,7 @@ async def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AssistantFile: """ Create an assistant file by attaching a @@ -260,7 +262,7 @@ async def retrieve( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AssistantFile: """ Retrieves an AssistantFile. @@ -296,7 +298,7 @@ def list( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AsyncPaginator[AssistantFile, AsyncCursorPage[AssistantFile]]: """ Returns a list of assistant files. @@ -358,7 +360,7 @@ async def delete( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> FileDeleteResponse: """ Delete an assistant file. diff --git a/src/openai/resources/beta/threads/messages/files.py b/src/openai/resources/beta/threads/messages/files.py index 70166eb7b2..e028a6fda7 100644 --- a/src/openai/resources/beta/threads/messages/files.py +++ b/src/openai/resources/beta/threads/messages/files.py @@ -5,6 +5,8 @@ from typing import TYPE_CHECKING from typing_extensions import Literal +import httpx + from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import maybe_transform from ....._resource import SyncAPIResource, AsyncAPIResource @@ -37,7 +39,7 @@ def retrieve( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> MessageFile: """ Retrieves a message file. @@ -74,7 +76,7 @@ def list( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> SyncCursorPage[MessageFile]: """Returns a list of message files. @@ -146,7 +148,7 @@ async def retrieve( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> MessageFile: """ Retrieves a message file. @@ -183,7 +185,7 @@ def list( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AsyncPaginator[MessageFile, AsyncCursorPage[MessageFile]]: """Returns a list of message files. diff --git a/src/openai/resources/beta/threads/messages/messages.py b/src/openai/resources/beta/threads/messages/messages.py index caec03f484..30ae072512 100644 --- a/src/openai/resources/beta/threads/messages/messages.py +++ b/src/openai/resources/beta/threads/messages/messages.py @@ -5,6 +5,8 @@ from typing import TYPE_CHECKING, List, Optional from typing_extensions import Literal +import httpx + from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import maybe_transform @@ -47,7 +49,7 @@ def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ThreadMessage: """ Create a message. @@ -104,7 +106,7 @@ def retrieve( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ThreadMessage: """ Retrieve a message. @@ -138,7 +140,7 @@ def update( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ThreadMessage: """ Modifies a message. @@ -180,7 +182,7 @@ def list( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> SyncCursorPage[ThreadMessage]: """ Returns a list of messages for a given thread. @@ -255,7 +257,7 @@ async def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ThreadMessage: """ Create a message. @@ -312,7 +314,7 @@ async def retrieve( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ThreadMessage: """ Retrieve a message. @@ -346,7 +348,7 @@ async def update( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ThreadMessage: """ Modifies a message. @@ -388,7 +390,7 @@ def list( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AsyncPaginator[ThreadMessage, AsyncCursorPage[ThreadMessage]]: """ Returns a list of messages for a given thread. diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 370056cbf4..969bfab70a 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -5,6 +5,8 @@ from typing import TYPE_CHECKING, List, Optional from typing_extensions import Literal +import httpx + from .steps import Steps, AsyncSteps, StepsWithRawResponse, AsyncStepsWithRawResponse from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import maybe_transform @@ -49,7 +51,7 @@ def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Run: """ Create a run. @@ -112,7 +114,7 @@ def retrieve( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Run: """ Retrieves a run. @@ -146,7 +148,7 @@ def update( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Run: """ Modifies a run. @@ -188,7 +190,7 @@ def list( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> SyncCursorPage[Run]: """ Returns a list of runs belonging to a thread. @@ -250,7 +252,7 @@ def cancel( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Run: """ Cancels a run that is `in_progress`. @@ -284,7 +286,7 @@ def submit_tool_outputs( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Run: """ When a run has the `status: "requires_action"` and `required_action.type` is @@ -339,7 +341,7 @@ async def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Run: """ Create a run. @@ -402,7 +404,7 @@ async def retrieve( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Run: """ Retrieves a run. @@ -436,7 +438,7 @@ async def update( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Run: """ Modifies a run. @@ -478,7 +480,7 @@ def list( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AsyncPaginator[Run, AsyncCursorPage[Run]]: """ Returns a list of runs belonging to a thread. @@ -540,7 +542,7 @@ async def cancel( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Run: """ Cancels a run that is `in_progress`. @@ -574,7 +576,7 @@ async def submit_tool_outputs( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Run: """ When a run has the `status: "requires_action"` and `required_action.type` is diff --git a/src/openai/resources/beta/threads/runs/steps.py b/src/openai/resources/beta/threads/runs/steps.py index bc6fd7fdc9..4fcc87a0ff 100644 --- a/src/openai/resources/beta/threads/runs/steps.py +++ b/src/openai/resources/beta/threads/runs/steps.py @@ -5,6 +5,8 @@ from typing import TYPE_CHECKING from typing_extensions import Literal +import httpx + from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import maybe_transform from ....._resource import SyncAPIResource, AsyncAPIResource @@ -37,7 +39,7 @@ def retrieve( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> RunStep: """ Retrieves a run step. @@ -74,7 +76,7 @@ def list( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> SyncCursorPage[RunStep]: """ Returns a list of run steps belonging to a run. @@ -145,7 +147,7 @@ async def retrieve( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> RunStep: """ Retrieves a run step. @@ -182,7 +184,7 @@ def list( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AsyncPaginator[RunStep, AsyncCursorPage[RunStep]]: """ Returns a list of run steps belonging to a run. diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 286630d81c..9469fc0513 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -4,6 +4,8 @@ from typing import TYPE_CHECKING, List, Optional +import httpx + from .runs import Runs, AsyncRuns, RunsWithRawResponse, AsyncRunsWithRawResponse from .messages import ( Messages, @@ -52,7 +54,7 @@ def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Thread: """ Create a thread. @@ -99,7 +101,7 @@ def retrieve( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Thread: """ Retrieves a thread. @@ -132,7 +134,7 @@ def update( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Thread: """ Modifies a thread. @@ -170,7 +172,7 @@ def delete( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ThreadDeleted: """ Delete a thread. @@ -207,7 +209,7 @@ def create_and_run( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Run: """ Create a thread and run it in one request. @@ -285,7 +287,7 @@ async def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Thread: """ Create a thread. @@ -332,7 +334,7 @@ async def retrieve( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Thread: """ Retrieves a thread. @@ -365,7 +367,7 @@ async def update( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Thread: """ Modifies a thread. @@ -403,7 +405,7 @@ async def delete( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ThreadDeleted: """ Delete a thread. @@ -440,7 +442,7 @@ async def create_and_run( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Run: """ Create a thread and run it in one request. diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index 2ecde23ce1..a46e7e70d6 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -5,6 +5,8 @@ from typing import TYPE_CHECKING, Dict, List, Union, Optional, overload from typing_extensions import Literal +import httpx + from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ..._utils import required_args, maybe_transform from ..._resource import SyncAPIResource, AsyncAPIResource @@ -75,7 +77,7 @@ def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ChatCompletion: """ Creates a model response for the given chat conversation. @@ -233,7 +235,7 @@ def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Stream[ChatCompletionChunk]: """ Creates a model response for the given chat conversation. @@ -391,7 +393,7 @@ def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ChatCompletion | Stream[ChatCompletionChunk]: """ Creates a model response for the given chat conversation. @@ -549,7 +551,7 @@ def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ChatCompletion | Stream[ChatCompletionChunk]: return self._post( "/chat/completions", @@ -634,7 +636,7 @@ async def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ChatCompletion: """ Creates a model response for the given chat conversation. @@ -792,7 +794,7 @@ async def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AsyncStream[ChatCompletionChunk]: """ Creates a model response for the given chat conversation. @@ -950,7 +952,7 @@ async def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ChatCompletion | AsyncStream[ChatCompletionChunk]: """ Creates a model response for the given chat conversation. @@ -1108,7 +1110,7 @@ async def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ChatCompletion | AsyncStream[ChatCompletionChunk]: return await self._post( "/chat/completions", diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index f1a938ba9a..baf6f04fef 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -5,6 +5,8 @@ from typing import TYPE_CHECKING, Dict, List, Union, Optional, overload from typing_extensions import Literal +import httpx + from ..types import Completion, completion_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import required_args, maybe_transform @@ -66,7 +68,7 @@ def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Completion: """ Creates a completion for the provided prompt and parameters. @@ -228,7 +230,7 @@ def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Stream[Completion]: """ Creates a completion for the provided prompt and parameters. @@ -390,7 +392,7 @@ def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Completion | Stream[Completion]: """ Creates a completion for the provided prompt and parameters. @@ -552,7 +554,7 @@ def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Completion | Stream[Completion]: return self._post( "/completions", @@ -634,7 +636,7 @@ async def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Completion: """ Creates a completion for the provided prompt and parameters. @@ -796,7 +798,7 @@ async def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AsyncStream[Completion]: """ Creates a completion for the provided prompt and parameters. @@ -958,7 +960,7 @@ async def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Completion | AsyncStream[Completion]: """ Creates a completion for the provided prompt and parameters. @@ -1120,7 +1122,7 @@ async def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Completion | AsyncStream[Completion]: return await self._post( "/completions", diff --git a/src/openai/resources/edits.py b/src/openai/resources/edits.py index 5c114c915f..eafaa82fdf 100644 --- a/src/openai/resources/edits.py +++ b/src/openai/resources/edits.py @@ -6,6 +6,8 @@ from typing import TYPE_CHECKING, Union, Optional from typing_extensions import Literal +import httpx + from ..types import Edit, edit_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import maybe_transform @@ -43,7 +45,7 @@ def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Edit: """ Creates a new edit for the provided input, instruction, and parameters. @@ -122,7 +124,7 @@ async def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Edit: """ Creates a new edit for the provided input, instruction, and parameters. diff --git a/src/openai/resources/embeddings.py b/src/openai/resources/embeddings.py index dd540fc796..c31ad9d931 100644 --- a/src/openai/resources/embeddings.py +++ b/src/openai/resources/embeddings.py @@ -6,6 +6,8 @@ from typing import TYPE_CHECKING, List, Union, cast from typing_extensions import Literal +import httpx + from ..types import CreateEmbeddingResponse, embedding_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import is_given, maybe_transform @@ -40,7 +42,7 @@ def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> CreateEmbeddingResponse: """ Creates an embedding vector representing the input text. @@ -133,7 +135,7 @@ async def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> CreateEmbeddingResponse: """ Creates an embedding vector representing the input text. diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index 16d3944a12..b317845c3a 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -6,6 +6,8 @@ from typing import TYPE_CHECKING, Mapping, cast from typing_extensions import Literal +import httpx + from ..types import FileObject, FileDeleted, file_list_params, file_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from .._utils import extract_files, maybe_transform, deepcopy_minimal @@ -37,7 +39,7 @@ def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> FileObject: """Upload a file that can be used across various endpoints/features. @@ -104,7 +106,7 @@ def retrieve( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> FileObject: """ Returns information about a specific file. @@ -135,7 +137,7 @@ def list( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> SyncPage[FileObject]: """ Returns a list of files that belong to the user's organization. @@ -173,7 +175,7 @@ def delete( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> FileDeleted: """ Delete a file. @@ -204,7 +206,7 @@ def retrieve_content( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> str: """ Returns the contents of the specified file. @@ -268,7 +270,7 @@ async def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> FileObject: """Upload a file that can be used across various endpoints/features. @@ -335,7 +337,7 @@ async def retrieve( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> FileObject: """ Returns information about a specific file. @@ -366,7 +368,7 @@ def list( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AsyncPaginator[FileObject, AsyncPage[FileObject]]: """ Returns a list of files that belong to the user's organization. @@ -404,7 +406,7 @@ async def delete( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> FileDeleted: """ Delete a file. @@ -435,7 +437,7 @@ async def retrieve_content( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> str: """ Returns the contents of the specified file. diff --git a/src/openai/resources/fine_tunes.py b/src/openai/resources/fine_tunes.py index 28f4225102..91c8201cbb 100644 --- a/src/openai/resources/fine_tunes.py +++ b/src/openai/resources/fine_tunes.py @@ -5,6 +5,8 @@ from typing import TYPE_CHECKING, List, Union, Optional, overload from typing_extensions import Literal +import httpx + from ..types import ( FineTune, FineTuneEvent, @@ -53,7 +55,7 @@ def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> FineTune: """ Creates a job that fine-tunes a specified model from a given dataset. @@ -197,7 +199,7 @@ def retrieve( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> FineTune: """ Gets info about the fine-tune job. @@ -229,7 +231,7 @@ def list( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> SyncPage[FineTune]: """List your organization's fine-tuning jobs""" return self._get_api_list( @@ -250,7 +252,7 @@ def cancel( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> FineTune: """ Immediately cancel a fine-tune job. @@ -283,7 +285,7 @@ def list_events( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = 86400, + timeout: float | httpx.Timeout | None | NotGiven = 86400, ) -> FineTuneEventsListResponse: """ Get fine-grained status updates for a fine-tune job. @@ -318,7 +320,7 @@ def list_events( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = 86400, + timeout: float | httpx.Timeout | None | NotGiven = 86400, ) -> Stream[FineTuneEvent]: """ Get fine-grained status updates for a fine-tune job. @@ -353,7 +355,7 @@ def list_events( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = 86400, + timeout: float | httpx.Timeout | None | NotGiven = 86400, ) -> FineTuneEventsListResponse | Stream[FineTuneEvent]: """ Get fine-grained status updates for a fine-tune job. @@ -387,7 +389,7 @@ def list_events( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = 86400, + timeout: float | httpx.Timeout | None | NotGiven = 86400, ) -> FineTuneEventsListResponse | Stream[FineTuneEvent]: return self._get( f"/fine-tunes/{fine_tune_id}/events", @@ -431,7 +433,7 @@ async def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> FineTune: """ Creates a job that fine-tunes a specified model from a given dataset. @@ -575,7 +577,7 @@ async def retrieve( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> FineTune: """ Gets info about the fine-tune job. @@ -607,7 +609,7 @@ def list( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AsyncPaginator[FineTune, AsyncPage[FineTune]]: """List your organization's fine-tuning jobs""" return self._get_api_list( @@ -628,7 +630,7 @@ async def cancel( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> FineTune: """ Immediately cancel a fine-tune job. @@ -661,7 +663,7 @@ async def list_events( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = 86400, + timeout: float | httpx.Timeout | None | NotGiven = 86400, ) -> FineTuneEventsListResponse: """ Get fine-grained status updates for a fine-tune job. @@ -696,7 +698,7 @@ async def list_events( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = 86400, + timeout: float | httpx.Timeout | None | NotGiven = 86400, ) -> AsyncStream[FineTuneEvent]: """ Get fine-grained status updates for a fine-tune job. @@ -731,7 +733,7 @@ async def list_events( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = 86400, + timeout: float | httpx.Timeout | None | NotGiven = 86400, ) -> FineTuneEventsListResponse | AsyncStream[FineTuneEvent]: """ Get fine-grained status updates for a fine-tune job. @@ -765,7 +767,7 @@ async def list_events( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = 86400, + timeout: float | httpx.Timeout | None | NotGiven = 86400, ) -> FineTuneEventsListResponse | AsyncStream[FineTuneEvent]: return await self._get( f"/fine-tunes/{fine_tune_id}/events", diff --git a/src/openai/resources/fine_tuning/jobs.py b/src/openai/resources/fine_tuning/jobs.py index b721c892b5..3d9aed8d91 100644 --- a/src/openai/resources/fine_tuning/jobs.py +++ b/src/openai/resources/fine_tuning/jobs.py @@ -5,6 +5,8 @@ from typing import TYPE_CHECKING, Union, Optional from typing_extensions import Literal +import httpx + from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ..._utils import maybe_transform from ..._resource import SyncAPIResource, AsyncAPIResource @@ -45,7 +47,7 @@ def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> FineTuningJob: """ Creates a job that fine-tunes a specified model from a given dataset. @@ -126,7 +128,7 @@ def retrieve( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> FineTuningJob: """ Get info about a fine-tuning job. @@ -160,7 +162,7 @@ def list( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> SyncCursorPage[FineTuningJob]: """ List your organization's fine-tuning jobs @@ -206,7 +208,7 @@ def cancel( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> FineTuningJob: """ Immediately cancel a fine-tune job. @@ -239,7 +241,7 @@ def list_events( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> SyncCursorPage[FineTuningJobEvent]: """ Get status updates for a fine-tuning job. @@ -297,7 +299,7 @@ async def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> FineTuningJob: """ Creates a job that fine-tunes a specified model from a given dataset. @@ -378,7 +380,7 @@ async def retrieve( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> FineTuningJob: """ Get info about a fine-tuning job. @@ -412,7 +414,7 @@ def list( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AsyncPaginator[FineTuningJob, AsyncCursorPage[FineTuningJob]]: """ List your organization's fine-tuning jobs @@ -458,7 +460,7 @@ async def cancel( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> FineTuningJob: """ Immediately cancel a fine-tune job. @@ -491,7 +493,7 @@ def list_events( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AsyncPaginator[FineTuningJobEvent, AsyncCursorPage[FineTuningJobEvent]]: """ Get status updates for a fine-tuning job. diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py index 9d4ae9936a..94b1bc1fc8 100644 --- a/src/openai/resources/images.py +++ b/src/openai/resources/images.py @@ -5,6 +5,8 @@ from typing import TYPE_CHECKING, Union, Mapping, Optional, cast from typing_extensions import Literal +import httpx + from ..types import ( ImagesResponse, image_edit_params, @@ -44,7 +46,7 @@ def create_variation( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ImagesResponse: """ Creates a variation of a given image. @@ -120,7 +122,7 @@ def edit( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ImagesResponse: """ Creates an edited or extended image given an original image and a prompt. @@ -204,7 +206,7 @@ def generate( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ImagesResponse: """ Creates an image given a prompt. @@ -289,7 +291,7 @@ async def create_variation( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ImagesResponse: """ Creates a variation of a given image. @@ -365,7 +367,7 @@ async def edit( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ImagesResponse: """ Creates an edited or extended image given an original image and a prompt. @@ -449,7 +451,7 @@ async def generate( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ImagesResponse: """ Creates an image given a prompt. diff --git a/src/openai/resources/models.py b/src/openai/resources/models.py index 689bbd6621..2d04bdc5cc 100644 --- a/src/openai/resources/models.py +++ b/src/openai/resources/models.py @@ -4,6 +4,8 @@ from typing import TYPE_CHECKING +import httpx + from ..types import Model, ModelDeleted from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._resource import SyncAPIResource, AsyncAPIResource @@ -33,7 +35,7 @@ def retrieve( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Model: """ Retrieves a model instance, providing basic information about the model such as @@ -64,7 +66,7 @@ def list( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> SyncPage[Model]: """ Lists the currently available models, and provides basic information about each @@ -88,7 +90,7 @@ def delete( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ModelDeleted: """Delete a fine-tuned model. @@ -129,7 +131,7 @@ async def retrieve( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Model: """ Retrieves a model instance, providing basic information about the model such as @@ -160,7 +162,7 @@ def list( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AsyncPaginator[Model, AsyncPage[Model]]: """ Lists the currently available models, and provides basic information about each @@ -184,7 +186,7 @@ async def delete( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ModelDeleted: """Delete a fine-tuned model. diff --git a/src/openai/resources/moderations.py b/src/openai/resources/moderations.py index 1ee3e72564..12a7c68a7b 100644 --- a/src/openai/resources/moderations.py +++ b/src/openai/resources/moderations.py @@ -5,6 +5,8 @@ from typing import TYPE_CHECKING, List, Union from typing_extensions import Literal +import httpx + from ..types import ModerationCreateResponse, moderation_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import maybe_transform @@ -35,7 +37,7 @@ def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ModerationCreateResponse: """ Classifies if text violates OpenAI's Content Policy @@ -93,7 +95,7 @@ async def create( extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, - timeout: float | None | NotGiven = NOT_GIVEN, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ModerationCreateResponse: """ Classifies if text violates OpenAI's Content Policy diff --git a/src/openai/types/beta/assistant.py b/src/openai/types/beta/assistant.py index 9130b60363..e15282a69a 100644 --- a/src/openai/types/beta/assistant.py +++ b/src/openai/types/beta/assistant.py @@ -6,7 +6,7 @@ from ..._models import BaseModel -__all__ = ["Assistant", "Tool", "ToolCodeInterpreter", "ToolRetreival", "ToolFunction", "ToolFunctionFunction"] +__all__ = ["Assistant", "Tool", "ToolCodeInterpreter", "ToolRetrieval", "ToolFunction", "ToolFunctionFunction"] class ToolCodeInterpreter(BaseModel): @@ -14,9 +14,9 @@ class ToolCodeInterpreter(BaseModel): """The type of tool being defined: `code_interpreter`""" -class ToolRetreival(BaseModel): - type: Literal["retreival"] - """The type of tool being defined: `retreival`""" +class ToolRetrieval(BaseModel): + type: Literal["retrieval"] + """The type of tool being defined: `retrieval`""" class ToolFunctionFunction(BaseModel): @@ -54,7 +54,7 @@ class ToolFunction(BaseModel): """The type of tool being defined: `function`""" -Tool = Union[ToolCodeInterpreter, ToolRetreival, ToolFunction] +Tool = Union[ToolCodeInterpreter, ToolRetrieval, ToolFunction] class Assistant(BaseModel): diff --git a/src/openai/types/beta/assistant_create_params.py b/src/openai/types/beta/assistant_create_params.py index 8b8f025c39..8272d5eb4d 100644 --- a/src/openai/types/beta/assistant_create_params.py +++ b/src/openai/types/beta/assistant_create_params.py @@ -67,8 +67,8 @@ class ToolAssistantToolsCode(TypedDict, total=False): class ToolAssistantToolsRetrieval(TypedDict, total=False): - type: Required[Literal["retreival"]] - """The type of tool being defined: `retreival`""" + type: Required[Literal["retrieval"]] + """The type of tool being defined: `retrieval`""" class ToolAssistantToolsFunctionFunction(TypedDict, total=False): diff --git a/src/openai/types/beta/assistant_update_params.py b/src/openai/types/beta/assistant_update_params.py index fa838f51e3..3916833b77 100644 --- a/src/openai/types/beta/assistant_update_params.py +++ b/src/openai/types/beta/assistant_update_params.py @@ -69,8 +69,8 @@ class ToolAssistantToolsCode(TypedDict, total=False): class ToolAssistantToolsRetrieval(TypedDict, total=False): - type: Required[Literal["retreival"]] - """The type of tool being defined: `retreival`""" + type: Required[Literal["retrieval"]] + """The type of tool being defined: `retrieval`""" class ToolAssistantToolsFunctionFunction(TypedDict, total=False): diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index 2955343ec0..d7391d4d62 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -106,8 +106,8 @@ class ToolAssistantToolsCode(TypedDict, total=False): class ToolAssistantToolsRetrieval(TypedDict, total=False): - type: Required[Literal["retreival"]] - """The type of tool being defined: `retreival`""" + type: Required[Literal["retrieval"]] + """The type of tool being defined: `retrieval`""" class ToolAssistantToolsFunctionFunction(TypedDict, total=False): diff --git a/src/openai/types/beta/threads/run.py b/src/openai/types/beta/threads/run.py index d06152fa5b..d30a32ec97 100644 --- a/src/openai/types/beta/threads/run.py +++ b/src/openai/types/beta/threads/run.py @@ -47,8 +47,8 @@ class ToolAssistantToolsCode(BaseModel): class ToolAssistantToolsRetrieval(BaseModel): - type: Literal["retreival"] - """The type of tool being defined: `retreival`""" + type: Literal["retrieval"] + """The type of tool being defined: `retrieval`""" class ToolAssistantToolsFunctionFunction(BaseModel): diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index 41d2eeea03..cf1bb9f05d 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -58,8 +58,8 @@ class ToolAssistantToolsCode(TypedDict, total=False): class ToolAssistantToolsRetrieval(TypedDict, total=False): - type: Required[Literal["retreival"]] - """The type of tool being defined: `retreival`""" + type: Required[Literal["retrieval"]] + """The type of tool being defined: `retrieval`""" class ToolAssistantToolsFunctionFunction(TypedDict, total=False): From e0aafc6c1a45334ac889fe3e54957d309c3af93f Mon Sep 17 00:00:00 2001 From: David Schnurr Date: Mon, 6 Nov 2023 15:58:23 -0800 Subject: [PATCH 064/816] codeowners (#696) --- .github/CODEOWNERS | 1 + 1 file changed, 1 insertion(+) create mode 100644 .github/CODEOWNERS diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000000..3ce5f8d004 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @openai/sdks-team From e9c26d1e253ff54ea50ea1b11d87c35405b24dda Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 6 Nov 2023 23:32:33 +0000 Subject: [PATCH 065/816] ci: setup automatic releases (#693) --- .github/workflows/create-releases.yml | 37 ++++++++++++++++ .github/workflows/publish-pypi.yml | 27 +++++++++++ .github/workflows/release-doctor.yml | 23 ++++++++++ .release-please-manifest.json | 3 ++ bin/check-release-environment | 25 +++++++++++ bin/publish-pypi | 6 +++ examples/audio.py | 34 ++++++++++++++ release-please-config.json | 64 +++++++++++++++++++++++++++ src/openai/_version.py | 2 +- 9 files changed, 220 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/create-releases.yml create mode 100644 .github/workflows/publish-pypi.yml create mode 100644 .github/workflows/release-doctor.yml create mode 100644 .release-please-manifest.json create mode 100644 bin/check-release-environment create mode 100644 bin/publish-pypi create mode 100755 examples/audio.py create mode 100644 release-please-config.json diff --git a/.github/workflows/create-releases.yml b/.github/workflows/create-releases.yml new file mode 100644 index 0000000000..7dbae006c0 --- /dev/null +++ b/.github/workflows/create-releases.yml @@ -0,0 +1,37 @@ +name: Create releases +on: + push: + branches: + - main + +jobs: + release: + name: release + if: github.ref == 'refs/heads/main' && github.repository == 'openai/openai-python' + runs-on: ubuntu-latest + environment: publish + + steps: + - uses: actions/checkout@v3 + + - uses: stainless-api/trigger-release-please@v1 + id: release + with: + repo: ${{ github.event.repository.full_name }} + stainless-api-key: ${{ secrets.STAINLESS_API_KEY }} + + - name: Install Rye + if: ${{ steps.release.outputs.releases_created }} + run: | + curl -sSf https://rye-up.com/get | bash + echo "$HOME/.rye/shims" >> $GITHUB_PATH + env: + RYE_VERSION: 0.15.2 + RYE_INSTALL_OPTION: "--yes" + + - name: Publish to PyPI + if: ${{ steps.release.outputs.releases_created }} + run: | + bash ./bin/publish-pypi + env: + PYPI_TOKEN: ${{ secrets.OPENAI_PYPI_TOKEN || secrets.PYPI_TOKEN }} diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml new file mode 100644 index 0000000000..026ed29c22 --- /dev/null +++ b/.github/workflows/publish-pypi.yml @@ -0,0 +1,27 @@ +# workflow for re-running publishing to PyPI in case it fails for some reason +# you can run this workflow by navigating to https://www.github.com/openai/openai-python/actions/workflows/publish-pypi.yml +name: Publish PyPI +on: + workflow_dispatch: + +jobs: + publish: + name: publish + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + + - name: Install Rye + run: | + curl -sSf https://rye-up.com/get | bash + echo "$HOME/.rye/shims" >> $GITHUB_PATH + env: + RYE_VERSION: 0.15.2 + RYE_INSTALL_OPTION: "--yes" + + - name: Publish to PyPI + run: | + bash ./bin/publish-pypi + env: + PYPI_TOKEN: ${{ secrets.OPENAI_PYPI_TOKEN || secrets.PYPI_TOKEN }} diff --git a/.github/workflows/release-doctor.yml b/.github/workflows/release-doctor.yml new file mode 100644 index 0000000000..108aa5973a --- /dev/null +++ b/.github/workflows/release-doctor.yml @@ -0,0 +1,23 @@ +name: Release Doctor +on: + push: + branches: + - main + workflow_dispatch: + +jobs: + release_doctor: + name: release doctor + runs-on: ubuntu-latest + environment: publish + if: github.repository == 'openai/openai-python' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch' || startsWith(github.head_ref, 'release-please') || github.head_ref == 'next') + + steps: + - uses: actions/checkout@v3 + + - name: Check release environment + run: | + bash ./bin/check-release-environment + env: + STAINLESS_API_KEY: ${{ secrets.STAINLESS_API_KEY }} + PYPI_TOKEN: ${{ secrets.OPENAI_PYPI_TOKEN || secrets.PYPI_TOKEN }} diff --git a/.release-please-manifest.json b/.release-please-manifest.json new file mode 100644 index 0000000000..b55c11f05d --- /dev/null +++ b/.release-please-manifest.json @@ -0,0 +1,3 @@ +{ + ".": "1.1.1" +} \ No newline at end of file diff --git a/bin/check-release-environment b/bin/check-release-environment new file mode 100644 index 0000000000..b0c8d34f0c --- /dev/null +++ b/bin/check-release-environment @@ -0,0 +1,25 @@ +#!/usr/bin/env bash + +errors=() + +if [ -z "${STAINLESS_API_KEY}" ]; then + errors+=("The STAINLESS_API_KEY secret has not been set. Please contact Stainless for an API key & set it in your organization secrets on GitHub.") +fi + +if [ -z "${PYPI_TOKEN}" ]; then + errors+=("The OPENAI_PYPI_TOKEN secret has not been set. Please set it in either this repository's secrets or your organization secrets.") +fi + +len=${#errors[@]} + +if [[ len -gt 0 ]]; then + echo -e "Found the following errors in the release environment:\n" + + for error in "${errors[@]}"; do + echo -e "- $error\n" + done + + exit 1 +fi + +echo "The environment is ready to push releases!" diff --git a/bin/publish-pypi b/bin/publish-pypi new file mode 100644 index 0000000000..826054e924 --- /dev/null +++ b/bin/publish-pypi @@ -0,0 +1,6 @@ +#!/usr/bin/env bash + +set -eux +mkdir -p dist +rye build --clean +rye publish --yes --token=$PYPI_TOKEN diff --git a/examples/audio.py b/examples/audio.py new file mode 100755 index 0000000000..a5f535dcd6 --- /dev/null +++ b/examples/audio.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python + +from pathlib import Path + +from openai import OpenAI + +# gets OPENAI_API_KEY from your environment variables +openai = OpenAI() + +speech_file_path = Path(__file__).parent / "speech.mp3" + + +def main() -> None: + # Create text-to-speech audio file + response = openai.audio.speech.create( + model="tts-1", voice="alloy", input="the quick brown fox jumped over the lazy dogs" + ) + + response.stream_to_file(speech_file_path) + + # Create transcription from audio file + transcription = openai.audio.transcriptions.create(model="whisper-1", file=speech_file_path) + print(transcription.text) + + # Create translation from audio file + translation = openai.audio.translations.create( + model="whisper-1", + file=speech_file_path, + ) + print(translation.text) + + +if __name__ == "__main__": + main() diff --git a/release-please-config.json b/release-please-config.json new file mode 100644 index 0000000000..5c66d801f5 --- /dev/null +++ b/release-please-config.json @@ -0,0 +1,64 @@ +{ + "packages": { + ".": {} + }, + "$schema": "https://raw.githubusercontent.com/stainless-api/release-please/main/schemas/config.json", + "include-v-in-tag": true, + "include-component-in-tag": false, + "bump-minor-pre-major": true, + "bump-patch-for-minor-pre-major": false, + "pull-request-header": "Automated Release PR", + "pull-request-title-pattern": "release: ${version}", + "changelog-sections": [ + { + "type": "feat", + "section": "Features" + }, + { + "type": "fix", + "section": "Bug Fixes" + }, + { + "type": "perf", + "section": "Performance Improvements" + }, + { + "type": "revert", + "section": "Reverts" + }, + { + "type": "chore", + "section": "Chores" + }, + { + "type": "docs", + "section": "Documentation" + }, + { + "type": "style", + "section": "Styles" + }, + { + "type": "refactor", + "section": "Refactors" + }, + { + "type": "test", + "section": "Tests", + "hidden": true + }, + { + "type": "build", + "section": "Build System" + }, + { + "type": "ci", + "section": "Continuous Integration", + "hidden": true + } + ], + "release-type": "python", + "extra-files": [ + "src/openai/_version.py" + ] +} \ No newline at end of file diff --git a/src/openai/_version.py b/src/openai/_version.py index b4ed828270..5147fcd1f1 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.1.1" +__version__ = "1.1.1" # x-release-please-version From f5ef2b3a45ba7764d04dc93b87379e6e2f3063e7 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 7 Nov 2023 13:04:47 +0000 Subject: [PATCH 066/816] fix: asssitant_deleted -> assistant_deleted (#711) --- api.md | 4 ++-- src/openai/resources/beta/assistants/assistants.py | 10 +++++----- src/openai/types/beta/__init__.py | 2 +- .../{asssitant_deleted.py => assistant_deleted.py} | 4 ++-- tests/api_resources/beta/test_assistants.py | 10 +++++----- 5 files changed, 15 insertions(+), 15 deletions(-) rename src/openai/types/beta/{asssitant_deleted.py => assistant_deleted.py} (75%) diff --git a/api.md b/api.md index 818ae73b31..95e9922129 100644 --- a/api.md +++ b/api.md @@ -197,7 +197,7 @@ Methods: Types: ```python -from openai.types.beta import Assistant, AsssitantDeleted +from openai.types.beta import Assistant, AssistantDeleted ``` Methods: @@ -206,7 +206,7 @@ Methods: - client.beta.assistants.retrieve(assistant_id) -> Assistant - client.beta.assistants.update(assistant_id, \*\*params) -> Assistant - client.beta.assistants.list(\*\*params) -> SyncCursorPage[Assistant] -- client.beta.assistants.delete(assistant_id) -> AsssitantDeleted +- client.beta.assistants.delete(assistant_id) -> AssistantDeleted ### Files diff --git a/src/openai/resources/beta/assistants/assistants.py b/src/openai/resources/beta/assistants/assistants.py index 6b81dc97f3..efa711ecf4 100644 --- a/src/openai/resources/beta/assistants/assistants.py +++ b/src/openai/resources/beta/assistants/assistants.py @@ -15,7 +15,7 @@ from ....pagination import SyncCursorPage, AsyncCursorPage from ....types.beta import ( Assistant, - AsssitantDeleted, + AssistantDeleted, assistant_list_params, assistant_create_params, assistant_update_params, @@ -298,7 +298,7 @@ def delete( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> AsssitantDeleted: + ) -> AssistantDeleted: """ Delete an assistant. @@ -317,7 +317,7 @@ def delete( options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), - cast_to=AsssitantDeleted, + cast_to=AssistantDeleted, ) @@ -591,7 +591,7 @@ async def delete( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> AsssitantDeleted: + ) -> AssistantDeleted: """ Delete an assistant. @@ -610,7 +610,7 @@ async def delete( options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), - cast_to=AsssitantDeleted, + cast_to=AssistantDeleted, ) diff --git a/src/openai/types/beta/__init__.py b/src/openai/types/beta/__init__.py index 8b834f286d..c03d823b8c 100644 --- a/src/openai/types/beta/__init__.py +++ b/src/openai/types/beta/__init__.py @@ -5,7 +5,7 @@ from .thread import Thread as Thread from .assistant import Assistant as Assistant from .thread_deleted import ThreadDeleted as ThreadDeleted -from .asssitant_deleted import AsssitantDeleted as AsssitantDeleted +from .assistant_deleted import AssistantDeleted as AssistantDeleted from .thread_create_params import ThreadCreateParams as ThreadCreateParams from .thread_update_params import ThreadUpdateParams as ThreadUpdateParams from .assistant_list_params import AssistantListParams as AssistantListParams diff --git a/src/openai/types/beta/asssitant_deleted.py b/src/openai/types/beta/assistant_deleted.py similarity index 75% rename from src/openai/types/beta/asssitant_deleted.py rename to src/openai/types/beta/assistant_deleted.py index 258210e7fe..23802caaf6 100644 --- a/src/openai/types/beta/asssitant_deleted.py +++ b/src/openai/types/beta/assistant_deleted.py @@ -4,10 +4,10 @@ from ..._models import BaseModel -__all__ = ["AsssitantDeleted"] +__all__ = ["AssistantDeleted"] -class AsssitantDeleted(BaseModel): +class AssistantDeleted(BaseModel): id: str deleted: bool diff --git a/tests/api_resources/beta/test_assistants.py b/tests/api_resources/beta/test_assistants.py index 5bbad1d7dd..82e975b46d 100644 --- a/tests/api_resources/beta/test_assistants.py +++ b/tests/api_resources/beta/test_assistants.py @@ -10,7 +10,7 @@ from tests.utils import assert_matches_type from openai._client import OpenAI, AsyncOpenAI from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta import Assistant, AsssitantDeleted +from openai.types.beta import Assistant, AssistantDeleted base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") api_key = "My API Key" @@ -123,7 +123,7 @@ def test_method_delete(self, client: OpenAI) -> None: assistant = client.beta.assistants.delete( "string", ) - assert_matches_type(AsssitantDeleted, assistant, path=["response"]) + assert_matches_type(AssistantDeleted, assistant, path=["response"]) @parametrize def test_raw_response_delete(self, client: OpenAI) -> None: @@ -132,7 +132,7 @@ def test_raw_response_delete(self, client: OpenAI) -> None: ) assert response.http_request.headers.get("X-Stainless-Lang") == "python" assistant = response.parse() - assert_matches_type(AsssitantDeleted, assistant, path=["response"]) + assert_matches_type(AssistantDeleted, assistant, path=["response"]) class TestAsyncAssistants: @@ -242,7 +242,7 @@ async def test_method_delete(self, client: AsyncOpenAI) -> None: assistant = await client.beta.assistants.delete( "string", ) - assert_matches_type(AsssitantDeleted, assistant, path=["response"]) + assert_matches_type(AssistantDeleted, assistant, path=["response"]) @parametrize async def test_raw_response_delete(self, client: AsyncOpenAI) -> None: @@ -251,4 +251,4 @@ async def test_raw_response_delete(self, client: AsyncOpenAI) -> None: ) assert response.http_request.headers.get("X-Stainless-Lang") == "python" assistant = response.parse() - assert_matches_type(AsssitantDeleted, assistant, path=["response"]) + assert_matches_type(AssistantDeleted, assistant, path=["response"]) From 86b263f1f4ed3987123e4884bbc4457f7bb22c9f Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 7 Nov 2023 16:52:10 +0000 Subject: [PATCH 067/816] chore(internal): fix some typos (#718) --- src/openai/_utils/_transform.py | 6 +++--- tests/test_extract_files.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/openai/_utils/_transform.py b/src/openai/_utils/_transform.py index db40bff27f..dc497ea329 100644 --- a/src/openai/_utils/_transform.py +++ b/src/openai/_utils/_transform.py @@ -95,7 +95,7 @@ class Params(TypedDict, total=False): return cast(_T, transformed) -def _get_annoted_type(type_: type) -> type | None: +def _get_annotated_type(type_: type) -> type | None: """If the given type is an `Annotated` type then it is returned, if not `None` is returned. This also unwraps the type when applicable, e.g. `Required[Annotated[T, ...]]` @@ -115,7 +115,7 @@ def _maybe_transform_key(key: str, type_: type) -> str: Note: this function only looks at `Annotated` types that contain `PropertInfo` metadata. """ - annotated_type = _get_annoted_type(type_) + annotated_type = _get_annotated_type(type_) if annotated_type is None: # no `Annotated` definition for this type, no transformation needed return key @@ -174,7 +174,7 @@ def _transform_recursive( def _transform_value(data: object, type_: type) -> object: - annotated_type = _get_annoted_type(type_) + annotated_type = _get_annotated_type(type_) if annotated_type is None: return data diff --git a/tests/test_extract_files.py b/tests/test_extract_files.py index 554487da42..0f6fb04d7d 100644 --- a/tests/test_extract_files.py +++ b/tests/test_extract_files.py @@ -54,7 +54,7 @@ def test_multiple_files() -> None: [], ], ], - ids=["dict expecting array", "arraye expecting dict", "unknown keys"], + ids=["dict expecting array", "array expecting dict", "unknown keys"], ) def test_ignores_incorrect_paths( query: dict[str, object], From a816967337fcedc6cea7efd7451640c30e705604 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 7 Nov 2023 17:35:58 +0000 Subject: [PATCH 068/816] chore(docs): fix github links (#719) --- README.md | 2 +- src/openai/_files.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8904d9ed52..cedbc72337 100644 --- a/README.md +++ b/README.md @@ -410,7 +410,7 @@ completion = response.parse() # get the object that `chat.completions.create()` print(completion) ``` -These methods return an [`APIResponse`](https://github.com/openai/openai-python/src/openai/_response.py) object. +These methods return an [`APIResponse`](https://github.com/openai/openai-python/tree/main/src/openai/_response.py) object. ### Configuring the HTTP client diff --git a/src/openai/_files.py b/src/openai/_files.py index 94cd553135..bebfb19501 100644 --- a/src/openai/_files.py +++ b/src/openai/_files.py @@ -29,7 +29,7 @@ def assert_is_file_content(obj: object, *, key: str | None = None) -> None: if not is_file_content(obj): prefix = f"Expected entry at `{key}`" if key is not None else f"Expected file input `{obj!r}`" raise RuntimeError( - f"{prefix} to be bytes, an io.IOBase instance, PathLike or a tuple but received {type(obj)} instead. See https://github.com/openai/openai-python#file-uploads" + f"{prefix} to be bytes, an io.IOBase instance, PathLike or a tuple but received {type(obj)} instead. See https://github.com/openai/openai-python/tree/main#file-uploads" ) from None From 4f89244dbf937ba1ba1e7688480813acc05b85a0 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 8 Nov 2023 11:59:29 +0000 Subject: [PATCH 069/816] fix(api): accidentally required params, add new models & other fixes (#729) - Mark chat completion image url as required - Add system_fingerprint to chat completions --- src/openai/resources/chat/completions.py | 16 ++++++++++++++++ src/openai/types/chat/chat_completion_chunk.py | 7 +++++++ .../chat_completion_content_part_image_param.py | 6 +++--- .../types/chat/completion_create_params.py | 2 ++ 4 files changed, 28 insertions(+), 3 deletions(-) diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index a46e7e70d6..75e0d66d58 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -43,6 +43,8 @@ def create( model: Union[ str, Literal[ + "gpt-4-1106-preview", + "gpt-4-vision-preview", "gpt-4", "gpt-4-0314", "gpt-4-0613", @@ -201,6 +203,8 @@ def create( model: Union[ str, Literal[ + "gpt-4-1106-preview", + "gpt-4-vision-preview", "gpt-4", "gpt-4-0314", "gpt-4-0613", @@ -359,6 +363,8 @@ def create( model: Union[ str, Literal[ + "gpt-4-1106-preview", + "gpt-4-vision-preview", "gpt-4", "gpt-4-0314", "gpt-4-0613", @@ -517,6 +523,8 @@ def create( model: Union[ str, Literal[ + "gpt-4-1106-preview", + "gpt-4-vision-preview", "gpt-4", "gpt-4-0314", "gpt-4-0613", @@ -602,6 +610,8 @@ async def create( model: Union[ str, Literal[ + "gpt-4-1106-preview", + "gpt-4-vision-preview", "gpt-4", "gpt-4-0314", "gpt-4-0613", @@ -760,6 +770,8 @@ async def create( model: Union[ str, Literal[ + "gpt-4-1106-preview", + "gpt-4-vision-preview", "gpt-4", "gpt-4-0314", "gpt-4-0613", @@ -918,6 +930,8 @@ async def create( model: Union[ str, Literal[ + "gpt-4-1106-preview", + "gpt-4-vision-preview", "gpt-4", "gpt-4-0314", "gpt-4-0613", @@ -1076,6 +1090,8 @@ async def create( model: Union[ str, Literal[ + "gpt-4-1106-preview", + "gpt-4-vision-preview", "gpt-4", "gpt-4-0314", "gpt-4-0613", diff --git a/src/openai/types/chat/chat_completion_chunk.py b/src/openai/types/chat/chat_completion_chunk.py index bbc46a37bb..568f530280 100644 --- a/src/openai/types/chat/chat_completion_chunk.py +++ b/src/openai/types/chat/chat_completion_chunk.py @@ -109,3 +109,10 @@ class ChatCompletionChunk(BaseModel): object: Literal["chat.completion.chunk"] """The object type, which is always `chat.completion.chunk`.""" + + system_fingerprint: Optional[str] = None + """This fingerprint represents the backend configuration that the model runs with. + + Can be used in conjunction with the `seed` request parameter to understand when + backend changes have been made that might impact determinism. + """ diff --git a/src/openai/types/chat/chat_completion_content_part_image_param.py b/src/openai/types/chat/chat_completion_content_part_image_param.py index 2051786562..eb9bd52689 100644 --- a/src/openai/types/chat/chat_completion_content_part_image_param.py +++ b/src/openai/types/chat/chat_completion_content_part_image_param.py @@ -8,12 +8,12 @@ class ImageURL(TypedDict, total=False): + url: Required[str] + """Either a URL of the image or the base64 encoded image data.""" + detail: Literal["auto", "low", "high"] """Specifies the detail level of the image.""" - url: str - """Either a URL of the image or the base64 encoded image data.""" - class ChatCompletionContentPartImageParam(TypedDict, total=False): image_url: Required[ImageURL] diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 44b1abe576..b310761077 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -35,6 +35,8 @@ class CompletionCreateParamsBase(TypedDict, total=False): Union[ str, Literal[ + "gpt-4-1106-preview", + "gpt-4-vision-preview", "gpt-4", "gpt-4-0314", "gpt-4-0613", From 97810fcb129ba3cc90cdb5ed06351c8a5b738ecd Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 8 Nov 2023 12:00:05 +0000 Subject: [PATCH 070/816] release: 1.1.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 16 ++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 19 insertions(+), 3 deletions(-) create mode 100644 CHANGELOG.md diff --git a/.release-please-manifest.json b/.release-please-manifest.json index b55c11f05d..9c6a481f5b 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.1.1" + ".": "1.1.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000000..8c97964977 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,16 @@ +# Changelog + +## 1.1.2 (2023-11-08) + +Full Changelog: [v1.1.1...v1.1.2](https://github.com/openai/openai-python/compare/v1.1.1...v1.1.2) + +### Bug Fixes + +* **api:** accidentally required params, add new models & other fixes ([#729](https://github.com/openai/openai-python/issues/729)) ([03c3e03](https://github.com/openai/openai-python/commit/03c3e03fc758cf4e59b81edf73a2618d80b560b7)) +* asssitant_deleted -> assistant_deleted ([#711](https://github.com/openai/openai-python/issues/711)) ([287b51e](https://github.com/openai/openai-python/commit/287b51e4f7cede9667c118007de1275eb04772c6)) + + +### Chores + +* **docs:** fix github links ([#719](https://github.com/openai/openai-python/issues/719)) ([0cda8ca](https://github.com/openai/openai-python/commit/0cda8cab718d53d7dc0604d9fac52838c9391565)) +* **internal:** fix some typos ([#718](https://github.com/openai/openai-python/issues/718)) ([894ad87](https://github.com/openai/openai-python/commit/894ad874aaa5d74530f561896ff31f68693418da)) diff --git a/pyproject.toml b/pyproject.toml index c5dd666475..0861b1278b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.1.1" +version = "1.1.2" description = "Client library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 5147fcd1f1..848573b8a1 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.1.1" # x-release-please-version +__version__ = "1.1.2" # x-release-please-version From ba424470504a470d1b0902847bcfae7149deae33 Mon Sep 17 00:00:00 2001 From: David Schnurr Date: Wed, 8 Nov 2023 10:31:05 -0800 Subject: [PATCH 071/816] issue templates (#698) * issue templates * Fix --- .github/ISSUE_TEMPLATE/bug_report.yml | 64 ++++++++++++++++++++++ .github/ISSUE_TEMPLATE/config.yml | 7 +++ .github/ISSUE_TEMPLATE/feature_request.yml | 28 ++++++++++ .github/pull_request_template.md | 10 ++++ 4 files changed, 109 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml create mode 100644 .github/pull_request_template.md diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000000..fa09dbe5b0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,64 @@ +name: Bug report +description: Report an issue or bug with this library +labels: ['bug'] +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to fill out this bug report! + - type: checkboxes + id: non_api + attributes: + label: Confirm this is an issue with the Python library and not an underlying OpenAI API + description: Issues with the underlying OpenAI API should be reported on our [Developer Community](https://community.openai.com/c/api/7) + options: + - label: This is an issue with the Python library + required: true + - type: textarea + id: what-happened + attributes: + label: Describe the bug + description: A clear and concise description of what the bug is, and any additional context. + placeholder: Tell us what you see! + validations: + required: true + - type: textarea + id: repro-steps + attributes: + label: To Reproduce + description: Steps to reproduce the behavior. + placeholder: | + 1. Fetch a '...' + 2. Update the '....' + 3. See error + validations: + required: true + - type: textarea + id: code-snippets + attributes: + label: Code snippets + description: If applicable, add code snippets to help explain your problem. + render: Python + validations: + required: false + - type: input + id: os + attributes: + label: OS + placeholder: macOS + validations: + required: true + - type: input + id: language-version + attributes: + label: Python version + placeholder: Python v3.11.4 + validations: + required: true + - type: input + id: lib-version + attributes: + label: Library version + placeholder: openai v1.0.1 + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000..0498cf7f6f --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,7 @@ +blank_issues_enabled: false +contact_links: + - name: OpenAI support + url: https://help.openai.com/ + about: | + Please only file issues here that you believe represent actual bugs or feature requests for the OpenAI Python library. + If you're having general trouble with the OpenAI API, please visit our help center to get support. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000000..b529547d08 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,28 @@ +name: Feature request +description: Suggest an idea for this library +labels: ['feature-request'] +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to fill out this feature request! + - type: checkboxes + id: non_api + attributes: + label: Confirm this is a feature request for the Python library and not the underlying OpenAI API. + description: Feature requests for the underlying OpenAI API should be reported on our [Developer Community](https://community.openai.com/c/api/7) + options: + - label: This is a feature request for the Python library + required: true + - type: textarea + id: feature + attributes: + label: Describe the feature or improvement you're requesting + description: A clear and concise description of what you want to happen. + validations: + required: true + - type: textarea + id: context + attributes: + label: Additional context + description: Add any other context about the feature request here. diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000000..4416b1e547 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,10 @@ + + + + + +- [ ] I understand that this repository is auto-generated and my pull request may not be merged + +## Changes being requested + +## Additional context & links From ebdcc3f5df0dae2d84664a55200006c00f55bd10 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 8 Nov 2023 18:23:59 +0000 Subject: [PATCH 072/816] chore(internal): improve github devcontainer setup (#737) --- .devcontainer/Dockerfile | 28 +++++----------------------- .devcontainer/devcontainer.json | 21 ++++++++++++++++++++- 2 files changed, 25 insertions(+), 24 deletions(-) diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index 73f1b9f237..6eb007253c 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -1,27 +1,9 @@ -# syntax=docker/dockerfile:1 -FROM debian:bookworm-slim +ARG VARIANT="3.9" +FROM mcr.microsoft.com/vscode/devcontainers/python:0-${VARIANT} -RUN apt-get update && apt-get install -y \ - libxkbcommon0 \ - ca-certificates \ - make \ - curl \ - git \ - unzip \ - libc++1 \ - vim \ - termcap \ - && apt-get clean autoclean +USER vscode RUN curl -sSf https://rye-up.com/get | RYE_VERSION="0.15.2" RYE_INSTALL_OPTION="--yes" bash -ENV PATH=/root/.rye/shims:$PATH +ENV PATH=/home/vscode/.rye/shims:$PATH -WORKDIR /workspace - -COPY README.md .python-version pyproject.toml requirements.lock requirements-dev.lock /workspace/ - -RUN rye sync --all-features - -COPY . /workspace - -CMD ["rye", "shell"] +RUN echo "[[ -d .venv ]] && source .venv/bin/activate" >> /home/vscode/.bashrc diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index d55fc4d671..b9da964dc1 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -3,7 +3,26 @@ { "name": "Debian", "build": { - "dockerfile": "Dockerfile" + "dockerfile": "Dockerfile", + "context": ".." + }, + + "postStartCommand": "rye sync --all-features", + + "customizations": { + "vscode": { + "extensions": [ + "ms-python.python" + ], + "settings": { + "terminal.integrated.shell.linux": "/bin/bash", + "python.pythonPath": ".venv/bin/python", + "python.typeChecking": "basic", + "terminal.integrated.env.linux": { + "PATH": "/home/vscode/.rye/shims:${env:PATH}" + } + } + } } // Features to add to the dev container. More info: https://containers.dev/features. From ee28c46f8178951dc72591883d07927bf27d0199 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 8 Nov 2023 19:16:55 +0000 Subject: [PATCH 073/816] fix(api): update embedding response object type (#739) --- src/openai/types/create_embedding_response.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/openai/types/create_embedding_response.py b/src/openai/types/create_embedding_response.py index 7382bed6b9..bf64037e16 100644 --- a/src/openai/types/create_embedding_response.py +++ b/src/openai/types/create_embedding_response.py @@ -24,8 +24,8 @@ class CreateEmbeddingResponse(BaseModel): model: str """The name of the model used to generate the embedding.""" - object: Literal["embedding"] - """The object type, which is always "embedding".""" + object: Literal["list"] + """The object type, which is always "list".""" usage: Usage """The usage information for the request.""" From a228a539a2efc85ac73dfae06443d079383fb82e Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 8 Nov 2023 19:51:57 +0000 Subject: [PATCH 074/816] feat(api): unify function types (#741) Also fixes an enum `assistant.run.step` -> `thread.run.step` --- api.md | 6 ++ src/openai/resources/chat/completions.py | 84 ++++++++++++++++--- src/openai/types/__init__.py | 2 + src/openai/types/beta/assistant.py | 35 +------- .../types/beta/assistant_create_params.py | 35 +------- .../types/beta/assistant_update_params.py | 35 +------- .../beta/thread_create_and_run_params.py | 35 +------- src/openai/types/beta/threads/run.py | 38 ++------- .../types/beta/threads/run_create_params.py | 35 +------- .../types/beta/threads/runs/run_step.py | 8 +- .../types/chat/chat_completion_chunk.py | 4 +- .../types/chat/chat_completion_tool_param.py | 32 +------ .../types/chat/completion_create_params.py | 28 +++---- src/openai/types/completion_choice.py | 2 +- src/openai/types/shared/__init__.py | 4 + src/openai/types/shared/function_object.py | 35 ++++++++ .../types/shared/function_parameters.py | 7 ++ src/openai/types/shared_params/__init__.py | 4 + .../types/shared_params/function_object.py | 36 ++++++++ .../shared_params/function_parameters.py | 9 ++ 20 files changed, 223 insertions(+), 251 deletions(-) create mode 100644 src/openai/types/shared/__init__.py create mode 100644 src/openai/types/shared/function_object.py create mode 100644 src/openai/types/shared/function_parameters.py create mode 100644 src/openai/types/shared_params/__init__.py create mode 100644 src/openai/types/shared_params/function_object.py create mode 100644 src/openai/types/shared_params/function_parameters.py diff --git a/api.md b/api.md index 95e9922129..0f5cdbbbbf 100644 --- a/api.md +++ b/api.md @@ -1,3 +1,9 @@ +# Shared Types + +```python +from openai.types import FunctionObject, FunctionParameters +``` + # Completions Types: diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index 75e0d66d58..ff36424442 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -137,8 +137,18 @@ def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) - response_format: An object specifying the format that the model must output. Used to enable JSON - mode. + response_format: An object specifying the format that the model must output. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in increased latency and appearance of a "stuck" request. Also + note that the message content may be partially cut off if + `finish_reason="length"`, which indicates the generation exceeded `max_tokens` + or the conversation exceeded the max context length. seed: This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and @@ -304,8 +314,18 @@ def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) - response_format: An object specifying the format that the model must output. Used to enable JSON - mode. + response_format: An object specifying the format that the model must output. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in increased latency and appearance of a "stuck" request. Also + note that the message content may be partially cut off if + `finish_reason="length"`, which indicates the generation exceeded `max_tokens` + or the conversation exceeded the max context length. seed: This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and @@ -464,8 +484,18 @@ def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) - response_format: An object specifying the format that the model must output. Used to enable JSON - mode. + response_format: An object specifying the format that the model must output. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in increased latency and appearance of a "stuck" request. Also + note that the message content may be partially cut off if + `finish_reason="length"`, which indicates the generation exceeded `max_tokens` + or the conversation exceeded the max context length. seed: This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and @@ -704,8 +734,18 @@ async def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) - response_format: An object specifying the format that the model must output. Used to enable JSON - mode. + response_format: An object specifying the format that the model must output. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in increased latency and appearance of a "stuck" request. Also + note that the message content may be partially cut off if + `finish_reason="length"`, which indicates the generation exceeded `max_tokens` + or the conversation exceeded the max context length. seed: This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and @@ -871,8 +911,18 @@ async def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) - response_format: An object specifying the format that the model must output. Used to enable JSON - mode. + response_format: An object specifying the format that the model must output. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in increased latency and appearance of a "stuck" request. Also + note that the message content may be partially cut off if + `finish_reason="length"`, which indicates the generation exceeded `max_tokens` + or the conversation exceeded the max context length. seed: This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and @@ -1031,8 +1081,18 @@ async def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) - response_format: An object specifying the format that the model must output. Used to enable JSON - mode. + response_format: An object specifying the format that the model must output. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in increased latency and appearance of a "stuck" request. Also + note that the message content may be partially cut off if + `finish_reason="length"`, which indicates the generation exceeded `max_tokens` + or the conversation exceeded the max context length. seed: This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index 8f21480d5e..5840599a27 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -5,6 +5,8 @@ from .edit import Edit as Edit from .image import Image as Image from .model import Model as Model +from .shared import FunctionObject as FunctionObject +from .shared import FunctionParameters as FunctionParameters from .embedding import Embedding as Embedding from .fine_tune import FineTune as FineTune from .completion import Completion as Completion diff --git a/src/openai/types/beta/assistant.py b/src/openai/types/beta/assistant.py index e15282a69a..63332123c0 100644 --- a/src/openai/types/beta/assistant.py +++ b/src/openai/types/beta/assistant.py @@ -1,12 +1,13 @@ # File generated from our OpenAPI spec by Stainless. import builtins -from typing import Dict, List, Union, Optional +from typing import List, Union, Optional from typing_extensions import Literal +from ..shared import FunctionObject from ..._models import BaseModel -__all__ = ["Assistant", "Tool", "ToolCodeInterpreter", "ToolRetrieval", "ToolFunction", "ToolFunctionFunction"] +__all__ = ["Assistant", "Tool", "ToolCodeInterpreter", "ToolRetrieval", "ToolFunction"] class ToolCodeInterpreter(BaseModel): @@ -19,36 +20,8 @@ class ToolRetrieval(BaseModel): """The type of tool being defined: `retrieval`""" -class ToolFunctionFunction(BaseModel): - description: str - """ - A description of what the function does, used by the model to choose when and - how to call the function. - """ - - name: str - """The name of the function to be called. - - Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length - of 64. - """ - - parameters: Dict[str, builtins.object] - """The parameters the functions accepts, described as a JSON Schema object. - - See the [guide](https://platform.openai.com/docs/guides/gpt/function-calling) - for examples, and the - [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for - documentation about the format. - - To describe a function that accepts no parameters, provide the value - `{"type": "object", "properties": {}}`. - """ - - class ToolFunction(BaseModel): - function: ToolFunctionFunction - """The function definition.""" + function: FunctionObject type: Literal["function"] """The type of tool being defined: `function`""" diff --git a/src/openai/types/beta/assistant_create_params.py b/src/openai/types/beta/assistant_create_params.py index 8272d5eb4d..ce7494efec 100644 --- a/src/openai/types/beta/assistant_create_params.py +++ b/src/openai/types/beta/assistant_create_params.py @@ -2,16 +2,17 @@ from __future__ import annotations -from typing import Dict, List, Union, Optional +from typing import List, Union, Optional from typing_extensions import Literal, Required, TypedDict +from ...types import shared_params + __all__ = [ "AssistantCreateParams", "Tool", "ToolAssistantToolsCode", "ToolAssistantToolsRetrieval", "ToolAssistantToolsFunction", - "ToolAssistantToolsFunctionFunction", ] @@ -71,36 +72,8 @@ class ToolAssistantToolsRetrieval(TypedDict, total=False): """The type of tool being defined: `retrieval`""" -class ToolAssistantToolsFunctionFunction(TypedDict, total=False): - description: Required[str] - """ - A description of what the function does, used by the model to choose when and - how to call the function. - """ - - name: Required[str] - """The name of the function to be called. - - Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length - of 64. - """ - - parameters: Required[Dict[str, object]] - """The parameters the functions accepts, described as a JSON Schema object. - - See the [guide](https://platform.openai.com/docs/guides/gpt/function-calling) - for examples, and the - [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for - documentation about the format. - - To describe a function that accepts no parameters, provide the value - `{"type": "object", "properties": {}}`. - """ - - class ToolAssistantToolsFunction(TypedDict, total=False): - function: Required[ToolAssistantToolsFunctionFunction] - """The function definition.""" + function: Required[shared_params.FunctionObject] type: Required[Literal["function"]] """The type of tool being defined: `function`""" diff --git a/src/openai/types/beta/assistant_update_params.py b/src/openai/types/beta/assistant_update_params.py index 3916833b77..07a186a0d2 100644 --- a/src/openai/types/beta/assistant_update_params.py +++ b/src/openai/types/beta/assistant_update_params.py @@ -2,16 +2,17 @@ from __future__ import annotations -from typing import Dict, List, Union, Optional +from typing import List, Union, Optional from typing_extensions import Literal, Required, TypedDict +from ...types import shared_params + __all__ = [ "AssistantUpdateParams", "Tool", "ToolAssistantToolsCode", "ToolAssistantToolsRetrieval", "ToolAssistantToolsFunction", - "ToolAssistantToolsFunctionFunction", ] @@ -73,36 +74,8 @@ class ToolAssistantToolsRetrieval(TypedDict, total=False): """The type of tool being defined: `retrieval`""" -class ToolAssistantToolsFunctionFunction(TypedDict, total=False): - description: Required[str] - """ - A description of what the function does, used by the model to choose when and - how to call the function. - """ - - name: Required[str] - """The name of the function to be called. - - Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length - of 64. - """ - - parameters: Required[Dict[str, object]] - """The parameters the functions accepts, described as a JSON Schema object. - - See the [guide](https://platform.openai.com/docs/guides/gpt/function-calling) - for examples, and the - [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for - documentation about the format. - - To describe a function that accepts no parameters, provide the value - `{"type": "object", "properties": {}}`. - """ - - class ToolAssistantToolsFunction(TypedDict, total=False): - function: Required[ToolAssistantToolsFunctionFunction] - """The function definition.""" + function: Required[shared_params.FunctionObject] type: Required[Literal["function"]] """The type of tool being defined: `function`""" diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index d7391d4d62..8e6b33249c 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -2,9 +2,11 @@ from __future__ import annotations -from typing import Dict, List, Union, Optional +from typing import List, Union, Optional from typing_extensions import Literal, Required, TypedDict +from ...types import shared_params + __all__ = [ "ThreadCreateAndRunParams", "Thread", @@ -13,7 +15,6 @@ "ToolAssistantToolsCode", "ToolAssistantToolsRetrieval", "ToolAssistantToolsFunction", - "ToolAssistantToolsFunctionFunction", ] @@ -110,36 +111,8 @@ class ToolAssistantToolsRetrieval(TypedDict, total=False): """The type of tool being defined: `retrieval`""" -class ToolAssistantToolsFunctionFunction(TypedDict, total=False): - description: Required[str] - """ - A description of what the function does, used by the model to choose when and - how to call the function. - """ - - name: Required[str] - """The name of the function to be called. - - Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length - of 64. - """ - - parameters: Required[Dict[str, object]] - """The parameters the functions accepts, described as a JSON Schema object. - - See the [guide](https://platform.openai.com/docs/guides/gpt/function-calling) - for examples, and the - [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for - documentation about the format. - - To describe a function that accepts no parameters, provide the value - `{"type": "object", "properties": {}}`. - """ - - class ToolAssistantToolsFunction(TypedDict, total=False): - function: Required[ToolAssistantToolsFunctionFunction] - """The function definition.""" + function: Required[shared_params.FunctionObject] type: Required[Literal["function"]] """The type of tool being defined: `function`""" diff --git a/src/openai/types/beta/threads/run.py b/src/openai/types/beta/threads/run.py index d30a32ec97..59a443f75b 100644 --- a/src/openai/types/beta/threads/run.py +++ b/src/openai/types/beta/threads/run.py @@ -1,9 +1,10 @@ # File generated from our OpenAPI spec by Stainless. import builtins -from typing import Dict, List, Union, Optional +from typing import List, Union, Optional from typing_extensions import Literal +from ...shared import FunctionObject from ...._models import BaseModel from .required_action_function_tool_call import RequiredActionFunctionToolCall @@ -16,7 +17,6 @@ "ToolAssistantToolsCode", "ToolAssistantToolsRetrieval", "ToolAssistantToolsFunction", - "ToolAssistantToolsFunctionFunction", ] @@ -51,36 +51,8 @@ class ToolAssistantToolsRetrieval(BaseModel): """The type of tool being defined: `retrieval`""" -class ToolAssistantToolsFunctionFunction(BaseModel): - description: str - """ - A description of what the function does, used by the model to choose when and - how to call the function. - """ - - name: str - """The name of the function to be called. - - Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length - of 64. - """ - - parameters: Dict[str, builtins.object] - """The parameters the functions accepts, described as a JSON Schema object. - - See the [guide](https://platform.openai.com/docs/guides/gpt/function-calling) - for examples, and the - [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for - documentation about the format. - - To describe a function that accepts no parameters, provide the value - `{"type": "object", "properties": {}}`. - """ - - class ToolAssistantToolsFunction(BaseModel): - function: ToolAssistantToolsFunctionFunction - """The function definition.""" + function: FunctionObject type: Literal["function"] """The type of tool being defined: `function`""" @@ -147,8 +119,8 @@ class Run(BaseModel): this run. """ - object: Literal["assistant.run"] - """The object type, which is always `assistant.run`.""" + object: Literal["thread.run"] + """The object type, which is always `thread.run`.""" required_action: Optional[RequiredAction] """Details on the action required to continue the run. diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index cf1bb9f05d..27e5a86a8e 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -2,16 +2,17 @@ from __future__ import annotations -from typing import Dict, List, Union, Optional +from typing import List, Union, Optional from typing_extensions import Literal, Required, TypedDict +from ....types import shared_params + __all__ = [ "RunCreateParams", "Tool", "ToolAssistantToolsCode", "ToolAssistantToolsRetrieval", "ToolAssistantToolsFunction", - "ToolAssistantToolsFunctionFunction", ] @@ -62,36 +63,8 @@ class ToolAssistantToolsRetrieval(TypedDict, total=False): """The type of tool being defined: `retrieval`""" -class ToolAssistantToolsFunctionFunction(TypedDict, total=False): - description: Required[str] - """ - A description of what the function does, used by the model to choose when and - how to call the function. - """ - - name: Required[str] - """The name of the function to be called. - - Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length - of 64. - """ - - parameters: Required[Dict[str, object]] - """The parameters the functions accepts, described as a JSON Schema object. - - See the [guide](https://platform.openai.com/docs/guides/gpt/function-calling) - for examples, and the - [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for - documentation about the format. - - To describe a function that accepts no parameters, provide the value - `{"type": "object", "properties": {}}`. - """ - - class ToolAssistantToolsFunction(TypedDict, total=False): - function: Required[ToolAssistantToolsFunctionFunction] - """The function definition.""" + function: Required[shared_params.FunctionObject] type: Required[Literal["function"]] """The type of tool being defined: `function`""" diff --git a/src/openai/types/beta/threads/runs/run_step.py b/src/openai/types/beta/threads/runs/run_step.py index 17a567dc0e..536cf04ab1 100644 --- a/src/openai/types/beta/threads/runs/run_step.py +++ b/src/openai/types/beta/threads/runs/run_step.py @@ -65,8 +65,8 @@ class RunStep(BaseModel): a maxium of 512 characters long. """ - object: Literal["assistant.run.step"] - """The object type, which is always `assistant.run.step``.""" + object: Literal["thread.run.step"] + """The object type, which is always `thread.run.step``.""" run_id: str """ @@ -76,8 +76,8 @@ class RunStep(BaseModel): status: Literal["in_progress", "cancelled", "failed", "completed", "expired"] """ - The status of the run, which can be either `in_progress`, `cancelled`, `failed`, - `completed`, or `expired`. + The status of the run step, which can be either `in_progress`, `cancelled`, + `failed`, `completed`, or `expired`. """ step_details: StepDetails diff --git a/src/openai/types/chat/chat_completion_chunk.py b/src/openai/types/chat/chat_completion_chunk.py index 568f530280..6be046b01e 100644 --- a/src/openai/types/chat/chat_completion_chunk.py +++ b/src/openai/types/chat/chat_completion_chunk.py @@ -111,8 +111,8 @@ class ChatCompletionChunk(BaseModel): """The object type, which is always `chat.completion.chunk`.""" system_fingerprint: Optional[str] = None - """This fingerprint represents the backend configuration that the model runs with. - + """ + This fingerprint represents the backend configuration that the model runs with. Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. """ diff --git a/src/openai/types/chat/chat_completion_tool_param.py b/src/openai/types/chat/chat_completion_tool_param.py index 4b7e6238c7..97e73f17ce 100644 --- a/src/openai/types/chat/chat_completion_tool_param.py +++ b/src/openai/types/chat/chat_completion_tool_param.py @@ -2,41 +2,15 @@ from __future__ import annotations -from typing import Dict from typing_extensions import Literal, Required, TypedDict -__all__ = ["ChatCompletionToolParam", "Function"] +from ...types import shared_params - -class Function(TypedDict, total=False): - name: Required[str] - """The name of the function to be called. - - Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length - of 64. - """ - - parameters: Required[Dict[str, object]] - """The parameters the functions accepts, described as a JSON Schema object. - - See the [guide](https://platform.openai.com/docs/guides/gpt/function-calling) - for examples, and the - [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for - documentation about the format. - - To describe a function that accepts no parameters, provide the value - `{"type": "object", "properties": {}}`. - """ - - description: str - """ - A description of what the function does, used by the model to choose when and - how to call the function. - """ +__all__ = ["ChatCompletionToolParam"] class ChatCompletionToolParam(TypedDict, total=False): - function: Required[Function] + function: Required[shared_params.FunctionObject] type: Required[Literal["function"]] """The type of the tool. Currently, only `function` is supported.""" diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index b310761077..51c864588b 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -5,6 +5,7 @@ from typing import Dict, List, Union, Optional from typing_extensions import Literal, Required, TypedDict +from ...types import shared_params from .chat_completion_tool_param import ChatCompletionToolParam from .chat_completion_message_param import ChatCompletionMessageParam from .chat_completion_tool_choice_option_param import ( @@ -121,7 +122,16 @@ class CompletionCreateParamsBase(TypedDict, total=False): response_format: ResponseFormat """An object specifying the format that the model must output. - Used to enable JSON mode. + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in increased latency and appearance of a "stuck" request. Also + note that the message content may be partially cut off if + `finish_reason="length"`, which indicates the generation exceeded `max_tokens` + or the conversation exceeded the max context length. """ seed: Optional[int] @@ -193,7 +203,7 @@ class Function(TypedDict, total=False): of 64. """ - parameters: Required[Dict[str, object]] + parameters: Required[shared_params.FunctionParameters] """The parameters the functions accepts, described as a JSON Schema object. See the [guide](https://platform.openai.com/docs/guides/gpt/function-calling) @@ -214,19 +224,7 @@ class Function(TypedDict, total=False): class ResponseFormat(TypedDict, total=False): type: Literal["text", "json_object"] - """Setting to `json_object` enables JSON mode. - - This guarantees that the message the model generates is valid JSON. - - Note that your system prompt must still instruct the model to produce JSON, and - to help ensure you don't forget, the API will throw an error if the string - `JSON` does not appear in your system message. Also note that the message - content may be partial (i.e. cut off) if `finish_reason="length"`, which - indicates the generation exceeded `max_tokens` or the conversation exceeded the - max context length. - - Must be one of `text` or `json_object`. - """ + """Must be one of `text` or `json_object`.""" class CompletionCreateParamsNonStreaming(CompletionCreateParamsBase): diff --git a/src/openai/types/completion_choice.py b/src/openai/types/completion_choice.py index e86d706ed1..71de0f9247 100644 --- a/src/openai/types/completion_choice.py +++ b/src/openai/types/completion_choice.py @@ -15,7 +15,7 @@ class Logprobs(BaseModel): tokens: Optional[List[str]] = None - top_logprobs: Optional[List[Dict[str, int]]] = None + top_logprobs: Optional[List[Dict[str, float]]] = None class CompletionChoice(BaseModel): diff --git a/src/openai/types/shared/__init__.py b/src/openai/types/shared/__init__.py new file mode 100644 index 0000000000..ab67c41471 --- /dev/null +++ b/src/openai/types/shared/__init__.py @@ -0,0 +1,4 @@ +# File generated from our OpenAPI spec by Stainless. + +from .function_object import FunctionObject as FunctionObject +from .function_parameters import FunctionParameters as FunctionParameters diff --git a/src/openai/types/shared/function_object.py b/src/openai/types/shared/function_object.py new file mode 100644 index 0000000000..f566fe530d --- /dev/null +++ b/src/openai/types/shared/function_object.py @@ -0,0 +1,35 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Optional + +from ..._models import BaseModel +from .function_parameters import FunctionParameters + +__all__ = ["FunctionObject"] + + +class FunctionObject(BaseModel): + name: str + """The name of the function to be called. + + Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length + of 64. + """ + + parameters: FunctionParameters + """The parameters the functions accepts, described as a JSON Schema object. + + See the [guide](https://platform.openai.com/docs/guides/gpt/function-calling) + for examples, and the + [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for + documentation about the format. + + To describe a function that accepts no parameters, provide the value + `{"type": "object", "properties": {}}`. + """ + + description: Optional[str] = None + """ + A description of what the function does, used by the model to choose when and + how to call the function. + """ diff --git a/src/openai/types/shared/function_parameters.py b/src/openai/types/shared/function_parameters.py new file mode 100644 index 0000000000..405c2d14cc --- /dev/null +++ b/src/openai/types/shared/function_parameters.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Dict + +__all__ = ["FunctionParameters"] + +FunctionParameters = Dict[str, object] diff --git a/src/openai/types/shared_params/__init__.py b/src/openai/types/shared_params/__init__.py new file mode 100644 index 0000000000..ab67c41471 --- /dev/null +++ b/src/openai/types/shared_params/__init__.py @@ -0,0 +1,4 @@ +# File generated from our OpenAPI spec by Stainless. + +from .function_object import FunctionObject as FunctionObject +from .function_parameters import FunctionParameters as FunctionParameters diff --git a/src/openai/types/shared_params/function_object.py b/src/openai/types/shared_params/function_object.py new file mode 100644 index 0000000000..d3f5d0aaf4 --- /dev/null +++ b/src/openai/types/shared_params/function_object.py @@ -0,0 +1,36 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +from ...types import shared_params + +__all__ = ["FunctionObject"] + + +class FunctionObject(TypedDict, total=False): + name: Required[str] + """The name of the function to be called. + + Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length + of 64. + """ + + parameters: Required[shared_params.FunctionParameters] + """The parameters the functions accepts, described as a JSON Schema object. + + See the [guide](https://platform.openai.com/docs/guides/gpt/function-calling) + for examples, and the + [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for + documentation about the format. + + To describe a function that accepts no parameters, provide the value + `{"type": "object", "properties": {}}`. + """ + + description: str + """ + A description of what the function does, used by the model to choose when and + how to call the function. + """ diff --git a/src/openai/types/shared_params/function_parameters.py b/src/openai/types/shared_params/function_parameters.py new file mode 100644 index 0000000000..a405f6b2e2 --- /dev/null +++ b/src/openai/types/shared_params/function_parameters.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Dict + +__all__ = ["FunctionParameters"] + +FunctionParameters = Dict[str, object] From d3d7e1be4a69a97b473340b8b707893e39cee42e Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 8 Nov 2023 20:28:22 +0000 Subject: [PATCH 075/816] fix(client): show a helpful error message if the v0 API is used (#743) --- src/openai/__init__.py | 1 + src/openai/lib/_old_api.py | 66 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 src/openai/lib/_old_api.py diff --git a/src/openai/__init__.py b/src/openai/__init__.py index da1157a767..d92dfe969a 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -74,6 +74,7 @@ from .version import VERSION as VERSION from .lib.azure import AzureOpenAI as AzureOpenAI from .lib.azure import AsyncAzureOpenAI as AsyncAzureOpenAI +from .lib._old_api import * _setup_logging() diff --git a/src/openai/lib/_old_api.py b/src/openai/lib/_old_api.py new file mode 100644 index 0000000000..c4038fcfaf --- /dev/null +++ b/src/openai/lib/_old_api.py @@ -0,0 +1,66 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING +from typing_extensions import override + +from .._utils import LazyProxy +from .._exceptions import OpenAIError + +INSTRUCTIONS = """ + +You tried to access openai.{symbol}, but this is no longer supported in openai>=1.0.0 - see the README at https://github.com/openai/openai-python for the API. + +You can run `openai migrate` to automatically upgrade your codebase to use the 1.0.0 interface. + +Alternatively, you can pin your installation to the old version, e.g. `pip install openai==0.28` + +A detailed migration guide is available here: https://github.com/openai/openai-python/discussions/742 +""" + + +class APIRemovedInV1(OpenAIError): + def __init__(self, *, symbol: str) -> None: + super().__init__(INSTRUCTIONS.format(symbol=symbol)) + + +class APIRemovedInV1Proxy(LazyProxy[None]): + def __init__(self, *, symbol: str) -> None: + super().__init__() + self._symbol = symbol + + @override + def __load__(self) -> None: + raise APIRemovedInV1(symbol=self._symbol) + + +SYMBOLS = [ + "Edit", + "File", + "Audio", + "Image", + "Model", + "Engine", + "Customer", + "FineTune", + "Embedding", + "Completion", + "Deployment", + "Moderation", + "ErrorObject", + "FineTuningJob", + "ChatCompletion", +] + +# we explicitly tell type checkers that nothing is exported +# from this file so that when we re-export the old symbols +# in `openai/__init__.py` they aren't added to the auto-complete +# suggestions given by editors +if TYPE_CHECKING: + __all__: list[str] = [] +else: + __all__ = SYMBOLS + + +__locals = locals() +for symbol in SYMBOLS: + __locals[symbol] = APIRemovedInV1Proxy(symbol=symbol) From 48834e400a6a5acb0aabefcde7ffe8c996c98d00 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 8 Nov 2023 22:16:27 +0000 Subject: [PATCH 076/816] refactor(api): rename FunctionObject to FunctionDefinition (#746) --- api.md | 2 +- src/openai/types/__init__.py | 2 +- src/openai/types/beta/assistant.py | 4 ++-- src/openai/types/beta/assistant_create_params.py | 2 +- src/openai/types/beta/assistant_update_params.py | 2 +- src/openai/types/beta/thread_create_and_run_params.py | 2 +- src/openai/types/beta/threads/run.py | 4 ++-- src/openai/types/beta/threads/run_create_params.py | 2 +- src/openai/types/chat/chat_completion_tool_param.py | 2 +- src/openai/types/shared/__init__.py | 2 +- .../shared/{function_object.py => function_definition.py} | 4 ++-- src/openai/types/shared_params/__init__.py | 2 +- .../{function_object.py => function_definition.py} | 4 ++-- 13 files changed, 17 insertions(+), 17 deletions(-) rename src/openai/types/shared/{function_object.py => function_definition.py} (93%) rename src/openai/types/shared_params/{function_object.py => function_definition.py} (92%) diff --git a/api.md b/api.md index 0f5cdbbbbf..e0237803de 100644 --- a/api.md +++ b/api.md @@ -1,7 +1,7 @@ # Shared Types ```python -from openai.types import FunctionObject, FunctionParameters +from openai.types import FunctionDefinition, FunctionParameters ``` # Completions diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index 5840599a27..1b4fca26ee 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -5,7 +5,7 @@ from .edit import Edit as Edit from .image import Image as Image from .model import Model as Model -from .shared import FunctionObject as FunctionObject +from .shared import FunctionDefinition as FunctionDefinition from .shared import FunctionParameters as FunctionParameters from .embedding import Embedding as Embedding from .fine_tune import FineTune as FineTune diff --git a/src/openai/types/beta/assistant.py b/src/openai/types/beta/assistant.py index 63332123c0..a21206765a 100644 --- a/src/openai/types/beta/assistant.py +++ b/src/openai/types/beta/assistant.py @@ -4,7 +4,7 @@ from typing import List, Union, Optional from typing_extensions import Literal -from ..shared import FunctionObject +from ..shared import FunctionDefinition from ..._models import BaseModel __all__ = ["Assistant", "Tool", "ToolCodeInterpreter", "ToolRetrieval", "ToolFunction"] @@ -21,7 +21,7 @@ class ToolRetrieval(BaseModel): class ToolFunction(BaseModel): - function: FunctionObject + function: FunctionDefinition type: Literal["function"] """The type of tool being defined: `function`""" diff --git a/src/openai/types/beta/assistant_create_params.py b/src/openai/types/beta/assistant_create_params.py index ce7494efec..539897a7ba 100644 --- a/src/openai/types/beta/assistant_create_params.py +++ b/src/openai/types/beta/assistant_create_params.py @@ -73,7 +73,7 @@ class ToolAssistantToolsRetrieval(TypedDict, total=False): class ToolAssistantToolsFunction(TypedDict, total=False): - function: Required[shared_params.FunctionObject] + function: Required[shared_params.FunctionDefinition] type: Required[Literal["function"]] """The type of tool being defined: `function`""" diff --git a/src/openai/types/beta/assistant_update_params.py b/src/openai/types/beta/assistant_update_params.py index 07a186a0d2..a0efd96ecd 100644 --- a/src/openai/types/beta/assistant_update_params.py +++ b/src/openai/types/beta/assistant_update_params.py @@ -75,7 +75,7 @@ class ToolAssistantToolsRetrieval(TypedDict, total=False): class ToolAssistantToolsFunction(TypedDict, total=False): - function: Required[shared_params.FunctionObject] + function: Required[shared_params.FunctionDefinition] type: Required[Literal["function"]] """The type of tool being defined: `function`""" diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index 8e6b33249c..9f58dcd875 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -112,7 +112,7 @@ class ToolAssistantToolsRetrieval(TypedDict, total=False): class ToolAssistantToolsFunction(TypedDict, total=False): - function: Required[shared_params.FunctionObject] + function: Required[shared_params.FunctionDefinition] type: Required[Literal["function"]] """The type of tool being defined: `function`""" diff --git a/src/openai/types/beta/threads/run.py b/src/openai/types/beta/threads/run.py index 59a443f75b..ffbba1e504 100644 --- a/src/openai/types/beta/threads/run.py +++ b/src/openai/types/beta/threads/run.py @@ -4,7 +4,7 @@ from typing import List, Union, Optional from typing_extensions import Literal -from ...shared import FunctionObject +from ...shared import FunctionDefinition from ...._models import BaseModel from .required_action_function_tool_call import RequiredActionFunctionToolCall @@ -52,7 +52,7 @@ class ToolAssistantToolsRetrieval(BaseModel): class ToolAssistantToolsFunction(BaseModel): - function: FunctionObject + function: FunctionDefinition type: Literal["function"] """The type of tool being defined: `function`""" diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index 27e5a86a8e..df92f4fd2c 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -64,7 +64,7 @@ class ToolAssistantToolsRetrieval(TypedDict, total=False): class ToolAssistantToolsFunction(TypedDict, total=False): - function: Required[shared_params.FunctionObject] + function: Required[shared_params.FunctionDefinition] type: Required[Literal["function"]] """The type of tool being defined: `function`""" diff --git a/src/openai/types/chat/chat_completion_tool_param.py b/src/openai/types/chat/chat_completion_tool_param.py index 97e73f17ce..54c223955e 100644 --- a/src/openai/types/chat/chat_completion_tool_param.py +++ b/src/openai/types/chat/chat_completion_tool_param.py @@ -10,7 +10,7 @@ class ChatCompletionToolParam(TypedDict, total=False): - function: Required[shared_params.FunctionObject] + function: Required[shared_params.FunctionDefinition] type: Required[Literal["function"]] """The type of the tool. Currently, only `function` is supported.""" diff --git a/src/openai/types/shared/__init__.py b/src/openai/types/shared/__init__.py index ab67c41471..05bc4ff9ba 100644 --- a/src/openai/types/shared/__init__.py +++ b/src/openai/types/shared/__init__.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. -from .function_object import FunctionObject as FunctionObject +from .function_definition import FunctionDefinition as FunctionDefinition from .function_parameters import FunctionParameters as FunctionParameters diff --git a/src/openai/types/shared/function_object.py b/src/openai/types/shared/function_definition.py similarity index 93% rename from src/openai/types/shared/function_object.py rename to src/openai/types/shared/function_definition.py index f566fe530d..bfcee50c85 100644 --- a/src/openai/types/shared/function_object.py +++ b/src/openai/types/shared/function_definition.py @@ -5,10 +5,10 @@ from ..._models import BaseModel from .function_parameters import FunctionParameters -__all__ = ["FunctionObject"] +__all__ = ["FunctionDefinition"] -class FunctionObject(BaseModel): +class FunctionDefinition(BaseModel): name: str """The name of the function to be called. diff --git a/src/openai/types/shared_params/__init__.py b/src/openai/types/shared_params/__init__.py index ab67c41471..05bc4ff9ba 100644 --- a/src/openai/types/shared_params/__init__.py +++ b/src/openai/types/shared_params/__init__.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. -from .function_object import FunctionObject as FunctionObject +from .function_definition import FunctionDefinition as FunctionDefinition from .function_parameters import FunctionParameters as FunctionParameters diff --git a/src/openai/types/shared_params/function_object.py b/src/openai/types/shared_params/function_definition.py similarity index 92% rename from src/openai/types/shared_params/function_object.py rename to src/openai/types/shared_params/function_definition.py index d3f5d0aaf4..6bb6fa6ff2 100644 --- a/src/openai/types/shared_params/function_object.py +++ b/src/openai/types/shared_params/function_definition.py @@ -6,10 +6,10 @@ from ...types import shared_params -__all__ = ["FunctionObject"] +__all__ = ["FunctionDefinition"] -class FunctionObject(TypedDict, total=False): +class FunctionDefinition(TypedDict, total=False): name: Required[str] """The name of the function to be called. From cbdafb591c89a9080d66807dc186a398b8c83c79 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 8 Nov 2023 22:27:27 +0000 Subject: [PATCH 077/816] feat(client): support passing chunk size for binary responses (#747) --- src/openai/_base_client.py | 18 ++++++++++++++---- src/openai/_types.py | 15 +++++++++++++-- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index e37759cdf8..b2fe242634 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -1727,9 +1727,14 @@ def iter_raw(self, chunk_size: Optional[int] = None) -> Iterator[bytes]: return self.response.iter_raw(chunk_size) @override - def stream_to_file(self, file: str | os.PathLike[str]) -> None: + def stream_to_file( + self, + file: str | os.PathLike[str], + *, + chunk_size: int | None = None, + ) -> None: with open(file, mode="wb") as f: - for data in self.response.iter_bytes(): + for data in self.response.iter_bytes(chunk_size): f.write(data) @override @@ -1757,10 +1762,15 @@ async def aiter_raw(self, chunk_size: Optional[int] = None) -> AsyncIterator[byt return self.response.aiter_raw(chunk_size) @override - async def astream_to_file(self, file: str | os.PathLike[str]) -> None: + async def astream_to_file( + self, + file: str | os.PathLike[str], + *, + chunk_size: int | None = None, + ) -> None: path = anyio.Path(file) async with await path.open(mode="wb") as f: - async for data in self.response.aiter_bytes(): + async for data in self.response.aiter_bytes(chunk_size): await f.write(data) @override diff --git a/src/openai/_types.py b/src/openai/_types.py index dabd15866f..0d05be9493 100644 --- a/src/openai/_types.py +++ b/src/openai/_types.py @@ -123,7 +123,12 @@ def iter_raw(self, chunk_size: Optional[int] = None) -> Iterator[bytes]: pass @abstractmethod - def stream_to_file(self, file: str | PathLike[str]) -> None: + def stream_to_file( + self, + file: str | PathLike[str], + *, + chunk_size: int | None = None, + ) -> None: """ Stream the output to the given file. """ @@ -172,7 +177,13 @@ async def aiter_raw(self, chunk_size: Optional[int] = None) -> AsyncIterator[byt """ pass - async def astream_to_file(self, file: str | PathLike[str]) -> None: + @abstractmethod + async def astream_to_file( + self, + file: str | PathLike[str], + *, + chunk_size: int | None = None, + ) -> None: """ Stream the output to the given file. """ From 8e4e5d490629a5abfbdf4b6a2ce20c7eee848a2e Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 8 Nov 2023 22:28:01 +0000 Subject: [PATCH 078/816] release: 1.2.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 25 +++++++++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 28 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 9c6a481f5b..d0ab6645f5 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.1.2" + ".": "1.2.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c97964977..1b58f41340 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,30 @@ # Changelog +## 1.2.0 (2023-11-08) + +Full Changelog: [v1.1.2...v1.2.0](https://github.com/openai/openai-python/compare/v1.1.2...v1.2.0) + +### Features + +* **api:** unify function types ([#741](https://github.com/openai/openai-python/issues/741)) ([ed16c4d](https://github.com/openai/openai-python/commit/ed16c4d2fec6cf4e33235d82b05ed9a777752204)) +* **client:** support passing chunk size for binary responses ([#747](https://github.com/openai/openai-python/issues/747)) ([c0c89b7](https://github.com/openai/openai-python/commit/c0c89b77a69ef098900e3a194894efcf72085d36)) + + +### Bug Fixes + +* **api:** update embedding response object type ([#739](https://github.com/openai/openai-python/issues/739)) ([29182c4](https://github.com/openai/openai-python/commit/29182c4818e2c56f46e961dba33e31dc30c25519)) +* **client:** show a helpful error message if the v0 API is used ([#743](https://github.com/openai/openai-python/issues/743)) ([920567c](https://github.com/openai/openai-python/commit/920567cb04df48a7f6cd2a3402a0b1f172c6290e)) + + +### Chores + +* **internal:** improve github devcontainer setup ([#737](https://github.com/openai/openai-python/issues/737)) ([0ac1abb](https://github.com/openai/openai-python/commit/0ac1abb07ec687a4f7b1150be10054dbd6e7cfbc)) + + +### Refactors + +* **api:** rename FunctionObject to FunctionDefinition ([#746](https://github.com/openai/openai-python/issues/746)) ([1afd138](https://github.com/openai/openai-python/commit/1afd13856c0e586ecbde8b24fe4f4bad9beeefdf)) + ## 1.1.2 (2023-11-08) Full Changelog: [v1.1.1...v1.1.2](https://github.com/openai/openai-python/compare/v1.1.1...v1.1.2) diff --git a/pyproject.toml b/pyproject.toml index 0861b1278b..1900794dfc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.1.2" +version = "1.2.0" description = "Client library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 848573b8a1..9d7e588fcf 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.1.2" # x-release-please-version +__version__ = "1.2.0" # x-release-please-version From aa6818997468b753546d55365d8142e2bb1c6640 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 9 Nov 2023 18:46:43 +0000 Subject: [PATCH 079/816] release: 1.2.1 (#754) * refactor(client): deprecate files.retrieve_content in favour of files.content (#753) The latter supports binary response types more elegantly. * docs(readme): fix nested params example (#756) * release: 1.2.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++ README.md | 11 +++- api.md | 1 + pyproject.toml | 2 +- src/openai/_version.py | 2 +- src/openai/resources/files.py | 85 +++++++++++++++++++++++++++++-- tests/api_resources/test_files.py | 73 ++++++++++++++++++++++---- 8 files changed, 170 insertions(+), 19 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index d0ab6645f5..d43a621a8e 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.2.0" + ".": "1.2.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 1b58f41340..1911aef970 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.2.1 (2023-11-09) + +Full Changelog: [v1.2.0...v1.2.1](https://github.com/openai/openai-python/compare/v1.2.0...v1.2.1) + +### Documentation + +* **readme:** fix nested params example ([#756](https://github.com/openai/openai-python/issues/756)) ([ffbe5ec](https://github.com/openai/openai-python/commit/ffbe5eca0f8790ebcdb27ffe845da178a3ef4c45)) + + +### Refactors + +* **client:** deprecate files.retrieve_content in favour of files.content ([#753](https://github.com/openai/openai-python/issues/753)) ([eea5bc1](https://github.com/openai/openai-python/commit/eea5bc173466f63a6e84bd2d741b4873ca056b4c)) + ## 1.2.0 (2023-11-08) Full Changelog: [v1.1.2...v1.2.0](https://github.com/openai/openai-python/compare/v1.1.2...v1.2.0) diff --git a/README.md b/README.md index cedbc72337..11a1236b5a 100644 --- a/README.md +++ b/README.md @@ -237,7 +237,16 @@ from openai import OpenAI client = OpenAI() -page = client.files.list() +completion = client.chat.completions.create( + messages=[ + { + "role": "user", + "content": "Can you generate an example json object describing a fruit?", + } + ], + model="gpt-3.5-turbo", + response_format={"type": "json_object"}, +) ``` ## File Uploads diff --git a/api.md b/api.md index e0237803de..a7ee177411 100644 --- a/api.md +++ b/api.md @@ -87,6 +87,7 @@ Methods: - client.files.retrieve(file_id) -> FileObject - client.files.list(\*\*params) -> SyncPage[FileObject] - client.files.delete(file_id) -> FileDeleted +- client.files.content(file_id) -> HttpxBinaryResponseContent - client.files.retrieve_content(file_id) -> str - client.files.wait_for_processing(\*args) -> FileObject diff --git a/pyproject.toml b/pyproject.toml index 1900794dfc..844f501c45 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.2.0" +version = "1.2.1" description = "Client library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 9d7e588fcf..46c55958e6 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.2.0" # x-release-please-version +__version__ = "1.2.1" # x-release-please-version diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index b317845c3a..a6f75e5a4c 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -3,6 +3,7 @@ from __future__ import annotations import time +import typing_extensions from typing import TYPE_CHECKING, Mapping, cast from typing_extensions import Literal @@ -14,7 +15,11 @@ from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ..pagination import SyncPage, AsyncPage -from .._base_client import AsyncPaginator, make_request_options +from .._base_client import ( + AsyncPaginator, + HttpxBinaryResponseContent, + make_request_options, +) if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI @@ -197,6 +202,38 @@ def delete( cast_to=FileDeleted, ) + def content( + self, + file_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> HttpxBinaryResponseContent: + """ + Returns the contents of the specified file. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get( + f"/files/{file_id}/content", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=HttpxBinaryResponseContent, + ) + + @typing_extensions.deprecated("The `.content()` method should be used instead") def retrieve_content( self, file_id: str, @@ -428,6 +465,38 @@ async def delete( cast_to=FileDeleted, ) + async def content( + self, + file_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> HttpxBinaryResponseContent: + """ + Returns the contents of the specified file. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._get( + f"/files/{file_id}/content", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=HttpxBinaryResponseContent, + ) + + @typing_extensions.deprecated("The `.content()` method should be used instead") async def retrieve_content( self, file_id: str, @@ -498,8 +567,11 @@ def __init__(self, files: Files) -> None: self.delete = to_raw_response_wrapper( files.delete, ) - self.retrieve_content = to_raw_response_wrapper( - files.retrieve_content, + self.content = to_raw_response_wrapper( + files.content, + ) + self.retrieve_content = to_raw_response_wrapper( # pyright: ignore[reportDeprecated] + files.retrieve_content # pyright: ignore[reportDeprecated], ) @@ -517,6 +589,9 @@ def __init__(self, files: AsyncFiles) -> None: self.delete = async_to_raw_response_wrapper( files.delete, ) - self.retrieve_content = async_to_raw_response_wrapper( - files.retrieve_content, + self.content = async_to_raw_response_wrapper( + files.content, + ) + self.retrieve_content = async_to_raw_response_wrapper( # pyright: ignore[reportDeprecated] + files.retrieve_content # pyright: ignore[reportDeprecated], ) diff --git a/tests/api_resources/test_files.py b/tests/api_resources/test_files.py index d668c2d0c7..a2c9d07314 100644 --- a/tests/api_resources/test_files.py +++ b/tests/api_resources/test_files.py @@ -4,14 +4,19 @@ import os +import httpx import pytest +from respx import MockRouter from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.types import FileObject, FileDeleted +from openai._types import BinaryResponseContent from openai._client import OpenAI, AsyncOpenAI from openai.pagination import SyncPage, AsyncPage +# pyright: reportDeprecated=false + base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") api_key = "My API Key" @@ -91,19 +96,43 @@ def test_raw_response_delete(self, client: OpenAI) -> None: assert_matches_type(FileDeleted, file, path=["response"]) @parametrize - def test_method_retrieve_content(self, client: OpenAI) -> None: - file = client.files.retrieve_content( + @pytest.mark.respx(base_url=base_url) + def test_method_content(self, client: OpenAI, respx_mock: MockRouter) -> None: + respx_mock.get("/files/{file_id}/content").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + file = client.files.content( "string", ) - assert_matches_type(str, file, path=["response"]) + assert isinstance(file, BinaryResponseContent) + assert file.json() == {"foo": "bar"} @parametrize - def test_raw_response_retrieve_content(self, client: OpenAI) -> None: - response = client.files.with_raw_response.retrieve_content( + @pytest.mark.respx(base_url=base_url) + def test_raw_response_content(self, client: OpenAI, respx_mock: MockRouter) -> None: + respx_mock.get("/files/{file_id}/content").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + response = client.files.with_raw_response.content( "string", ) assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() + assert isinstance(file, BinaryResponseContent) + assert file.json() == {"foo": "bar"} + + @parametrize + def test_method_retrieve_content(self, client: OpenAI) -> None: + with pytest.warns(DeprecationWarning): + file = client.files.retrieve_content( + "string", + ) + assert_matches_type(str, file, path=["response"]) + + @parametrize + def test_raw_response_retrieve_content(self, client: OpenAI) -> None: + with pytest.warns(DeprecationWarning): + response = client.files.with_raw_response.retrieve_content( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() assert_matches_type(str, file, path=["response"]) @@ -182,17 +211,41 @@ async def test_raw_response_delete(self, client: AsyncOpenAI) -> None: assert_matches_type(FileDeleted, file, path=["response"]) @parametrize - async def test_method_retrieve_content(self, client: AsyncOpenAI) -> None: - file = await client.files.retrieve_content( + @pytest.mark.respx(base_url=base_url) + async def test_method_content(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: + respx_mock.get("/files/{file_id}/content").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + file = await client.files.content( "string", ) - assert_matches_type(str, file, path=["response"]) + assert isinstance(file, BinaryResponseContent) + assert file.json() == {"foo": "bar"} @parametrize - async def test_raw_response_retrieve_content(self, client: AsyncOpenAI) -> None: - response = await client.files.with_raw_response.retrieve_content( + @pytest.mark.respx(base_url=base_url) + async def test_raw_response_content(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: + respx_mock.get("/files/{file_id}/content").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + response = await client.files.with_raw_response.content( "string", ) assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() + assert isinstance(file, BinaryResponseContent) + assert file.json() == {"foo": "bar"} + + @parametrize + async def test_method_retrieve_content(self, client: AsyncOpenAI) -> None: + with pytest.warns(DeprecationWarning): + file = await client.files.retrieve_content( + "string", + ) + assert_matches_type(str, file, path=["response"]) + + @parametrize + async def test_raw_response_retrieve_content(self, client: AsyncOpenAI) -> None: + with pytest.warns(DeprecationWarning): + response = await client.files.with_raw_response.retrieve_content( + "string", + ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() assert_matches_type(str, file, path=["response"]) From 1455a7c122cc7c8f522576c269cf642925f56869 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 9 Nov 2023 20:17:50 +0000 Subject: [PATCH 080/816] fix(client): correctly assign error properties (#759) --- src/openai/_client.py | 40 +++++++++++++++++++++------------------- 1 file changed, 21 insertions(+), 19 deletions(-) diff --git a/src/openai/_client.py b/src/openai/_client.py index 6476d2b1a8..7820d5f96d 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -20,7 +20,7 @@ ProxiesTypes, RequestOptions, ) -from ._utils import is_given +from ._utils import is_given, is_mapping from ._version import __version__ from ._streaming import Stream as Stream from ._streaming import AsyncStream as AsyncStream @@ -221,30 +221,31 @@ def _make_status_error( body: object, response: httpx.Response, ) -> APIStatusError: + data = body.get("error", body) if is_mapping(body) else body if response.status_code == 400: - return _exceptions.BadRequestError(err_msg, response=response, body=body) + return _exceptions.BadRequestError(err_msg, response=response, body=data) if response.status_code == 401: - return _exceptions.AuthenticationError(err_msg, response=response, body=body) + return _exceptions.AuthenticationError(err_msg, response=response, body=data) if response.status_code == 403: - return _exceptions.PermissionDeniedError(err_msg, response=response, body=body) + return _exceptions.PermissionDeniedError(err_msg, response=response, body=data) if response.status_code == 404: - return _exceptions.NotFoundError(err_msg, response=response, body=body) + return _exceptions.NotFoundError(err_msg, response=response, body=data) if response.status_code == 409: - return _exceptions.ConflictError(err_msg, response=response, body=body) + return _exceptions.ConflictError(err_msg, response=response, body=data) if response.status_code == 422: - return _exceptions.UnprocessableEntityError(err_msg, response=response, body=body) + return _exceptions.UnprocessableEntityError(err_msg, response=response, body=data) if response.status_code == 429: - return _exceptions.RateLimitError(err_msg, response=response, body=body) + return _exceptions.RateLimitError(err_msg, response=response, body=data) if response.status_code >= 500: - return _exceptions.InternalServerError(err_msg, response=response, body=body) - return APIStatusError(err_msg, response=response, body=body) + return _exceptions.InternalServerError(err_msg, response=response, body=data) + return APIStatusError(err_msg, response=response, body=data) class AsyncOpenAI(AsyncAPIClient): @@ -431,30 +432,31 @@ def _make_status_error( body: object, response: httpx.Response, ) -> APIStatusError: + data = body.get("error", body) if is_mapping(body) else body if response.status_code == 400: - return _exceptions.BadRequestError(err_msg, response=response, body=body) + return _exceptions.BadRequestError(err_msg, response=response, body=data) if response.status_code == 401: - return _exceptions.AuthenticationError(err_msg, response=response, body=body) + return _exceptions.AuthenticationError(err_msg, response=response, body=data) if response.status_code == 403: - return _exceptions.PermissionDeniedError(err_msg, response=response, body=body) + return _exceptions.PermissionDeniedError(err_msg, response=response, body=data) if response.status_code == 404: - return _exceptions.NotFoundError(err_msg, response=response, body=body) + return _exceptions.NotFoundError(err_msg, response=response, body=data) if response.status_code == 409: - return _exceptions.ConflictError(err_msg, response=response, body=body) + return _exceptions.ConflictError(err_msg, response=response, body=data) if response.status_code == 422: - return _exceptions.UnprocessableEntityError(err_msg, response=response, body=body) + return _exceptions.UnprocessableEntityError(err_msg, response=response, body=data) if response.status_code == 429: - return _exceptions.RateLimitError(err_msg, response=response, body=body) + return _exceptions.RateLimitError(err_msg, response=response, body=data) if response.status_code >= 500: - return _exceptions.InternalServerError(err_msg, response=response, body=body) - return APIStatusError(err_msg, response=response, body=body) + return _exceptions.InternalServerError(err_msg, response=response, body=data) + return APIStatusError(err_msg, response=response, body=data) class OpenAIWithRawResponse: From 448ac7d046d12c26064b2050f3ce82bde3a24943 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 9 Nov 2023 20:23:35 +0000 Subject: [PATCH 081/816] docs(readme): link to migration guide (#761) --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 11a1236b5a..1e8bf6ecec 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,9 @@ The API documentation can be found [here](https://platform.openai.com/docs). ## Installation +> [!IMPORTANT] +> The SDK was rewritten in v1, which was released November 6th 2023. See the [v1 migration guide](https://github.com/openai/openai-python/discussions/742), which includes scripts to automatically update your code. + ```sh pip install openai ``` From 45f60e82cf31571b055de948fdf75d44c67a9097 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 9 Nov 2023 20:24:13 +0000 Subject: [PATCH 082/816] release: 1.2.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index d43a621a8e..029e2d7cb4 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.2.1" + ".": "1.2.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 1911aef970..591c32b504 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.2.2 (2023-11-09) + +Full Changelog: [v1.2.1...v1.2.2](https://github.com/openai/openai-python/compare/v1.2.1...v1.2.2) + +### Bug Fixes + +* **client:** correctly assign error properties ([#759](https://github.com/openai/openai-python/issues/759)) ([ef264d2](https://github.com/openai/openai-python/commit/ef264d2293b77784f69039291ca2a17a454851cb)) + + +### Documentation + +* **readme:** link to migration guide ([#761](https://github.com/openai/openai-python/issues/761)) ([ddde839](https://github.com/openai/openai-python/commit/ddde8392be19e7ad77280374806667ecaef612da)) + ## 1.2.1 (2023-11-09) Full Changelog: [v1.2.0...v1.2.1](https://github.com/openai/openai-python/compare/v1.2.0...v1.2.1) diff --git a/pyproject.toml b/pyproject.toml index 844f501c45..7674d01e92 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.2.1" +version = "1.2.2" description = "Client library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 46c55958e6..b00734d2f4 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.2.1" # x-release-please-version +__version__ = "1.2.2" # x-release-please-version From b185cb3196ce1e7b9455e1cbfe0c2167ab566bd9 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 9 Nov 2023 22:57:00 +0000 Subject: [PATCH 083/816] docs: reword package description (#764) --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 7674d01e92..de28d4e913 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,7 +1,7 @@ [project] name = "openai" version = "1.2.2" -description = "Client library for the openai API" +description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" authors = [ From 460a28217e86b66aaeaf867f3d2f64dbae57a692 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 10 Nov 2023 08:24:51 +0000 Subject: [PATCH 084/816] fix: prevent IndexError in fine-tunes CLI (#768) --- src/openai/lib/_validators.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/openai/lib/_validators.py b/src/openai/lib/_validators.py index 8e4ed3c9f4..c8608c0cef 100644 --- a/src/openai/lib/_validators.py +++ b/src/openai/lib/_validators.py @@ -407,7 +407,7 @@ def completions_space_start_validator(df: pd.DataFrame) -> Remediation: """ def add_space_start(x: Any) -> Any: - x["completion"] = x["completion"].apply(lambda x: ("" if x[0] == " " else " ") + x) + x["completion"] = x["completion"].apply(lambda s: ("" if s.startswith(" ") else " ") + s) return x optional_msg = None From 7e2b2544f0206254d3ca094a3a4247397578497f Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 10 Nov 2023 10:00:50 +0000 Subject: [PATCH 085/816] fix(client): correctly flush the stream response body (#771) --- src/openai/_streaming.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/openai/_streaming.py b/src/openai/_streaming.py index cee737f4f5..095746630b 100644 --- a/src/openai/_streaming.py +++ b/src/openai/_streaming.py @@ -47,8 +47,9 @@ def __stream__(self) -> Iterator[ResponseT]: cast_to = self._cast_to response = self.response process_data = self._client._process_response_data + iterator = self._iter_events() - for sse in self._iter_events(): + for sse in iterator: if sse.data.startswith("[DONE]"): break @@ -63,6 +64,10 @@ def __stream__(self) -> Iterator[ResponseT]: yield process_data(data=data, cast_to=cast_to, response=response) + # Ensure the entire stream is consumed + for sse in iterator: + ... + class AsyncStream(Generic[ResponseT]): """Provides the core interface to iterate over an asynchronous stream response.""" @@ -97,8 +102,9 @@ async def __stream__(self) -> AsyncIterator[ResponseT]: cast_to = self._cast_to response = self.response process_data = self._client._process_response_data + iterator = self._iter_events() - async for sse in self._iter_events(): + async for sse in iterator: if sse.data.startswith("[DONE]"): break @@ -113,6 +119,10 @@ async def __stream__(self) -> AsyncIterator[ResponseT]: yield process_data(data=data, cast_to=cast_to, response=response) + # Ensure the entire stream is consumed + async for sse in iterator: + ... + class ServerSentEvent: def __init__( From c5975bd02faf2e2b107a2cbfaead0c68b42c85b9 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 10 Nov 2023 12:51:04 +0000 Subject: [PATCH 086/816] fix(models): mark unknown fields as set in pydantic v1 (#772) --- src/openai/_models.py | 1 + tests/api_resources/audio/test_speech.py | 6 ++++++ tests/api_resources/test_files.py | 4 ++++ tests/test_client.py | 12 ++++++------ tests/test_module_client.py | 7 +++++-- tests/test_transform.py | 11 +++++++++-- 6 files changed, 31 insertions(+), 10 deletions(-) diff --git a/src/openai/_models.py b/src/openai/_models.py index 00d787ca87..ebaef99454 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -121,6 +121,7 @@ def construct( if PYDANTIC_V2: _extra[key] = value else: + _fields_set.add(key) fields_values[key] = value object.__setattr__(m, "__dict__", fields_values) diff --git a/tests/api_resources/audio/test_speech.py b/tests/api_resources/audio/test_speech.py index 89814c2dd3..50b00b73b4 100644 --- a/tests/api_resources/audio/test_speech.py +++ b/tests/api_resources/audio/test_speech.py @@ -21,6 +21,7 @@ class TestSpeech: loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + @pytest.mark.skip(reason="Mocked tests are currently broken") @parametrize @pytest.mark.respx(base_url=base_url) def test_method_create(self, client: OpenAI, respx_mock: MockRouter) -> None: @@ -33,6 +34,7 @@ def test_method_create(self, client: OpenAI, respx_mock: MockRouter) -> None: assert isinstance(speech, BinaryResponseContent) assert speech.json() == {"foo": "bar"} + @pytest.mark.skip(reason="Mocked tests are currently broken") @parametrize @pytest.mark.respx(base_url=base_url) def test_method_create_with_all_params(self, client: OpenAI, respx_mock: MockRouter) -> None: @@ -48,6 +50,7 @@ def test_method_create_with_all_params(self, client: OpenAI, respx_mock: MockRou assert isinstance(speech, BinaryResponseContent) assert speech.json() == {"foo": "bar"} + @pytest.mark.skip(reason="Mocked tests are currently broken") @parametrize @pytest.mark.respx(base_url=base_url) def test_raw_response_create(self, client: OpenAI, respx_mock: MockRouter) -> None: @@ -68,6 +71,7 @@ class TestAsyncSpeech: loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + @pytest.mark.skip(reason="Mocked tests are currently broken") @parametrize @pytest.mark.respx(base_url=base_url) async def test_method_create(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: @@ -80,6 +84,7 @@ async def test_method_create(self, client: AsyncOpenAI, respx_mock: MockRouter) assert isinstance(speech, BinaryResponseContent) assert speech.json() == {"foo": "bar"} + @pytest.mark.skip(reason="Mocked tests are currently broken") @parametrize @pytest.mark.respx(base_url=base_url) async def test_method_create_with_all_params(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: @@ -95,6 +100,7 @@ async def test_method_create_with_all_params(self, client: AsyncOpenAI, respx_mo assert isinstance(speech, BinaryResponseContent) assert speech.json() == {"foo": "bar"} + @pytest.mark.skip(reason="Mocked tests are currently broken") @parametrize @pytest.mark.respx(base_url=base_url) async def test_raw_response_create(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: diff --git a/tests/api_resources/test_files.py b/tests/api_resources/test_files.py index a2c9d07314..e4cf493319 100644 --- a/tests/api_resources/test_files.py +++ b/tests/api_resources/test_files.py @@ -95,6 +95,7 @@ def test_raw_response_delete(self, client: OpenAI) -> None: file = response.parse() assert_matches_type(FileDeleted, file, path=["response"]) + @pytest.mark.skip(reason="mocked response isn't working yet") @parametrize @pytest.mark.respx(base_url=base_url) def test_method_content(self, client: OpenAI, respx_mock: MockRouter) -> None: @@ -105,6 +106,7 @@ def test_method_content(self, client: OpenAI, respx_mock: MockRouter) -> None: assert isinstance(file, BinaryResponseContent) assert file.json() == {"foo": "bar"} + @pytest.mark.skip(reason="mocked response isn't working yet") @parametrize @pytest.mark.respx(base_url=base_url) def test_raw_response_content(self, client: OpenAI, respx_mock: MockRouter) -> None: @@ -210,6 +212,7 @@ async def test_raw_response_delete(self, client: AsyncOpenAI) -> None: file = response.parse() assert_matches_type(FileDeleted, file, path=["response"]) + @pytest.mark.skip(reason="mocked response isn't working yet") @parametrize @pytest.mark.respx(base_url=base_url) async def test_method_content(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: @@ -220,6 +223,7 @@ async def test_method_content(self, client: AsyncOpenAI, respx_mock: MockRouter) assert isinstance(file, BinaryResponseContent) assert file.json() == {"foo": "bar"} + @pytest.mark.skip(reason="mocked response isn't working yet") @parametrize @pytest.mark.respx(base_url=base_url) async def test_raw_response_content(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: diff --git a/tests/test_client.py b/tests/test_client.py index 3b70594ecd..e3daa4d2b1 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -41,12 +41,12 @@ class TestOpenAI: @pytest.mark.respx(base_url=base_url) def test_raw_response(self, respx_mock: MockRouter) -> None: - respx_mock.post("/foo").mock(return_value=httpx.Response(200, json='{"foo": "bar"}')) + respx_mock.post("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"})) response = self.client.post("/foo", cast_to=httpx.Response) assert response.status_code == 200 assert isinstance(response, httpx.Response) - assert response.json() == '{"foo": "bar"}' + assert response.json() == {"foo": "bar"} @pytest.mark.respx(base_url=base_url) def test_raw_response_for_binary(self, respx_mock: MockRouter) -> None: @@ -57,7 +57,7 @@ def test_raw_response_for_binary(self, respx_mock: MockRouter) -> None: response = self.client.post("/foo", cast_to=httpx.Response) assert response.status_code == 200 assert isinstance(response, httpx.Response) - assert response.json() == '{"foo": "bar"}' + assert response.json() == {"foo": "bar"} def test_copy(self) -> None: copied = self.client.copy() @@ -571,12 +571,12 @@ class TestAsyncOpenAI: @pytest.mark.respx(base_url=base_url) @pytest.mark.asyncio async def test_raw_response(self, respx_mock: MockRouter) -> None: - respx_mock.post("/foo").mock(return_value=httpx.Response(200, json='{"foo": "bar"}')) + respx_mock.post("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"})) response = await self.client.post("/foo", cast_to=httpx.Response) assert response.status_code == 200 assert isinstance(response, httpx.Response) - assert response.json() == '{"foo": "bar"}' + assert response.json() == {"foo": "bar"} @pytest.mark.respx(base_url=base_url) @pytest.mark.asyncio @@ -588,7 +588,7 @@ async def test_raw_response_for_binary(self, respx_mock: MockRouter) -> None: response = await self.client.post("/foo", cast_to=httpx.Response) assert response.status_code == 200 assert isinstance(response, httpx.Response) - assert response.json() == '{"foo": "bar"}' + assert response.json() == {"foo": "bar"} def test_copy(self) -> None: copied = self.client.copy() diff --git a/tests/test_module_client.py b/tests/test_module_client.py index 0beca37f61..50b7369e19 100644 --- a/tests/test_module_client.py +++ b/tests/test_module_client.py @@ -125,7 +125,10 @@ def test_azure_api_key_env_without_api_version() -> None: openai.api_type = None _os.environ["AZURE_OPENAI_API_KEY"] = "example API key" - with pytest.raises(ValueError, match=r"Expected `api_version` to be given for the Azure client"): + with pytest.raises( + ValueError, + match=r"Must provide either the `api_version` argument or the `OPENAI_API_VERSION` environment variable", + ): openai.completions._client @@ -137,7 +140,7 @@ def test_azure_api_key_and_version_env() -> None: with pytest.raises( ValueError, - match=r"Must provide one of the `base_url` or `azure_endpoint` arguments, or the `OPENAI_BASE_URL`", + match=r"Must provide one of the `base_url` or `azure_endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable", ): openai.completions._client diff --git a/tests/test_transform.py b/tests/test_transform.py index 3fc89bb093..483db680f8 100644 --- a/tests/test_transform.py +++ b/tests/test_transform.py @@ -7,6 +7,7 @@ import pytest from openai._utils import PropertyInfo, transform, parse_datetime +from openai._compat import PYDANTIC_V2 from openai._models import BaseModel @@ -210,14 +211,20 @@ def test_pydantic_unknown_field() -> None: def test_pydantic_mismatched_types() -> None: model = MyModel.construct(foo=True) - with pytest.warns(UserWarning): + if PYDANTIC_V2: + with pytest.warns(UserWarning): + params = transform(model, Any) + else: params = transform(model, Any) assert params == {"foo": True} def test_pydantic_mismatched_object_type() -> None: model = MyModel.construct(foo=MyModel.construct(hello="world")) - with pytest.warns(UserWarning): + if PYDANTIC_V2: + with pytest.warns(UserWarning): + params = transform(model, Any) + else: params = transform(model, Any) assert params == {"foo": {"hello": "world"}} From a10655ad0c7b00d1047f36636f9f8b7cfd1e2c23 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 10 Nov 2023 16:07:32 +0000 Subject: [PATCH 087/816] fix(client): serialise pydantic v1 default fields correctly in params (#776) --- src/openai/_utils/_transform.py | 2 +- tests/test_transform.py | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/openai/_utils/_transform.py b/src/openai/_utils/_transform.py index dc497ea329..d953505fff 100644 --- a/src/openai/_utils/_transform.py +++ b/src/openai/_utils/_transform.py @@ -168,7 +168,7 @@ def _transform_recursive( return data if isinstance(data, pydantic.BaseModel): - return model_dump(data, exclude_unset=True, exclude_defaults=True) + return model_dump(data, exclude_unset=True) return _transform_value(data, annotation) diff --git a/tests/test_transform.py b/tests/test_transform.py index 483db680f8..5e15385f4d 100644 --- a/tests/test_transform.py +++ b/tests/test_transform.py @@ -237,3 +237,29 @@ def test_pydantic_nested_objects() -> None: model = ModelNestedObjects.construct(nested={"foo": "stainless"}) assert isinstance(model.nested, MyModel) assert transform(model, Any) == {"nested": {"foo": "stainless"}} + + +class ModelWithDefaultField(BaseModel): + foo: str + with_none_default: Union[str, None] = None + with_str_default: str = "foo" + + +def test_pydantic_default_field() -> None: + # should be excluded when defaults are used + model = ModelWithDefaultField.construct() + assert model.with_none_default is None + assert model.with_str_default == "foo" + assert transform(model, Any) == {} + + # should be included when the default value is explicitly given + model = ModelWithDefaultField.construct(with_none_default=None, with_str_default="foo") + assert model.with_none_default is None + assert model.with_str_default == "foo" + assert transform(model, Any) == {"with_none_default": None, "with_str_default": "foo"} + + # should be included when a non-default value is explicitly given + model = ModelWithDefaultField.construct(with_none_default="bar", with_str_default="baz") + assert model.with_none_default == "bar" + assert model.with_str_default == "baz" + assert transform(model, Any) == {"with_none_default": "bar", "with_str_default": "baz"} From 2425c15243f92d6c05918f3a731d43bf86c6d08f Mon Sep 17 00:00:00 2001 From: thiswillbeyourgithub <26625900+thiswillbeyourgithub@users.noreply.github.com> Date: Fri, 10 Nov 2023 18:23:33 +0100 Subject: [PATCH 088/816] fix(cli/audio): file format detection failing for whisper (#733) Signed-off-by: thiswillbeyourgithub <26625900+thiswillbeyourgithub@users.noreply.github.com> --- src/openai/cli/_api/audio.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/openai/cli/_api/audio.py b/src/openai/cli/_api/audio.py index eaf57748ad..90d21b9932 100644 --- a/src/openai/cli/_api/audio.py +++ b/src/openai/cli/_api/audio.py @@ -66,7 +66,7 @@ def transcribe(args: CLITranscribeArgs) -> None: buffer_reader = BufferReader(file_reader.read(), desc="Upload progress") model = get_client().audio.transcriptions.create( - file=buffer_reader, + file=(args.file, buffer_reader), model=args.model, language=args.language or NOT_GIVEN, temperature=args.temperature or NOT_GIVEN, @@ -83,7 +83,7 @@ def translate(args: CLITranslationArgs) -> None: buffer_reader = BufferReader(file_reader.read(), desc="Upload progress") model = get_client().audio.translations.create( - file=buffer_reader, + file=(args.file, buffer_reader), model=args.model, temperature=args.temperature or NOT_GIVEN, prompt=args.prompt or NOT_GIVEN, From 4948308f37ecd9872708f42dc0f92dc5ab5ab4d8 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 10 Nov 2023 17:36:08 +0000 Subject: [PATCH 089/816] release: 1.2.3 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 17 +++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 20 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 029e2d7cb4..a237539253 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.2.2" + ".": "1.2.3" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 591c32b504..955fe7a405 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,22 @@ # Changelog +## 1.2.3 (2023-11-10) + +Full Changelog: [v1.2.2...v1.2.3](https://github.com/openai/openai-python/compare/v1.2.2...v1.2.3) + +### Bug Fixes + +* **cli/audio:** file format detection failing for whisper ([#733](https://github.com/openai/openai-python/issues/733)) ([01079d6](https://github.com/openai/openai-python/commit/01079d6dca13e0ec158dff81e0706d8a9d6c02ef)) +* **client:** correctly flush the stream response body ([#771](https://github.com/openai/openai-python/issues/771)) ([0d52731](https://github.com/openai/openai-python/commit/0d5273165c96286f8456ae04b9eb0de5144e52f8)) +* **client:** serialise pydantic v1 default fields correctly in params ([#776](https://github.com/openai/openai-python/issues/776)) ([d4c49ad](https://github.com/openai/openai-python/commit/d4c49ad2be9c0d926eece5fd33f6836279ea21e2)) +* **models:** mark unknown fields as set in pydantic v1 ([#772](https://github.com/openai/openai-python/issues/772)) ([ae032a1](https://github.com/openai/openai-python/commit/ae032a1ba4efa72284a572bfaf0305af50142835)) +* prevent IndexError in fine-tunes CLI ([#768](https://github.com/openai/openai-python/issues/768)) ([42f1633](https://github.com/openai/openai-python/commit/42f16332cf0f96f243f9797d6406283865254355)) + + +### Documentation + +* reword package description ([#764](https://github.com/openai/openai-python/issues/764)) ([9ff10df](https://github.com/openai/openai-python/commit/9ff10df30ca2d44978eb5f982ccf039c9f1bf1bf)) + ## 1.2.2 (2023-11-09) Full Changelog: [v1.2.1...v1.2.2](https://github.com/openai/openai-python/compare/v1.2.1...v1.2.2) diff --git a/pyproject.toml b/pyproject.toml index de28d4e913..e27c6de9ab 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.2.2" +version = "1.2.3" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index b00734d2f4..ebf5d47703 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.2.2" # x-release-please-version +__version__ = "1.2.3" # x-release-please-version From e661da69b4a11d48edfe21d2b12f53c201593596 Mon Sep 17 00:00:00 2001 From: Krista Pratico Date: Fri, 10 Nov 2023 14:39:58 -0800 Subject: [PATCH 090/816] add images/generations to azure endpoints list (#778) --- src/openai/lib/azure.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/openai/lib/azure.py b/src/openai/lib/azure.py index f5fcd24fd1..d31313e95a 100644 --- a/src/openai/lib/azure.py +++ b/src/openai/lib/azure.py @@ -22,6 +22,7 @@ "/embeddings", "/audio/transcriptions", "/audio/translations", + "/images/generations", ] ) From b607e20a7ec75542212fb2e8a1a34602558ea3bd Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 13 Nov 2023 18:12:52 +0000 Subject: [PATCH 091/816] fix(client): retry if SSLWantReadError occurs in the async client (#804) --- src/openai/_base_client.py | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index b2fe242634..3db8b6fa35 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -1320,12 +1320,6 @@ async def _request( if retries > 0: return await self._retry_request(options, cast_to, retries, stream=stream, stream_cls=stream_cls) raise APITimeoutError(request=request) from err - except httpx.ReadTimeout as err: - # We explicitly do not retry on ReadTimeout errors as this means - # that the server processing the request has taken 60 seconds - # (our default timeout). This likely indicates that something - # is not working as expected on the server side. - raise except httpx.TimeoutException as err: if retries > 0: return await self._retry_request(options, cast_to, retries, stream=stream, stream_cls=stream_cls) From 65e29a2efa455a06deb59e243f27796c4ca2254c Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 13 Nov 2023 18:13:35 +0000 Subject: [PATCH 092/816] release: 1.2.4 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index a237539253..862a05b695 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.2.3" + ".": "1.2.4" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 955fe7a405..e1e8a331f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.2.4 (2023-11-13) + +Full Changelog: [v1.2.3...v1.2.4](https://github.com/openai/openai-python/compare/v1.2.3...v1.2.4) + +### Bug Fixes + +* **client:** retry if SSLWantReadError occurs in the async client ([#804](https://github.com/openai/openai-python/issues/804)) ([be82288](https://github.com/openai/openai-python/commit/be82288f3c88c10c9ac20ba3b8cb53b5c7a4e2f9)) + ## 1.2.3 (2023-11-10) Full Changelog: [v1.2.2...v1.2.3](https://github.com/openai/openai-python/compare/v1.2.2...v1.2.3) diff --git a/pyproject.toml b/pyproject.toml index e27c6de9ab..dc08634e4a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.2.3" +version = "1.2.4" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index ebf5d47703..f22b1aae3f 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.2.3" # x-release-please-version +__version__ = "1.2.4" # x-release-please-version From 812839cbc9fa76181a4b13382901e6104b0669db Mon Sep 17 00:00:00 2001 From: Mikyo King Date: Mon, 13 Nov 2023 11:19:50 -0700 Subject: [PATCH 093/816] docs(readme): fix broken azure_ad notebook link (#781) The notebook link in the main README pointed an old directory. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1e8bf6ecec..f3698a9ff4 100644 --- a/README.md +++ b/README.md @@ -489,7 +489,7 @@ In addition to the options provided in the base `OpenAI` client, the following o - `azure_ad_token` - `azure_ad_token_provider` -An example of using the client with Azure Active Directory can be found [here](https://github.com/openai/openai-python/blob/v1/examples/azure_ad.py). +An example of using the client with Azure Active Directory can be found [here](https://github.com/openai/openai-python/blob/main/examples/azure_ad.py). ## Versioning From a73d1ce9d4b20479cba4005f2cb1f03d923dabc6 Mon Sep 17 00:00:00 2001 From: nikkie Date: Tue, 14 Nov 2023 03:54:56 +0900 Subject: [PATCH 094/816] Fix typo in docstring of _types.NotGiven (#794) --- src/openai/_types.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/openai/_types.py b/src/openai/_types.py index 0d05be9493..9e962a1078 100644 --- a/src/openai/_types.py +++ b/src/openai/_types.py @@ -279,8 +279,8 @@ class NotGiven: ```py def get(timeout: Union[int, NotGiven, None] = NotGiven()) -> Response: ... - get(timout=1) # 1s timeout - get(timout=None) # No timeout + get(timeout=1) # 1s timeout + get(timeout=None) # No timeout get() # Default timeout behavior, which may not be statically known at the method definition. ``` """ From 7d06760d8d31bef6ff977461a37eb9e2e9527724 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 13 Nov 2023 19:15:18 +0000 Subject: [PATCH 095/816] chore: fix typo in docs and add request header for function calls (#807) --- src/openai/cli/_errors.py | 4 ++-- src/openai/cli/_utils.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/openai/cli/_errors.py b/src/openai/cli/_errors.py index ac2a3780d0..2bf06070d6 100644 --- a/src/openai/cli/_errors.py +++ b/src/openai/cli/_errors.py @@ -4,7 +4,7 @@ import pydantic -from ._utils import Colours, organization_info +from ._utils import Colors, organization_info from .._exceptions import APIError, OpenAIError @@ -20,4 +20,4 @@ def display_error(err: CLIError | APIError | pydantic.ValidationError) -> None: if isinstance(err, SilentCLIError): return - sys.stderr.write("{}{}Error:{} {}\n".format(organization_info(), Colours.FAIL, Colours.ENDC, err)) + sys.stderr.write("{}{}Error:{} {}\n".format(organization_info(), Colors.FAIL, Colors.ENDC, err)) diff --git a/src/openai/cli/_utils.py b/src/openai/cli/_utils.py index 027ab08de3..673eed613c 100644 --- a/src/openai/cli/_utils.py +++ b/src/openai/cli/_utils.py @@ -9,7 +9,7 @@ from .._models import BaseModel -class Colours: +class Colors: HEADER = "\033[95m" OKBLUE = "\033[94m" OKGREEN = "\033[92m" From e9300e0ea899919e105c3b858c9b5af2a6c34803 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 13 Nov 2023 19:54:29 +0000 Subject: [PATCH 096/816] chore(internal): fix devcontainer interpeter path (#810) --- .devcontainer/devcontainer.json | 1 + 1 file changed, 1 insertion(+) diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index b9da964dc1..bbeb30b148 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -17,6 +17,7 @@ "settings": { "terminal.integrated.shell.linux": "/bin/bash", "python.pythonPath": ".venv/bin/python", + "python.defaultInterpreterPath": ".venv/bin/python", "python.typeChecking": "basic", "terminal.integrated.env.linux": { "PATH": "/home/vscode/.rye/shims:${env:PATH}" From ea4fa238abdcddbf14aa7d42b7689cdd00a2d290 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 13 Nov 2023 20:44:11 +0000 Subject: [PATCH 097/816] fix(breaking!): correct broken type names in moderation categories (#811) Migration: - `self_minus_harm_intent` -> `self_harm_intent` - `self_minus_harm_instructions` -> `self_harm_instructions` - `self_minus_harm` -> `self_harm` --- src/openai/types/moderation.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/openai/types/moderation.py b/src/openai/types/moderation.py index bf586fc24a..3602a46985 100644 --- a/src/openai/types/moderation.py +++ b/src/openai/types/moderation.py @@ -35,20 +35,20 @@ class Categories(BaseModel): orientation, disability status, or caste. """ - self_minus_harm: bool = FieldInfo(alias="self-harm") + self_harm: bool = FieldInfo(alias="self-harm") """ Content that promotes, encourages, or depicts acts of self-harm, such as suicide, cutting, and eating disorders. """ - self_minus_harm_instructions: bool = FieldInfo(alias="self-harm/instructions") + self_harm_instructions: bool = FieldInfo(alias="self-harm/instructions") """ Content that encourages performing acts of self-harm, such as suicide, cutting, and eating disorders, or that gives instructions or advice on how to commit such acts. """ - self_minus_harm_intent: bool = FieldInfo(alias="self-harm/intent") + self_harm_intent: bool = FieldInfo(alias="self-harm/intent") """ Content where the speaker expresses that they are engaging or intend to engage in acts of self-harm, such as suicide, cutting, and eating disorders. @@ -84,13 +84,13 @@ class CategoryScores(BaseModel): hate_threatening: float = FieldInfo(alias="hate/threatening") """The score for the category 'hate/threatening'.""" - self_minus_harm: float = FieldInfo(alias="self-harm") + self_harm: float = FieldInfo(alias="self-harm") """The score for the category 'self-harm'.""" - self_minus_harm_instructions: float = FieldInfo(alias="self-harm/instructions") + self_harm_instructions: float = FieldInfo(alias="self-harm/instructions") """The score for the category 'self-harm/instructions'.""" - self_minus_harm_intent: float = FieldInfo(alias="self-harm/intent") + self_harm_intent: float = FieldInfo(alias="self-harm/intent") """The score for the category 'self-harm/intent'.""" sexual: float From 98b3240b8696472c43b954b8643cc7c0deb22908 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 14 Nov 2023 03:48:14 +0000 Subject: [PATCH 098/816] feat(api): add gpt-3.5-turbo-1106 (#813) --- src/openai/resources/chat/completions.py | 8 ++++++++ src/openai/types/chat/completion_create_params.py | 1 + 2 files changed, 9 insertions(+) diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index ff36424442..d0657b2f73 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -51,6 +51,7 @@ def create( "gpt-4-32k", "gpt-4-32k-0314", "gpt-4-32k-0613", + "gpt-3.5-turbo-1106", "gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0301", @@ -221,6 +222,7 @@ def create( "gpt-4-32k", "gpt-4-32k-0314", "gpt-4-32k-0613", + "gpt-3.5-turbo-1106", "gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0301", @@ -391,6 +393,7 @@ def create( "gpt-4-32k", "gpt-4-32k-0314", "gpt-4-32k-0613", + "gpt-3.5-turbo-1106", "gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0301", @@ -561,6 +564,7 @@ def create( "gpt-4-32k", "gpt-4-32k-0314", "gpt-4-32k-0613", + "gpt-3.5-turbo-1106", "gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0301", @@ -648,6 +652,7 @@ async def create( "gpt-4-32k", "gpt-4-32k-0314", "gpt-4-32k-0613", + "gpt-3.5-turbo-1106", "gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0301", @@ -818,6 +823,7 @@ async def create( "gpt-4-32k", "gpt-4-32k-0314", "gpt-4-32k-0613", + "gpt-3.5-turbo-1106", "gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0301", @@ -988,6 +994,7 @@ async def create( "gpt-4-32k", "gpt-4-32k-0314", "gpt-4-32k-0613", + "gpt-3.5-turbo-1106", "gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0301", @@ -1158,6 +1165,7 @@ async def create( "gpt-4-32k", "gpt-4-32k-0314", "gpt-4-32k-0613", + "gpt-3.5-turbo-1106", "gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0301", diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 51c864588b..69fe250eca 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -44,6 +44,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): "gpt-4-32k", "gpt-4-32k-0314", "gpt-4-32k-0613", + "gpt-3.5-turbo-1106", "gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0301", From 7758c54b0b70edd665dce73661475f18973116d6 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 14 Nov 2023 04:00:24 +0000 Subject: [PATCH 099/816] docs: add azure env vars (#814) --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index f3698a9ff4..e7e65828b8 100644 --- a/README.md +++ b/README.md @@ -483,10 +483,10 @@ print(completion.model_dump_json(indent=2)) In addition to the options provided in the base `OpenAI` client, the following options are provided: -- `azure_endpoint` +- `azure_endpoint` (or the `AZURE_OPENAI_ENDPOINT` environment variable) - `azure_deployment` -- `api_version` -- `azure_ad_token` +- `api_version` (or the `OPENAI_API_VERSION` environment variable) +- `azure_ad_token` (or the `AZURE_OPENAI_AD_TOKEN` environment variable) - `azure_ad_token_provider` An example of using the client with Azure Active Directory can be found [here](https://github.com/openai/openai-python/blob/main/examples/azure_ad.py). From 71d317233bb4399994fddfc70133c7795836f21f Mon Sep 17 00:00:00 2001 From: Ikko Eltociear Ashimine Date: Tue, 14 Nov 2023 19:03:55 +0900 Subject: [PATCH 100/816] docs: fix code comment typo (#790) specifc -> specific --- src/openai/_models.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/openai/_models.py b/src/openai/_models.py index ebaef99454..6d5aad5963 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -149,7 +149,7 @@ def construct( if not PYDANTIC_V2: # we define aliases for some of the new pydantic v2 methods so # that we can just document these methods without having to specify - # a specifc pydantic version as some users may not know which + # a specific pydantic version as some users may not know which # pydantic version they are currently using @override From 0733934fbcdda57ae4506563924b63c867f3dcf7 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 15 Nov 2023 16:54:17 +0000 Subject: [PATCH 101/816] feat(client): support reading the base url from an env variable (#829) --- README.md | 1 + src/openai/_client.py | 4 ++++ tests/test_client.py | 12 ++++++++++++ tests/utils.py | 17 ++++++++++++++++- 4 files changed, 33 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e7e65828b8..82eeb57ccb 100644 --- a/README.md +++ b/README.md @@ -437,6 +437,7 @@ import httpx from openai import OpenAI client = OpenAI( + # Or use the `OPENAI_BASE_URL` env var base_url="http://my.test.server.example.com:8083/", http_client=httpx.Client( proxies="http://my.test.proxy.example.com/", diff --git a/src/openai/_client.py b/src/openai/_client.py index 7820d5f96d..6664dc4233 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -99,6 +99,8 @@ def __init__( organization = os.environ.get("OPENAI_ORG_ID") self.organization = organization + if base_url is None: + base_url = os.environ.get("OPENAI_BASE_URL") if base_url is None: base_url = f"https://api.openai.com/v1" @@ -307,6 +309,8 @@ def __init__( organization = os.environ.get("OPENAI_ORG_ID") self.organization = organization + if base_url is None: + base_url = os.environ.get("OPENAI_BASE_URL") if base_url is None: base_url = f"https://api.openai.com/v1" diff --git a/tests/test_client.py b/tests/test_client.py index e3daa4d2b1..e295d193e8 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -26,6 +26,8 @@ make_request_options, ) +from .utils import update_env + base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") api_key = "My API Key" @@ -399,6 +401,11 @@ class Model2(BaseModel): assert isinstance(response, Model1) assert response.foo == 1 + def test_base_url_env(self) -> None: + with update_env(OPENAI_BASE_URL="http://localhost:5000/from/env"): + client = OpenAI(api_key=api_key, _strict_response_validation=True) + assert client.base_url == "http://localhost:5000/from/env/" + @pytest.mark.parametrize( "client", [ @@ -932,6 +939,11 @@ class Model2(BaseModel): assert isinstance(response, Model1) assert response.foo == 1 + def test_base_url_env(self) -> None: + with update_env(OPENAI_BASE_URL="http://localhost:5000/from/env"): + client = AsyncOpenAI(api_key=api_key, _strict_response_validation=True) + assert client.base_url == "http://localhost:5000/from/env/" + @pytest.mark.parametrize( "client", [ diff --git a/tests/utils.py b/tests/utils.py index 3cccab223a..b513794017 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -1,7 +1,9 @@ from __future__ import annotations +import os import traceback -from typing import Any, TypeVar, cast +import contextlib +from typing import Any, TypeVar, Iterator, cast from datetime import date, datetime from typing_extensions import Literal, get_args, get_origin, assert_type @@ -103,3 +105,16 @@ def _assert_list_type(type_: type[object], value: object) -> None: inner_type = get_args(type_)[0] for entry in value: assert_type(inner_type, entry) # type: ignore + + +@contextlib.contextmanager +def update_env(**new_env: str) -> Iterator[None]: + old = os.environ.copy() + + try: + os.environ.update(new_env) + + yield None + finally: + os.environ.clear() + os.environ.update(old) From d3cb40ca6a5d2cbbeff94f50baea20162b7966bc Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 15 Nov 2023 16:55:00 +0000 Subject: [PATCH 102/816] release: 1.3.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 27 +++++++++++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 30 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 862a05b695..2a8f4ffddf 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.2.4" + ".": "1.3.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index e1e8a331f9..fceac1bb0f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,32 @@ # Changelog +## 1.3.0 (2023-11-15) + +Full Changelog: [v1.2.4...v1.3.0](https://github.com/openai/openai-python/compare/v1.2.4...v1.3.0) + +### Features + +* **api:** add gpt-3.5-turbo-1106 ([#813](https://github.com/openai/openai-python/issues/813)) ([9bb3c4e](https://github.com/openai/openai-python/commit/9bb3c4ed88c890db2605a793aa39fffa1d84e8ef)) +* **client:** support reading the base url from an env variable ([#829](https://github.com/openai/openai-python/issues/829)) ([ca5fdc6](https://github.com/openai/openai-python/commit/ca5fdc6ca006a3550cc5eeea70dd3d96b9ba305a)) + + +### Bug Fixes + +* **breaking!:** correct broken type names in moderation categories ([#811](https://github.com/openai/openai-python/issues/811)) ([0bc211f](https://github.com/openai/openai-python/commit/0bc211fd46f4fcc1f7687bdfdce26894b679cb4f)) + + +### Chores + +* fix typo in docs and add request header for function calls ([#807](https://github.com/openai/openai-python/issues/807)) ([cbef703](https://github.com/openai/openai-python/commit/cbef7030c7b21a0c766fe83c62657cea1cd8d31c)) +* **internal:** fix devcontainer interpeter path ([#810](https://github.com/openai/openai-python/issues/810)) ([0acc07d](https://github.com/openai/openai-python/commit/0acc07dd8281ba881f91689b8a5e4254e8743fbc)) + + +### Documentation + +* add azure env vars ([#814](https://github.com/openai/openai-python/issues/814)) ([bd8e32a](https://github.com/openai/openai-python/commit/bd8e32a380218d0c9ff43643ccc1a25b3c35120d)) +* fix code comment typo ([#790](https://github.com/openai/openai-python/issues/790)) ([8407a27](https://github.com/openai/openai-python/commit/8407a27e848ae611eb087c8d10632447d7c55498)) +* **readme:** fix broken azure_ad notebook link ([#781](https://github.com/openai/openai-python/issues/781)) ([3b92cdf](https://github.com/openai/openai-python/commit/3b92cdfa5490b50a72811bec2f6e54e070847961)) + ## 1.2.4 (2023-11-13) Full Changelog: [v1.2.3...v1.2.4](https://github.com/openai/openai-python/compare/v1.2.3...v1.2.4) diff --git a/pyproject.toml b/pyproject.toml index dc08634e4a..83c54f81ca 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.2.4" +version = "1.3.0" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index f22b1aae3f..79690d85e5 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.2.4" # x-release-please-version +__version__ = "1.3.0" # x-release-please-version From 23d03a1c561e57dab93c361962f41b9c3320b845 Mon Sep 17 00:00:00 2001 From: ashjeanbird <132003136+ashjeanbird@users.noreply.github.com> Date: Wed, 15 Nov 2023 17:56:35 -1000 Subject: [PATCH 103/816] Adds DALL-E note to Azure OpenAI in v1 SDK (#766) * Adds DALL-E note to Azure OpenAI in v1 SDK Adds important note for Azure OpenAI users. * Updates DALL-E docs to include workaround Included a link to the workaround --- README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 82eeb57ccb..94592bb2a6 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ The API documentation can be found [here](https://platform.openai.com/docs). ## Installation > [!IMPORTANT] -> The SDK was rewritten in v1, which was released November 6th 2023. See the [v1 migration guide](https://github.com/openai/openai-python/discussions/742), which includes scripts to automatically update your code. +> The SDK was rewritten in v1, which was released November 6th 2023. See the [v1 migration guide](https://github.com/openai/openai-python/discussions/742), which includes scripts to automatically update your code. ```sh pip install openai @@ -459,6 +459,10 @@ class instead of the `OpenAI` class. > The Azure API shape differs from the core API shape which means that the static types for responses / params > won't always be correct. +The latest release of the OpenAI Python library doesn't currently support DALL-E when used with Azure OpenAI. DALL-E with Azure OpenAI is still supported with 0.28.1. For those who can't wait for native support for DALL-E and Azure OpenAI we're providing [two code examples](https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/migration?tabs=python%2Cdalle-fix#dall-e-fix) which can be used as a workaround. + + + ```py from openai import AzureOpenAI From db6cd7649a14eb96c4cd124dc4b9b70da68996f4 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 16 Nov 2023 17:30:31 +0000 Subject: [PATCH 104/816] release: 1.3.1 (#839) * chore(internal): add publish script (#838) * release: 1.3.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ README.md | 6 +----- pyproject.toml | 2 +- src/openai/_version.py | 2 +- 5 files changed, 12 insertions(+), 8 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 2a8f4ffddf..0e5b256d26 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.3.0" + ".": "1.3.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index fceac1bb0f..cfe2ba9887 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.3.1 (2023-11-16) + +Full Changelog: [v1.3.0...v1.3.1](https://github.com/openai/openai-python/compare/v1.3.0...v1.3.1) + +### Chores + +* **internal:** add publish script ([#838](https://github.com/openai/openai-python/issues/838)) ([3ea41bc](https://github.com/openai/openai-python/commit/3ea41bcede374c4e5c92d85108281637c3382e12)) + ## 1.3.0 (2023-11-15) Full Changelog: [v1.2.4...v1.3.0](https://github.com/openai/openai-python/compare/v1.2.4...v1.3.0) diff --git a/README.md b/README.md index 94592bb2a6..82eeb57ccb 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ The API documentation can be found [here](https://platform.openai.com/docs). ## Installation > [!IMPORTANT] -> The SDK was rewritten in v1, which was released November 6th 2023. See the [v1 migration guide](https://github.com/openai/openai-python/discussions/742), which includes scripts to automatically update your code. +> The SDK was rewritten in v1, which was released November 6th 2023. See the [v1 migration guide](https://github.com/openai/openai-python/discussions/742), which includes scripts to automatically update your code. ```sh pip install openai @@ -459,10 +459,6 @@ class instead of the `OpenAI` class. > The Azure API shape differs from the core API shape which means that the static types for responses / params > won't always be correct. -The latest release of the OpenAI Python library doesn't currently support DALL-E when used with Azure OpenAI. DALL-E with Azure OpenAI is still supported with 0.28.1. For those who can't wait for native support for DALL-E and Azure OpenAI we're providing [two code examples](https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/migration?tabs=python%2Cdalle-fix#dall-e-fix) which can be used as a workaround. - - - ```py from openai import AzureOpenAI diff --git a/pyproject.toml b/pyproject.toml index 83c54f81ca..cf091a9a0d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.3.0" +version = "1.3.1" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 79690d85e5..052b27a609 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.3.0" # x-release-please-version +__version__ = "1.3.1" # x-release-please-version From f4b9655f4065ab8432f028c33f973a1945a760ee Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 16 Nov 2023 20:00:06 +0000 Subject: [PATCH 105/816] release: 1.3.2 (#842) * docs(readme): minor updates (#841) * release: 1.3.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ README.md | 5 ++++- pyproject.toml | 2 +- src/openai/_version.py | 2 +- 5 files changed, 15 insertions(+), 4 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 0e5b256d26..c658eefeff 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.3.1" + ".": "1.3.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index cfe2ba9887..040aa45486 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.3.2 (2023-11-16) + +Full Changelog: [v1.3.1...v1.3.2](https://github.com/openai/openai-python/compare/v1.3.1...v1.3.2) + +### Documentation + +* **readme:** minor updates ([#841](https://github.com/openai/openai-python/issues/841)) ([7273ad1](https://github.com/openai/openai-python/commit/7273ad1510043d3e264969c72403a1a237401910)) + ## 1.3.1 (2023-11-16) Full Changelog: [v1.3.0...v1.3.1](https://github.com/openai/openai-python/compare/v1.3.0...v1.3.1) diff --git a/README.md b/README.md index 82eeb57ccb..d916d3d0ea 100644 --- a/README.md +++ b/README.md @@ -156,7 +156,10 @@ We recommend that you always instantiate a client (e.g., with `client = OpenAI() ## Using types -Nested request parameters are [TypedDicts](https://docs.python.org/3/library/typing.html#typing.TypedDict). Responses are [Pydantic models](https://docs.pydantic.dev), which provide helper methods for things like serializing back into JSON ([v1](https://docs.pydantic.dev/1.10/usage/models/), [v2](https://docs.pydantic.dev/latest/usage/serialization/)). To get a dictionary, call `model.model_dump()`. +Nested request parameters are [TypedDicts](https://docs.python.org/3/library/typing.html#typing.TypedDict). Responses are [Pydantic models](https://docs.pydantic.dev), which provide helper methods for things like: + +- Serializing back into JSON, `model.model_dump_json(indent=2, exclude_unset=True)` +- Converting to a dictionary, `model.model_dump(exclude_unset=True)` Typed requests and responses provide autocomplete and documentation within your editor. If you would like to see type errors in VS Code to help catch bugs earlier, set `python.analysis.typeCheckingMode` to `basic`. diff --git a/pyproject.toml b/pyproject.toml index cf091a9a0d..e6c3422db5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.3.1" +version = "1.3.2" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 052b27a609..12c20f5fa2 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.3.1" # x-release-please-version +__version__ = "1.3.2" # x-release-please-version From 90aa5eb3ed6b92d9a1de89c0ee063f4768f92256 Mon Sep 17 00:00:00 2001 From: David Schnurr Date: Thu, 16 Nov 2023 21:57:12 -0800 Subject: [PATCH 106/816] Remove DALL-E note (#830) From 01d3b37305b28a45d0d9adfbc23c958bf924fe05 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 17 Nov 2023 23:35:26 +0000 Subject: [PATCH 107/816] release: 1.3.3 (#847) * chore(internal): update type hint for helper function (#846) * release: 1.3.3 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_utils/_transform.py | 4 ++-- src/openai/_version.py | 2 +- 5 files changed, 13 insertions(+), 5 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index c658eefeff..8022176dd3 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.3.2" + ".": "1.3.3" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 040aa45486..970724b4b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.3.3 (2023-11-17) + +Full Changelog: [v1.3.2...v1.3.3](https://github.com/openai/openai-python/compare/v1.3.2...v1.3.3) + +### Chores + +* **internal:** update type hint for helper function ([#846](https://github.com/openai/openai-python/issues/846)) ([9a5966c](https://github.com/openai/openai-python/commit/9a5966c70fce620a183de580938556730564a405)) + ## 1.3.2 (2023-11-16) Full Changelog: [v1.3.1...v1.3.2](https://github.com/openai/openai-python/compare/v1.3.1...v1.3.2) diff --git a/pyproject.toml b/pyproject.toml index e6c3422db5..8c9c6022f2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.3.2" +version = "1.3.3" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_utils/_transform.py b/src/openai/_utils/_transform.py index d953505fff..769f7362b9 100644 --- a/src/openai/_utils/_transform.py +++ b/src/openai/_utils/_transform.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import Any, List, Mapping, TypeVar, cast +from typing import Any, Mapping, TypeVar, cast from datetime import date, datetime from typing_extensions import Literal, get_args, override, get_type_hints @@ -60,7 +60,7 @@ def __repr__(self) -> str: def maybe_transform( - data: Mapping[str, object] | List[Any] | None, + data: object, expected_type: object, ) -> Any | None: """Wrapper over `transform()` that allows `None` to be passed. diff --git a/src/openai/_version.py b/src/openai/_version.py index 12c20f5fa2..b04859b6bb 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.3.2" # x-release-please-version +__version__ = "1.3.3" # x-release-please-version From f6c2aedfe3dfceeabd551909b572d72c7cef4373 Mon Sep 17 00:00:00 2001 From: Muhammed Al-Dulaimi Date: Sun, 19 Nov 2023 03:29:28 +0300 Subject: [PATCH 108/816] Add assistants example (#773) --- examples/assistant.py | 53 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 examples/assistant.py diff --git a/examples/assistant.py b/examples/assistant.py new file mode 100644 index 0000000000..ad3c1376de --- /dev/null +++ b/examples/assistant.py @@ -0,0 +1,53 @@ +import openai +import time + +# gets API Key from environment variable OPENAI_API_KEY +client = openai.OpenAI() + +assistant = client.beta.assistants.create( + name="Math Tutor", + instructions="You are a personal math tutor. Write and run code to answer math questions.", + tools=[{"type": "code_interpreter"}], + model="gpt-4-1106-preview", +) + +thread = client.beta.threads.create() + +message = client.beta.threads.messages.create( + thread_id=thread.id, + role="user", + content="I need to solve the equation `3x + 11 = 14`. Can you help me?" +) + +run = client.beta.threads.runs.create( + thread_id=thread.id, + assistant_id=assistant.id, + instructions="Please address the user as Jane Doe. The user has a premium account." +) + +print("checking assistant status. ") +while True: + run = client.beta.threads.runs.retrieve( + thread_id=thread.id, + run_id=run.id + ) + + if run.status == "completed": + print("done!") + messages = client.beta.threads.messages.list( + thread_id=thread.id + ) + + print("messages: ") + for message in messages: + print({ + "role": message.role, + "message": message.content[0].text.value + }) + + client.beta.assistants.delete(assistant.id) + + break + else: + print("in progress...") + time.sleep(5) \ No newline at end of file From 2343e63022837c867d79932d624352d570ff7173 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 20 Nov 2023 17:08:37 -0500 Subject: [PATCH 109/816] chore(examples): fix static types in assistants example (#852) --- examples/assistant.py | 30 ++++++++++++------------------ 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/examples/assistant.py b/examples/assistant.py index ad3c1376de..c5fbb82a3a 100644 --- a/examples/assistant.py +++ b/examples/assistant.py @@ -1,6 +1,7 @@ -import openai import time +import openai + # gets API Key from environment variable OPENAI_API_KEY client = openai.OpenAI() @@ -16,38 +17,31 @@ message = client.beta.threads.messages.create( thread_id=thread.id, role="user", - content="I need to solve the equation `3x + 11 = 14`. Can you help me?" + content="I need to solve the equation `3x + 11 = 14`. Can you help me?", ) run = client.beta.threads.runs.create( - thread_id=thread.id, - assistant_id=assistant.id, - instructions="Please address the user as Jane Doe. The user has a premium account." + thread_id=thread.id, + assistant_id=assistant.id, + instructions="Please address the user as Jane Doe. The user has a premium account.", ) print("checking assistant status. ") while True: - run = client.beta.threads.runs.retrieve( - thread_id=thread.id, - run_id=run.id - ) + run = client.beta.threads.runs.retrieve(thread_id=thread.id, run_id=run.id) if run.status == "completed": print("done!") - messages = client.beta.threads.messages.list( - thread_id=thread.id - ) + messages = client.beta.threads.messages.list(thread_id=thread.id) print("messages: ") for message in messages: - print({ - "role": message.role, - "message": message.content[0].text.value - }) + assert message.content[0].type == "text" + print({"role": message.role, "message": message.content[0].text.value}) client.beta.assistants.delete(assistant.id) - + break else: print("in progress...") - time.sleep(5) \ No newline at end of file + time.sleep(5) From c26014e26c119eb9cf396175bcad2002082d1526 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 20 Nov 2023 19:24:05 -0500 Subject: [PATCH 110/816] fix(client): attempt to parse unknown json content types (#854) --- src/openai/_base_client.py | 20 ++++++++++++------ src/openai/_models.py | 13 ++++++++++++ src/openai/_response.py | 31 +++++++++++++++++++--------- tests/test_client.py | 42 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 90 insertions(+), 16 deletions(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 3db8b6fa35..a168301f75 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -74,7 +74,12 @@ RAW_RESPONSE_HEADER, ) from ._streaming import Stream, AsyncStream -from ._exceptions import APIStatusError, APITimeoutError, APIConnectionError +from ._exceptions import ( + APIStatusError, + APITimeoutError, + APIConnectionError, + APIResponseValidationError, +) log: logging.Logger = logging.getLogger(__name__) @@ -518,13 +523,16 @@ def _process_response_data( if cast_to is UnknownResponse: return cast(ResponseT, data) - if inspect.isclass(cast_to) and issubclass(cast_to, ModelBuilderProtocol): - return cast(ResponseT, cast_to.build(response=response, data=data)) + try: + if inspect.isclass(cast_to) and issubclass(cast_to, ModelBuilderProtocol): + return cast(ResponseT, cast_to.build(response=response, data=data)) - if self._strict_response_validation: - return cast(ResponseT, validate_type(type_=cast_to, value=data)) + if self._strict_response_validation: + return cast(ResponseT, validate_type(type_=cast_to, value=data)) - return cast(ResponseT, construct_type(type_=cast_to, value=data)) + return cast(ResponseT, construct_type(type_=cast_to, value=data)) + except pydantic.ValidationError as err: + raise APIResponseValidationError(response=response, body=data) from err @property def qs(self) -> Querystring: diff --git a/src/openai/_models.py b/src/openai/_models.py index 6d5aad5963..5b8c96010f 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -263,6 +263,19 @@ def _construct_field(value: object, field: FieldInfo, key: str) -> object: return construct_type(value=value, type_=type_) +def is_basemodel(type_: type) -> bool: + """Returns whether or not the given type is either a `BaseModel` or a union of `BaseModel`""" + origin = get_origin(type_) or type_ + if is_union(type_): + for variant in get_args(type_): + if is_basemodel(variant): + return True + + return False + + return issubclass(origin, BaseModel) or issubclass(origin, GenericModel) + + def construct_type(*, value: object, type_: type) -> object: """Loose coercion to the expected type with construction of nested values. diff --git a/src/openai/_response.py b/src/openai/_response.py index 3cc8fd8cc1..933c37525e 100644 --- a/src/openai/_response.py +++ b/src/openai/_response.py @@ -1,17 +1,17 @@ from __future__ import annotations import inspect +import logging import datetime import functools from typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, cast from typing_extensions import Awaitable, ParamSpec, get_args, override, get_origin import httpx -import pydantic from ._types import NoneType, UnknownResponse, BinaryResponseContent from ._utils import is_given -from ._models import BaseModel +from ._models import BaseModel, is_basemodel from ._constants import RAW_RESPONSE_HEADER from ._exceptions import APIResponseValidationError @@ -23,6 +23,8 @@ P = ParamSpec("P") R = TypeVar("R") +log: logging.Logger = logging.getLogger(__name__) + class APIResponse(Generic[R]): _cast_to: type[R] @@ -174,6 +176,18 @@ def _parse(self) -> R: # in the response, e.g. application/json; charset=utf-8 content_type, *_ = response.headers.get("content-type").split(";") if content_type != "application/json": + if is_basemodel(cast_to): + try: + data = response.json() + except Exception as exc: + log.debug("Could not read JSON from response data due to %s - %s", type(exc), exc) + else: + return self._client._process_response_data( + data=data, + cast_to=cast_to, # type: ignore + response=response, + ) + if self._client._strict_response_validation: raise APIResponseValidationError( response=response, @@ -188,14 +202,11 @@ def _parse(self) -> R: data = response.json() - try: - return self._client._process_response_data( - data=data, - cast_to=cast_to, # type: ignore - response=response, - ) - except pydantic.ValidationError as err: - raise APIResponseValidationError(response=response, body=data) from err + return self._client._process_response_data( + data=data, + cast_to=cast_to, # type: ignore + response=response, + ) @override def __repr__(self) -> str: diff --git a/tests/test_client.py b/tests/test_client.py index e295d193e8..c5dbfe4bfe 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -401,6 +401,27 @@ class Model2(BaseModel): assert isinstance(response, Model1) assert response.foo == 1 + @pytest.mark.respx(base_url=base_url) + def test_non_application_json_content_type_for_json_data(self, respx_mock: MockRouter) -> None: + """ + Response that sets Content-Type to something other than application/json but returns json data + """ + + class Model(BaseModel): + foo: int + + respx_mock.get("/foo").mock( + return_value=httpx.Response( + 200, + content=json.dumps({"foo": 2}), + headers={"Content-Type": "application/text"}, + ) + ) + + response = self.client.get("/foo", cast_to=Model) + assert isinstance(response, Model) + assert response.foo == 2 + def test_base_url_env(self) -> None: with update_env(OPENAI_BASE_URL="http://localhost:5000/from/env"): client = OpenAI(api_key=api_key, _strict_response_validation=True) @@ -939,6 +960,27 @@ class Model2(BaseModel): assert isinstance(response, Model1) assert response.foo == 1 + @pytest.mark.respx(base_url=base_url) + async def test_non_application_json_content_type_for_json_data(self, respx_mock: MockRouter) -> None: + """ + Response that sets Content-Type to something other than application/json but returns json data + """ + + class Model(BaseModel): + foo: int + + respx_mock.get("/foo").mock( + return_value=httpx.Response( + 200, + content=json.dumps({"foo": 2}), + headers={"Content-Type": "application/text"}, + ) + ) + + response = await self.client.get("/foo", cast_to=Model) + assert isinstance(response, Model) + assert response.foo == 2 + def test_base_url_env(self) -> None: with update_env(OPENAI_BASE_URL="http://localhost:5000/from/env"): client = AsyncOpenAI(api_key=api_key, _strict_response_validation=True) From b085b1296ec9e3ba6f628d95c20b344a84e7b1cc Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 20 Nov 2023 19:24:46 -0500 Subject: [PATCH 111/816] release: 1.3.4 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 8022176dd3..c050b0fe03 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.3.3" + ".": "1.3.4" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 970724b4b8..1caef71db9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.3.4 (2023-11-21) + +Full Changelog: [v1.3.3...v1.3.4](https://github.com/openai/openai-python/compare/v1.3.3...v1.3.4) + +### Bug Fixes + +* **client:** attempt to parse unknown json content types ([#854](https://github.com/openai/openai-python/issues/854)) ([ba50466](https://github.com/openai/openai-python/commit/ba5046611029a67714d5120b9cc6a3c7fecce10c)) + + +### Chores + +* **examples:** fix static types in assistants example ([#852](https://github.com/openai/openai-python/issues/852)) ([5b47b2c](https://github.com/openai/openai-python/commit/5b47b2c542b9b4fb143af121022e2d5ad0890ef4)) + ## 1.3.3 (2023-11-17) Full Changelog: [v1.3.2...v1.3.3](https://github.com/openai/openai-python/compare/v1.3.2...v1.3.3) diff --git a/pyproject.toml b/pyproject.toml index 8c9c6022f2..ae6fbaeeca 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.3.3" +version = "1.3.4" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index b04859b6bb..ddfc847864 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.3.3" # x-release-please-version +__version__ = "1.3.4" # x-release-please-version From 97a6895b9d137a8ca8996f773917773de5f5b4c4 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 21 Nov 2023 13:14:58 -0500 Subject: [PATCH 112/816] fix(azure): ensure custom options can be passed to copy (#858) --- src/openai/_client.py | 18 ++++---- src/openai/lib/azure.py | 94 +++++++++++++++++++++++++++++++++++++++-- tests/lib/test_azure.py | 30 +++++++++++++ 3 files changed, 129 insertions(+), 13 deletions(-) diff --git a/src/openai/_client.py b/src/openai/_client.py index 6664dc4233..aa00073281 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -4,8 +4,8 @@ import os import asyncio -from typing import Union, Mapping -from typing_extensions import override +from typing import Any, Union, Mapping +from typing_extensions import Self, override import httpx @@ -164,12 +164,10 @@ def copy( set_default_headers: Mapping[str, str] | None = None, default_query: Mapping[str, object] | None = None, set_default_query: Mapping[str, object] | None = None, - ) -> OpenAI: + _extra_kwargs: Mapping[str, Any] = {}, + ) -> Self: """ Create a new client instance re-using the same options given to the current client with optional overriding. - - It should be noted that this does not share the underlying httpx client class which may lead - to performance issues. """ if default_headers is not None and set_default_headers is not None: raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive") @@ -199,6 +197,7 @@ def copy( max_retries=max_retries if is_given(max_retries) else self.max_retries, default_headers=headers, default_query=params, + **_extra_kwargs, ) # Alias for `copy` for nicer inline usage, e.g. @@ -374,12 +373,10 @@ def copy( set_default_headers: Mapping[str, str] | None = None, default_query: Mapping[str, object] | None = None, set_default_query: Mapping[str, object] | None = None, - ) -> AsyncOpenAI: + _extra_kwargs: Mapping[str, Any] = {}, + ) -> Self: """ Create a new client instance re-using the same options given to the current client with optional overriding. - - It should be noted that this does not share the underlying httpx client class which may lead - to performance issues. """ if default_headers is not None and set_default_headers is not None: raise ValueError("The `default_headers` and `set_default_headers` arguments are mutually exclusive") @@ -409,6 +406,7 @@ def copy( max_retries=max_retries if is_given(max_retries) else self.max_retries, default_headers=headers, default_query=params, + **_extra_kwargs, ) # Alias for `copy` for nicer inline usage, e.g. diff --git a/src/openai/lib/azure.py b/src/openai/lib/azure.py index d31313e95a..27bebd8cab 100644 --- a/src/openai/lib/azure.py +++ b/src/openai/lib/azure.py @@ -3,7 +3,7 @@ import os import inspect from typing import Any, Union, Mapping, TypeVar, Callable, Awaitable, overload -from typing_extensions import override +from typing_extensions import Self, override import httpx @@ -178,7 +178,7 @@ def __init__( if default_query is None: default_query = {"api-version": api_version} else: - default_query = {"api-version": api_version, **default_query} + default_query = {**default_query, "api-version": api_version} if base_url is None: if azure_endpoint is None: @@ -212,9 +212,53 @@ def __init__( http_client=http_client, _strict_response_validation=_strict_response_validation, ) + self._api_version = api_version self._azure_ad_token = azure_ad_token self._azure_ad_token_provider = azure_ad_token_provider + @override + def copy( + self, + *, + api_key: str | None = None, + organization: str | None = None, + api_version: str | None = None, + azure_ad_token: str | None = None, + azure_ad_token_provider: AzureADTokenProvider | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + http_client: httpx.Client | None = None, + max_retries: int | NotGiven = NOT_GIVEN, + default_headers: Mapping[str, str] | None = None, + set_default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + set_default_query: Mapping[str, object] | None = None, + _extra_kwargs: Mapping[str, Any] = {}, + ) -> Self: + """ + Create a new client instance re-using the same options given to the current client with optional overriding. + """ + return super().copy( + api_key=api_key, + organization=organization, + base_url=base_url, + timeout=timeout, + http_client=http_client, + max_retries=max_retries, + default_headers=default_headers, + set_default_headers=set_default_headers, + default_query=default_query, + set_default_query=set_default_query, + _extra_kwargs={ + "api_version": api_version or self._api_version, + "azure_ad_token": azure_ad_token or self._azure_ad_token, + "azure_ad_token_provider": azure_ad_token_provider or self._azure_ad_token_provider, + **_extra_kwargs, + }, + ) + + with_options = copy + def _get_azure_ad_token(self) -> str | None: if self._azure_ad_token is not None: return self._azure_ad_token @@ -367,7 +411,7 @@ def __init__( if default_query is None: default_query = {"api-version": api_version} else: - default_query = {"api-version": api_version, **default_query} + default_query = {**default_query, "api-version": api_version} if base_url is None: if azure_endpoint is None: @@ -401,9 +445,53 @@ def __init__( http_client=http_client, _strict_response_validation=_strict_response_validation, ) + self._api_version = api_version self._azure_ad_token = azure_ad_token self._azure_ad_token_provider = azure_ad_token_provider + @override + def copy( + self, + *, + api_key: str | None = None, + organization: str | None = None, + api_version: str | None = None, + azure_ad_token: str | None = None, + azure_ad_token_provider: AsyncAzureADTokenProvider | None = None, + base_url: str | httpx.URL | None = None, + timeout: float | Timeout | None | NotGiven = NOT_GIVEN, + http_client: httpx.AsyncClient | None = None, + max_retries: int | NotGiven = NOT_GIVEN, + default_headers: Mapping[str, str] | None = None, + set_default_headers: Mapping[str, str] | None = None, + default_query: Mapping[str, object] | None = None, + set_default_query: Mapping[str, object] | None = None, + _extra_kwargs: Mapping[str, Any] = {}, + ) -> Self: + """ + Create a new client instance re-using the same options given to the current client with optional overriding. + """ + return super().copy( + api_key=api_key, + organization=organization, + base_url=base_url, + timeout=timeout, + http_client=http_client, + max_retries=max_retries, + default_headers=default_headers, + set_default_headers=set_default_headers, + default_query=default_query, + set_default_query=set_default_query, + _extra_kwargs={ + "api_version": api_version or self._api_version, + "azure_ad_token": azure_ad_token or self._azure_ad_token, + "azure_ad_token_provider": azure_ad_token_provider or self._azure_ad_token_provider, + **_extra_kwargs, + }, + ) + + with_options = copy + async def _get_azure_ad_token(self) -> str | None: if self._azure_ad_token is not None: return self._azure_ad_token diff --git a/tests/lib/test_azure.py b/tests/lib/test_azure.py index b0bd87571b..9360b2925a 100644 --- a/tests/lib/test_azure.py +++ b/tests/lib/test_azure.py @@ -1,4 +1,5 @@ from typing import Union +from typing_extensions import Literal import pytest @@ -34,3 +35,32 @@ def test_implicit_deployment_path(client: Client) -> None: req.url == "https://example-resource.azure.openai.com/openai/deployments/my-deployment-model/chat/completions?api-version=2023-07-01" ) + + +@pytest.mark.parametrize( + "client,method", + [ + (sync_client, "copy"), + (sync_client, "with_options"), + (async_client, "copy"), + (async_client, "with_options"), + ], +) +def test_client_copying(client: Client, method: Literal["copy", "with_options"]) -> None: + if method == "copy": + copied = client.copy() + else: + copied = client.with_options() + + assert copied._custom_query == {"api-version": "2023-07-01"} + + +@pytest.mark.parametrize( + "client", + [sync_client, async_client], +) +def test_client_copying_override_options(client: Client) -> None: + copied = client.copy( + api_version="2022-05-01", + ) + assert copied._custom_query == {"api-version": "2022-05-01"} From 7322b6643aaed4c1d9e5db231f6d88f9cc5266a3 Mon Sep 17 00:00:00 2001 From: Roberto Pastor Muela <37798125+RobPasMue@users.noreply.github.com> Date: Tue, 21 Nov 2023 20:26:55 +0100 Subject: [PATCH 113/816] chore(package): add license classifier (#826) Having the license classifier in PyPI is also important so that it is uplaoded as part of the package's metadata. Otherwise, when querying it to PyPI this information is not shown in the package's metadata. --- pyproject.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/pyproject.toml b/pyproject.toml index ae6fbaeeca..21004dac06 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -31,6 +31,7 @@ classifiers = [ "Operating System :: POSIX :: Linux", "Operating System :: Microsoft :: Windows", "Topic :: Software Development :: Libraries :: Python Modules", + "License :: OSI Approved :: Apache Software License", ] [project.optional-dependencies] From 58eed2b40932c43cf0eda02afcd072fb1f6a878a Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 21 Nov 2023 14:34:24 -0500 Subject: [PATCH 114/816] chore(package): add license classifier metadata (#860) --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 21004dac06..85ad9e2177 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -31,7 +31,7 @@ classifiers = [ "Operating System :: POSIX :: Linux", "Operating System :: Microsoft :: Windows", "Topic :: Software Development :: Libraries :: Python Modules", - "License :: OSI Approved :: Apache Software License", + "License :: OSI Approved :: Apache Software License" ] [project.optional-dependencies] From 9f828cb1ea7c22a6388fcd71b5de1a0dde3a9a9f Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 21 Nov 2023 14:35:04 -0500 Subject: [PATCH 115/816] release: 1.3.5 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 14 ++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 17 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index c050b0fe03..13787787c4 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.3.4" + ".": "1.3.5" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 1caef71db9..0869b3888c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,19 @@ # Changelog +## 1.3.5 (2023-11-21) + +Full Changelog: [v1.3.4...v1.3.5](https://github.com/openai/openai-python/compare/v1.3.4...v1.3.5) + +### Bug Fixes + +* **azure:** ensure custom options can be passed to copy ([#858](https://github.com/openai/openai-python/issues/858)) ([05ca0d6](https://github.com/openai/openai-python/commit/05ca0d68e84d40f975614d27cb52c0f382104377)) + + +### Chores + +* **package:** add license classifier ([#826](https://github.com/openai/openai-python/issues/826)) ([bec004d](https://github.com/openai/openai-python/commit/bec004d030b277e05bdd51f66fae1e881291c30b)) +* **package:** add license classifier metadata ([#860](https://github.com/openai/openai-python/issues/860)) ([80dffb1](https://github.com/openai/openai-python/commit/80dffb17ff0a10b0b9ea704c4247521e48b68408)) + ## 1.3.4 (2023-11-21) Full Changelog: [v1.3.3...v1.3.4](https://github.com/openai/openai-python/compare/v1.3.3...v1.3.4) diff --git a/pyproject.toml b/pyproject.toml index 85ad9e2177..f17def16b6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.3.4" +version = "1.3.5" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index ddfc847864..1ef6479491 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.3.4" # x-release-please-version +__version__ = "1.3.5" # x-release-please-version From af67cfab4210d8e497c05390ce14f39105c77519 Mon Sep 17 00:00:00 2001 From: Logan Kilpatrick Date: Tue, 28 Nov 2023 13:44:46 -0800 Subject: [PATCH 116/816] Update README.md (#892) --- README.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index d916d3d0ea..33ec6add52 100644 --- a/README.md +++ b/README.md @@ -94,8 +94,9 @@ stream = client.chat.completions.create( messages=[{"role": "user", "content": "Say this is a test"}], stream=True, ) -for part in stream: - print(part.choices[0].delta.content or "") +for chunk in stream: + if chunk.choices[0].delta.content is not None: + print(chunk.choices[0].delta.content, end="") ``` The async client uses the exact same interface. @@ -110,8 +111,9 @@ stream = await client.chat.completions.create( messages=[{"role": "user", "content": "Say this is a test"}], stream=True, ) -async for part in stream: - print(part.choices[0].delta.content or "") +async for chunk in stream: + if chunk.choices[0].delta.content is not None: + print(chunk.choices[0].delta.content, end="") ``` ## Module-level client From 2fc3204ecef7839296314b7248d9b63292aeb49e Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 22 Nov 2023 21:23:46 -0500 Subject: [PATCH 117/816] fix(client): add support for streaming binary responses (#866) --- examples/audio.py | 5 ++++- src/openai/_base_client.py | 8 ++++++-- src/openai/_models.py | 2 ++ src/openai/_types.py | 23 +++++++++++++++++++++-- src/openai/resources/audio/speech.py | 20 ++++++++++++++++++-- src/openai/resources/files.py | 20 ++++++++++++++++++-- 6 files changed, 69 insertions(+), 9 deletions(-) diff --git a/examples/audio.py b/examples/audio.py index a5f535dcd6..e86acbf828 100755 --- a/examples/audio.py +++ b/examples/audio.py @@ -13,7 +13,10 @@ def main() -> None: # Create text-to-speech audio file response = openai.audio.speech.create( - model="tts-1", voice="alloy", input="the quick brown fox jumped over the lazy dogs" + model="tts-1", + voice="alloy", + input="the quick brown fox jumped over the lazy dogs", + stream=True, ) response.stream_to_file(speech_file_path) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index a168301f75..9a023ba961 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -863,7 +863,7 @@ def _request( self._prepare_request(request) try: - response = self._client.send(request, auth=self.custom_auth, stream=stream) + response = self._client.send(request, auth=self.custom_auth, stream=stream or options.stream or False) log.debug( 'HTTP Request: %s %s "%i %s"', request.method, request.url, response.status_code, response.reason_phrase ) @@ -1304,7 +1304,7 @@ async def _request( await self._prepare_request(request) try: - response = await self._client.send(request, auth=self.custom_auth, stream=stream) + response = await self._client.send(request, auth=self.custom_auth, stream=stream or options.stream or False) log.debug( 'HTTP Request: %s %s "%i %s"', request.method, request.url, response.status_code, response.reason_phrase ) @@ -1541,6 +1541,7 @@ def make_request_options( idempotency_key: str | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, post_parser: PostParser | NotGiven = NOT_GIVEN, + stream: bool | None = None, ) -> RequestOptions: """Create a dict of type RequestOptions without keys of NotGiven values.""" options: RequestOptions = {} @@ -1562,6 +1563,9 @@ def make_request_options( if idempotency_key is not None: options["idempotency_key"] = idempotency_key + if stream is not None: + options["stream"] = stream + if is_given(post_parser): # internal options["post_parser"] = post_parser # type: ignore diff --git a/src/openai/_models.py b/src/openai/_models.py index 5b8c96010f..a0e596149c 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -403,6 +403,7 @@ class FinalRequestOptionsInput(TypedDict, total=False): params: Query headers: Headers max_retries: int + stream: bool | None timeout: float | Timeout | None files: HttpxRequestFiles | None idempotency_key: str @@ -420,6 +421,7 @@ class FinalRequestOptions(pydantic.BaseModel): timeout: Union[float, Timeout, None, NotGiven] = NotGiven() files: Union[HttpxRequestFiles, None] = None idempotency_key: Union[str, None] = None + stream: Union[bool, None] = None post_parser: Union[Callable[[Any], Any], NotGiven] = NotGiven() # It should be noted that we cannot use `json` here as that would override diff --git a/src/openai/_types.py b/src/openai/_types.py index 9e962a1078..013b658f0e 100644 --- a/src/openai/_types.py +++ b/src/openai/_types.py @@ -130,7 +130,16 @@ def stream_to_file( chunk_size: int | None = None, ) -> None: """ - Stream the output to the given file. + Stream the output to the given file. NOTE, requires passing `stream=True` + to the request for expected behavior, e.g., + + response = openai.audio.speech.create( + model="tts-1", + voice="alloy", + input="the quick brown fox jumped over the lazy dogs", + stream=True, + ) + response.stream_to_file(speech_file_path) """ pass @@ -185,7 +194,16 @@ async def astream_to_file( chunk_size: int | None = None, ) -> None: """ - Stream the output to the given file. + Stream the output to the given file. NOTE, requires passing `stream=True` + to the request for expected behavior, e.g., + + response = await openai.audio.speech.create( + model="tts-1", + voice="alloy", + input="the quick brown fox jumped over the lazy dogs", + stream=True, + ) + response.stream_to_file(speech_file_path) """ pass @@ -257,6 +275,7 @@ async def aclose(self) -> None: class RequestOptions(TypedDict, total=False): headers: Headers max_retries: int + stream: bool timeout: float | Timeout | None params: Query extra_json: AnyMapping diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index 458843866f..66916d0d50 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -41,6 +41,7 @@ def create( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + stream: bool | None = None, ) -> HttpxBinaryResponseContent: """ Generates audio from the input text. @@ -67,6 +68,9 @@ def create( extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds + + stream: Whether or not the response content should be streamed (i.e. not read to + completion immediately), default False """ return self._post( "/audio/speech", @@ -81,7 +85,11 @@ def create( speech_create_params.SpeechCreateParams, ), options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + stream=stream, ), cast_to=HttpxBinaryResponseContent, ) @@ -108,6 +116,7 @@ async def create( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + stream: bool | None = None, ) -> HttpxBinaryResponseContent: """ Generates audio from the input text. @@ -134,6 +143,9 @@ async def create( extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds + + stream: Whether or not the response content should be streamed (i.e. not read to + completion immediately), default False """ return await self._post( "/audio/speech", @@ -148,7 +160,11 @@ async def create( speech_create_params.SpeechCreateParams, ), options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + stream=stream, ), cast_to=HttpxBinaryResponseContent, ) diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index a6f75e5a4c..be6eff1e08 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -212,6 +212,7 @@ def content( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + stream: bool | None = None, ) -> HttpxBinaryResponseContent: """ Returns the contents of the specified file. @@ -224,11 +225,18 @@ def content( extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds + + stream: Whether or not the response content should be streamed (i.e. not read to + completion immediately), default False """ return self._get( f"/files/{file_id}/content", options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + stream=stream, ), cast_to=HttpxBinaryResponseContent, ) @@ -475,6 +483,7 @@ async def content( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + stream: bool | None = None, ) -> HttpxBinaryResponseContent: """ Returns the contents of the specified file. @@ -487,11 +496,18 @@ async def content( extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds + + stream: Whether or not the response content should be streamed (i.e. not read to + completion immediately), default False """ return await self._get( f"/files/{file_id}/content", options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + stream=stream, ), cast_to=HttpxBinaryResponseContent, ) From 2d85e1e78fc866310767298354e91e2437151eb9 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 23 Nov 2023 17:34:15 -0500 Subject: [PATCH 118/816] chore: revert binary streaming change (#875) --- examples/audio.py | 5 +---- src/openai/_base_client.py | 8 ++------ src/openai/_models.py | 2 -- src/openai/_types.py | 23 ++--------------------- src/openai/resources/audio/speech.py | 20 ++------------------ src/openai/resources/files.py | 20 ++------------------ 6 files changed, 9 insertions(+), 69 deletions(-) diff --git a/examples/audio.py b/examples/audio.py index e86acbf828..a5f535dcd6 100755 --- a/examples/audio.py +++ b/examples/audio.py @@ -13,10 +13,7 @@ def main() -> None: # Create text-to-speech audio file response = openai.audio.speech.create( - model="tts-1", - voice="alloy", - input="the quick brown fox jumped over the lazy dogs", - stream=True, + model="tts-1", voice="alloy", input="the quick brown fox jumped over the lazy dogs" ) response.stream_to_file(speech_file_path) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 9a023ba961..a168301f75 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -863,7 +863,7 @@ def _request( self._prepare_request(request) try: - response = self._client.send(request, auth=self.custom_auth, stream=stream or options.stream or False) + response = self._client.send(request, auth=self.custom_auth, stream=stream) log.debug( 'HTTP Request: %s %s "%i %s"', request.method, request.url, response.status_code, response.reason_phrase ) @@ -1304,7 +1304,7 @@ async def _request( await self._prepare_request(request) try: - response = await self._client.send(request, auth=self.custom_auth, stream=stream or options.stream or False) + response = await self._client.send(request, auth=self.custom_auth, stream=stream) log.debug( 'HTTP Request: %s %s "%i %s"', request.method, request.url, response.status_code, response.reason_phrase ) @@ -1541,7 +1541,6 @@ def make_request_options( idempotency_key: str | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, post_parser: PostParser | NotGiven = NOT_GIVEN, - stream: bool | None = None, ) -> RequestOptions: """Create a dict of type RequestOptions without keys of NotGiven values.""" options: RequestOptions = {} @@ -1563,9 +1562,6 @@ def make_request_options( if idempotency_key is not None: options["idempotency_key"] = idempotency_key - if stream is not None: - options["stream"] = stream - if is_given(post_parser): # internal options["post_parser"] = post_parser # type: ignore diff --git a/src/openai/_models.py b/src/openai/_models.py index a0e596149c..5b8c96010f 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -403,7 +403,6 @@ class FinalRequestOptionsInput(TypedDict, total=False): params: Query headers: Headers max_retries: int - stream: bool | None timeout: float | Timeout | None files: HttpxRequestFiles | None idempotency_key: str @@ -421,7 +420,6 @@ class FinalRequestOptions(pydantic.BaseModel): timeout: Union[float, Timeout, None, NotGiven] = NotGiven() files: Union[HttpxRequestFiles, None] = None idempotency_key: Union[str, None] = None - stream: Union[bool, None] = None post_parser: Union[Callable[[Any], Any], NotGiven] = NotGiven() # It should be noted that we cannot use `json` here as that would override diff --git a/src/openai/_types.py b/src/openai/_types.py index 013b658f0e..9e962a1078 100644 --- a/src/openai/_types.py +++ b/src/openai/_types.py @@ -130,16 +130,7 @@ def stream_to_file( chunk_size: int | None = None, ) -> None: """ - Stream the output to the given file. NOTE, requires passing `stream=True` - to the request for expected behavior, e.g., - - response = openai.audio.speech.create( - model="tts-1", - voice="alloy", - input="the quick brown fox jumped over the lazy dogs", - stream=True, - ) - response.stream_to_file(speech_file_path) + Stream the output to the given file. """ pass @@ -194,16 +185,7 @@ async def astream_to_file( chunk_size: int | None = None, ) -> None: """ - Stream the output to the given file. NOTE, requires passing `stream=True` - to the request for expected behavior, e.g., - - response = await openai.audio.speech.create( - model="tts-1", - voice="alloy", - input="the quick brown fox jumped over the lazy dogs", - stream=True, - ) - response.stream_to_file(speech_file_path) + Stream the output to the given file. """ pass @@ -275,7 +257,6 @@ async def aclose(self) -> None: class RequestOptions(TypedDict, total=False): headers: Headers max_retries: int - stream: bool timeout: float | Timeout | None params: Query extra_json: AnyMapping diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index 66916d0d50..458843866f 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -41,7 +41,6 @@ def create( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - stream: bool | None = None, ) -> HttpxBinaryResponseContent: """ Generates audio from the input text. @@ -68,9 +67,6 @@ def create( extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds - - stream: Whether or not the response content should be streamed (i.e. not read to - completion immediately), default False """ return self._post( "/audio/speech", @@ -85,11 +81,7 @@ def create( speech_create_params.SpeechCreateParams, ), options=make_request_options( - extra_headers=extra_headers, - extra_query=extra_query, - extra_body=extra_body, - timeout=timeout, - stream=stream, + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=HttpxBinaryResponseContent, ) @@ -116,7 +108,6 @@ async def create( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - stream: bool | None = None, ) -> HttpxBinaryResponseContent: """ Generates audio from the input text. @@ -143,9 +134,6 @@ async def create( extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds - - stream: Whether or not the response content should be streamed (i.e. not read to - completion immediately), default False """ return await self._post( "/audio/speech", @@ -160,11 +148,7 @@ async def create( speech_create_params.SpeechCreateParams, ), options=make_request_options( - extra_headers=extra_headers, - extra_query=extra_query, - extra_body=extra_body, - timeout=timeout, - stream=stream, + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=HttpxBinaryResponseContent, ) diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index be6eff1e08..a6f75e5a4c 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -212,7 +212,6 @@ def content( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - stream: bool | None = None, ) -> HttpxBinaryResponseContent: """ Returns the contents of the specified file. @@ -225,18 +224,11 @@ def content( extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds - - stream: Whether or not the response content should be streamed (i.e. not read to - completion immediately), default False """ return self._get( f"/files/{file_id}/content", options=make_request_options( - extra_headers=extra_headers, - extra_query=extra_query, - extra_body=extra_body, - timeout=timeout, - stream=stream, + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=HttpxBinaryResponseContent, ) @@ -483,7 +475,6 @@ async def content( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - stream: bool | None = None, ) -> HttpxBinaryResponseContent: """ Returns the contents of the specified file. @@ -496,18 +487,11 @@ async def content( extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds - - stream: Whether or not the response content should be streamed (i.e. not read to - completion immediately), default False """ return await self._get( f"/files/{file_id}/content", options=make_request_options( - extra_headers=extra_headers, - extra_query=extra_query, - extra_body=extra_body, - timeout=timeout, - stream=stream, + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=HttpxBinaryResponseContent, ) From dad2b56d8da41a7e4ce22b33da6d85550dffbc13 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 24 Nov 2023 11:42:36 -0500 Subject: [PATCH 119/816] chore(internal): send more detailed x-stainless headers (#877) --- pyproject.toml | 1 + src/openai/_client.py | 4 +++- src/openai/_utils/__init__.py | 1 + src/openai/_utils/_utils.py | 9 +++++++++ 4 files changed, 14 insertions(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index f17def16b6..d2d85a5018 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -13,6 +13,7 @@ dependencies = [ "typing-extensions>=4.5, <5", "anyio>=3.5.0, <4", "distro>=1.7.0, <2", + "sniffio", "tqdm > 4" ] requires-python = ">= 3.7.1" diff --git a/src/openai/_client.py b/src/openai/_client.py index aa00073281..202162070b 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -20,7 +20,7 @@ ProxiesTypes, RequestOptions, ) -from ._utils import is_given, is_mapping +from ._utils import is_given, is_mapping, get_async_library from ._version import __version__ from ._streaming import Stream as Stream from ._streaming import AsyncStream as AsyncStream @@ -147,6 +147,7 @@ def auth_headers(self) -> dict[str, str]: def default_headers(self) -> dict[str, str | Omit]: return { **super().default_headers, + "X-Stainless-Async": "false", "OpenAI-Organization": self.organization if self.organization is not None else Omit(), **self._custom_headers, } @@ -356,6 +357,7 @@ def auth_headers(self) -> dict[str, str]: def default_headers(self) -> dict[str, str | Omit]: return { **super().default_headers, + "X-Stainless-Async": f"async:{get_async_library()}", "OpenAI-Organization": self.organization if self.organization is not None else Omit(), **self._custom_headers, } diff --git a/src/openai/_utils/__init__.py b/src/openai/_utils/__init__.py index d3397212de..400ca9b828 100644 --- a/src/openai/_utils/__init__.py +++ b/src/openai/_utils/__init__.py @@ -25,6 +25,7 @@ from ._utils import deepcopy_minimal as deepcopy_minimal from ._utils import extract_type_arg as extract_type_arg from ._utils import is_required_type as is_required_type +from ._utils import get_async_library as get_async_library from ._utils import is_annotated_type as is_annotated_type from ._utils import maybe_coerce_float as maybe_coerce_float from ._utils import get_required_header as get_required_header diff --git a/src/openai/_utils/_utils.py b/src/openai/_utils/_utils.py index 4b51dcb2e8..d2bfc91a70 100644 --- a/src/openai/_utils/_utils.py +++ b/src/openai/_utils/_utils.py @@ -18,6 +18,8 @@ from pathlib import Path from typing_extensions import Required, Annotated, TypeGuard, get_args, get_origin +import sniffio + from .._types import Headers, NotGiven, FileTypes, NotGivenOr, HeadersLike from .._compat import is_union as _is_union from .._compat import parse_date as parse_date @@ -406,3 +408,10 @@ def get_required_header(headers: HeadersLike, header: str) -> str: return value raise ValueError(f"Could not find {header} header") + + +def get_async_library() -> str: + try: + return sniffio.current_async_library() + except Exception: + return "false" From 9c8789c284fce2372110ecd8f855fe4aa0a4f3a7 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 28 Nov 2023 00:26:59 -0500 Subject: [PATCH 120/816] docs: update readme code snippet (#890) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 33ec6add52..3861b7db2b 100644 --- a/README.md +++ b/README.md @@ -252,7 +252,7 @@ completion = client.chat.completions.create( "content": "Can you generate an example json object describing a fruit?", } ], - model="gpt-3.5-turbo", + model="gpt-3.5-turbo-1106", response_format={"type": "json_object"}, ) ``` From 0990e31c94911b10295ebf47affbc370a4bd88dd Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 28 Nov 2023 08:43:59 -0500 Subject: [PATCH 121/816] chore(deps): bump mypy to v1.7.1 (#891) --- pyproject.toml | 2 +- requirements-dev.lock | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index d2d85a5018..351c464313 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -49,7 +49,7 @@ openai = "openai.cli:main" managed = true dev-dependencies = [ "pyright==1.1.332", - "mypy==1.6.1", + "mypy==1.7.1", "black==23.3.0", "respx==0.19.2", "pytest==7.1.1", diff --git a/requirements-dev.lock b/requirements-dev.lock index 0747babdc5..683454d678 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -16,10 +16,10 @@ azure-identity==1.15.0 black==23.3.0 certifi==2023.7.22 cffi==1.16.0 -charset-normalizer==3.3.1 +charset-normalizer==3.3.2 click==8.1.7 colorlog==6.7.0 -cryptography==41.0.5 +cryptography==41.0.7 dirty-equals==0.6.0 distlib==0.3.7 distro==1.8.0 @@ -31,15 +31,15 @@ httpx==0.23.0 idna==3.4 iniconfig==2.0.0 isort==5.10.1 -msal==1.24.1 +msal==1.25.0 msal-extensions==1.0.0 -mypy==1.6.1 +mypy==1.7.1 mypy-extensions==1.0.0 nodeenv==1.8.0 nox==2023.4.22 -numpy==1.26.1 +numpy==1.26.2 packaging==23.2 -pandas==2.1.1 +pandas==2.1.3 pandas-stubs==2.1.1.230928 pathspec==0.11.2 platformdirs==3.11.0 @@ -68,7 +68,7 @@ types-pytz==2023.3.1.1 types-tqdm==4.66.0.2 typing-extensions==4.8.0 tzdata==2023.3 -urllib3==2.0.7 +urllib3==2.1.0 virtualenv==20.24.5 # The following packages are considered to be unsafe in a requirements file: setuptools==68.2.2 From 738abb59190d049efe6ab7df72115409ee5c372c Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 28 Nov 2023 17:01:57 -0500 Subject: [PATCH 122/816] docs(readme): update examples (#893) --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 3861b7db2b..96865aba78 100644 --- a/README.md +++ b/README.md @@ -94,9 +94,9 @@ stream = client.chat.completions.create( messages=[{"role": "user", "content": "Say this is a test"}], stream=True, ) -for chunk in stream: +for part in stream: if chunk.choices[0].delta.content is not None: - print(chunk.choices[0].delta.content, end="") + print(part.choices[0].delta.content) ``` The async client uses the exact same interface. @@ -111,9 +111,9 @@ stream = await client.chat.completions.create( messages=[{"role": "user", "content": "Say this is a test"}], stream=True, ) -async for chunk in stream: +async for part in stream: if chunk.choices[0].delta.content is not None: - print(chunk.choices[0].delta.content, end="") + print(part.choices[0].delta.content) ``` ## Module-level client From 54c7c512b276ee0789e9bf6a0234d9cd34dd44e5 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 28 Nov 2023 17:18:32 -0500 Subject: [PATCH 123/816] docs(readme): minor updates (#894) --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 96865aba78..83392e9585 100644 --- a/README.md +++ b/README.md @@ -94,7 +94,7 @@ stream = client.chat.completions.create( messages=[{"role": "user", "content": "Say this is a test"}], stream=True, ) -for part in stream: +for chunk in stream: if chunk.choices[0].delta.content is not None: print(part.choices[0].delta.content) ``` @@ -111,7 +111,7 @@ stream = await client.chat.completions.create( messages=[{"role": "user", "content": "Say this is a test"}], stream=True, ) -async for part in stream: +async for chunk in stream: if chunk.choices[0].delta.content is not None: print(part.choices[0].delta.content) ``` From 17ac6779958b2b74999c634c4ea4c7b74906027a Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 28 Nov 2023 17:19:13 -0500 Subject: [PATCH 124/816] release: 1.3.6 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 22 ++++++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 25 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 13787787c4..907051ec7d 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.3.5" + ".": "1.3.6" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 0869b3888c..a4c324e4f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,27 @@ # Changelog +## 1.3.6 (2023-11-28) + +Full Changelog: [v1.3.5...v1.3.6](https://github.com/openai/openai-python/compare/v1.3.5...v1.3.6) + +### Bug Fixes + +* **client:** add support for streaming binary responses ([#866](https://github.com/openai/openai-python/issues/866)) ([2470d25](https://github.com/openai/openai-python/commit/2470d251b751e92e8950bc9e3026965e9925ac1c)) + + +### Chores + +* **deps:** bump mypy to v1.7.1 ([#891](https://github.com/openai/openai-python/issues/891)) ([11fcb2a](https://github.com/openai/openai-python/commit/11fcb2a3cd4205b307c13c65ad47d9e315b0084d)) +* **internal:** send more detailed x-stainless headers ([#877](https://github.com/openai/openai-python/issues/877)) ([69e0549](https://github.com/openai/openai-python/commit/69e054947d587ff2548b101ece690d21d3c38f74)) +* revert binary streaming change ([#875](https://github.com/openai/openai-python/issues/875)) ([0a06d6a](https://github.com/openai/openai-python/commit/0a06d6a078c5ee898dae75bab4988e1a1936bfbf)) + + +### Documentation + +* **readme:** minor updates ([#894](https://github.com/openai/openai-python/issues/894)) ([5458457](https://github.com/openai/openai-python/commit/54584572df4c2a086172d812c6acb84e3405328b)) +* **readme:** update examples ([#893](https://github.com/openai/openai-python/issues/893)) ([124da87](https://github.com/openai/openai-python/commit/124da8720c44d40c083d29179f46a265761c1f4f)) +* update readme code snippet ([#890](https://github.com/openai/openai-python/issues/890)) ([c522f21](https://github.com/openai/openai-python/commit/c522f21e2a685454185d57e462e74a28499460f9)) + ## 1.3.5 (2023-11-21) Full Changelog: [v1.3.4...v1.3.5](https://github.com/openai/openai-python/compare/v1.3.4...v1.3.5) diff --git a/pyproject.toml b/pyproject.toml index 351c464313..daa765a7c2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.3.5" +version = "1.3.6" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 1ef6479491..bf8fdd1b4f 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.3.5" # x-release-please-version +__version__ = "1.3.6" # x-release-please-version From 84c85bdffde6bdfe8fd152ba5eec371e9260d0a8 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 29 Nov 2023 06:38:46 -0500 Subject: [PATCH 125/816] fix(client): don't cause crashes when inspecting the module (#897) --- src/openai/_utils/_proxy.py | 26 ++++++++++++++++++++++---- src/openai/lib/_old_api.py | 12 +++++++++--- 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/src/openai/_utils/_proxy.py b/src/openai/_utils/_proxy.py index aa934a3fbc..3c9e790a25 100644 --- a/src/openai/_utils/_proxy.py +++ b/src/openai/_utils/_proxy.py @@ -18,25 +18,43 @@ class LazyProxy(Generic[T], ABC): def __init__(self) -> None: self.__proxied: T | None = None + # Note: we have to special case proxies that themselves return proxies + # to support using a proxy as a catch-all for any random access, e.g. `proxy.foo.bar.baz` + def __getattr__(self, attr: str) -> object: - return getattr(self.__get_proxied__(), attr) + proxied = self.__get_proxied__() + if isinstance(proxied, LazyProxy): + return proxied # pyright: ignore + return getattr(proxied, attr) @override def __repr__(self) -> str: + proxied = self.__get_proxied__() + if isinstance(proxied, LazyProxy): + return proxied.__class__.__name__ return repr(self.__get_proxied__()) @override def __str__(self) -> str: - return str(self.__get_proxied__()) + proxied = self.__get_proxied__() + if isinstance(proxied, LazyProxy): + return proxied.__class__.__name__ + return str(proxied) @override def __dir__(self) -> Iterable[str]: - return self.__get_proxied__().__dir__() + proxied = self.__get_proxied__() + if isinstance(proxied, LazyProxy): + return [] + return proxied.__dir__() @property # type: ignore @override def __class__(self) -> type: - return self.__get_proxied__().__class__ + proxied = self.__get_proxied__() + if issubclass(type(proxied), LazyProxy): + return type(proxied) + return proxied.__class__ def __get_proxied__(self) -> T: if not self.should_cache: diff --git a/src/openai/lib/_old_api.py b/src/openai/lib/_old_api.py index c4038fcfaf..929c87e80b 100644 --- a/src/openai/lib/_old_api.py +++ b/src/openai/lib/_old_api.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any from typing_extensions import override from .._utils import LazyProxy @@ -23,13 +23,19 @@ def __init__(self, *, symbol: str) -> None: super().__init__(INSTRUCTIONS.format(symbol=symbol)) -class APIRemovedInV1Proxy(LazyProxy[None]): +class APIRemovedInV1Proxy(LazyProxy[Any]): def __init__(self, *, symbol: str) -> None: super().__init__() self._symbol = symbol @override - def __load__(self) -> None: + def __load__(self) -> Any: + # return the proxy until it is eventually called so that + # we don't break people that are just checking the attributes + # of a module + return self + + def __call__(self, *_args: Any, **_kwargs: Any) -> Any: raise APIRemovedInV1(symbol=self._symbol) From 2e7e897a6632188c66618d9b53e61cbf9331b4b0 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 29 Nov 2023 07:25:50 -0500 Subject: [PATCH 126/816] chore(internal): add tests for proxy change (#899) --- tests/lib/test_old_api.py | 17 +++++++++++++++++ tests/test_utils/test_proxy.py | 23 +++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 tests/lib/test_old_api.py create mode 100644 tests/test_utils/test_proxy.py diff --git a/tests/lib/test_old_api.py b/tests/lib/test_old_api.py new file mode 100644 index 0000000000..261b8acb94 --- /dev/null +++ b/tests/lib/test_old_api.py @@ -0,0 +1,17 @@ +import pytest + +import openai +from openai.lib._old_api import APIRemovedInV1 + + +def test_basic_attribute_access_works() -> None: + for attr in dir(openai): + dir(getattr(openai, attr)) + + +def test_helpful_error_is_raised() -> None: + with pytest.raises(APIRemovedInV1): + openai.Completion.create() # type: ignore + + with pytest.raises(APIRemovedInV1): + openai.ChatCompletion.create() # type: ignore diff --git a/tests/test_utils/test_proxy.py b/tests/test_utils/test_proxy.py new file mode 100644 index 0000000000..57c059150d --- /dev/null +++ b/tests/test_utils/test_proxy.py @@ -0,0 +1,23 @@ +import operator +from typing import Any +from typing_extensions import override + +from openai._utils import LazyProxy + + +class RecursiveLazyProxy(LazyProxy[Any]): + @override + def __load__(self) -> Any: + return self + + def __call__(self, *_args: Any, **_kwds: Any) -> Any: + raise RuntimeError("This should never be called!") + + +def test_recursive_proxy() -> None: + proxy = RecursiveLazyProxy() + assert repr(proxy) == "RecursiveLazyProxy" + assert str(proxy) == "RecursiveLazyProxy" + assert dir(proxy) == [] + assert getattr(type(proxy), "__name__") == "RecursiveLazyProxy" + assert type(operator.attrgetter("name.foo.bar.baz")(proxy)).__name__ == "RecursiveLazyProxy" From 7aad3405c2d460259bfc35d93e8d062e7e11c3e3 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 29 Nov 2023 19:02:45 -0500 Subject: [PATCH 127/816] fix(client): ensure retried requests are closed (#902) --- src/openai/_base_client.py | 100 +++++++++++++---- src/openai/_constants.py | 1 + tests/test_client.py | 222 ++++++++++++++++++++++++++++++++++++- 3 files changed, 302 insertions(+), 21 deletions(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index a168301f75..89d9ce4815 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -72,6 +72,7 @@ DEFAULT_TIMEOUT, DEFAULT_MAX_RETRIES, RAW_RESPONSE_HEADER, + STREAMED_RAW_RESPONSE_HEADER, ) from ._streaming import Stream, AsyncStream from ._exceptions import ( @@ -363,14 +364,21 @@ def _make_status_error_from_response( self, response: httpx.Response, ) -> APIStatusError: - err_text = response.text.strip() - body = err_text + if response.is_closed and not response.is_stream_consumed: + # We can't read the response body as it has been closed + # before it was read. This can happen if an event hook + # raises a status error. + body = None + err_msg = f"Error code: {response.status_code}" + else: + err_text = response.text.strip() + body = err_text - try: - body = json.loads(err_text) - err_msg = f"Error code: {response.status_code} - {body}" - except Exception: - err_msg = err_text or f"Error code: {response.status_code}" + try: + body = json.loads(err_text) + err_msg = f"Error code: {response.status_code} - {body}" + except Exception: + err_msg = err_text or f"Error code: {response.status_code}" return self._make_status_error(err_msg, body=body, response=response) @@ -534,6 +542,12 @@ def _process_response_data( except pydantic.ValidationError as err: raise APIResponseValidationError(response=response, body=data) from err + def _should_stream_response_body(self, *, request: httpx.Request) -> bool: + if request.headers.get(STREAMED_RAW_RESPONSE_HEADER) == "true": + return True + + return False + @property def qs(self) -> Querystring: return Querystring() @@ -606,7 +620,7 @@ def _calculate_retry_timeout( if response_headers is not None: retry_header = response_headers.get("retry-after") try: - retry_after = int(retry_header) + retry_after = float(retry_header) except Exception: retry_date_tuple = email.utils.parsedate_tz(retry_header) if retry_date_tuple is None: @@ -862,14 +876,21 @@ def _request( request = self._build_request(options) self._prepare_request(request) + response = None + try: - response = self._client.send(request, auth=self.custom_auth, stream=stream) + response = self._client.send( + request, + auth=self.custom_auth, + stream=stream or self._should_stream_response_body(request=request), + ) log.debug( 'HTTP Request: %s %s "%i %s"', request.method, request.url, response.status_code, response.reason_phrase ) response.raise_for_status() except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code if retries > 0 and self._should_retry(err.response): + err.response.close() return self._retry_request( options, cast_to, @@ -881,9 +902,14 @@ def _request( # If the response is streamed then we need to explicitly read the response # to completion before attempting to access the response text. - err.response.read() + if not err.response.is_closed: + err.response.read() + raise self._make_status_error_from_response(err.response) from None except httpx.TimeoutException as err: + if response is not None: + response.close() + if retries > 0: return self._retry_request( options, @@ -891,9 +917,14 @@ def _request( retries, stream=stream, stream_cls=stream_cls, + response_headers=response.headers if response is not None else None, ) + raise APITimeoutError(request=request) from err except Exception as err: + if response is not None: + response.close() + if retries > 0: return self._retry_request( options, @@ -901,7 +932,9 @@ def _request( retries, stream=stream, stream_cls=stream_cls, + response_headers=response.headers if response is not None else None, ) + raise APIConnectionError(request=request) from err return self._process_response( @@ -917,7 +950,7 @@ def _retry_request( options: FinalRequestOptions, cast_to: Type[ResponseT], remaining_retries: int, - response_headers: Optional[httpx.Headers] = None, + response_headers: httpx.Headers | None, *, stream: bool, stream_cls: type[_StreamT] | None, @@ -1303,14 +1336,21 @@ async def _request( request = self._build_request(options) await self._prepare_request(request) + response = None + try: - response = await self._client.send(request, auth=self.custom_auth, stream=stream) + response = await self._client.send( + request, + auth=self.custom_auth, + stream=stream or self._should_stream_response_body(request=request), + ) log.debug( 'HTTP Request: %s %s "%i %s"', request.method, request.url, response.status_code, response.reason_phrase ) response.raise_for_status() except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code if retries > 0 and self._should_retry(err.response): + await err.response.aclose() return await self._retry_request( options, cast_to, @@ -1322,19 +1362,39 @@ async def _request( # If the response is streamed then we need to explicitly read the response # to completion before attempting to access the response text. - await err.response.aread() + if not err.response.is_closed: + await err.response.aread() + raise self._make_status_error_from_response(err.response) from None - except httpx.ConnectTimeout as err: - if retries > 0: - return await self._retry_request(options, cast_to, retries, stream=stream, stream_cls=stream_cls) - raise APITimeoutError(request=request) from err except httpx.TimeoutException as err: + if response is not None: + await response.aclose() + if retries > 0: - return await self._retry_request(options, cast_to, retries, stream=stream, stream_cls=stream_cls) + return await self._retry_request( + options, + cast_to, + retries, + stream=stream, + stream_cls=stream_cls, + response_headers=response.headers if response is not None else None, + ) + raise APITimeoutError(request=request) from err except Exception as err: + if response is not None: + await response.aclose() + if retries > 0: - return await self._retry_request(options, cast_to, retries, stream=stream, stream_cls=stream_cls) + return await self._retry_request( + options, + cast_to, + retries, + stream=stream, + stream_cls=stream_cls, + response_headers=response.headers if response is not None else None, + ) + raise APIConnectionError(request=request) from err return self._process_response( @@ -1350,7 +1410,7 @@ async def _retry_request( options: FinalRequestOptions, cast_to: Type[ResponseT], remaining_retries: int, - response_headers: Optional[httpx.Headers] = None, + response_headers: httpx.Headers | None, *, stream: bool, stream_cls: type[_AsyncStreamT] | None, diff --git a/src/openai/_constants.py b/src/openai/_constants.py index 2e402300d3..7c13feaa25 100644 --- a/src/openai/_constants.py +++ b/src/openai/_constants.py @@ -3,6 +3,7 @@ import httpx RAW_RESPONSE_HEADER = "X-Stainless-Raw-Response" +STREAMED_RAW_RESPONSE_HEADER = "X-Stainless-Streamed-Raw-Response" # default timeout is 10 minutes DEFAULT_TIMEOUT = httpx.Timeout(timeout=600.0, connect=5.0) diff --git a/tests/test_client.py b/tests/test_client.py index c5dbfe4bfe..51aa90a480 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -18,7 +18,12 @@ from openai._client import OpenAI, AsyncOpenAI from openai._models import BaseModel, FinalRequestOptions from openai._streaming import Stream, AsyncStream -from openai._exceptions import APIResponseValidationError +from openai._exceptions import ( + APIStatusError, + APITimeoutError, + APIConnectionError, + APIResponseValidationError, +) from openai._base_client import ( DEFAULT_TIMEOUT, HTTPX_DEFAULT_TIMEOUT, @@ -38,6 +43,24 @@ def _get_params(client: BaseClient[Any, Any]) -> dict[str, str]: return dict(url.params) +_original_response_init = cast(Any, httpx.Response.__init__) # type: ignore + + +def _low_retry_response_init(*args: Any, **kwargs: Any) -> Any: + headers = cast("list[tuple[bytes, bytes]]", kwargs["headers"]) + headers.append((b"retry-after", b"0.1")) + + return _original_response_init(*args, **kwargs) + + +def _get_open_connections(client: OpenAI | AsyncOpenAI) -> int: + transport = client._client._transport + assert isinstance(transport, httpx.HTTPTransport) or isinstance(transport, httpx.AsyncHTTPTransport) + + pool = transport._pool + return len(pool._requests) + + class TestOpenAI: client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -592,6 +615,104 @@ def test_parse_retry_after_header(self, remaining_retries: int, retry_after: str calculated = client._calculate_retry_timeout(remaining_retries, options, headers) assert calculated == pytest.approx(timeout, 0.5 * 0.875) # pyright: ignore[reportUnknownMemberType] + @mock.patch("httpx.Response.__init__", _low_retry_response_init) + def test_retrying_timeout_errors_doesnt_leak(self) -> None: + def raise_for_status(response: httpx.Response) -> None: + raise httpx.TimeoutException("Test timeout error", request=response.request) + + with mock.patch("httpx.Response.raise_for_status", raise_for_status): + with pytest.raises(APITimeoutError): + self.client.post( + "/chat/completions", + body=dict( + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-3.5-turbo", + ), + cast_to=httpx.Response, + options={"headers": {"X-Stainless-Streamed-Raw-Response": "true"}}, + ) + + assert _get_open_connections(self.client) == 0 + + @mock.patch("httpx.Response.__init__", _low_retry_response_init) + def test_retrying_runtime_errors_doesnt_leak(self) -> None: + def raise_for_status(_response: httpx.Response) -> None: + raise RuntimeError("Test error") + + with mock.patch("httpx.Response.raise_for_status", raise_for_status): + with pytest.raises(APIConnectionError): + self.client.post( + "/chat/completions", + body=dict( + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-3.5-turbo", + ), + cast_to=httpx.Response, + options={"headers": {"X-Stainless-Streamed-Raw-Response": "true"}}, + ) + + assert _get_open_connections(self.client) == 0 + + @mock.patch("httpx.Response.__init__", _low_retry_response_init) + def test_retrying_status_errors_doesnt_leak(self) -> None: + def raise_for_status(response: httpx.Response) -> None: + response.status_code = 500 + raise httpx.HTTPStatusError("Test 500 error", response=response, request=response.request) + + with mock.patch("httpx.Response.raise_for_status", raise_for_status): + with pytest.raises(APIStatusError): + self.client.post( + "/chat/completions", + body=dict( + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-3.5-turbo", + ), + cast_to=httpx.Response, + options={"headers": {"X-Stainless-Streamed-Raw-Response": "true"}}, + ) + + assert _get_open_connections(self.client) == 0 + + @pytest.mark.respx(base_url=base_url) + def test_status_error_within_httpx(self, respx_mock: MockRouter) -> None: + respx_mock.post("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + + def on_response(response: httpx.Response) -> None: + raise httpx.HTTPStatusError( + "Simulating an error inside httpx", + response=response, + request=response.request, + ) + + client = OpenAI( + base_url=base_url, + api_key=api_key, + _strict_response_validation=True, + http_client=httpx.Client( + event_hooks={ + "response": [on_response], + } + ), + max_retries=0, + ) + with pytest.raises(APIStatusError): + client.post("/foo", cast_to=httpx.Response) + class TestAsyncOpenAI: client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -1162,3 +1283,102 @@ async def test_parse_retry_after_header(self, remaining_retries: int, retry_afte options = FinalRequestOptions(method="get", url="/foo", max_retries=3) calculated = client._calculate_retry_timeout(remaining_retries, options, headers) assert calculated == pytest.approx(timeout, 0.5 * 0.875) # pyright: ignore[reportUnknownMemberType] + + @mock.patch("httpx.Response.__init__", _low_retry_response_init) + async def test_retrying_timeout_errors_doesnt_leak(self) -> None: + def raise_for_status(response: httpx.Response) -> None: + raise httpx.TimeoutException("Test timeout error", request=response.request) + + with mock.patch("httpx.Response.raise_for_status", raise_for_status): + with pytest.raises(APITimeoutError): + await self.client.post( + "/chat/completions", + body=dict( + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-3.5-turbo", + ), + cast_to=httpx.Response, + options={"headers": {"X-Stainless-Streamed-Raw-Response": "true"}}, + ) + + assert _get_open_connections(self.client) == 0 + + @mock.patch("httpx.Response.__init__", _low_retry_response_init) + async def test_retrying_runtime_errors_doesnt_leak(self) -> None: + def raise_for_status(_response: httpx.Response) -> None: + raise RuntimeError("Test error") + + with mock.patch("httpx.Response.raise_for_status", raise_for_status): + with pytest.raises(APIConnectionError): + await self.client.post( + "/chat/completions", + body=dict( + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-3.5-turbo", + ), + cast_to=httpx.Response, + options={"headers": {"X-Stainless-Streamed-Raw-Response": "true"}}, + ) + + assert _get_open_connections(self.client) == 0 + + @mock.patch("httpx.Response.__init__", _low_retry_response_init) + async def test_retrying_status_errors_doesnt_leak(self) -> None: + def raise_for_status(response: httpx.Response) -> None: + response.status_code = 500 + raise httpx.HTTPStatusError("Test 500 error", response=response, request=response.request) + + with mock.patch("httpx.Response.raise_for_status", raise_for_status): + with pytest.raises(APIStatusError): + await self.client.post( + "/chat/completions", + body=dict( + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-3.5-turbo", + ), + cast_to=httpx.Response, + options={"headers": {"X-Stainless-Streamed-Raw-Response": "true"}}, + ) + + assert _get_open_connections(self.client) == 0 + + @pytest.mark.respx(base_url=base_url) + @pytest.mark.asyncio + async def test_status_error_within_httpx(self, respx_mock: MockRouter) -> None: + respx_mock.post("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + + def on_response(response: httpx.Response) -> None: + raise httpx.HTTPStatusError( + "Simulating an error inside httpx", + response=response, + request=response.request, + ) + + client = AsyncOpenAI( + base_url=base_url, + api_key=api_key, + _strict_response_validation=True, + http_client=httpx.AsyncClient( + event_hooks={ + "response": [on_response], + } + ), + max_retries=0, + ) + with pytest.raises(APIStatusError): + await client.post("/foo", cast_to=httpx.Response) From bcfbab7078d7e7c1ac1fcea05e32aba578e46bbb Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 29 Nov 2023 21:29:58 -0500 Subject: [PATCH 128/816] docs: fix typo in readme (#904) --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 83392e9585..380ccc58d9 100644 --- a/README.md +++ b/README.md @@ -96,7 +96,7 @@ stream = client.chat.completions.create( ) for chunk in stream: if chunk.choices[0].delta.content is not None: - print(part.choices[0].delta.content) + print(chunk.choices[0].delta.content) ``` The async client uses the exact same interface. @@ -113,7 +113,7 @@ stream = await client.chat.completions.create( ) async for chunk in stream: if chunk.choices[0].delta.content is not None: - print(part.choices[0].delta.content) + print(chunk.choices[0].delta.content) ``` ## Module-level client From fb5ba01c4cf3ac7c96bf08818f3e943fb3696111 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 30 Nov 2023 08:20:46 -0500 Subject: [PATCH 129/816] docs(readme): update example snippets (#907) --- README.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 380ccc58d9..4cabdb897d 100644 --- a/README.md +++ b/README.md @@ -26,11 +26,12 @@ pip install openai The full API of this library can be found in [api.md](https://www.github.com/openai/openai-python/blob/main/api.md). ```python +import os from openai import OpenAI client = OpenAI( - # defaults to os.environ.get("OPENAI_API_KEY") - api_key="My API Key", + # This is the default and can be omitted + api_key=os.environ.get("OPENAI_API_KEY"), ) chat_completion = client.chat.completions.create( @@ -54,12 +55,13 @@ so that your API Key is not stored in source control. Simply import `AsyncOpenAI` instead of `OpenAI` and use `await` with each API call: ```python +import os import asyncio from openai import AsyncOpenAI client = AsyncOpenAI( - # defaults to os.environ.get("OPENAI_API_KEY") - api_key="My API Key", + # This is the default and can be omitted + api_key=os.environ.get("OPENAI_API_KEY"), ) From 6817fcd8a25c3b5c722bac8ee134c67e24a1c8ed Mon Sep 17 00:00:00 2001 From: Evgenii Date: Thu, 30 Nov 2023 20:46:48 +0300 Subject: [PATCH 130/816] chore(internal): replace string concatenation with f-strings (#908) --- src/openai/_utils/_utils.py | 2 +- src/openai/lib/_validators.py | 6 +++--- tests/test_required_args.py | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/openai/_utils/_utils.py b/src/openai/_utils/_utils.py index d2bfc91a70..83f88cc3e7 100644 --- a/src/openai/_utils/_utils.py +++ b/src/openai/_utils/_utils.py @@ -230,7 +230,7 @@ def human_join(seq: Sequence[str], *, delim: str = ", ", final: str = "or") -> s def quote(string: str) -> str: """Add single quotation marks around the given string. Does *not* do any escaping.""" - return "'" + string + "'" + return f"'{string}'" def required_args(*variants: Sequence[str]) -> Callable[[CallableT], CallableT]: diff --git a/src/openai/lib/_validators.py b/src/openai/lib/_validators.py index c8608c0cef..ae48aafa88 100644 --- a/src/openai/lib/_validators.py +++ b/src/openai/lib/_validators.py @@ -309,10 +309,10 @@ def common_completion_prefix_validator(df: pd.DataFrame) -> Remediation: return Remediation(name="common_prefix") def remove_common_prefix(x: Any, prefix: Any, ws_prefix: Any) -> Any: - x["completion"] = x["completion"].str[len(prefix) :] + x["completion"] = x["completion"].str[len(prefix):] if ws_prefix: # keep the single whitespace as prefix - x["completion"] = " " + x["completion"] + x["completion"] = f" {x['completion']}" return x if (df.completion == common_prefix).all(): @@ -624,7 +624,7 @@ def get_outfnames(fname: str, split: bool) -> list[str]: while True: index_suffix = f" ({i})" if i > 0 else "" candidate_fnames = [ - os.path.splitext(fname)[0] + "_prepared" + suffix + index_suffix + ".jsonl" for suffix in suffixes + f"{os.path.splitext(fname)[0]}_prepared{suffix}{index_suffix}.jsonl" for suffix in suffixes ] if not any(os.path.isfile(f) for f in candidate_fnames): return candidate_fnames diff --git a/tests/test_required_args.py b/tests/test_required_args.py index 1de017db24..5d1a5224ff 100644 --- a/tests/test_required_args.py +++ b/tests/test_required_args.py @@ -43,7 +43,7 @@ def foo(*, a: str | None = None) -> str | None: def test_multiple_params() -> None: @required_args(["a", "b", "c"]) def foo(a: str = "", *, b: str = "", c: str = "") -> str | None: - return a + " " + b + " " + c + return f"{a} {b} {c}" assert foo(a="a", b="b", c="c") == "a b c" From 104e5a54609c6fd003701a0f6f52e56cdeb806c3 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 30 Nov 2023 12:52:50 -0500 Subject: [PATCH 131/816] chore(internal): replace string concatenation with f-strings (#909) --- src/openai/lib/_validators.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/openai/lib/_validators.py b/src/openai/lib/_validators.py index ae48aafa88..e36f0e95fb 100644 --- a/src/openai/lib/_validators.py +++ b/src/openai/lib/_validators.py @@ -309,7 +309,7 @@ def common_completion_prefix_validator(df: pd.DataFrame) -> Remediation: return Remediation(name="common_prefix") def remove_common_prefix(x: Any, prefix: Any, ws_prefix: Any) -> Any: - x["completion"] = x["completion"].str[len(prefix):] + x["completion"] = x["completion"].str[len(prefix) :] if ws_prefix: # keep the single whitespace as prefix x["completion"] = f" {x['completion']}" @@ -623,9 +623,7 @@ def get_outfnames(fname: str, split: bool) -> list[str]: i = 0 while True: index_suffix = f" ({i})" if i > 0 else "" - candidate_fnames = [ - f"{os.path.splitext(fname)[0]}_prepared{suffix}{index_suffix}.jsonl" for suffix in suffixes - ] + candidate_fnames = [f"{os.path.splitext(fname)[0]}_prepared{suffix}{index_suffix}.jsonl" for suffix in suffixes] if not any(os.path.isfile(f) for f in candidate_fnames): return candidate_fnames i += 1 From 4d9ece0e6a7f6ea5e321bf49258e02955c6484be Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 1 Dec 2023 10:10:40 -0500 Subject: [PATCH 132/816] chore(internal): remove unused type var (#915) --- src/openai/pagination.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/openai/pagination.py b/src/openai/pagination.py index 4ec300f2d1..17f2d1a4ca 100644 --- a/src/openai/pagination.py +++ b/src/openai/pagination.py @@ -1,16 +1,13 @@ # File generated from our OpenAPI spec by Stainless. -from typing import Any, List, Generic, TypeVar, Optional, cast +from typing import Any, List, Generic, Optional, cast from typing_extensions import Literal, Protocol, override, runtime_checkable from ._types import ModelT -from ._models import BaseModel from ._base_client import BasePage, PageInfo, BaseSyncPage, BaseAsyncPage __all__ = ["SyncPage", "AsyncPage", "SyncCursorPage", "AsyncCursorPage"] -_BaseModelT = TypeVar("_BaseModelT", bound=BaseModel) - @runtime_checkable class CursorPageItem(Protocol): From f6f38a9bc42b371c2f9f889471f319bf82208970 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 1 Dec 2023 12:55:01 -0500 Subject: [PATCH 133/816] fix(client): correct base_url setter implementation (#919) Co-Authored-By: tomoish --- src/openai/_base_client.py | 2 +- tests/test_client.py | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 89d9ce4815..2e5678e8e6 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -592,7 +592,7 @@ def base_url(http://github.com/self) -> URL: @base_url.setter def base_url(http://github.com/self,%20url:%20URL%20|%20str) -> None: - self._client.base_url = url if isinstance(url, URL) else URL(url) + self._base_url = self._enforce_trailing_slash(url if isinstance(url, URL) else URL(url)) @lru_cache(maxsize=None) def platform_headers(self) -> Dict[str, str]: diff --git a/tests/test_client.py b/tests/test_client.py index 51aa90a480..1f1ec6fc98 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -445,6 +445,14 @@ class Model(BaseModel): assert isinstance(response, Model) assert response.foo == 2 + def test_base_url_setter(self) -> None: + client = OpenAI(base_url="https://example.com/from_init", api_key=api_key, _strict_response_validation=True) + assert client.base_url == "https://example.com/from_init/" + + client.base_url = "https://example.com/from_setter" # type: ignore[assignment] + + assert client.base_url == "https://example.com/from_setter/" + def test_base_url_env(self) -> None: with update_env(OPENAI_BASE_URL="http://localhost:5000/from/env"): client = OpenAI(api_key=api_key, _strict_response_validation=True) @@ -1102,6 +1110,16 @@ class Model(BaseModel): assert isinstance(response, Model) assert response.foo == 2 + def test_base_url_setter(self) -> None: + client = AsyncOpenAI( + base_url="https://example.com/from_init", api_key=api_key, _strict_response_validation=True + ) + assert client.base_url == "https://example.com/from_init/" + + client.base_url = "https://example.com/from_setter" # type: ignore[assignment] + + assert client.base_url == "https://example.com/from_setter/" + def test_base_url_env(self) -> None: with update_env(OPENAI_BASE_URL="http://localhost:5000/from/env"): client = AsyncOpenAI(api_key=api_key, _strict_response_validation=True) From e36956673d9049713c91bca6ce7aebe58638f483 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 1 Dec 2023 12:55:42 -0500 Subject: [PATCH 134/816] release: 1.3.7 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 24 ++++++++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 27 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 907051ec7d..2fd8c9c83a 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.3.6" + ".": "1.3.7" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index a4c324e4f9..88ff899ec3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,29 @@ # Changelog +## 1.3.7 (2023-12-01) + +Full Changelog: [v1.3.6...v1.3.7](https://github.com/openai/openai-python/compare/v1.3.6...v1.3.7) + +### Bug Fixes + +* **client:** correct base_url setter implementation ([#919](https://github.com/openai/openai-python/issues/919)) ([135d9cf](https://github.com/openai/openai-python/commit/135d9cf2820f1524764bf536a9322830bdcd5875)) +* **client:** don't cause crashes when inspecting the module ([#897](https://github.com/openai/openai-python/issues/897)) ([db029a5](https://github.com/openai/openai-python/commit/db029a596c90b1af4ef0bfb1cdf31f54b2f5755d)) +* **client:** ensure retried requests are closed ([#902](https://github.com/openai/openai-python/issues/902)) ([e025e6b](https://github.com/openai/openai-python/commit/e025e6bee44ea145d948869ef0c79bac0c376b9f)) + + +### Chores + +* **internal:** add tests for proxy change ([#899](https://github.com/openai/openai-python/issues/899)) ([71a13d0](https://github.com/openai/openai-python/commit/71a13d0c70d105b2b97720c72a1003b942cda2ae)) +* **internal:** remove unused type var ([#915](https://github.com/openai/openai-python/issues/915)) ([4233bcd](https://github.com/openai/openai-python/commit/4233bcdae5f467f10454fcc008a6e728fa846830)) +* **internal:** replace string concatenation with f-strings ([#908](https://github.com/openai/openai-python/issues/908)) ([663a8f6](https://github.com/openai/openai-python/commit/663a8f6dead5aa523d1e8779e75af1dabb1690c4)) +* **internal:** replace string concatenation with f-strings ([#909](https://github.com/openai/openai-python/issues/909)) ([caab767](https://github.com/openai/openai-python/commit/caab767156375114078cf8d85031863361326b5f)) + + +### Documentation + +* fix typo in readme ([#904](https://github.com/openai/openai-python/issues/904)) ([472cd44](https://github.com/openai/openai-python/commit/472cd44e45a45b0b4f12583a5402e8aeb121d7a2)) +* **readme:** update example snippets ([#907](https://github.com/openai/openai-python/issues/907)) ([bbb648e](https://github.com/openai/openai-python/commit/bbb648ef81eb11f81b457e2cbf33a832f4d29a76)) + ## 1.3.6 (2023-11-28) Full Changelog: [v1.3.5...v1.3.6](https://github.com/openai/openai-python/compare/v1.3.5...v1.3.6) diff --git a/pyproject.toml b/pyproject.toml index daa765a7c2..81ef1ca317 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.3.6" +version = "1.3.7" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index bf8fdd1b4f..3103f3b767 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.3.6" # x-release-please-version +__version__ = "1.3.7" # x-release-please-version From 31573844c7aa0ba27c1c4280caab9f092622f526 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 4 Dec 2023 05:27:44 -0500 Subject: [PATCH 135/816] chore(package): lift anyio v4 restriction (#927) --- pyproject.toml | 4 ++-- requirements-dev.lock | 11 +++++------ requirements.lock | 13 ++++++------- tests/test_client.py | 14 +++++++------- 4 files changed, 20 insertions(+), 22 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 81ef1ca317..c468220495 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,7 +11,7 @@ dependencies = [ "httpx>=0.23.0, <1", "pydantic>=1.9.0, <3", "typing-extensions>=4.5, <5", - "anyio>=3.5.0, <4", + "anyio>=3.5.0, <5", "distro>=1.7.0, <2", "sniffio", "tqdm > 4" @@ -51,7 +51,7 @@ dev-dependencies = [ "pyright==1.1.332", "mypy==1.7.1", "black==23.3.0", - "respx==0.19.2", + "respx==0.20.2", "pytest==7.1.1", "pytest-asyncio==0.21.1", "ruff==0.0.282", diff --git a/requirements-dev.lock b/requirements-dev.lock index 683454d678..0ed1974794 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -8,7 +8,7 @@ -e file:. annotated-types==0.6.0 -anyio==3.7.1 +anyio==4.1.0 argcomplete==3.1.2 attrs==23.1.0 azure-core==1.29.5 @@ -25,9 +25,9 @@ distlib==0.3.7 distro==1.8.0 exceptiongroup==1.1.3 filelock==3.12.4 -h11==0.12.0 -httpcore==0.15.0 -httpx==0.23.0 +h11==0.14.0 +httpcore==1.0.2 +httpx==0.25.2 idna==3.4 iniconfig==2.0.0 isort==5.10.1 @@ -56,8 +56,7 @@ pytest-asyncio==0.21.1 python-dateutil==2.8.2 pytz==2023.3.post1 requests==2.31.0 -respx==0.19.2 -rfc3986==1.5.0 +respx==0.20.2 ruff==0.0.282 six==1.16.0 sniffio==1.3.0 diff --git a/requirements.lock b/requirements.lock index be9606fc3c..c178f26a88 100644 --- a/requirements.lock +++ b/requirements.lock @@ -8,22 +8,21 @@ -e file:. annotated-types==0.6.0 -anyio==3.7.1 +anyio==4.1.0 certifi==2023.7.22 distro==1.8.0 exceptiongroup==1.1.3 -h11==0.12.0 -httpcore==0.15.0 -httpx==0.23.0 +h11==0.14.0 +httpcore==1.0.2 +httpx==0.25.2 idna==3.4 -numpy==1.26.1 -pandas==2.1.1 +numpy==1.26.2 +pandas==2.1.3 pandas-stubs==2.1.1.230928 pydantic==2.4.2 pydantic-core==2.10.1 python-dateutil==2.8.2 pytz==2023.3.post1 -rfc3986==1.5.0 six==1.16.0 sniffio==1.3.0 tqdm==4.66.1 diff --git a/tests/test_client.py b/tests/test_client.py index 1f1ec6fc98..f8653507ef 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -6,7 +6,7 @@ import json import asyncio import inspect -from typing import Any, Dict, Union, cast +from typing import Any, Union, cast from unittest import mock import httpx @@ -357,7 +357,7 @@ def test_request_extra_query(self) -> None: ), ), ) - params = cast(Dict[str, str], dict(request.url.params)) + params = dict(request.url.params) assert params == {"my_query_param": "Foo"} # if both `query` and `extra_query` are given, they are merged @@ -371,7 +371,7 @@ def test_request_extra_query(self) -> None: ), ), ) - params = cast(Dict[str, str], dict(request.url.params)) + params = dict(request.url.params) assert params == {"bar": "1", "foo": "2"} # `extra_query` takes priority over `query` when keys clash @@ -385,7 +385,7 @@ def test_request_extra_query(self) -> None: ), ), ) - params = cast(Dict[str, str], dict(request.url.params)) + params = dict(request.url.params) assert params == {"foo": "2"} @pytest.mark.respx(base_url=base_url) @@ -1022,7 +1022,7 @@ def test_request_extra_query(self) -> None: ), ), ) - params = cast(Dict[str, str], dict(request.url.params)) + params = dict(request.url.params) assert params == {"my_query_param": "Foo"} # if both `query` and `extra_query` are given, they are merged @@ -1036,7 +1036,7 @@ def test_request_extra_query(self) -> None: ), ), ) - params = cast(Dict[str, str], dict(request.url.params)) + params = dict(request.url.params) assert params == {"bar": "1", "foo": "2"} # `extra_query` takes priority over `query` when keys clash @@ -1050,7 +1050,7 @@ def test_request_extra_query(self) -> None: ), ), ) - params = cast(Dict[str, str], dict(request.url.params)) + params = dict(request.url.params) assert params == {"foo": "2"} @pytest.mark.respx(base_url=base_url) From f61de9900efe1c9d92b3331a109dd43f14349e2c Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 4 Dec 2023 05:45:51 -0500 Subject: [PATCH 136/816] ci: ensure PR titles use conventional commits (#929) --- .github/workflows/lint-pr.yml | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 .github/workflows/lint-pr.yml diff --git a/.github/workflows/lint-pr.yml b/.github/workflows/lint-pr.yml new file mode 100644 index 0000000000..4074fb2ca1 --- /dev/null +++ b/.github/workflows/lint-pr.yml @@ -0,0 +1,21 @@ +name: "Lint PR" + +on: + pull_request_target: + types: + - opened + - edited + - synchronize + +permissions: + pull-requests: read + +jobs: + pr_title: + name: Validate PR title + runs-on: ubuntu-latest + if: github.ref == 'refs/heads/main' && github.repository == 'openai/openai-python' + steps: + - uses: amannn/action-semantic-pull-request@v5 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} From 3d63cf25716a674a965910ef7a1ab902774c5b79 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 6 Dec 2023 01:04:32 +0000 Subject: [PATCH 137/816] ci: remove PR title linter (#934) --- .github/workflows/lint-pr.yml | 21 --------------------- 1 file changed, 21 deletions(-) delete mode 100644 .github/workflows/lint-pr.yml diff --git a/.github/workflows/lint-pr.yml b/.github/workflows/lint-pr.yml deleted file mode 100644 index 4074fb2ca1..0000000000 --- a/.github/workflows/lint-pr.yml +++ /dev/null @@ -1,21 +0,0 @@ -name: "Lint PR" - -on: - pull_request_target: - types: - - opened - - edited - - synchronize - -permissions: - pull-requests: read - -jobs: - pr_title: - name: Validate PR title - runs-on: ubuntu-latest - if: github.ref == 'refs/heads/main' && github.repository == 'openai/openai-python' - steps: - - uses: amannn/action-semantic-pull-request@v5 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} From 3c6ecceeca7fc6858b85b81e71623ef695f856e3 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 7 Dec 2023 10:12:38 +0000 Subject: [PATCH 138/816] chore(internal): reformat imports (#939) --- pyproject.toml | 37 ++++----- requirements-dev.lock | 5 +- src/openai/__init__.py | 29 +++---- src/openai/_client.py | 3 +- src/openai/_compat.py | 30 ++++---- src/openai/_extras/__init__.py | 3 +- src/openai/_models.py | 14 +--- src/openai/_types.py | 9 +-- src/openai/_utils/__init__.py | 76 ++++++++++--------- src/openai/_utils/_utils.py | 4 +- src/openai/resources/__init__.py | 49 ++---------- src/openai/resources/audio/__init__.py | 14 +--- src/openai/resources/audio/audio.py | 14 +--- src/openai/resources/audio/speech.py | 13 +++- src/openai/resources/audio/transcriptions.py | 13 +++- src/openai/resources/audio/translations.py | 13 +++- src/openai/resources/beta/__init__.py | 14 +--- .../resources/beta/assistants/__init__.py | 7 +- .../resources/beta/assistants/assistants.py | 13 +++- src/openai/resources/beta/assistants/files.py | 13 +++- src/openai/resources/beta/beta.py | 14 +--- src/openai/resources/beta/threads/__init__.py | 14 +--- .../beta/threads/messages/__init__.py | 7 +- .../resources/beta/threads/messages/files.py | 13 +++- .../beta/threads/messages/messages.py | 13 +++- .../resources/beta/threads/runs/runs.py | 13 +++- .../resources/beta/threads/runs/steps.py | 13 +++- src/openai/resources/beta/threads/threads.py | 17 +++-- src/openai/resources/chat/__init__.py | 7 +- src/openai/resources/chat/chat.py | 7 +- src/openai/resources/chat/completions.py | 12 ++- src/openai/resources/completions.py | 12 ++- src/openai/resources/edits.py | 12 ++- src/openai/resources/embeddings.py | 15 +++- src/openai/resources/files.py | 16 +++- src/openai/resources/fine_tunes.py | 13 +++- src/openai/resources/fine_tuning/__init__.py | 7 +- src/openai/resources/fine_tuning/jobs.py | 13 +++- src/openai/resources/images.py | 13 +++- src/openai/resources/models.py | 13 +++- src/openai/resources/moderations.py | 12 ++- src/openai/types/__init__.py | 23 ++---- src/openai/types/audio/__init__.py | 8 +- src/openai/types/beta/__init__.py | 4 +- src/openai/types/beta/threads/__init__.py | 12 +-- .../types/beta/threads/runs/__init__.py | 4 +- src/openai/types/chat/__init__.py | 28 ++----- .../chat_completion_content_part_param.py | 4 +- .../types/chat/completion_create_params.py | 8 +- tests/api_resources/beta/test_assistants.py | 5 +- tests/api_resources/beta/test_threads.py | 5 +- tests/api_resources/beta/threads/test_runs.py | 4 +- tests/api_resources/fine_tuning/test_jobs.py | 5 +- tests/utils.py | 7 +- 54 files changed, 384 insertions(+), 362 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index c468220495..44e7bcb0ed 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -48,16 +48,16 @@ openai = "openai.cli:main" [tool.rye] managed = true dev-dependencies = [ - "pyright==1.1.332", - "mypy==1.7.1", - "black==23.3.0", - "respx==0.20.2", - "pytest==7.1.1", - "pytest-asyncio==0.21.1", - "ruff==0.0.282", - "isort==5.10.1", - "time-machine==2.9.0", - "nox==2023.4.22", + # version pins are in requirements-dev.lock + "pyright", + "mypy", + "black", + "respx", + "pytest", + "pytest-asyncio", + "ruff", + "time-machine", + "nox", "dirty-equals>=0.6.0", "azure-identity >=1.14.1", "types-tqdm > 4" @@ -68,12 +68,10 @@ format = { chain = [ "format:black", "format:docs", "format:ruff", - "format:isort", ]} "format:black" = "black ." "format:docs" = "python bin/blacken-docs.py README.md api.md" "format:ruff" = "ruff --fix ." -"format:isort" = "isort ." "check:ruff" = "ruff ." @@ -128,16 +126,13 @@ reportImplicitOverride = true reportImportCycles = false reportPrivateUsage = false -[tool.isort] -profile = "black" -length_sort = true -extra_standard_library = ["typing_extensions"] - [tool.ruff] line-length = 120 -format = "grouped" +output-format = "grouped" target-version = "py37" select = [ + # isort + "I", # remove unused imports "F401", # bare except statements @@ -155,6 +150,12 @@ unfixable = [ ] ignore-init-module-imports = true +[tool.ruff.lint.isort] +length-sort = true +length-sort-straight = true +combine-as-imports = true +extra-standard-library = ["typing_extensions"] +known-first-party = ["openai", "tests"] [tool.ruff.per-file-ignores] "bin/**.py" = ["T201", "T203"] diff --git a/requirements-dev.lock b/requirements-dev.lock index 0ed1974794..bc993b16de 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -30,8 +30,7 @@ httpcore==1.0.2 httpx==0.25.2 idna==3.4 iniconfig==2.0.0 -isort==5.10.1 -msal==1.25.0 +msal==1.26.0 msal-extensions==1.0.0 mypy==1.7.1 mypy-extensions==1.0.0 @@ -57,7 +56,7 @@ python-dateutil==2.8.2 pytz==2023.3.post1 requests==2.31.0 respx==0.20.2 -ruff==0.0.282 +ruff==0.1.7 six==1.16.0 sniffio==1.3.0 time-machine==2.9.0 diff --git a/src/openai/__init__.py b/src/openai/__init__.py index d92dfe969a..20ab72ee25 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -72,8 +72,7 @@ from .lib import azure as _azure from .version import VERSION as VERSION -from .lib.azure import AzureOpenAI as AzureOpenAI -from .lib.azure import AsyncAzureOpenAI as AsyncAzureOpenAI +from .lib.azure import AzureOpenAI as AzureOpenAI, AsyncAzureOpenAI as AsyncAzureOpenAI from .lib._old_api import * _setup_logging() @@ -330,15 +329,17 @@ def _reset_client() -> None: # type: ignore[reportUnusedFunction] _client = None -from ._module_client import beta as beta -from ._module_client import chat as chat -from ._module_client import audio as audio -from ._module_client import edits as edits -from ._module_client import files as files -from ._module_client import images as images -from ._module_client import models as models -from ._module_client import embeddings as embeddings -from ._module_client import fine_tunes as fine_tunes -from ._module_client import completions as completions -from ._module_client import fine_tuning as fine_tuning -from ._module_client import moderations as moderations +from ._module_client import ( + beta as beta, + chat as chat, + audio as audio, + edits as edits, + files as files, + images as images, + models as models, + embeddings as embeddings, + fine_tunes as fine_tunes, + completions as completions, + fine_tuning as fine_tuning, + moderations as moderations, +) diff --git a/src/openai/_client.py b/src/openai/_client.py index 202162070b..79054aba2f 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -22,8 +22,7 @@ ) from ._utils import is_given, is_mapping, get_async_library from ._version import __version__ -from ._streaming import Stream as Stream -from ._streaming import AsyncStream as AsyncStream +from ._streaming import Stream as Stream, AsyncStream as AsyncStream from ._exceptions import OpenAIError, APIStatusError from ._base_client import DEFAULT_MAX_RETRIES, SyncAPIClient, AsyncAPIClient diff --git a/src/openai/_compat.py b/src/openai/_compat.py index 34323c9b7e..d95db8ed1e 100644 --- a/src/openai/_compat.py +++ b/src/openai/_compat.py @@ -43,21 +43,23 @@ def is_typeddict(type_: type[Any]) -> bool: # noqa: ARG001 else: if PYDANTIC_V2: - from pydantic.v1.typing import get_args as get_args - from pydantic.v1.typing import is_union as is_union - from pydantic.v1.typing import get_origin as get_origin - from pydantic.v1.typing import is_typeddict as is_typeddict - from pydantic.v1.typing import is_literal_type as is_literal_type - from pydantic.v1.datetime_parse import parse_date as parse_date - from pydantic.v1.datetime_parse import parse_datetime as parse_datetime + from pydantic.v1.typing import ( + get_args as get_args, + is_union as is_union, + get_origin as get_origin, + is_typeddict as is_typeddict, + is_literal_type as is_literal_type, + ) + from pydantic.v1.datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime else: - from pydantic.typing import get_args as get_args - from pydantic.typing import is_union as is_union - from pydantic.typing import get_origin as get_origin - from pydantic.typing import is_typeddict as is_typeddict - from pydantic.typing import is_literal_type as is_literal_type - from pydantic.datetime_parse import parse_date as parse_date - from pydantic.datetime_parse import parse_datetime as parse_datetime + from pydantic.typing import ( + get_args as get_args, + is_union as is_union, + get_origin as get_origin, + is_typeddict as is_typeddict, + is_literal_type as is_literal_type, + ) + from pydantic.datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime # refactored config diff --git a/src/openai/_extras/__init__.py b/src/openai/_extras/__init__.py index dc6625c5dc..864dac4171 100644 --- a/src/openai/_extras/__init__.py +++ b/src/openai/_extras/__init__.py @@ -1,3 +1,2 @@ -from .numpy_proxy import numpy as numpy -from .numpy_proxy import has_numpy as has_numpy +from .numpy_proxy import numpy as numpy, has_numpy as has_numpy from .pandas_proxy import pandas as pandas diff --git a/src/openai/_models.py b/src/openai/_models.py index 5b8c96010f..cdd44ccb0a 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -30,17 +30,11 @@ AnyMapping, HttpxRequestFiles, ) -from ._utils import ( - is_list, - is_given, - is_mapping, - parse_date, - parse_datetime, - strip_not_given, -) -from ._compat import PYDANTIC_V2, ConfigDict -from ._compat import GenericModel as BaseGenericModel +from ._utils import is_list, is_given, is_mapping, parse_date, parse_datetime, strip_not_given from ._compat import ( + PYDANTIC_V2, + ConfigDict, + GenericModel as BaseGenericModel, get_args, is_union, parse_obj, diff --git a/src/openai/_types.py b/src/openai/_types.py index 9e962a1078..6f298c18c4 100644 --- a/src/openai/_types.py +++ b/src/openai/_types.py @@ -19,14 +19,7 @@ Sequence, AsyncIterator, ) -from typing_extensions import ( - Literal, - Protocol, - TypeAlias, - TypedDict, - override, - runtime_checkable, -) +from typing_extensions import Literal, Protocol, TypeAlias, TypedDict, override, runtime_checkable import pydantic from httpx import URL, Proxy, Timeout, Response, BaseTransport, AsyncBaseTransport diff --git a/src/openai/_utils/__init__.py b/src/openai/_utils/__init__.py index 400ca9b828..e98636c92f 100644 --- a/src/openai/_utils/__init__.py +++ b/src/openai/_utils/__init__.py @@ -1,37 +1,41 @@ from ._proxy import LazyProxy as LazyProxy -from ._utils import flatten as flatten -from ._utils import is_dict as is_dict -from ._utils import is_list as is_list -from ._utils import is_given as is_given -from ._utils import is_tuple as is_tuple -from ._utils import is_mapping as is_mapping -from ._utils import is_tuple_t as is_tuple_t -from ._utils import parse_date as parse_date -from ._utils import is_sequence as is_sequence -from ._utils import coerce_float as coerce_float -from ._utils import is_list_type as is_list_type -from ._utils import is_mapping_t as is_mapping_t -from ._utils import removeprefix as removeprefix -from ._utils import removesuffix as removesuffix -from ._utils import extract_files as extract_files -from ._utils import is_sequence_t as is_sequence_t -from ._utils import is_union_type as is_union_type -from ._utils import required_args as required_args -from ._utils import coerce_boolean as coerce_boolean -from ._utils import coerce_integer as coerce_integer -from ._utils import file_from_path as file_from_path -from ._utils import parse_datetime as parse_datetime -from ._utils import strip_not_given as strip_not_given -from ._utils import deepcopy_minimal as deepcopy_minimal -from ._utils import extract_type_arg as extract_type_arg -from ._utils import is_required_type as is_required_type -from ._utils import get_async_library as get_async_library -from ._utils import is_annotated_type as is_annotated_type -from ._utils import maybe_coerce_float as maybe_coerce_float -from ._utils import get_required_header as get_required_header -from ._utils import maybe_coerce_boolean as maybe_coerce_boolean -from ._utils import maybe_coerce_integer as maybe_coerce_integer -from ._utils import strip_annotated_type as strip_annotated_type -from ._transform import PropertyInfo as PropertyInfo -from ._transform import transform as transform -from ._transform import maybe_transform as maybe_transform +from ._utils import ( + flatten as flatten, + is_dict as is_dict, + is_list as is_list, + is_given as is_given, + is_tuple as is_tuple, + is_mapping as is_mapping, + is_tuple_t as is_tuple_t, + parse_date as parse_date, + is_sequence as is_sequence, + coerce_float as coerce_float, + is_list_type as is_list_type, + is_mapping_t as is_mapping_t, + removeprefix as removeprefix, + removesuffix as removesuffix, + extract_files as extract_files, + is_sequence_t as is_sequence_t, + is_union_type as is_union_type, + required_args as required_args, + coerce_boolean as coerce_boolean, + coerce_integer as coerce_integer, + file_from_path as file_from_path, + parse_datetime as parse_datetime, + strip_not_given as strip_not_given, + deepcopy_minimal as deepcopy_minimal, + extract_type_arg as extract_type_arg, + is_required_type as is_required_type, + get_async_library as get_async_library, + is_annotated_type as is_annotated_type, + maybe_coerce_float as maybe_coerce_float, + get_required_header as get_required_header, + maybe_coerce_boolean as maybe_coerce_boolean, + maybe_coerce_integer as maybe_coerce_integer, + strip_annotated_type as strip_annotated_type, +) +from ._transform import ( + PropertyInfo as PropertyInfo, + transform as transform, + maybe_transform as maybe_transform, +) diff --git a/src/openai/_utils/_utils.py b/src/openai/_utils/_utils.py index 83f88cc3e7..cce6923810 100644 --- a/src/openai/_utils/_utils.py +++ b/src/openai/_utils/_utils.py @@ -21,9 +21,7 @@ import sniffio from .._types import Headers, NotGiven, FileTypes, NotGivenOr, HeadersLike -from .._compat import is_union as _is_union -from .._compat import parse_date as parse_date -from .._compat import parse_datetime as parse_datetime +from .._compat import is_union as _is_union, parse_date as parse_date, parse_datetime as parse_datetime _T = TypeVar("_T") _TupleT = TypeVar("_TupleT", bound=Tuple[object, ...]) diff --git a/src/openai/resources/__init__.py b/src/openai/resources/__init__.py index e0f4f08d5c..2cdbeb6ae1 100644 --- a/src/openai/resources/__init__.py +++ b/src/openai/resources/__init__.py @@ -5,48 +5,13 @@ from .audio import Audio, AsyncAudio, AudioWithRawResponse, AsyncAudioWithRawResponse from .edits import Edits, AsyncEdits, EditsWithRawResponse, AsyncEditsWithRawResponse from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from .images import ( - Images, - AsyncImages, - ImagesWithRawResponse, - AsyncImagesWithRawResponse, -) -from .models import ( - Models, - AsyncModels, - ModelsWithRawResponse, - AsyncModelsWithRawResponse, -) -from .embeddings import ( - Embeddings, - AsyncEmbeddings, - EmbeddingsWithRawResponse, - AsyncEmbeddingsWithRawResponse, -) -from .fine_tunes import ( - FineTunes, - AsyncFineTunes, - FineTunesWithRawResponse, - AsyncFineTunesWithRawResponse, -) -from .completions import ( - Completions, - AsyncCompletions, - CompletionsWithRawResponse, - AsyncCompletionsWithRawResponse, -) -from .fine_tuning import ( - FineTuning, - AsyncFineTuning, - FineTuningWithRawResponse, - AsyncFineTuningWithRawResponse, -) -from .moderations import ( - Moderations, - AsyncModerations, - ModerationsWithRawResponse, - AsyncModerationsWithRawResponse, -) +from .images import Images, AsyncImages, ImagesWithRawResponse, AsyncImagesWithRawResponse +from .models import Models, AsyncModels, ModelsWithRawResponse, AsyncModelsWithRawResponse +from .embeddings import Embeddings, AsyncEmbeddings, EmbeddingsWithRawResponse, AsyncEmbeddingsWithRawResponse +from .fine_tunes import FineTunes, AsyncFineTunes, FineTunesWithRawResponse, AsyncFineTunesWithRawResponse +from .completions import Completions, AsyncCompletions, CompletionsWithRawResponse, AsyncCompletionsWithRawResponse +from .fine_tuning import FineTuning, AsyncFineTuning, FineTuningWithRawResponse, AsyncFineTuningWithRawResponse +from .moderations import Moderations, AsyncModerations, ModerationsWithRawResponse, AsyncModerationsWithRawResponse __all__ = [ "Completions", diff --git a/src/openai/resources/audio/__init__.py b/src/openai/resources/audio/__init__.py index 76547b5f34..b6ff4322d4 100644 --- a/src/openai/resources/audio/__init__.py +++ b/src/openai/resources/audio/__init__.py @@ -1,18 +1,8 @@ # File generated from our OpenAPI spec by Stainless. from .audio import Audio, AsyncAudio, AudioWithRawResponse, AsyncAudioWithRawResponse -from .speech import ( - Speech, - AsyncSpeech, - SpeechWithRawResponse, - AsyncSpeechWithRawResponse, -) -from .translations import ( - Translations, - AsyncTranslations, - TranslationsWithRawResponse, - AsyncTranslationsWithRawResponse, -) +from .speech import Speech, AsyncSpeech, SpeechWithRawResponse, AsyncSpeechWithRawResponse +from .translations import Translations, AsyncTranslations, TranslationsWithRawResponse, AsyncTranslationsWithRawResponse from .transcriptions import ( Transcriptions, AsyncTranscriptions, diff --git a/src/openai/resources/audio/audio.py b/src/openai/resources/audio/audio.py index 6f7226ee59..6b9242f0c2 100644 --- a/src/openai/resources/audio/audio.py +++ b/src/openai/resources/audio/audio.py @@ -4,19 +4,9 @@ from typing import TYPE_CHECKING -from .speech import ( - Speech, - AsyncSpeech, - SpeechWithRawResponse, - AsyncSpeechWithRawResponse, -) +from .speech import Speech, AsyncSpeech, SpeechWithRawResponse, AsyncSpeechWithRawResponse from ..._resource import SyncAPIResource, AsyncAPIResource -from .translations import ( - Translations, - AsyncTranslations, - TranslationsWithRawResponse, - AsyncTranslationsWithRawResponse, -) +from .translations import Translations, AsyncTranslations, TranslationsWithRawResponse, AsyncTranslationsWithRawResponse from .transcriptions import ( Transcriptions, AsyncTranscriptions, diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index 458843866f..ac81a80777 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -7,12 +7,21 @@ import httpx -from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ..._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ..._utils import maybe_transform from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ...types.audio import speech_create_params -from ..._base_client import HttpxBinaryResponseContent, make_request_options +from ..._base_client import ( + HttpxBinaryResponseContent, + make_request_options, +) if TYPE_CHECKING: from ..._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index d2b4452411..54be1c99a6 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -7,12 +7,21 @@ import httpx -from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes +from ..._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, + FileTypes, +) from ..._utils import extract_files, maybe_transform, deepcopy_minimal from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ...types.audio import Transcription, transcription_create_params -from ..._base_client import make_request_options +from ..._base_client import ( + make_request_options, +) if TYPE_CHECKING: from ..._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index fe7f7f2a40..c4489004ac 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -7,12 +7,21 @@ import httpx -from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes +from ..._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, + FileTypes, +) from ..._utils import extract_files, maybe_transform, deepcopy_minimal from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ...types.audio import Translation, translation_create_params -from ..._base_client import make_request_options +from ..._base_client import ( + make_request_options, +) if TYPE_CHECKING: from ..._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/beta/__init__.py b/src/openai/resources/beta/__init__.py index 55ad243cca..561f8bef60 100644 --- a/src/openai/resources/beta/__init__.py +++ b/src/openai/resources/beta/__init__.py @@ -1,18 +1,8 @@ # File generated from our OpenAPI spec by Stainless. from .beta import Beta, AsyncBeta, BetaWithRawResponse, AsyncBetaWithRawResponse -from .threads import ( - Threads, - AsyncThreads, - ThreadsWithRawResponse, - AsyncThreadsWithRawResponse, -) -from .assistants import ( - Assistants, - AsyncAssistants, - AssistantsWithRawResponse, - AsyncAssistantsWithRawResponse, -) +from .threads import Threads, AsyncThreads, ThreadsWithRawResponse, AsyncThreadsWithRawResponse +from .assistants import Assistants, AsyncAssistants, AssistantsWithRawResponse, AsyncAssistantsWithRawResponse __all__ = [ "Assistants", diff --git a/src/openai/resources/beta/assistants/__init__.py b/src/openai/resources/beta/assistants/__init__.py index 6efb0b21ec..205b2cf0f5 100644 --- a/src/openai/resources/beta/assistants/__init__.py +++ b/src/openai/resources/beta/assistants/__init__.py @@ -1,12 +1,7 @@ # File generated from our OpenAPI spec by Stainless. from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from .assistants import ( - Assistants, - AsyncAssistants, - AssistantsWithRawResponse, - AsyncAssistantsWithRawResponse, -) +from .assistants import Assistants, AsyncAssistants, AssistantsWithRawResponse, AsyncAssistantsWithRawResponse __all__ = [ "Files", diff --git a/src/openai/resources/beta/assistants/assistants.py b/src/openai/resources/beta/assistants/assistants.py index efa711ecf4..944019bed9 100644 --- a/src/openai/resources/beta/assistants/assistants.py +++ b/src/openai/resources/beta/assistants/assistants.py @@ -8,7 +8,13 @@ import httpx from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ...._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ...._utils import maybe_transform from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_raw_response_wrapper, async_to_raw_response_wrapper @@ -20,7 +26,10 @@ assistant_create_params, assistant_update_params, ) -from ...._base_client import AsyncPaginator, make_request_options +from ...._base_client import ( + AsyncPaginator, + make_request_options, +) if TYPE_CHECKING: from ...._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/beta/assistants/files.py b/src/openai/resources/beta/assistants/files.py index 5ac5897ca3..5682587487 100644 --- a/src/openai/resources/beta/assistants/files.py +++ b/src/openai/resources/beta/assistants/files.py @@ -7,12 +7,21 @@ import httpx -from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ...._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ...._utils import maybe_transform from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ....pagination import SyncCursorPage, AsyncCursorPage -from ...._base_client import AsyncPaginator, make_request_options +from ...._base_client import ( + AsyncPaginator, + make_request_options, +) from ....types.beta.assistants import ( AssistantFile, FileDeleteResponse, diff --git a/src/openai/resources/beta/beta.py b/src/openai/resources/beta/beta.py index b552561763..5cea6c1460 100644 --- a/src/openai/resources/beta/beta.py +++ b/src/openai/resources/beta/beta.py @@ -4,18 +4,8 @@ from typing import TYPE_CHECKING -from .threads import ( - Threads, - AsyncThreads, - ThreadsWithRawResponse, - AsyncThreadsWithRawResponse, -) -from .assistants import ( - Assistants, - AsyncAssistants, - AssistantsWithRawResponse, - AsyncAssistantsWithRawResponse, -) +from .threads import Threads, AsyncThreads, ThreadsWithRawResponse, AsyncThreadsWithRawResponse +from .assistants import Assistants, AsyncAssistants, AssistantsWithRawResponse, AsyncAssistantsWithRawResponse from ..._resource import SyncAPIResource, AsyncAPIResource if TYPE_CHECKING: diff --git a/src/openai/resources/beta/threads/__init__.py b/src/openai/resources/beta/threads/__init__.py index b9aaada465..fe7c5e5a20 100644 --- a/src/openai/resources/beta/threads/__init__.py +++ b/src/openai/resources/beta/threads/__init__.py @@ -1,18 +1,8 @@ # File generated from our OpenAPI spec by Stainless. from .runs import Runs, AsyncRuns, RunsWithRawResponse, AsyncRunsWithRawResponse -from .threads import ( - Threads, - AsyncThreads, - ThreadsWithRawResponse, - AsyncThreadsWithRawResponse, -) -from .messages import ( - Messages, - AsyncMessages, - MessagesWithRawResponse, - AsyncMessagesWithRawResponse, -) +from .threads import Threads, AsyncThreads, ThreadsWithRawResponse, AsyncThreadsWithRawResponse +from .messages import Messages, AsyncMessages, MessagesWithRawResponse, AsyncMessagesWithRawResponse __all__ = [ "Runs", diff --git a/src/openai/resources/beta/threads/messages/__init__.py b/src/openai/resources/beta/threads/messages/__init__.py index d8d4ce448c..cef618ed14 100644 --- a/src/openai/resources/beta/threads/messages/__init__.py +++ b/src/openai/resources/beta/threads/messages/__init__.py @@ -1,12 +1,7 @@ # File generated from our OpenAPI spec by Stainless. from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from .messages import ( - Messages, - AsyncMessages, - MessagesWithRawResponse, - AsyncMessagesWithRawResponse, -) +from .messages import Messages, AsyncMessages, MessagesWithRawResponse, AsyncMessagesWithRawResponse __all__ = [ "Files", diff --git a/src/openai/resources/beta/threads/messages/files.py b/src/openai/resources/beta/threads/messages/files.py index e028a6fda7..24c9680f3d 100644 --- a/src/openai/resources/beta/threads/messages/files.py +++ b/src/openai/resources/beta/threads/messages/files.py @@ -7,12 +7,21 @@ import httpx -from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ....._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ....._utils import maybe_transform from ....._resource import SyncAPIResource, AsyncAPIResource from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .....pagination import SyncCursorPage, AsyncCursorPage -from ....._base_client import AsyncPaginator, make_request_options +from ....._base_client import ( + AsyncPaginator, + make_request_options, +) from .....types.beta.threads.messages import MessageFile, file_list_params if TYPE_CHECKING: diff --git a/src/openai/resources/beta/threads/messages/messages.py b/src/openai/resources/beta/threads/messages/messages.py index 30ae072512..9a6f5706c3 100644 --- a/src/openai/resources/beta/threads/messages/messages.py +++ b/src/openai/resources/beta/threads/messages/messages.py @@ -8,12 +8,21 @@ import httpx from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ....._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ....._utils import maybe_transform from ....._resource import SyncAPIResource, AsyncAPIResource from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .....pagination import SyncCursorPage, AsyncCursorPage -from ....._base_client import AsyncPaginator, make_request_options +from ....._base_client import ( + AsyncPaginator, + make_request_options, +) from .....types.beta.threads import ( ThreadMessage, message_list_params, diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 969bfab70a..719e35ea46 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -8,12 +8,21 @@ import httpx from .steps import Steps, AsyncSteps, StepsWithRawResponse, AsyncStepsWithRawResponse -from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ....._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ....._utils import maybe_transform from ....._resource import SyncAPIResource, AsyncAPIResource from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .....pagination import SyncCursorPage, AsyncCursorPage -from ....._base_client import AsyncPaginator, make_request_options +from ....._base_client import ( + AsyncPaginator, + make_request_options, +) from .....types.beta.threads import ( Run, run_list_params, diff --git a/src/openai/resources/beta/threads/runs/steps.py b/src/openai/resources/beta/threads/runs/steps.py index 4fcc87a0ff..f26034cf82 100644 --- a/src/openai/resources/beta/threads/runs/steps.py +++ b/src/openai/resources/beta/threads/runs/steps.py @@ -7,12 +7,21 @@ import httpx -from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ....._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ....._utils import maybe_transform from ....._resource import SyncAPIResource, AsyncAPIResource from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .....pagination import SyncCursorPage, AsyncCursorPage -from ....._base_client import AsyncPaginator, make_request_options +from ....._base_client import ( + AsyncPaginator, + make_request_options, +) from .....types.beta.threads.runs import RunStep, step_list_params if TYPE_CHECKING: diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 9469fc0513..b37667485d 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -7,13 +7,14 @@ import httpx from .runs import Runs, AsyncRuns, RunsWithRawResponse, AsyncRunsWithRawResponse -from .messages import ( - Messages, - AsyncMessages, - MessagesWithRawResponse, - AsyncMessagesWithRawResponse, +from .messages import Messages, AsyncMessages, MessagesWithRawResponse, AsyncMessagesWithRawResponse +from ...._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, ) -from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ...._utils import maybe_transform from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_raw_response_wrapper, async_to_raw_response_wrapper @@ -24,7 +25,9 @@ thread_update_params, thread_create_and_run_params, ) -from ...._base_client import make_request_options +from ...._base_client import ( + make_request_options, +) from ....types.beta.threads import Run if TYPE_CHECKING: diff --git a/src/openai/resources/chat/__init__.py b/src/openai/resources/chat/__init__.py index 2e56c0cbfa..85b246509e 100644 --- a/src/openai/resources/chat/__init__.py +++ b/src/openai/resources/chat/__init__.py @@ -1,12 +1,7 @@ # File generated from our OpenAPI spec by Stainless. from .chat import Chat, AsyncChat, ChatWithRawResponse, AsyncChatWithRawResponse -from .completions import ( - Completions, - AsyncCompletions, - CompletionsWithRawResponse, - AsyncCompletionsWithRawResponse, -) +from .completions import Completions, AsyncCompletions, CompletionsWithRawResponse, AsyncCompletionsWithRawResponse __all__ = [ "Completions", diff --git a/src/openai/resources/chat/chat.py b/src/openai/resources/chat/chat.py index 3847b20512..d93a501b1f 100644 --- a/src/openai/resources/chat/chat.py +++ b/src/openai/resources/chat/chat.py @@ -5,12 +5,7 @@ from typing import TYPE_CHECKING from ..._resource import SyncAPIResource, AsyncAPIResource -from .completions import ( - Completions, - AsyncCompletions, - CompletionsWithRawResponse, - AsyncCompletionsWithRawResponse, -) +from .completions import Completions, AsyncCompletions, CompletionsWithRawResponse, AsyncCompletionsWithRawResponse if TYPE_CHECKING: from ..._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index d0657b2f73..e29554c26d 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -7,7 +7,13 @@ import httpx -from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ..._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ..._utils import required_args, maybe_transform from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper @@ -20,7 +26,9 @@ ChatCompletionToolChoiceOptionParam, completion_create_params, ) -from ..._base_client import make_request_options +from ..._base_client import ( + make_request_options, +) if TYPE_CHECKING: from ..._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index baf6f04fef..39484c6f7b 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -8,12 +8,20 @@ import httpx from ..types import Completion, completion_create_params -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from .._utils import required_args, maybe_transform from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .._streaming import Stream, AsyncStream -from .._base_client import make_request_options +from .._base_client import ( + make_request_options, +) if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/edits.py b/src/openai/resources/edits.py index eafaa82fdf..587da02c8f 100644 --- a/src/openai/resources/edits.py +++ b/src/openai/resources/edits.py @@ -9,11 +9,19 @@ import httpx from ..types import Edit, edit_create_params -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from .._utils import maybe_transform from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper -from .._base_client import make_request_options +from .._base_client import ( + make_request_options, +) if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/embeddings.py b/src/openai/resources/embeddings.py index c31ad9d931..2ff3d3d44f 100644 --- a/src/openai/resources/embeddings.py +++ b/src/openai/resources/embeddings.py @@ -9,13 +9,20 @@ import httpx from ..types import CreateEmbeddingResponse, embedding_create_params -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from .._utils import is_given, maybe_transform -from .._extras import numpy as np -from .._extras import has_numpy +from .._extras import numpy as np, has_numpy from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper -from .._base_client import make_request_options +from .._base_client import ( + make_request_options, +) if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index a6f75e5a4c..b9f815af85 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -9,8 +9,20 @@ import httpx -from ..types import FileObject, FileDeleted, file_list_params, file_create_params -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes +from ..types import ( + FileObject, + FileDeleted, + file_list_params, + file_create_params, +) +from .._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, + FileTypes, +) from .._utils import extract_files, maybe_transform, deepcopy_minimal from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper diff --git a/src/openai/resources/fine_tunes.py b/src/openai/resources/fine_tunes.py index 91c8201cbb..f50d78717b 100644 --- a/src/openai/resources/fine_tunes.py +++ b/src/openai/resources/fine_tunes.py @@ -14,13 +14,22 @@ fine_tune_create_params, fine_tune_list_events_params, ) -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from .._utils import maybe_transform from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .._streaming import Stream, AsyncStream from ..pagination import SyncPage, AsyncPage -from .._base_client import AsyncPaginator, make_request_options +from .._base_client import ( + AsyncPaginator, + make_request_options, +) if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/fine_tuning/__init__.py b/src/openai/resources/fine_tuning/__init__.py index 9133c25d4a..27445fb707 100644 --- a/src/openai/resources/fine_tuning/__init__.py +++ b/src/openai/resources/fine_tuning/__init__.py @@ -1,12 +1,7 @@ # File generated from our OpenAPI spec by Stainless. from .jobs import Jobs, AsyncJobs, JobsWithRawResponse, AsyncJobsWithRawResponse -from .fine_tuning import ( - FineTuning, - AsyncFineTuning, - FineTuningWithRawResponse, - AsyncFineTuningWithRawResponse, -) +from .fine_tuning import FineTuning, AsyncFineTuning, FineTuningWithRawResponse, AsyncFineTuningWithRawResponse __all__ = [ "Jobs", diff --git a/src/openai/resources/fine_tuning/jobs.py b/src/openai/resources/fine_tuning/jobs.py index 3d9aed8d91..55eee67044 100644 --- a/src/openai/resources/fine_tuning/jobs.py +++ b/src/openai/resources/fine_tuning/jobs.py @@ -7,12 +7,21 @@ import httpx -from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ..._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ..._utils import maybe_transform from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ...pagination import SyncCursorPage, AsyncCursorPage -from ..._base_client import AsyncPaginator, make_request_options +from ..._base_client import ( + AsyncPaginator, + make_request_options, +) from ...types.fine_tuning import ( FineTuningJob, FineTuningJobEvent, diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py index 94b1bc1fc8..0e1313078f 100644 --- a/src/openai/resources/images.py +++ b/src/openai/resources/images.py @@ -13,11 +13,20 @@ image_generate_params, image_create_variation_params, ) -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes +from .._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, + FileTypes, +) from .._utils import extract_files, maybe_transform, deepcopy_minimal from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper -from .._base_client import make_request_options +from .._base_client import ( + make_request_options, +) if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/models.py b/src/openai/resources/models.py index 2d04bdc5cc..a44a7ffbb0 100644 --- a/src/openai/resources/models.py +++ b/src/openai/resources/models.py @@ -7,11 +7,20 @@ import httpx from ..types import Model, ModelDeleted -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ..pagination import SyncPage, AsyncPage -from .._base_client import AsyncPaginator, make_request_options +from .._base_client import ( + AsyncPaginator, + make_request_options, +) if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/moderations.py b/src/openai/resources/moderations.py index 12a7c68a7b..9de7cd640f 100644 --- a/src/openai/resources/moderations.py +++ b/src/openai/resources/moderations.py @@ -8,11 +8,19 @@ import httpx from ..types import ModerationCreateResponse, moderation_create_params -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from .._utils import maybe_transform from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper -from .._base_client import make_request_options +from .._base_client import ( + make_request_options, +) if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index 1b4fca26ee..df2b580587 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -5,8 +5,7 @@ from .edit import Edit as Edit from .image import Image as Image from .model import Model as Model -from .shared import FunctionDefinition as FunctionDefinition -from .shared import FunctionParameters as FunctionParameters +from .shared import FunctionDefinition as FunctionDefinition, FunctionParameters as FunctionParameters from .embedding import Embedding as Embedding from .fine_tune import FineTune as FineTune from .completion import Completion as Completion @@ -28,18 +27,8 @@ from .fine_tune_create_params import FineTuneCreateParams as FineTuneCreateParams from .completion_create_params import CompletionCreateParams as CompletionCreateParams from .moderation_create_params import ModerationCreateParams as ModerationCreateParams -from .create_embedding_response import ( - CreateEmbeddingResponse as CreateEmbeddingResponse, -) -from .moderation_create_response import ( - ModerationCreateResponse as ModerationCreateResponse, -) -from .fine_tune_list_events_params import ( - FineTuneListEventsParams as FineTuneListEventsParams, -) -from .image_create_variation_params import ( - ImageCreateVariationParams as ImageCreateVariationParams, -) -from .fine_tune_events_list_response import ( - FineTuneEventsListResponse as FineTuneEventsListResponse, -) +from .create_embedding_response import CreateEmbeddingResponse as CreateEmbeddingResponse +from .moderation_create_response import ModerationCreateResponse as ModerationCreateResponse +from .fine_tune_list_events_params import FineTuneListEventsParams as FineTuneListEventsParams +from .image_create_variation_params import ImageCreateVariationParams as ImageCreateVariationParams +from .fine_tune_events_list_response import FineTuneEventsListResponse as FineTuneEventsListResponse diff --git a/src/openai/types/audio/__init__.py b/src/openai/types/audio/__init__.py index 83afa060f8..ba5f7fd8e0 100644 --- a/src/openai/types/audio/__init__.py +++ b/src/openai/types/audio/__init__.py @@ -5,9 +5,5 @@ from .translation import Translation as Translation from .transcription import Transcription as Transcription from .speech_create_params import SpeechCreateParams as SpeechCreateParams -from .translation_create_params import ( - TranslationCreateParams as TranslationCreateParams, -) -from .transcription_create_params import ( - TranscriptionCreateParams as TranscriptionCreateParams, -) +from .translation_create_params import TranslationCreateParams as TranslationCreateParams +from .transcription_create_params import TranscriptionCreateParams as TranscriptionCreateParams diff --git a/src/openai/types/beta/__init__.py b/src/openai/types/beta/__init__.py index c03d823b8c..e6742521e9 100644 --- a/src/openai/types/beta/__init__.py +++ b/src/openai/types/beta/__init__.py @@ -11,6 +11,4 @@ from .assistant_list_params import AssistantListParams as AssistantListParams from .assistant_create_params import AssistantCreateParams as AssistantCreateParams from .assistant_update_params import AssistantUpdateParams as AssistantUpdateParams -from .thread_create_and_run_params import ( - ThreadCreateAndRunParams as ThreadCreateAndRunParams, -) +from .thread_create_and_run_params import ThreadCreateAndRunParams as ThreadCreateAndRunParams diff --git a/src/openai/types/beta/threads/__init__.py b/src/openai/types/beta/threads/__init__.py index 0cb557a514..8c77466dec 100644 --- a/src/openai/types/beta/threads/__init__.py +++ b/src/openai/types/beta/threads/__init__.py @@ -11,12 +11,6 @@ from .message_content_text import MessageContentText as MessageContentText from .message_create_params import MessageCreateParams as MessageCreateParams from .message_update_params import MessageUpdateParams as MessageUpdateParams -from .message_content_image_file import ( - MessageContentImageFile as MessageContentImageFile, -) -from .run_submit_tool_outputs_params import ( - RunSubmitToolOutputsParams as RunSubmitToolOutputsParams, -) -from .required_action_function_tool_call import ( - RequiredActionFunctionToolCall as RequiredActionFunctionToolCall, -) +from .message_content_image_file import MessageContentImageFile as MessageContentImageFile +from .run_submit_tool_outputs_params import RunSubmitToolOutputsParams as RunSubmitToolOutputsParams +from .required_action_function_tool_call import RequiredActionFunctionToolCall as RequiredActionFunctionToolCall diff --git a/src/openai/types/beta/threads/runs/__init__.py b/src/openai/types/beta/threads/runs/__init__.py index 72b972a986..16cb852922 100644 --- a/src/openai/types/beta/threads/runs/__init__.py +++ b/src/openai/types/beta/threads/runs/__init__.py @@ -8,6 +8,4 @@ from .function_tool_call import FunctionToolCall as FunctionToolCall from .retrieval_tool_call import RetrievalToolCall as RetrievalToolCall from .tool_calls_step_details import ToolCallsStepDetails as ToolCallsStepDetails -from .message_creation_step_details import ( - MessageCreationStepDetails as MessageCreationStepDetails, -) +from .message_creation_step_details import MessageCreationStepDetails as MessageCreationStepDetails diff --git a/src/openai/types/chat/__init__.py b/src/openai/types/chat/__init__.py index 5fe182f41e..3f90919619 100644 --- a/src/openai/types/chat/__init__.py +++ b/src/openai/types/chat/__init__.py @@ -7,27 +7,13 @@ from .chat_completion_chunk import ChatCompletionChunk as ChatCompletionChunk from .chat_completion_message import ChatCompletionMessage as ChatCompletionMessage from .completion_create_params import CompletionCreateParams as CompletionCreateParams -from .chat_completion_tool_param import ( - ChatCompletionToolParam as ChatCompletionToolParam, -) -from .chat_completion_message_param import ( - ChatCompletionMessageParam as ChatCompletionMessageParam, -) -from .chat_completion_message_tool_call import ( - ChatCompletionMessageToolCall as ChatCompletionMessageToolCall, -) -from .chat_completion_content_part_param import ( - ChatCompletionContentPartParam as ChatCompletionContentPartParam, -) -from .chat_completion_tool_message_param import ( - ChatCompletionToolMessageParam as ChatCompletionToolMessageParam, -) -from .chat_completion_user_message_param import ( - ChatCompletionUserMessageParam as ChatCompletionUserMessageParam, -) -from .chat_completion_system_message_param import ( - ChatCompletionSystemMessageParam as ChatCompletionSystemMessageParam, -) +from .chat_completion_tool_param import ChatCompletionToolParam as ChatCompletionToolParam +from .chat_completion_message_param import ChatCompletionMessageParam as ChatCompletionMessageParam +from .chat_completion_message_tool_call import ChatCompletionMessageToolCall as ChatCompletionMessageToolCall +from .chat_completion_content_part_param import ChatCompletionContentPartParam as ChatCompletionContentPartParam +from .chat_completion_tool_message_param import ChatCompletionToolMessageParam as ChatCompletionToolMessageParam +from .chat_completion_user_message_param import ChatCompletionUserMessageParam as ChatCompletionUserMessageParam +from .chat_completion_system_message_param import ChatCompletionSystemMessageParam as ChatCompletionSystemMessageParam from .chat_completion_function_message_param import ( ChatCompletionFunctionMessageParam as ChatCompletionFunctionMessageParam, ) diff --git a/src/openai/types/chat/chat_completion_content_part_param.py b/src/openai/types/chat/chat_completion_content_part_param.py index 587578e2ef..8e58239258 100644 --- a/src/openai/types/chat/chat_completion_content_part_param.py +++ b/src/openai/types/chat/chat_completion_content_part_param.py @@ -5,9 +5,7 @@ from typing import Union from .chat_completion_content_part_text_param import ChatCompletionContentPartTextParam -from .chat_completion_content_part_image_param import ( - ChatCompletionContentPartImageParam, -) +from .chat_completion_content_part_image_param import ChatCompletionContentPartImageParam __all__ = ["ChatCompletionContentPartParam"] diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 69fe250eca..0d8495b0c1 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -8,12 +8,8 @@ from ...types import shared_params from .chat_completion_tool_param import ChatCompletionToolParam from .chat_completion_message_param import ChatCompletionMessageParam -from .chat_completion_tool_choice_option_param import ( - ChatCompletionToolChoiceOptionParam, -) -from .chat_completion_function_call_option_param import ( - ChatCompletionFunctionCallOptionParam, -) +from .chat_completion_tool_choice_option_param import ChatCompletionToolChoiceOptionParam +from .chat_completion_function_call_option_param import ChatCompletionFunctionCallOptionParam __all__ = [ "CompletionCreateParamsBase", diff --git a/tests/api_resources/beta/test_assistants.py b/tests/api_resources/beta/test_assistants.py index 82e975b46d..97e74c61e4 100644 --- a/tests/api_resources/beta/test_assistants.py +++ b/tests/api_resources/beta/test_assistants.py @@ -10,7 +10,10 @@ from tests.utils import assert_matches_type from openai._client import OpenAI, AsyncOpenAI from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta import Assistant, AssistantDeleted +from openai.types.beta import ( + Assistant, + AssistantDeleted, +) base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") api_key = "My API Key" diff --git a/tests/api_resources/beta/test_threads.py b/tests/api_resources/beta/test_threads.py index 8fa1fc20ea..860159ffb3 100644 --- a/tests/api_resources/beta/test_threads.py +++ b/tests/api_resources/beta/test_threads.py @@ -9,7 +9,10 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai._client import OpenAI, AsyncOpenAI -from openai.types.beta import Thread, ThreadDeleted +from openai.types.beta import ( + Thread, + ThreadDeleted, +) from openai.types.beta.threads import Run base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index d323dfc354..39de3fa29d 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -10,7 +10,9 @@ from tests.utils import assert_matches_type from openai._client import OpenAI, AsyncOpenAI from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta.threads import Run +from openai.types.beta.threads import ( + Run, +) base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") api_key = "My API Key" diff --git a/tests/api_resources/fine_tuning/test_jobs.py b/tests/api_resources/fine_tuning/test_jobs.py index 5716a23d54..927ca9bbdd 100644 --- a/tests/api_resources/fine_tuning/test_jobs.py +++ b/tests/api_resources/fine_tuning/test_jobs.py @@ -10,7 +10,10 @@ from tests.utils import assert_matches_type from openai._client import OpenAI, AsyncOpenAI from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.fine_tuning import FineTuningJob, FineTuningJobEvent +from openai.types.fine_tuning import ( + FineTuningJob, + FineTuningJobEvent, +) base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") api_key = "My API Key" diff --git a/tests/utils.py b/tests/utils.py index b513794017..db2ca5601b 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -8,7 +8,12 @@ from typing_extensions import Literal, get_args, get_origin, assert_type from openai._types import NoneType -from openai._utils import is_dict, is_list, is_list_type, is_union_type +from openai._utils import ( + is_dict, + is_list, + is_list_type, + is_union_type, +) from openai._compat import PYDANTIC_V2, field_outer_type, get_model_fields from openai._models import BaseModel From 01b690c11c64bd9db2486939f99520dbd8be2471 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 7 Dec 2023 10:57:27 +0000 Subject: [PATCH 139/816] chore(internal): update formatting (#941) --- src/openai/__init__.py | 12 +----------- src/openai/_client.py | 12 ++++++++++-- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/src/openai/__init__.py b/src/openai/__init__.py index 20ab72ee25..d695b68980 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -8,17 +8,7 @@ from . import types from ._types import NoneType, Transport, ProxiesTypes from ._utils import file_from_path -from ._client import ( - Client, - OpenAI, - Stream, - Timeout, - Transport, - AsyncClient, - AsyncOpenAI, - AsyncStream, - RequestOptions, -) +from ._client import Client, OpenAI, Stream, Timeout, Transport, AsyncClient, AsyncOpenAI, AsyncStream, RequestOptions from ._version import __title__, __version__ from ._exceptions import ( APIError, diff --git a/src/openai/_client.py b/src/openai/_client.py index 79054aba2f..7f8744c98b 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -20,11 +20,19 @@ ProxiesTypes, RequestOptions, ) -from ._utils import is_given, is_mapping, get_async_library +from ._utils import ( + is_given, + is_mapping, + get_async_library, +) from ._version import __version__ from ._streaming import Stream as Stream, AsyncStream as AsyncStream from ._exceptions import OpenAIError, APIStatusError -from ._base_client import DEFAULT_MAX_RETRIES, SyncAPIClient, AsyncAPIClient +from ._base_client import ( + DEFAULT_MAX_RETRIES, + SyncAPIClient, + AsyncAPIClient, +) __all__ = [ "Timeout", From 60ccec6baa826c5d434bde29e6444b62ab3aee2e Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 7 Dec 2023 14:36:08 +0000 Subject: [PATCH 140/816] fix(pagination): use correct type hint for .object (#943) --- src/openai/pagination.py | 42 ++++++++++++++++++++++++++-------------- 1 file changed, 28 insertions(+), 14 deletions(-) diff --git a/src/openai/pagination.py b/src/openai/pagination.py index 17f2d1a4ca..d47deb17be 100644 --- a/src/openai/pagination.py +++ b/src/openai/pagination.py @@ -1,7 +1,7 @@ # File generated from our OpenAPI spec by Stainless. from typing import Any, List, Generic, Optional, cast -from typing_extensions import Literal, Protocol, override, runtime_checkable +from typing_extensions import Protocol, override, runtime_checkable from ._types import ModelT from ._base_client import BasePage, PageInfo, BaseSyncPage, BaseAsyncPage @@ -11,18 +11,21 @@ @runtime_checkable class CursorPageItem(Protocol): - id: str + id: Optional[str] class SyncPage(BaseSyncPage[ModelT], BasePage[ModelT], Generic[ModelT]): """Note: no pagination actually occurs yet, this is for forwards-compatibility.""" data: List[ModelT] - object: Literal["list"] + object: str @override def _get_page_items(self) -> List[ModelT]: - return self.data + data = self.data + if not data: + return [] + return data @override def next_page_info(self) -> None: @@ -37,11 +40,14 @@ class AsyncPage(BaseAsyncPage[ModelT], BasePage[ModelT], Generic[ModelT]): """Note: no pagination actually occurs yet, this is for forwards-compatibility.""" data: List[ModelT] - object: Literal["list"] + object: str @override def _get_page_items(self) -> List[ModelT]: - return self.data + data = self.data + if not data: + return [] + return data @override def next_page_info(self) -> None: @@ -57,15 +63,19 @@ class SyncCursorPage(BaseSyncPage[ModelT], BasePage[ModelT], Generic[ModelT]): @override def _get_page_items(self) -> List[ModelT]: - return self.data + data = self.data + if not data: + return [] + return data @override def next_page_info(self) -> Optional[PageInfo]: - if not self.data: + data = self.data + if not data: return None - item = cast(Any, self.data[-1]) - if not isinstance(item, CursorPageItem): + item = cast(Any, data[-1]) + if not isinstance(item, CursorPageItem) or item.id is None: # TODO emit warning log return None @@ -77,15 +87,19 @@ class AsyncCursorPage(BaseAsyncPage[ModelT], BasePage[ModelT], Generic[ModelT]): @override def _get_page_items(self) -> List[ModelT]: - return self.data + data = self.data + if not data: + return [] + return data @override def next_page_info(self) -> Optional[PageInfo]: - if not self.data: + data = self.data + if not data: return None - item = cast(Any, self.data[-1]) - if not isinstance(item, CursorPageItem): + item = cast(Any, data[-1]) + if not isinstance(item, CursorPageItem) or item.id is None: # TODO emit warning log return None From 8ad790ae9db8848eb3ac38703d0bb7c1d82b343b Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 7 Dec 2023 14:55:19 +0000 Subject: [PATCH 141/816] chore(internal): reformat imports (#944) --- pyproject.toml | 37 +++++---- requirements-dev.lock | 19 +---- src/openai/__init__.py | 41 ++++++---- src/openai/_client.py | 15 +--- src/openai/_compat.py | 30 ++++---- src/openai/_extras/__init__.py | 3 +- src/openai/_models.py | 14 +++- src/openai/_types.py | 9 ++- src/openai/_utils/__init__.py | 76 +++++++++---------- src/openai/_utils/_utils.py | 4 +- src/openai/resources/__init__.py | 49 ++++++++++-- src/openai/resources/audio/__init__.py | 14 +++- src/openai/resources/audio/audio.py | 14 +++- src/openai/resources/audio/speech.py | 13 +--- src/openai/resources/audio/transcriptions.py | 13 +--- src/openai/resources/audio/translations.py | 13 +--- src/openai/resources/beta/__init__.py | 14 +++- .../resources/beta/assistants/__init__.py | 7 +- .../resources/beta/assistants/assistants.py | 13 +--- src/openai/resources/beta/assistants/files.py | 13 +--- src/openai/resources/beta/beta.py | 14 +++- src/openai/resources/beta/threads/__init__.py | 14 +++- .../beta/threads/messages/__init__.py | 7 +- .../resources/beta/threads/messages/files.py | 13 +--- .../beta/threads/messages/messages.py | 13 +--- .../resources/beta/threads/runs/runs.py | 13 +--- .../resources/beta/threads/runs/steps.py | 13 +--- src/openai/resources/beta/threads/threads.py | 17 ++--- src/openai/resources/chat/__init__.py | 7 +- src/openai/resources/chat/chat.py | 7 +- src/openai/resources/chat/completions.py | 12 +-- src/openai/resources/completions.py | 12 +-- src/openai/resources/edits.py | 12 +-- src/openai/resources/embeddings.py | 15 +--- src/openai/resources/files.py | 16 +--- src/openai/resources/fine_tunes.py | 13 +--- src/openai/resources/fine_tuning/__init__.py | 7 +- src/openai/resources/fine_tuning/jobs.py | 13 +--- src/openai/resources/images.py | 13 +--- src/openai/resources/models.py | 13 +--- src/openai/resources/moderations.py | 12 +-- src/openai/types/__init__.py | 23 ++++-- src/openai/types/audio/__init__.py | 8 +- src/openai/types/beta/__init__.py | 4 +- src/openai/types/beta/threads/__init__.py | 12 ++- .../types/beta/threads/runs/__init__.py | 4 +- src/openai/types/chat/__init__.py | 28 +++++-- .../chat_completion_content_part_param.py | 4 +- .../types/chat/completion_create_params.py | 8 +- tests/api_resources/beta/test_assistants.py | 5 +- tests/api_resources/beta/test_threads.py | 5 +- tests/api_resources/beta/threads/test_runs.py | 4 +- tests/api_resources/fine_tuning/test_jobs.py | 5 +- tests/utils.py | 7 +- 54 files changed, 374 insertions(+), 410 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 44e7bcb0ed..c468220495 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -48,16 +48,16 @@ openai = "openai.cli:main" [tool.rye] managed = true dev-dependencies = [ - # version pins are in requirements-dev.lock - "pyright", - "mypy", - "black", - "respx", - "pytest", - "pytest-asyncio", - "ruff", - "time-machine", - "nox", + "pyright==1.1.332", + "mypy==1.7.1", + "black==23.3.0", + "respx==0.20.2", + "pytest==7.1.1", + "pytest-asyncio==0.21.1", + "ruff==0.0.282", + "isort==5.10.1", + "time-machine==2.9.0", + "nox==2023.4.22", "dirty-equals>=0.6.0", "azure-identity >=1.14.1", "types-tqdm > 4" @@ -68,10 +68,12 @@ format = { chain = [ "format:black", "format:docs", "format:ruff", + "format:isort", ]} "format:black" = "black ." "format:docs" = "python bin/blacken-docs.py README.md api.md" "format:ruff" = "ruff --fix ." +"format:isort" = "isort ." "check:ruff" = "ruff ." @@ -126,13 +128,16 @@ reportImplicitOverride = true reportImportCycles = false reportPrivateUsage = false +[tool.isort] +profile = "black" +length_sort = true +extra_standard_library = ["typing_extensions"] + [tool.ruff] line-length = 120 -output-format = "grouped" +format = "grouped" target-version = "py37" select = [ - # isort - "I", # remove unused imports "F401", # bare except statements @@ -150,12 +155,6 @@ unfixable = [ ] ignore-init-module-imports = true -[tool.ruff.lint.isort] -length-sort = true -length-sort-straight = true -combine-as-imports = true -extra-standard-library = ["typing_extensions"] -known-first-party = ["openai", "tests"] [tool.ruff.per-file-ignores] "bin/**.py" = ["T201", "T203"] diff --git a/requirements-dev.lock b/requirements-dev.lock index bc993b16de..b1a9428a09 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -11,15 +11,11 @@ annotated-types==0.6.0 anyio==4.1.0 argcomplete==3.1.2 attrs==23.1.0 -azure-core==1.29.5 azure-identity==1.15.0 black==23.3.0 certifi==2023.7.22 -cffi==1.16.0 -charset-normalizer==3.3.2 click==8.1.7 colorlog==6.7.0 -cryptography==41.0.7 dirty-equals==0.6.0 distlib==0.3.7 distro==1.8.0 @@ -30,43 +26,32 @@ httpcore==1.0.2 httpx==0.25.2 idna==3.4 iniconfig==2.0.0 -msal==1.26.0 -msal-extensions==1.0.0 +isort==5.10.1 mypy==1.7.1 mypy-extensions==1.0.0 nodeenv==1.8.0 nox==2023.4.22 -numpy==1.26.2 packaging==23.2 -pandas==2.1.3 -pandas-stubs==2.1.1.230928 pathspec==0.11.2 platformdirs==3.11.0 pluggy==1.3.0 -portalocker==2.8.2 py==1.11.0 -pycparser==2.21 pydantic==2.4.2 pydantic-core==2.10.1 -pyjwt==2.8.0 pyright==1.1.332 pytest==7.1.1 pytest-asyncio==0.21.1 python-dateutil==2.8.2 pytz==2023.3.post1 -requests==2.31.0 respx==0.20.2 -ruff==0.1.7 +ruff==0.0.282 six==1.16.0 sniffio==1.3.0 time-machine==2.9.0 tomli==2.0.1 tqdm==4.66.1 -types-pytz==2023.3.1.1 types-tqdm==4.66.0.2 typing-extensions==4.8.0 -tzdata==2023.3 -urllib3==2.1.0 virtualenv==20.24.5 # The following packages are considered to be unsafe in a requirements file: setuptools==68.2.2 diff --git a/src/openai/__init__.py b/src/openai/__init__.py index d695b68980..d92dfe969a 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -8,7 +8,17 @@ from . import types from ._types import NoneType, Transport, ProxiesTypes from ._utils import file_from_path -from ._client import Client, OpenAI, Stream, Timeout, Transport, AsyncClient, AsyncOpenAI, AsyncStream, RequestOptions +from ._client import ( + Client, + OpenAI, + Stream, + Timeout, + Transport, + AsyncClient, + AsyncOpenAI, + AsyncStream, + RequestOptions, +) from ._version import __title__, __version__ from ._exceptions import ( APIError, @@ -62,7 +72,8 @@ from .lib import azure as _azure from .version import VERSION as VERSION -from .lib.azure import AzureOpenAI as AzureOpenAI, AsyncAzureOpenAI as AsyncAzureOpenAI +from .lib.azure import AzureOpenAI as AzureOpenAI +from .lib.azure import AsyncAzureOpenAI as AsyncAzureOpenAI from .lib._old_api import * _setup_logging() @@ -319,17 +330,15 @@ def _reset_client() -> None: # type: ignore[reportUnusedFunction] _client = None -from ._module_client import ( - beta as beta, - chat as chat, - audio as audio, - edits as edits, - files as files, - images as images, - models as models, - embeddings as embeddings, - fine_tunes as fine_tunes, - completions as completions, - fine_tuning as fine_tuning, - moderations as moderations, -) +from ._module_client import beta as beta +from ._module_client import chat as chat +from ._module_client import audio as audio +from ._module_client import edits as edits +from ._module_client import files as files +from ._module_client import images as images +from ._module_client import models as models +from ._module_client import embeddings as embeddings +from ._module_client import fine_tunes as fine_tunes +from ._module_client import completions as completions +from ._module_client import fine_tuning as fine_tuning +from ._module_client import moderations as moderations diff --git a/src/openai/_client.py b/src/openai/_client.py index 7f8744c98b..202162070b 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -20,19 +20,12 @@ ProxiesTypes, RequestOptions, ) -from ._utils import ( - is_given, - is_mapping, - get_async_library, -) +from ._utils import is_given, is_mapping, get_async_library from ._version import __version__ -from ._streaming import Stream as Stream, AsyncStream as AsyncStream +from ._streaming import Stream as Stream +from ._streaming import AsyncStream as AsyncStream from ._exceptions import OpenAIError, APIStatusError -from ._base_client import ( - DEFAULT_MAX_RETRIES, - SyncAPIClient, - AsyncAPIClient, -) +from ._base_client import DEFAULT_MAX_RETRIES, SyncAPIClient, AsyncAPIClient __all__ = [ "Timeout", diff --git a/src/openai/_compat.py b/src/openai/_compat.py index d95db8ed1e..34323c9b7e 100644 --- a/src/openai/_compat.py +++ b/src/openai/_compat.py @@ -43,23 +43,21 @@ def is_typeddict(type_: type[Any]) -> bool: # noqa: ARG001 else: if PYDANTIC_V2: - from pydantic.v1.typing import ( - get_args as get_args, - is_union as is_union, - get_origin as get_origin, - is_typeddict as is_typeddict, - is_literal_type as is_literal_type, - ) - from pydantic.v1.datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime + from pydantic.v1.typing import get_args as get_args + from pydantic.v1.typing import is_union as is_union + from pydantic.v1.typing import get_origin as get_origin + from pydantic.v1.typing import is_typeddict as is_typeddict + from pydantic.v1.typing import is_literal_type as is_literal_type + from pydantic.v1.datetime_parse import parse_date as parse_date + from pydantic.v1.datetime_parse import parse_datetime as parse_datetime else: - from pydantic.typing import ( - get_args as get_args, - is_union as is_union, - get_origin as get_origin, - is_typeddict as is_typeddict, - is_literal_type as is_literal_type, - ) - from pydantic.datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime + from pydantic.typing import get_args as get_args + from pydantic.typing import is_union as is_union + from pydantic.typing import get_origin as get_origin + from pydantic.typing import is_typeddict as is_typeddict + from pydantic.typing import is_literal_type as is_literal_type + from pydantic.datetime_parse import parse_date as parse_date + from pydantic.datetime_parse import parse_datetime as parse_datetime # refactored config diff --git a/src/openai/_extras/__init__.py b/src/openai/_extras/__init__.py index 864dac4171..dc6625c5dc 100644 --- a/src/openai/_extras/__init__.py +++ b/src/openai/_extras/__init__.py @@ -1,2 +1,3 @@ -from .numpy_proxy import numpy as numpy, has_numpy as has_numpy +from .numpy_proxy import numpy as numpy +from .numpy_proxy import has_numpy as has_numpy from .pandas_proxy import pandas as pandas diff --git a/src/openai/_models.py b/src/openai/_models.py index cdd44ccb0a..5b8c96010f 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -30,11 +30,17 @@ AnyMapping, HttpxRequestFiles, ) -from ._utils import is_list, is_given, is_mapping, parse_date, parse_datetime, strip_not_given +from ._utils import ( + is_list, + is_given, + is_mapping, + parse_date, + parse_datetime, + strip_not_given, +) +from ._compat import PYDANTIC_V2, ConfigDict +from ._compat import GenericModel as BaseGenericModel from ._compat import ( - PYDANTIC_V2, - ConfigDict, - GenericModel as BaseGenericModel, get_args, is_union, parse_obj, diff --git a/src/openai/_types.py b/src/openai/_types.py index 6f298c18c4..9e962a1078 100644 --- a/src/openai/_types.py +++ b/src/openai/_types.py @@ -19,7 +19,14 @@ Sequence, AsyncIterator, ) -from typing_extensions import Literal, Protocol, TypeAlias, TypedDict, override, runtime_checkable +from typing_extensions import ( + Literal, + Protocol, + TypeAlias, + TypedDict, + override, + runtime_checkable, +) import pydantic from httpx import URL, Proxy, Timeout, Response, BaseTransport, AsyncBaseTransport diff --git a/src/openai/_utils/__init__.py b/src/openai/_utils/__init__.py index e98636c92f..400ca9b828 100644 --- a/src/openai/_utils/__init__.py +++ b/src/openai/_utils/__init__.py @@ -1,41 +1,37 @@ from ._proxy import LazyProxy as LazyProxy -from ._utils import ( - flatten as flatten, - is_dict as is_dict, - is_list as is_list, - is_given as is_given, - is_tuple as is_tuple, - is_mapping as is_mapping, - is_tuple_t as is_tuple_t, - parse_date as parse_date, - is_sequence as is_sequence, - coerce_float as coerce_float, - is_list_type as is_list_type, - is_mapping_t as is_mapping_t, - removeprefix as removeprefix, - removesuffix as removesuffix, - extract_files as extract_files, - is_sequence_t as is_sequence_t, - is_union_type as is_union_type, - required_args as required_args, - coerce_boolean as coerce_boolean, - coerce_integer as coerce_integer, - file_from_path as file_from_path, - parse_datetime as parse_datetime, - strip_not_given as strip_not_given, - deepcopy_minimal as deepcopy_minimal, - extract_type_arg as extract_type_arg, - is_required_type as is_required_type, - get_async_library as get_async_library, - is_annotated_type as is_annotated_type, - maybe_coerce_float as maybe_coerce_float, - get_required_header as get_required_header, - maybe_coerce_boolean as maybe_coerce_boolean, - maybe_coerce_integer as maybe_coerce_integer, - strip_annotated_type as strip_annotated_type, -) -from ._transform import ( - PropertyInfo as PropertyInfo, - transform as transform, - maybe_transform as maybe_transform, -) +from ._utils import flatten as flatten +from ._utils import is_dict as is_dict +from ._utils import is_list as is_list +from ._utils import is_given as is_given +from ._utils import is_tuple as is_tuple +from ._utils import is_mapping as is_mapping +from ._utils import is_tuple_t as is_tuple_t +from ._utils import parse_date as parse_date +from ._utils import is_sequence as is_sequence +from ._utils import coerce_float as coerce_float +from ._utils import is_list_type as is_list_type +from ._utils import is_mapping_t as is_mapping_t +from ._utils import removeprefix as removeprefix +from ._utils import removesuffix as removesuffix +from ._utils import extract_files as extract_files +from ._utils import is_sequence_t as is_sequence_t +from ._utils import is_union_type as is_union_type +from ._utils import required_args as required_args +from ._utils import coerce_boolean as coerce_boolean +from ._utils import coerce_integer as coerce_integer +from ._utils import file_from_path as file_from_path +from ._utils import parse_datetime as parse_datetime +from ._utils import strip_not_given as strip_not_given +from ._utils import deepcopy_minimal as deepcopy_minimal +from ._utils import extract_type_arg as extract_type_arg +from ._utils import is_required_type as is_required_type +from ._utils import get_async_library as get_async_library +from ._utils import is_annotated_type as is_annotated_type +from ._utils import maybe_coerce_float as maybe_coerce_float +from ._utils import get_required_header as get_required_header +from ._utils import maybe_coerce_boolean as maybe_coerce_boolean +from ._utils import maybe_coerce_integer as maybe_coerce_integer +from ._utils import strip_annotated_type as strip_annotated_type +from ._transform import PropertyInfo as PropertyInfo +from ._transform import transform as transform +from ._transform import maybe_transform as maybe_transform diff --git a/src/openai/_utils/_utils.py b/src/openai/_utils/_utils.py index cce6923810..83f88cc3e7 100644 --- a/src/openai/_utils/_utils.py +++ b/src/openai/_utils/_utils.py @@ -21,7 +21,9 @@ import sniffio from .._types import Headers, NotGiven, FileTypes, NotGivenOr, HeadersLike -from .._compat import is_union as _is_union, parse_date as parse_date, parse_datetime as parse_datetime +from .._compat import is_union as _is_union +from .._compat import parse_date as parse_date +from .._compat import parse_datetime as parse_datetime _T = TypeVar("_T") _TupleT = TypeVar("_TupleT", bound=Tuple[object, ...]) diff --git a/src/openai/resources/__init__.py b/src/openai/resources/__init__.py index 2cdbeb6ae1..e0f4f08d5c 100644 --- a/src/openai/resources/__init__.py +++ b/src/openai/resources/__init__.py @@ -5,13 +5,48 @@ from .audio import Audio, AsyncAudio, AudioWithRawResponse, AsyncAudioWithRawResponse from .edits import Edits, AsyncEdits, EditsWithRawResponse, AsyncEditsWithRawResponse from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from .images import Images, AsyncImages, ImagesWithRawResponse, AsyncImagesWithRawResponse -from .models import Models, AsyncModels, ModelsWithRawResponse, AsyncModelsWithRawResponse -from .embeddings import Embeddings, AsyncEmbeddings, EmbeddingsWithRawResponse, AsyncEmbeddingsWithRawResponse -from .fine_tunes import FineTunes, AsyncFineTunes, FineTunesWithRawResponse, AsyncFineTunesWithRawResponse -from .completions import Completions, AsyncCompletions, CompletionsWithRawResponse, AsyncCompletionsWithRawResponse -from .fine_tuning import FineTuning, AsyncFineTuning, FineTuningWithRawResponse, AsyncFineTuningWithRawResponse -from .moderations import Moderations, AsyncModerations, ModerationsWithRawResponse, AsyncModerationsWithRawResponse +from .images import ( + Images, + AsyncImages, + ImagesWithRawResponse, + AsyncImagesWithRawResponse, +) +from .models import ( + Models, + AsyncModels, + ModelsWithRawResponse, + AsyncModelsWithRawResponse, +) +from .embeddings import ( + Embeddings, + AsyncEmbeddings, + EmbeddingsWithRawResponse, + AsyncEmbeddingsWithRawResponse, +) +from .fine_tunes import ( + FineTunes, + AsyncFineTunes, + FineTunesWithRawResponse, + AsyncFineTunesWithRawResponse, +) +from .completions import ( + Completions, + AsyncCompletions, + CompletionsWithRawResponse, + AsyncCompletionsWithRawResponse, +) +from .fine_tuning import ( + FineTuning, + AsyncFineTuning, + FineTuningWithRawResponse, + AsyncFineTuningWithRawResponse, +) +from .moderations import ( + Moderations, + AsyncModerations, + ModerationsWithRawResponse, + AsyncModerationsWithRawResponse, +) __all__ = [ "Completions", diff --git a/src/openai/resources/audio/__init__.py b/src/openai/resources/audio/__init__.py index b6ff4322d4..76547b5f34 100644 --- a/src/openai/resources/audio/__init__.py +++ b/src/openai/resources/audio/__init__.py @@ -1,8 +1,18 @@ # File generated from our OpenAPI spec by Stainless. from .audio import Audio, AsyncAudio, AudioWithRawResponse, AsyncAudioWithRawResponse -from .speech import Speech, AsyncSpeech, SpeechWithRawResponse, AsyncSpeechWithRawResponse -from .translations import Translations, AsyncTranslations, TranslationsWithRawResponse, AsyncTranslationsWithRawResponse +from .speech import ( + Speech, + AsyncSpeech, + SpeechWithRawResponse, + AsyncSpeechWithRawResponse, +) +from .translations import ( + Translations, + AsyncTranslations, + TranslationsWithRawResponse, + AsyncTranslationsWithRawResponse, +) from .transcriptions import ( Transcriptions, AsyncTranscriptions, diff --git a/src/openai/resources/audio/audio.py b/src/openai/resources/audio/audio.py index 6b9242f0c2..6f7226ee59 100644 --- a/src/openai/resources/audio/audio.py +++ b/src/openai/resources/audio/audio.py @@ -4,9 +4,19 @@ from typing import TYPE_CHECKING -from .speech import Speech, AsyncSpeech, SpeechWithRawResponse, AsyncSpeechWithRawResponse +from .speech import ( + Speech, + AsyncSpeech, + SpeechWithRawResponse, + AsyncSpeechWithRawResponse, +) from ..._resource import SyncAPIResource, AsyncAPIResource -from .translations import Translations, AsyncTranslations, TranslationsWithRawResponse, AsyncTranslationsWithRawResponse +from .translations import ( + Translations, + AsyncTranslations, + TranslationsWithRawResponse, + AsyncTranslationsWithRawResponse, +) from .transcriptions import ( Transcriptions, AsyncTranscriptions, diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index ac81a80777..458843866f 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -7,21 +7,12 @@ import httpx -from ..._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ..._utils import maybe_transform from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ...types.audio import speech_create_params -from ..._base_client import ( - HttpxBinaryResponseContent, - make_request_options, -) +from ..._base_client import HttpxBinaryResponseContent, make_request_options if TYPE_CHECKING: from ..._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index 54be1c99a6..d2b4452411 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -7,21 +7,12 @@ import httpx -from ..._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, - FileTypes, -) +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from ..._utils import extract_files, maybe_transform, deepcopy_minimal from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ...types.audio import Transcription, transcription_create_params -from ..._base_client import ( - make_request_options, -) +from ..._base_client import make_request_options if TYPE_CHECKING: from ..._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index c4489004ac..fe7f7f2a40 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -7,21 +7,12 @@ import httpx -from ..._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, - FileTypes, -) +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from ..._utils import extract_files, maybe_transform, deepcopy_minimal from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ...types.audio import Translation, translation_create_params -from ..._base_client import ( - make_request_options, -) +from ..._base_client import make_request_options if TYPE_CHECKING: from ..._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/beta/__init__.py b/src/openai/resources/beta/__init__.py index 561f8bef60..55ad243cca 100644 --- a/src/openai/resources/beta/__init__.py +++ b/src/openai/resources/beta/__init__.py @@ -1,8 +1,18 @@ # File generated from our OpenAPI spec by Stainless. from .beta import Beta, AsyncBeta, BetaWithRawResponse, AsyncBetaWithRawResponse -from .threads import Threads, AsyncThreads, ThreadsWithRawResponse, AsyncThreadsWithRawResponse -from .assistants import Assistants, AsyncAssistants, AssistantsWithRawResponse, AsyncAssistantsWithRawResponse +from .threads import ( + Threads, + AsyncThreads, + ThreadsWithRawResponse, + AsyncThreadsWithRawResponse, +) +from .assistants import ( + Assistants, + AsyncAssistants, + AssistantsWithRawResponse, + AsyncAssistantsWithRawResponse, +) __all__ = [ "Assistants", diff --git a/src/openai/resources/beta/assistants/__init__.py b/src/openai/resources/beta/assistants/__init__.py index 205b2cf0f5..6efb0b21ec 100644 --- a/src/openai/resources/beta/assistants/__init__.py +++ b/src/openai/resources/beta/assistants/__init__.py @@ -1,7 +1,12 @@ # File generated from our OpenAPI spec by Stainless. from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from .assistants import Assistants, AsyncAssistants, AssistantsWithRawResponse, AsyncAssistantsWithRawResponse +from .assistants import ( + Assistants, + AsyncAssistants, + AssistantsWithRawResponse, + AsyncAssistantsWithRawResponse, +) __all__ = [ "Files", diff --git a/src/openai/resources/beta/assistants/assistants.py b/src/openai/resources/beta/assistants/assistants.py index 944019bed9..efa711ecf4 100644 --- a/src/openai/resources/beta/assistants/assistants.py +++ b/src/openai/resources/beta/assistants/assistants.py @@ -8,13 +8,7 @@ import httpx from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from ...._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ...._utils import maybe_transform from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_raw_response_wrapper, async_to_raw_response_wrapper @@ -26,10 +20,7 @@ assistant_create_params, assistant_update_params, ) -from ...._base_client import ( - AsyncPaginator, - make_request_options, -) +from ...._base_client import AsyncPaginator, make_request_options if TYPE_CHECKING: from ...._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/beta/assistants/files.py b/src/openai/resources/beta/assistants/files.py index 5682587487..5ac5897ca3 100644 --- a/src/openai/resources/beta/assistants/files.py +++ b/src/openai/resources/beta/assistants/files.py @@ -7,21 +7,12 @@ import httpx -from ...._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ...._utils import maybe_transform from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ....pagination import SyncCursorPage, AsyncCursorPage -from ...._base_client import ( - AsyncPaginator, - make_request_options, -) +from ...._base_client import AsyncPaginator, make_request_options from ....types.beta.assistants import ( AssistantFile, FileDeleteResponse, diff --git a/src/openai/resources/beta/beta.py b/src/openai/resources/beta/beta.py index 5cea6c1460..b552561763 100644 --- a/src/openai/resources/beta/beta.py +++ b/src/openai/resources/beta/beta.py @@ -4,8 +4,18 @@ from typing import TYPE_CHECKING -from .threads import Threads, AsyncThreads, ThreadsWithRawResponse, AsyncThreadsWithRawResponse -from .assistants import Assistants, AsyncAssistants, AssistantsWithRawResponse, AsyncAssistantsWithRawResponse +from .threads import ( + Threads, + AsyncThreads, + ThreadsWithRawResponse, + AsyncThreadsWithRawResponse, +) +from .assistants import ( + Assistants, + AsyncAssistants, + AssistantsWithRawResponse, + AsyncAssistantsWithRawResponse, +) from ..._resource import SyncAPIResource, AsyncAPIResource if TYPE_CHECKING: diff --git a/src/openai/resources/beta/threads/__init__.py b/src/openai/resources/beta/threads/__init__.py index fe7c5e5a20..b9aaada465 100644 --- a/src/openai/resources/beta/threads/__init__.py +++ b/src/openai/resources/beta/threads/__init__.py @@ -1,8 +1,18 @@ # File generated from our OpenAPI spec by Stainless. from .runs import Runs, AsyncRuns, RunsWithRawResponse, AsyncRunsWithRawResponse -from .threads import Threads, AsyncThreads, ThreadsWithRawResponse, AsyncThreadsWithRawResponse -from .messages import Messages, AsyncMessages, MessagesWithRawResponse, AsyncMessagesWithRawResponse +from .threads import ( + Threads, + AsyncThreads, + ThreadsWithRawResponse, + AsyncThreadsWithRawResponse, +) +from .messages import ( + Messages, + AsyncMessages, + MessagesWithRawResponse, + AsyncMessagesWithRawResponse, +) __all__ = [ "Runs", diff --git a/src/openai/resources/beta/threads/messages/__init__.py b/src/openai/resources/beta/threads/messages/__init__.py index cef618ed14..d8d4ce448c 100644 --- a/src/openai/resources/beta/threads/messages/__init__.py +++ b/src/openai/resources/beta/threads/messages/__init__.py @@ -1,7 +1,12 @@ # File generated from our OpenAPI spec by Stainless. from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from .messages import Messages, AsyncMessages, MessagesWithRawResponse, AsyncMessagesWithRawResponse +from .messages import ( + Messages, + AsyncMessages, + MessagesWithRawResponse, + AsyncMessagesWithRawResponse, +) __all__ = [ "Files", diff --git a/src/openai/resources/beta/threads/messages/files.py b/src/openai/resources/beta/threads/messages/files.py index 24c9680f3d..e028a6fda7 100644 --- a/src/openai/resources/beta/threads/messages/files.py +++ b/src/openai/resources/beta/threads/messages/files.py @@ -7,21 +7,12 @@ import httpx -from ....._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import maybe_transform from ....._resource import SyncAPIResource, AsyncAPIResource from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .....pagination import SyncCursorPage, AsyncCursorPage -from ....._base_client import ( - AsyncPaginator, - make_request_options, -) +from ....._base_client import AsyncPaginator, make_request_options from .....types.beta.threads.messages import MessageFile, file_list_params if TYPE_CHECKING: diff --git a/src/openai/resources/beta/threads/messages/messages.py b/src/openai/resources/beta/threads/messages/messages.py index 9a6f5706c3..30ae072512 100644 --- a/src/openai/resources/beta/threads/messages/messages.py +++ b/src/openai/resources/beta/threads/messages/messages.py @@ -8,21 +8,12 @@ import httpx from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from ....._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import maybe_transform from ....._resource import SyncAPIResource, AsyncAPIResource from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .....pagination import SyncCursorPage, AsyncCursorPage -from ....._base_client import ( - AsyncPaginator, - make_request_options, -) +from ....._base_client import AsyncPaginator, make_request_options from .....types.beta.threads import ( ThreadMessage, message_list_params, diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 719e35ea46..969bfab70a 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -8,21 +8,12 @@ import httpx from .steps import Steps, AsyncSteps, StepsWithRawResponse, AsyncStepsWithRawResponse -from ....._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import maybe_transform from ....._resource import SyncAPIResource, AsyncAPIResource from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .....pagination import SyncCursorPage, AsyncCursorPage -from ....._base_client import ( - AsyncPaginator, - make_request_options, -) +from ....._base_client import AsyncPaginator, make_request_options from .....types.beta.threads import ( Run, run_list_params, diff --git a/src/openai/resources/beta/threads/runs/steps.py b/src/openai/resources/beta/threads/runs/steps.py index f26034cf82..4fcc87a0ff 100644 --- a/src/openai/resources/beta/threads/runs/steps.py +++ b/src/openai/resources/beta/threads/runs/steps.py @@ -7,21 +7,12 @@ import httpx -from ....._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import maybe_transform from ....._resource import SyncAPIResource, AsyncAPIResource from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .....pagination import SyncCursorPage, AsyncCursorPage -from ....._base_client import ( - AsyncPaginator, - make_request_options, -) +from ....._base_client import AsyncPaginator, make_request_options from .....types.beta.threads.runs import RunStep, step_list_params if TYPE_CHECKING: diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index b37667485d..9469fc0513 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -7,14 +7,13 @@ import httpx from .runs import Runs, AsyncRuns, RunsWithRawResponse, AsyncRunsWithRawResponse -from .messages import Messages, AsyncMessages, MessagesWithRawResponse, AsyncMessagesWithRawResponse -from ...._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, +from .messages import ( + Messages, + AsyncMessages, + MessagesWithRawResponse, + AsyncMessagesWithRawResponse, ) +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ...._utils import maybe_transform from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_raw_response_wrapper, async_to_raw_response_wrapper @@ -25,9 +24,7 @@ thread_update_params, thread_create_and_run_params, ) -from ...._base_client import ( - make_request_options, -) +from ...._base_client import make_request_options from ....types.beta.threads import Run if TYPE_CHECKING: diff --git a/src/openai/resources/chat/__init__.py b/src/openai/resources/chat/__init__.py index 85b246509e..2e56c0cbfa 100644 --- a/src/openai/resources/chat/__init__.py +++ b/src/openai/resources/chat/__init__.py @@ -1,7 +1,12 @@ # File generated from our OpenAPI spec by Stainless. from .chat import Chat, AsyncChat, ChatWithRawResponse, AsyncChatWithRawResponse -from .completions import Completions, AsyncCompletions, CompletionsWithRawResponse, AsyncCompletionsWithRawResponse +from .completions import ( + Completions, + AsyncCompletions, + CompletionsWithRawResponse, + AsyncCompletionsWithRawResponse, +) __all__ = [ "Completions", diff --git a/src/openai/resources/chat/chat.py b/src/openai/resources/chat/chat.py index d93a501b1f..3847b20512 100644 --- a/src/openai/resources/chat/chat.py +++ b/src/openai/resources/chat/chat.py @@ -5,7 +5,12 @@ from typing import TYPE_CHECKING from ..._resource import SyncAPIResource, AsyncAPIResource -from .completions import Completions, AsyncCompletions, CompletionsWithRawResponse, AsyncCompletionsWithRawResponse +from .completions import ( + Completions, + AsyncCompletions, + CompletionsWithRawResponse, + AsyncCompletionsWithRawResponse, +) if TYPE_CHECKING: from ..._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index e29554c26d..d0657b2f73 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -7,13 +7,7 @@ import httpx -from ..._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ..._utils import required_args, maybe_transform from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper @@ -26,9 +20,7 @@ ChatCompletionToolChoiceOptionParam, completion_create_params, ) -from ..._base_client import ( - make_request_options, -) +from ..._base_client import make_request_options if TYPE_CHECKING: from ..._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index 39484c6f7b..baf6f04fef 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -8,20 +8,12 @@ import httpx from ..types import Completion, completion_create_params -from .._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import required_args, maybe_transform from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .._streaming import Stream, AsyncStream -from .._base_client import ( - make_request_options, -) +from .._base_client import make_request_options if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/edits.py b/src/openai/resources/edits.py index 587da02c8f..eafaa82fdf 100644 --- a/src/openai/resources/edits.py +++ b/src/openai/resources/edits.py @@ -9,19 +9,11 @@ import httpx from ..types import Edit, edit_create_params -from .._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import maybe_transform from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper -from .._base_client import ( - make_request_options, -) +from .._base_client import make_request_options if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/embeddings.py b/src/openai/resources/embeddings.py index 2ff3d3d44f..c31ad9d931 100644 --- a/src/openai/resources/embeddings.py +++ b/src/openai/resources/embeddings.py @@ -9,20 +9,13 @@ import httpx from ..types import CreateEmbeddingResponse, embedding_create_params -from .._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import is_given, maybe_transform -from .._extras import numpy as np, has_numpy +from .._extras import numpy as np +from .._extras import has_numpy from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper -from .._base_client import ( - make_request_options, -) +from .._base_client import make_request_options if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index b9f815af85..a6f75e5a4c 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -9,20 +9,8 @@ import httpx -from ..types import ( - FileObject, - FileDeleted, - file_list_params, - file_create_params, -) -from .._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, - FileTypes, -) +from ..types import FileObject, FileDeleted, file_list_params, file_create_params +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from .._utils import extract_files, maybe_transform, deepcopy_minimal from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper diff --git a/src/openai/resources/fine_tunes.py b/src/openai/resources/fine_tunes.py index f50d78717b..91c8201cbb 100644 --- a/src/openai/resources/fine_tunes.py +++ b/src/openai/resources/fine_tunes.py @@ -14,22 +14,13 @@ fine_tune_create_params, fine_tune_list_events_params, ) -from .._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import maybe_transform from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .._streaming import Stream, AsyncStream from ..pagination import SyncPage, AsyncPage -from .._base_client import ( - AsyncPaginator, - make_request_options, -) +from .._base_client import AsyncPaginator, make_request_options if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/fine_tuning/__init__.py b/src/openai/resources/fine_tuning/__init__.py index 27445fb707..9133c25d4a 100644 --- a/src/openai/resources/fine_tuning/__init__.py +++ b/src/openai/resources/fine_tuning/__init__.py @@ -1,7 +1,12 @@ # File generated from our OpenAPI spec by Stainless. from .jobs import Jobs, AsyncJobs, JobsWithRawResponse, AsyncJobsWithRawResponse -from .fine_tuning import FineTuning, AsyncFineTuning, FineTuningWithRawResponse, AsyncFineTuningWithRawResponse +from .fine_tuning import ( + FineTuning, + AsyncFineTuning, + FineTuningWithRawResponse, + AsyncFineTuningWithRawResponse, +) __all__ = [ "Jobs", diff --git a/src/openai/resources/fine_tuning/jobs.py b/src/openai/resources/fine_tuning/jobs.py index 55eee67044..3d9aed8d91 100644 --- a/src/openai/resources/fine_tuning/jobs.py +++ b/src/openai/resources/fine_tuning/jobs.py @@ -7,21 +7,12 @@ import httpx -from ..._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ..._utils import maybe_transform from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ...pagination import SyncCursorPage, AsyncCursorPage -from ..._base_client import ( - AsyncPaginator, - make_request_options, -) +from ..._base_client import AsyncPaginator, make_request_options from ...types.fine_tuning import ( FineTuningJob, FineTuningJobEvent, diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py index 0e1313078f..94b1bc1fc8 100644 --- a/src/openai/resources/images.py +++ b/src/openai/resources/images.py @@ -13,20 +13,11 @@ image_generate_params, image_create_variation_params, ) -from .._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, - FileTypes, -) +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from .._utils import extract_files, maybe_transform, deepcopy_minimal from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper -from .._base_client import ( - make_request_options, -) +from .._base_client import make_request_options if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/models.py b/src/openai/resources/models.py index a44a7ffbb0..2d04bdc5cc 100644 --- a/src/openai/resources/models.py +++ b/src/openai/resources/models.py @@ -7,20 +7,11 @@ import httpx from ..types import Model, ModelDeleted -from .._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ..pagination import SyncPage, AsyncPage -from .._base_client import ( - AsyncPaginator, - make_request_options, -) +from .._base_client import AsyncPaginator, make_request_options if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/moderations.py b/src/openai/resources/moderations.py index 9de7cd640f..12a7c68a7b 100644 --- a/src/openai/resources/moderations.py +++ b/src/openai/resources/moderations.py @@ -8,19 +8,11 @@ import httpx from ..types import ModerationCreateResponse, moderation_create_params -from .._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import maybe_transform from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper -from .._base_client import ( - make_request_options, -) +from .._base_client import make_request_options if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index df2b580587..1b4fca26ee 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -5,7 +5,8 @@ from .edit import Edit as Edit from .image import Image as Image from .model import Model as Model -from .shared import FunctionDefinition as FunctionDefinition, FunctionParameters as FunctionParameters +from .shared import FunctionDefinition as FunctionDefinition +from .shared import FunctionParameters as FunctionParameters from .embedding import Embedding as Embedding from .fine_tune import FineTune as FineTune from .completion import Completion as Completion @@ -27,8 +28,18 @@ from .fine_tune_create_params import FineTuneCreateParams as FineTuneCreateParams from .completion_create_params import CompletionCreateParams as CompletionCreateParams from .moderation_create_params import ModerationCreateParams as ModerationCreateParams -from .create_embedding_response import CreateEmbeddingResponse as CreateEmbeddingResponse -from .moderation_create_response import ModerationCreateResponse as ModerationCreateResponse -from .fine_tune_list_events_params import FineTuneListEventsParams as FineTuneListEventsParams -from .image_create_variation_params import ImageCreateVariationParams as ImageCreateVariationParams -from .fine_tune_events_list_response import FineTuneEventsListResponse as FineTuneEventsListResponse +from .create_embedding_response import ( + CreateEmbeddingResponse as CreateEmbeddingResponse, +) +from .moderation_create_response import ( + ModerationCreateResponse as ModerationCreateResponse, +) +from .fine_tune_list_events_params import ( + FineTuneListEventsParams as FineTuneListEventsParams, +) +from .image_create_variation_params import ( + ImageCreateVariationParams as ImageCreateVariationParams, +) +from .fine_tune_events_list_response import ( + FineTuneEventsListResponse as FineTuneEventsListResponse, +) diff --git a/src/openai/types/audio/__init__.py b/src/openai/types/audio/__init__.py index ba5f7fd8e0..83afa060f8 100644 --- a/src/openai/types/audio/__init__.py +++ b/src/openai/types/audio/__init__.py @@ -5,5 +5,9 @@ from .translation import Translation as Translation from .transcription import Transcription as Transcription from .speech_create_params import SpeechCreateParams as SpeechCreateParams -from .translation_create_params import TranslationCreateParams as TranslationCreateParams -from .transcription_create_params import TranscriptionCreateParams as TranscriptionCreateParams +from .translation_create_params import ( + TranslationCreateParams as TranslationCreateParams, +) +from .transcription_create_params import ( + TranscriptionCreateParams as TranscriptionCreateParams, +) diff --git a/src/openai/types/beta/__init__.py b/src/openai/types/beta/__init__.py index e6742521e9..c03d823b8c 100644 --- a/src/openai/types/beta/__init__.py +++ b/src/openai/types/beta/__init__.py @@ -11,4 +11,6 @@ from .assistant_list_params import AssistantListParams as AssistantListParams from .assistant_create_params import AssistantCreateParams as AssistantCreateParams from .assistant_update_params import AssistantUpdateParams as AssistantUpdateParams -from .thread_create_and_run_params import ThreadCreateAndRunParams as ThreadCreateAndRunParams +from .thread_create_and_run_params import ( + ThreadCreateAndRunParams as ThreadCreateAndRunParams, +) diff --git a/src/openai/types/beta/threads/__init__.py b/src/openai/types/beta/threads/__init__.py index 8c77466dec..0cb557a514 100644 --- a/src/openai/types/beta/threads/__init__.py +++ b/src/openai/types/beta/threads/__init__.py @@ -11,6 +11,12 @@ from .message_content_text import MessageContentText as MessageContentText from .message_create_params import MessageCreateParams as MessageCreateParams from .message_update_params import MessageUpdateParams as MessageUpdateParams -from .message_content_image_file import MessageContentImageFile as MessageContentImageFile -from .run_submit_tool_outputs_params import RunSubmitToolOutputsParams as RunSubmitToolOutputsParams -from .required_action_function_tool_call import RequiredActionFunctionToolCall as RequiredActionFunctionToolCall +from .message_content_image_file import ( + MessageContentImageFile as MessageContentImageFile, +) +from .run_submit_tool_outputs_params import ( + RunSubmitToolOutputsParams as RunSubmitToolOutputsParams, +) +from .required_action_function_tool_call import ( + RequiredActionFunctionToolCall as RequiredActionFunctionToolCall, +) diff --git a/src/openai/types/beta/threads/runs/__init__.py b/src/openai/types/beta/threads/runs/__init__.py index 16cb852922..72b972a986 100644 --- a/src/openai/types/beta/threads/runs/__init__.py +++ b/src/openai/types/beta/threads/runs/__init__.py @@ -8,4 +8,6 @@ from .function_tool_call import FunctionToolCall as FunctionToolCall from .retrieval_tool_call import RetrievalToolCall as RetrievalToolCall from .tool_calls_step_details import ToolCallsStepDetails as ToolCallsStepDetails -from .message_creation_step_details import MessageCreationStepDetails as MessageCreationStepDetails +from .message_creation_step_details import ( + MessageCreationStepDetails as MessageCreationStepDetails, +) diff --git a/src/openai/types/chat/__init__.py b/src/openai/types/chat/__init__.py index 3f90919619..5fe182f41e 100644 --- a/src/openai/types/chat/__init__.py +++ b/src/openai/types/chat/__init__.py @@ -7,13 +7,27 @@ from .chat_completion_chunk import ChatCompletionChunk as ChatCompletionChunk from .chat_completion_message import ChatCompletionMessage as ChatCompletionMessage from .completion_create_params import CompletionCreateParams as CompletionCreateParams -from .chat_completion_tool_param import ChatCompletionToolParam as ChatCompletionToolParam -from .chat_completion_message_param import ChatCompletionMessageParam as ChatCompletionMessageParam -from .chat_completion_message_tool_call import ChatCompletionMessageToolCall as ChatCompletionMessageToolCall -from .chat_completion_content_part_param import ChatCompletionContentPartParam as ChatCompletionContentPartParam -from .chat_completion_tool_message_param import ChatCompletionToolMessageParam as ChatCompletionToolMessageParam -from .chat_completion_user_message_param import ChatCompletionUserMessageParam as ChatCompletionUserMessageParam -from .chat_completion_system_message_param import ChatCompletionSystemMessageParam as ChatCompletionSystemMessageParam +from .chat_completion_tool_param import ( + ChatCompletionToolParam as ChatCompletionToolParam, +) +from .chat_completion_message_param import ( + ChatCompletionMessageParam as ChatCompletionMessageParam, +) +from .chat_completion_message_tool_call import ( + ChatCompletionMessageToolCall as ChatCompletionMessageToolCall, +) +from .chat_completion_content_part_param import ( + ChatCompletionContentPartParam as ChatCompletionContentPartParam, +) +from .chat_completion_tool_message_param import ( + ChatCompletionToolMessageParam as ChatCompletionToolMessageParam, +) +from .chat_completion_user_message_param import ( + ChatCompletionUserMessageParam as ChatCompletionUserMessageParam, +) +from .chat_completion_system_message_param import ( + ChatCompletionSystemMessageParam as ChatCompletionSystemMessageParam, +) from .chat_completion_function_message_param import ( ChatCompletionFunctionMessageParam as ChatCompletionFunctionMessageParam, ) diff --git a/src/openai/types/chat/chat_completion_content_part_param.py b/src/openai/types/chat/chat_completion_content_part_param.py index 8e58239258..587578e2ef 100644 --- a/src/openai/types/chat/chat_completion_content_part_param.py +++ b/src/openai/types/chat/chat_completion_content_part_param.py @@ -5,7 +5,9 @@ from typing import Union from .chat_completion_content_part_text_param import ChatCompletionContentPartTextParam -from .chat_completion_content_part_image_param import ChatCompletionContentPartImageParam +from .chat_completion_content_part_image_param import ( + ChatCompletionContentPartImageParam, +) __all__ = ["ChatCompletionContentPartParam"] diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 0d8495b0c1..69fe250eca 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -8,8 +8,12 @@ from ...types import shared_params from .chat_completion_tool_param import ChatCompletionToolParam from .chat_completion_message_param import ChatCompletionMessageParam -from .chat_completion_tool_choice_option_param import ChatCompletionToolChoiceOptionParam -from .chat_completion_function_call_option_param import ChatCompletionFunctionCallOptionParam +from .chat_completion_tool_choice_option_param import ( + ChatCompletionToolChoiceOptionParam, +) +from .chat_completion_function_call_option_param import ( + ChatCompletionFunctionCallOptionParam, +) __all__ = [ "CompletionCreateParamsBase", diff --git a/tests/api_resources/beta/test_assistants.py b/tests/api_resources/beta/test_assistants.py index 97e74c61e4..82e975b46d 100644 --- a/tests/api_resources/beta/test_assistants.py +++ b/tests/api_resources/beta/test_assistants.py @@ -10,10 +10,7 @@ from tests.utils import assert_matches_type from openai._client import OpenAI, AsyncOpenAI from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta import ( - Assistant, - AssistantDeleted, -) +from openai.types.beta import Assistant, AssistantDeleted base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") api_key = "My API Key" diff --git a/tests/api_resources/beta/test_threads.py b/tests/api_resources/beta/test_threads.py index 860159ffb3..8fa1fc20ea 100644 --- a/tests/api_resources/beta/test_threads.py +++ b/tests/api_resources/beta/test_threads.py @@ -9,10 +9,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai._client import OpenAI, AsyncOpenAI -from openai.types.beta import ( - Thread, - ThreadDeleted, -) +from openai.types.beta import Thread, ThreadDeleted from openai.types.beta.threads import Run base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index 39de3fa29d..d323dfc354 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -10,9 +10,7 @@ from tests.utils import assert_matches_type from openai._client import OpenAI, AsyncOpenAI from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta.threads import ( - Run, -) +from openai.types.beta.threads import Run base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") api_key = "My API Key" diff --git a/tests/api_resources/fine_tuning/test_jobs.py b/tests/api_resources/fine_tuning/test_jobs.py index 927ca9bbdd..5716a23d54 100644 --- a/tests/api_resources/fine_tuning/test_jobs.py +++ b/tests/api_resources/fine_tuning/test_jobs.py @@ -10,10 +10,7 @@ from tests.utils import assert_matches_type from openai._client import OpenAI, AsyncOpenAI from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.fine_tuning import ( - FineTuningJob, - FineTuningJobEvent, -) +from openai.types.fine_tuning import FineTuningJob, FineTuningJobEvent base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") api_key = "My API Key" diff --git a/tests/utils.py b/tests/utils.py index db2ca5601b..b513794017 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -8,12 +8,7 @@ from typing_extensions import Literal, get_args, get_origin, assert_type from openai._types import NoneType -from openai._utils import ( - is_dict, - is_list, - is_list_type, - is_union_type, -) +from openai._utils import is_dict, is_list, is_list_type, is_union_type from openai._compat import PYDANTIC_V2, field_outer_type, get_model_fields from openai._models import BaseModel From e967f5a5a6bb9adae6f5a15b48f50aedd64267d5 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 7 Dec 2023 18:27:29 +0000 Subject: [PATCH 142/816] chore(internal): enable more lint rules (#945) --- pyproject.toml | 31 +++++++++++++++++++----------- requirements-dev.lock | 18 ++++++++++++++++- src/openai/__init__.py | 2 +- src/openai/_extras/numpy_proxy.py | 4 ++-- src/openai/_extras/pandas_proxy.py | 4 ++-- src/openai/_streaming.py | 4 ++-- src/openai/_types.py | 1 + src/openai/_utils/_utils.py | 8 +++++--- src/openai/cli/_progress.py | 2 +- src/openai/cli/_tools/migrate.py | 4 ++-- tests/test_client.py | 5 +++-- tests/test_module_client.py | 6 +++--- tests/test_utils/test_proxy.py | 2 +- tests/utils.py | 2 +- 14 files changed, 61 insertions(+), 32 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index c468220495..8fe6a69b6c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -47,17 +47,18 @@ openai = "openai.cli:main" [tool.rye] managed = true +# version pins are in requirements-dev.lock dev-dependencies = [ - "pyright==1.1.332", - "mypy==1.7.1", - "black==23.3.0", - "respx==0.20.2", - "pytest==7.1.1", - "pytest-asyncio==0.21.1", - "ruff==0.0.282", - "isort==5.10.1", - "time-machine==2.9.0", - "nox==2023.4.22", + "pyright", + "mypy", + "black", + "respx", + "pytest", + "pytest-asyncio", + "ruff", + "isort", + "time-machine", + "nox", "dirty-equals>=0.6.0", "azure-identity >=1.14.1", "types-tqdm > 4" @@ -135,9 +136,11 @@ extra_standard_library = ["typing_extensions"] [tool.ruff] line-length = 120 -format = "grouped" +output-format = "grouped" target-version = "py37" select = [ + # bugbear rules + "B", # remove unused imports "F401", # bare except statements @@ -148,6 +151,12 @@ select = [ "T201", "T203", ] +ignore = [ + # lru_cache in methods, will be fixed separately + "B019", + # mutable defaults + "B006", +] unfixable = [ # disable auto fix for print statements "T201", diff --git a/requirements-dev.lock b/requirements-dev.lock index b1a9428a09..6df8805579 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -11,11 +11,15 @@ annotated-types==0.6.0 anyio==4.1.0 argcomplete==3.1.2 attrs==23.1.0 +azure-core==1.29.5 azure-identity==1.15.0 black==23.3.0 certifi==2023.7.22 +cffi==1.16.0 +charset-normalizer==3.3.2 click==8.1.7 colorlog==6.7.0 +cryptography==41.0.7 dirty-equals==0.6.0 distlib==0.3.7 distro==1.8.0 @@ -27,31 +31,43 @@ httpx==0.25.2 idna==3.4 iniconfig==2.0.0 isort==5.10.1 +msal==1.26.0 +msal-extensions==1.0.0 mypy==1.7.1 mypy-extensions==1.0.0 nodeenv==1.8.0 nox==2023.4.22 +numpy==1.26.2 packaging==23.2 +pandas==2.1.3 +pandas-stubs==2.1.1.230928 pathspec==0.11.2 platformdirs==3.11.0 pluggy==1.3.0 +portalocker==2.8.2 py==1.11.0 +pycparser==2.21 pydantic==2.4.2 pydantic-core==2.10.1 +pyjwt==2.8.0 pyright==1.1.332 pytest==7.1.1 pytest-asyncio==0.21.1 python-dateutil==2.8.2 pytz==2023.3.post1 +requests==2.31.0 respx==0.20.2 -ruff==0.0.282 +ruff==0.1.7 six==1.16.0 sniffio==1.3.0 time-machine==2.9.0 tomli==2.0.1 tqdm==4.66.1 +types-pytz==2023.3.1.1 types-tqdm==4.66.0.2 typing-extensions==4.8.0 +tzdata==2023.3 +urllib3==2.1.0 virtualenv==20.24.5 # The following packages are considered to be unsafe in a requirements file: setuptools==68.2.2 diff --git a/src/openai/__init__.py b/src/openai/__init__.py index d92dfe969a..d90f777cdc 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -86,7 +86,7 @@ for __name in __all__: if not __name.startswith("__"): try: - setattr(__locals[__name], "__module__", "openai") + __locals[__name].__module__ = "openai" except (TypeError, AttributeError): # Some of our exported symbols are builtins which we can't set attributes for. pass diff --git a/src/openai/_extras/numpy_proxy.py b/src/openai/_extras/numpy_proxy.py index 408eaebd3b..3809991c46 100644 --- a/src/openai/_extras/numpy_proxy.py +++ b/src/openai/_extras/numpy_proxy.py @@ -20,8 +20,8 @@ class NumpyProxy(LazyProxy[Any]): def __load__(self) -> Any: try: import numpy - except ImportError: - raise MissingDependencyError(NUMPY_INSTRUCTIONS) + except ImportError as err: + raise MissingDependencyError(NUMPY_INSTRUCTIONS) from err return numpy diff --git a/src/openai/_extras/pandas_proxy.py b/src/openai/_extras/pandas_proxy.py index 2fc0d2a7eb..a24f7fb604 100644 --- a/src/openai/_extras/pandas_proxy.py +++ b/src/openai/_extras/pandas_proxy.py @@ -20,8 +20,8 @@ class PandasProxy(LazyProxy[Any]): def __load__(self) -> Any: try: import pandas - except ImportError: - raise MissingDependencyError(PANDAS_INSTRUCTIONS) + except ImportError as err: + raise MissingDependencyError(PANDAS_INSTRUCTIONS) from err return pandas diff --git a/src/openai/_streaming.py b/src/openai/_streaming.py index 095746630b..e48324fc78 100644 --- a/src/openai/_streaming.py +++ b/src/openai/_streaming.py @@ -65,7 +65,7 @@ def __stream__(self) -> Iterator[ResponseT]: yield process_data(data=data, cast_to=cast_to, response=response) # Ensure the entire stream is consumed - for sse in iterator: + for _sse in iterator: ... @@ -120,7 +120,7 @@ async def __stream__(self) -> AsyncIterator[ResponseT]: yield process_data(data=data, cast_to=cast_to, response=response) # Ensure the entire stream is consumed - async for sse in iterator: + async for _sse in iterator: ... diff --git a/src/openai/_types.py b/src/openai/_types.py index 9e962a1078..8d543171eb 100644 --- a/src/openai/_types.py +++ b/src/openai/_types.py @@ -44,6 +44,7 @@ class BinaryResponseContent(ABC): + @abstractmethod def __init__( self, response: Any, diff --git a/src/openai/_utils/_utils.py b/src/openai/_utils/_utils.py index 83f88cc3e7..c874d3682d 100644 --- a/src/openai/_utils/_utils.py +++ b/src/openai/_utils/_utils.py @@ -194,8 +194,8 @@ def extract_type_arg(typ: type, index: int) -> type: args = get_args(typ) try: return cast(type, args[index]) - except IndexError: - raise RuntimeError(f"Expected type {typ} to have a type argument at index {index} but it did not") + except IndexError as err: + raise RuntimeError(f"Expected type {typ} to have a type argument at index {index} but it did not") from err def deepcopy_minimal(item: _T) -> _T: @@ -275,7 +275,9 @@ def wrapper(*args: object, **kwargs: object) -> object: try: given_params.add(positional[i]) except IndexError: - raise TypeError(f"{func.__name__}() takes {len(positional)} argument(s) but {len(args)} were given") + raise TypeError( + f"{func.__name__}() takes {len(positional)} argument(s) but {len(args)} were given" + ) from None for key in kwargs.keys(): given_params.add(key) diff --git a/src/openai/cli/_progress.py b/src/openai/cli/_progress.py index 390aaa9dfe..8a7f2525de 100644 --- a/src/openai/cli/_progress.py +++ b/src/openai/cli/_progress.py @@ -35,7 +35,7 @@ def read(self, n: int | None = -1) -> bytes: try: self._callback(self._progress) except Exception as e: # catches exception from the callback - raise CancelledError("The upload was cancelled: {}".format(e)) + raise CancelledError("The upload was cancelled: {}".format(e)) from e return chunk diff --git a/src/openai/cli/_tools/migrate.py b/src/openai/cli/_tools/migrate.py index 714bead8e3..14773302e1 100644 --- a/src/openai/cli/_tools/migrate.py +++ b/src/openai/cli/_tools/migrate.py @@ -41,7 +41,7 @@ def grit(args: GritArgs) -> None: except subprocess.CalledProcessError: # stdout and stderr are forwarded by subprocess so an error will already # have been displayed - raise SilentCLIError() + raise SilentCLIError() from None class MigrateArgs(BaseModel): @@ -57,7 +57,7 @@ def migrate(args: MigrateArgs) -> None: except subprocess.CalledProcessError: # stdout and stderr are forwarded by subprocess so an error will already # have been displayed - raise SilentCLIError() + raise SilentCLIError() from None # handles downloading the Grit CLI until they provide their own PyPi package diff --git a/tests/test_client.py b/tests/test_client.py index f8653507ef..c633e5eabc 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -19,6 +19,7 @@ from openai._models import BaseModel, FinalRequestOptions from openai._streaming import Stream, AsyncStream from openai._exceptions import ( + OpenAIError, APIStatusError, APITimeoutError, APIConnectionError, @@ -269,7 +270,7 @@ def test_validate_headers(self) -> None: request = client._build_request(FinalRequestOptions(method="get", url="/foo")) assert request.headers.get("Authorization") == f"Bearer {api_key}" - with pytest.raises(Exception): + with pytest.raises(OpenAIError): client2 = OpenAI(base_url=base_url, api_key=None, _strict_response_validation=True) _ = client2 @@ -934,7 +935,7 @@ def test_validate_headers(self) -> None: request = client._build_request(FinalRequestOptions(method="get", url="/foo")) assert request.headers.get("Authorization") == f"Bearer {api_key}" - with pytest.raises(Exception): + with pytest.raises(OpenAIError): client2 = AsyncOpenAI(base_url=base_url, api_key=None, _strict_response_validation=True) _ = client2 diff --git a/tests/test_module_client.py b/tests/test_module_client.py index 50b7369e19..40b0bde10b 100644 --- a/tests/test_module_client.py +++ b/tests/test_module_client.py @@ -129,7 +129,7 @@ def test_azure_api_key_env_without_api_version() -> None: ValueError, match=r"Must provide either the `api_version` argument or the `OPENAI_API_VERSION` environment variable", ): - openai.completions._client + openai.completions._client # noqa: B018 def test_azure_api_key_and_version_env() -> None: @@ -142,7 +142,7 @@ def test_azure_api_key_and_version_env() -> None: ValueError, match=r"Must provide one of the `base_url` or `azure_endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable", ): - openai.completions._client + openai.completions._client # noqa: B018 def test_azure_api_key_version_and_endpoint_env() -> None: @@ -152,7 +152,7 @@ def test_azure_api_key_version_and_endpoint_env() -> None: _os.environ["OPENAI_API_VERSION"] = "example-version" _os.environ["AZURE_OPENAI_ENDPOINT"] = "https://www.example/" - openai.completions._client + openai.completions._client # noqa: B018 assert openai.api_type == "azure" diff --git a/tests/test_utils/test_proxy.py b/tests/test_utils/test_proxy.py index 57c059150d..aedd3731ee 100644 --- a/tests/test_utils/test_proxy.py +++ b/tests/test_utils/test_proxy.py @@ -19,5 +19,5 @@ def test_recursive_proxy() -> None: assert repr(proxy) == "RecursiveLazyProxy" assert str(proxy) == "RecursiveLazyProxy" assert dir(proxy) == [] - assert getattr(type(proxy), "__name__") == "RecursiveLazyProxy" + assert type(proxy).__name__ == "RecursiveLazyProxy" assert type(operator.attrgetter("name.foo.bar.baz")(proxy)).__name__ == "RecursiveLazyProxy" diff --git a/tests/utils.py b/tests/utils.py index b513794017..57486c733a 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -91,7 +91,7 @@ def assert_matches_type( traceback.print_exc() continue - assert False, "Did not match any variants" + raise AssertionError("Did not match any variants") elif issubclass(origin, BaseModel): assert isinstance(value, type_) assert assert_matches_model(type_, cast(Any, value), path=path) From 478f3c083181a24d8432c085c8a16d59dee3c47d Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 8 Dec 2023 00:49:21 +0000 Subject: [PATCH 143/816] docs: fix typo in example (#950) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4cabdb897d..471fd88ab1 100644 --- a/README.md +++ b/README.md @@ -109,7 +109,7 @@ from openai import AsyncOpenAI client = AsyncOpenAI() stream = await client.chat.completions.create( - prompt="Say this is a test", + model="gpt-4", messages=[{"role": "user", "content": "Say this is a test"}], stream=True, ) From d468f301a897ee1f15c5d01b245a37aa03fe0da0 Mon Sep 17 00:00:00 2001 From: Hao Cen Date: Fri, 8 Dec 2023 02:02:18 -0800 Subject: [PATCH 144/816] fix(errors): properly assign APIError.body (#949) Co-authored-by: Hao Cen --- src/openai/_exceptions.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/openai/_exceptions.py b/src/openai/_exceptions.py index b79ac5fd64..40b163270d 100644 --- a/src/openai/_exceptions.py +++ b/src/openai/_exceptions.py @@ -48,6 +48,7 @@ def __init__(self, message: str, request: httpx.Request, *, body: object | None) super().__init__(message) self.request = request self.message = message + self.body = body if is_dict(body): self.code = cast(Any, body.get("code")) From d052708a5b7f61c17d858419c625d70dbd661e3b Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 8 Dec 2023 19:02:27 +0000 Subject: [PATCH 145/816] fix: avoid leaking memory when Client.with_options is used (#956) Fixes https://github.com/openai/openai-python/issues/865. --- pyproject.toml | 2 - src/openai/_base_client.py | 28 +++++---- src/openai/_client.py | 4 +- tests/test_client.py | 124 +++++++++++++++++++++++++++++++++++++ 4 files changed, 141 insertions(+), 17 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 8fe6a69b6c..ab49281348 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -152,8 +152,6 @@ select = [ "T203", ] ignore = [ - # lru_cache in methods, will be fixed separately - "B019", # mutable defaults "B006", ] diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 2e5678e8e6..bbbb8a54ab 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -403,14 +403,12 @@ def _build_headers(self, options: FinalRequestOptions) -> httpx.Headers: headers_dict = _merge_mappings(self.default_headers, custom_headers) self._validate_headers(headers_dict, custom_headers) + # headers are case-insensitive while dictionaries are not. headers = httpx.Headers(headers_dict) idempotency_header = self._idempotency_header if idempotency_header and options.method.lower() != "get" and idempotency_header not in headers: - if not options.idempotency_key: - options.idempotency_key = self._idempotency_key() - - headers[idempotency_header] = options.idempotency_key + headers[idempotency_header] = options.idempotency_key or self._idempotency_key() return headers @@ -594,16 +592,8 @@ def base_url(http://github.com/self) -> URL: def base_url(http://github.com/self,%20url:%20URL%20|%20str) -> None: self._base_url = self._enforce_trailing_slash(url if isinstance(url, URL) else URL(url)) - @lru_cache(maxsize=None) def platform_headers(self) -> Dict[str, str]: - return { - "X-Stainless-Lang": "python", - "X-Stainless-Package-Version": self._version, - "X-Stainless-OS": str(get_platform()), - "X-Stainless-Arch": str(get_architecture()), - "X-Stainless-Runtime": platform.python_implementation(), - "X-Stainless-Runtime-Version": platform.python_version(), - } + return platform_headers(self._version) def _calculate_retry_timeout( self, @@ -1691,6 +1681,18 @@ def get_platform() -> Platform: return "Unknown" +@lru_cache(maxsize=None) +def platform_headers(version: str) -> Dict[str, str]: + return { + "X-Stainless-Lang": "python", + "X-Stainless-Package-Version": version, + "X-Stainless-OS": str(get_platform()), + "X-Stainless-Arch": str(get_architecture()), + "X-Stainless-Runtime": platform.python_implementation(), + "X-Stainless-Runtime-Version": platform.python_version(), + } + + class OtherArch: def __init__(self, name: str) -> None: self.name = name diff --git a/src/openai/_client.py b/src/openai/_client.py index 202162070b..8cf0fa6797 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -192,7 +192,7 @@ def copy( return self.__class__( api_key=api_key or self.api_key, organization=organization or self.organization, - base_url=base_url or str(self.base_url), + base_url=base_url or self.base_url, timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, http_client=http_client, max_retries=max_retries if is_given(max_retries) else self.max_retries, @@ -402,7 +402,7 @@ def copy( return self.__class__( api_key=api_key or self.api_key, organization=organization or self.organization, - base_url=base_url or str(self.base_url), + base_url=base_url or self.base_url, timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, http_client=http_client, max_retries=max_retries if is_given(max_retries) else self.max_retries, diff --git a/tests/test_client.py b/tests/test_client.py index c633e5eabc..cd374a49db 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -2,10 +2,12 @@ from __future__ import annotations +import gc import os import json import asyncio import inspect +import tracemalloc from typing import Any, Union, cast from unittest import mock @@ -195,6 +197,67 @@ def test_copy_signature(self) -> None: copy_param = copy_signature.parameters.get(name) assert copy_param is not None, f"copy() signature is missing the {name} param" + def test_copy_build_request(self) -> None: + options = FinalRequestOptions(method="get", url="/foo") + + def build_request(options: FinalRequestOptions) -> None: + client = self.client.copy() + client._build_request(options) + + # ensure that the machinery is warmed up before tracing starts. + build_request(options) + gc.collect() + + tracemalloc.start(1000) + + snapshot_before = tracemalloc.take_snapshot() + + ITERATIONS = 10 + for _ in range(ITERATIONS): + build_request(options) + gc.collect() + + snapshot_after = tracemalloc.take_snapshot() + + tracemalloc.stop() + + def add_leak(leaks: list[tracemalloc.StatisticDiff], diff: tracemalloc.StatisticDiff) -> None: + if diff.count == 0: + # Avoid false positives by considering only leaks (i.e. allocations that persist). + return + + if diff.count % ITERATIONS != 0: + # Avoid false positives by considering only leaks that appear per iteration. + return + + for frame in diff.traceback: + if any( + frame.filename.endswith(fragment) + for fragment in [ + # to_raw_response_wrapper leaks through the @functools.wraps() decorator. + # + # removing the decorator fixes the leak for reasons we don't understand. + "openai/_response.py", + # pydantic.BaseModel.model_dump || pydantic.BaseModel.dict leak memory for some reason. + "openai/_compat.py", + # Standard library leaks we don't care about. + "/logging/__init__.py", + ] + ): + return + + leaks.append(diff) + + leaks: list[tracemalloc.StatisticDiff] = [] + for diff in snapshot_after.compare_to(snapshot_before, "traceback"): + add_leak(leaks, diff) + if leaks: + for leak in leaks: + print("MEMORY LEAK:", leak) + for frame in leak.traceback: + print(frame) + raise AssertionError() + def test_request_timeout(self) -> None: request = self.client._build_request(FinalRequestOptions(method="get", url="/foo")) timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore @@ -858,6 +921,67 @@ def test_copy_signature(self) -> None: copy_param = copy_signature.parameters.get(name) assert copy_param is not None, f"copy() signature is missing the {name} param" + def test_copy_build_request(self) -> None: + options = FinalRequestOptions(method="get", url="/foo") + + def build_request(options: FinalRequestOptions) -> None: + client = self.client.copy() + client._build_request(options) + + # ensure that the machinery is warmed up before tracing starts. + build_request(options) + gc.collect() + + tracemalloc.start(1000) + + snapshot_before = tracemalloc.take_snapshot() + + ITERATIONS = 10 + for _ in range(ITERATIONS): + build_request(options) + gc.collect() + + snapshot_after = tracemalloc.take_snapshot() + + tracemalloc.stop() + + def add_leak(leaks: list[tracemalloc.StatisticDiff], diff: tracemalloc.StatisticDiff) -> None: + if diff.count == 0: + # Avoid false positives by considering only leaks (i.e. allocations that persist). + return + + if diff.count % ITERATIONS != 0: + # Avoid false positives by considering only leaks that appear per iteration. + return + + for frame in diff.traceback: + if any( + frame.filename.endswith(fragment) + for fragment in [ + # to_raw_response_wrapper leaks through the @functools.wraps() decorator. + # + # removing the decorator fixes the leak for reasons we don't understand. + "openai/_response.py", + # pydantic.BaseModel.model_dump || pydantic.BaseModel.dict leak memory for some reason. + "openai/_compat.py", + # Standard library leaks we don't care about. + "/logging/__init__.py", + ] + ): + return + + leaks.append(diff) + + leaks: list[tracemalloc.StatisticDiff] = [] + for diff in snapshot_after.compare_to(snapshot_before, "traceback"): + add_leak(leaks, diff) + if leaks: + for leak in leaks: + print("MEMORY LEAK:", leak) + for frame in leak.traceback: + print(frame) + raise AssertionError() + async def test_request_timeout(self) -> None: request = self.client._build_request(FinalRequestOptions(method="get", url="/foo")) timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore From 790df765d41f27b9a6b88ce7b8af713939f8dc22 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 8 Dec 2023 19:03:12 +0000 Subject: [PATCH 146/816] release: 1.3.8 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 24 ++++++++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 27 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 2fd8c9c83a..c2f2ae6bbd 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.3.7" + ".": "1.3.8" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 88ff899ec3..1cb12572d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,29 @@ # Changelog +## 1.3.8 (2023-12-08) + +Full Changelog: [v1.3.7...v1.3.8](https://github.com/openai/openai-python/compare/v1.3.7...v1.3.8) + +### Bug Fixes + +* avoid leaking memory when Client.with_options is used ([#956](https://github.com/openai/openai-python/issues/956)) ([e37ecca](https://github.com/openai/openai-python/commit/e37ecca04040ce946822a7e40f5604532a59ee85)) +* **errors:** properly assign APIError.body ([#949](https://github.com/openai/openai-python/issues/949)) ([c70e194](https://github.com/openai/openai-python/commit/c70e194f0a253409ec851607ae5219e3b5a8c442)) +* **pagination:** use correct type hint for .object ([#943](https://github.com/openai/openai-python/issues/943)) ([23fe7ee](https://github.com/openai/openai-python/commit/23fe7ee48a71539b0d1e95ceff349264aae4090e)) + + +### Chores + +* **internal:** enable more lint rules ([#945](https://github.com/openai/openai-python/issues/945)) ([2c8add6](https://github.com/openai/openai-python/commit/2c8add64a261dea731bd162bb0cca222518d5440)) +* **internal:** reformat imports ([#939](https://github.com/openai/openai-python/issues/939)) ([ec65124](https://github.com/openai/openai-python/commit/ec651249de2f4e4cf959f816e1b52f03d3b1017a)) +* **internal:** reformat imports ([#944](https://github.com/openai/openai-python/issues/944)) ([5290639](https://github.com/openai/openai-python/commit/52906391c9b6633656ec7934e6bbac553ec667cd)) +* **internal:** update formatting ([#941](https://github.com/openai/openai-python/issues/941)) ([8e5a156](https://github.com/openai/openai-python/commit/8e5a156d555fe68731ba0604a7455cc03cb451ce)) +* **package:** lift anyio v4 restriction ([#927](https://github.com/openai/openai-python/issues/927)) ([be0438a](https://github.com/openai/openai-python/commit/be0438a2e399bb0e0a94907229d02fc61ab479c0)) + + +### Documentation + +* fix typo in example ([#950](https://github.com/openai/openai-python/issues/950)) ([54f0ce0](https://github.com/openai/openai-python/commit/54f0ce0000abe32e97ae400f2975c028b8a84273)) + ## 1.3.7 (2023-12-01) Full Changelog: [v1.3.6...v1.3.7](https://github.com/openai/openai-python/compare/v1.3.6...v1.3.7) diff --git a/pyproject.toml b/pyproject.toml index ab49281348..fab8bf4250 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.3.7" +version = "1.3.8" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 3103f3b767..7c90447cbc 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.3.7" # x-release-please-version +__version__ = "1.3.8" # x-release-please-version From dfe1c8da2a7ab0680722811bc019a551eef1a03e Mon Sep 17 00:00:00 2001 From: Sahand Sojoodi Date: Sat, 9 Dec 2023 15:16:52 -0500 Subject: [PATCH 147/816] docs: small Improvement in the async chat response code (#959) --- README.md | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 471fd88ab1..b7f278fe53 100644 --- a/README.md +++ b/README.md @@ -108,14 +108,17 @@ from openai import AsyncOpenAI client = AsyncOpenAI() -stream = await client.chat.completions.create( - model="gpt-4", - messages=[{"role": "user", "content": "Say this is a test"}], - stream=True, -) -async for chunk in stream: - if chunk.choices[0].delta.content is not None: - print(chunk.choices[0].delta.content) +async def main(): + stream = await client.chat.completions.create( + model="gpt-4", + messages=[{"role": "user", "content": "Say this is a test"}], + stream=True, + ) + async for chunk in stream: + if chunk.choices[0].delta.content is not None: + print(chunk.choices[0].delta.content) + +asyncio.run(main()) ``` ## Module-level client From a3da0196ffb0ea31e70bf935193caa6f92a0a22b Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 11 Dec 2023 10:01:08 +0000 Subject: [PATCH 148/816] docs: small streaming readme improvements (#962) --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index b7f278fe53..2e95b8f581 100644 --- a/README.md +++ b/README.md @@ -97,8 +97,7 @@ stream = client.chat.completions.create( stream=True, ) for chunk in stream: - if chunk.choices[0].delta.content is not None: - print(chunk.choices[0].delta.content) + print(chunk.choices[0].delta.content or "", end="") ``` The async client uses the exact same interface. @@ -108,6 +107,7 @@ from openai import AsyncOpenAI client = AsyncOpenAI() + async def main(): stream = await client.chat.completions.create( model="gpt-4", @@ -115,8 +115,8 @@ async def main(): stream=True, ) async for chunk in stream: - if chunk.choices[0].delta.content is not None: - print(chunk.choices[0].delta.content) + print(chunk.choices[0].delta.content or "", end="") + asyncio.run(main()) ``` From 1381f46e9ea0ee15afab42202b85edb48b1b794f Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 11 Dec 2023 23:55:22 +0000 Subject: [PATCH 149/816] docs: improve README timeout comment (#964) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2e95b8f581..f89d0bdb28 100644 --- a/README.md +++ b/README.md @@ -362,7 +362,7 @@ from openai import OpenAI # Configure the default for all requests: client = OpenAI( - # default is 60s + # 20 seconds (default is 10 minutes) timeout=20.0, ) From a7ebc26085fa0bb5ceeadc8aebb72dd2dfc9d5a6 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 12 Dec 2023 14:53:07 +0000 Subject: [PATCH 150/816] refactor(client): simplify cleanup (#966) This removes Client.__del__, but users are not expected to call this directly. --- pyproject.toml | 2 +- src/openai/__init__.py | 7 ------- src/openai/_base_client.py | 26 ++++++++++++++++++++------ src/openai/_client.py | 24 ------------------------ tests/test_client.py | 23 ++--------------------- 5 files changed, 23 insertions(+), 59 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index fab8bf4250..57fe2afc6d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -84,7 +84,7 @@ typecheck = { chain = [ ]} "typecheck:pyright" = "pyright" "typecheck:verify-types" = "pyright --verifytypes openai --ignoreexternal" -"typecheck:mypy" = "mypy --enable-incomplete-feature=Unpack ." +"typecheck:mypy" = "mypy ." [build-system] requires = ["hatchling"] diff --git a/src/openai/__init__.py b/src/openai/__init__.py index d90f777cdc..0d66b3c682 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -221,13 +221,6 @@ def _client(self, value: _httpx.Client) -> None: # type: ignore http_client = value - @override - def __del__(self) -> None: - try: - super().__del__() - except Exception: - pass - class _AzureModuleClient(_ModuleClient, AzureOpenAI): # type: ignore ... diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index bbbb8a54ab..04a20bfd91 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -5,6 +5,7 @@ import time import uuid import email +import asyncio import inspect import logging import platform @@ -672,9 +673,16 @@ def _idempotency_key(self) -> str: return f"stainless-python-retry-{uuid.uuid4()}" +class SyncHttpxClientWrapper(httpx.Client): + def __del__(self) -> None: + try: + self.close() + except Exception: + pass + + class SyncAPIClient(BaseClient[httpx.Client, Stream[Any]]): _client: httpx.Client - _has_custom_http_client: bool _default_stream_cls: type[Stream[Any]] | None = None def __init__( @@ -747,7 +755,7 @@ def __init__( custom_headers=custom_headers, _strict_response_validation=_strict_response_validation, ) - self._client = http_client or httpx.Client( + self._client = http_client or SyncHttpxClientWrapper( base_url=base_url, # cast to a valid type because mypy doesn't understand our type narrowing timeout=cast(Timeout, timeout), @@ -755,7 +763,6 @@ def __init__( transport=transport, limits=limits, ) - self._has_custom_http_client = bool(http_client) def is_closed(self) -> bool: return self._client.is_closed @@ -1135,9 +1142,17 @@ def get_api_list( return self._request_api_list(model, page, opts) +class AsyncHttpxClientWrapper(httpx.AsyncClient): + def __del__(self) -> None: + try: + # TODO(someday): support non asyncio runtimes here + asyncio.get_running_loop().create_task(self.aclose()) + except Exception: + pass + + class AsyncAPIClient(BaseClient[httpx.AsyncClient, AsyncStream[Any]]): _client: httpx.AsyncClient - _has_custom_http_client: bool _default_stream_cls: type[AsyncStream[Any]] | None = None def __init__( @@ -1210,7 +1225,7 @@ def __init__( custom_headers=custom_headers, _strict_response_validation=_strict_response_validation, ) - self._client = http_client or httpx.AsyncClient( + self._client = http_client or AsyncHttpxClientWrapper( base_url=base_url, # cast to a valid type because mypy doesn't understand our type narrowing timeout=cast(Timeout, timeout), @@ -1218,7 +1233,6 @@ def __init__( transport=transport, limits=limits, ) - self._has_custom_http_client = bool(http_client) def is_closed(self) -> bool: return self._client.is_closed diff --git a/src/openai/_client.py b/src/openai/_client.py index 8cf0fa6797..dacadf5aff 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -3,7 +3,6 @@ from __future__ import annotations import os -import asyncio from typing import Any, Union, Mapping from typing_extensions import Self, override @@ -205,16 +204,6 @@ def copy( # client.with_options(timeout=10).foo.create(...) with_options = copy - def __del__(self) -> None: - if not hasattr(self, "_has_custom_http_client") or not hasattr(self, "close"): - # this can happen if the '__init__' method raised an error - return - - if self._has_custom_http_client: - return - - self.close() - @override def _make_status_error( self, @@ -415,19 +404,6 @@ def copy( # client.with_options(timeout=10).foo.create(...) with_options = copy - def __del__(self) -> None: - if not hasattr(self, "_has_custom_http_client") or not hasattr(self, "close"): - # this can happen if the '__init__' method raised an error - return - - if self._has_custom_http_client: - return - - try: - asyncio.get_running_loop().create_task(self.close()) - except Exception: - pass - @override def _make_status_error( self, diff --git a/tests/test_client.py b/tests/test_client.py index cd374a49db..92998769d8 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -591,14 +591,6 @@ def test_absolute_request_url(http://github.com/self,%20client:%20OpenAI) -> None: ) assert request.url == "https://myapi.com/foo" - def test_client_del(self) -> None: - client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - assert not client.is_closed() - - client.__del__() - - assert client.is_closed() - def test_copied_client_does_not_close_http(self) -> None: client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) assert not client.is_closed() @@ -606,9 +598,8 @@ def test_copied_client_does_not_close_http(self) -> None: copied = client.copy() assert copied is not client - copied.__del__() + del copied - assert not copied.is_closed() assert not client.is_closed() def test_client_context_manager(self) -> None: @@ -1325,15 +1316,6 @@ def test_absolute_request_url(http://github.com/self,%20client:%20AsyncOpenAI) -> None: ) assert request.url == "https://myapi.com/foo" - async def test_client_del(self) -> None: - client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - assert not client.is_closed() - - client.__del__() - - await asyncio.sleep(0.2) - assert client.is_closed() - async def test_copied_client_does_not_close_http(self) -> None: client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) assert not client.is_closed() @@ -1341,10 +1323,9 @@ async def test_copied_client_does_not_close_http(self) -> None: copied = client.copy() assert copied is not client - copied.__del__() + del copied await asyncio.sleep(0.2) - assert not copied.is_closed() assert not client.is_closed() async def test_client_context_manager(self) -> None: From ba4f7a976247de8aa79fcd362e056ec9ce5ea4a0 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 12 Dec 2023 18:17:24 -0500 Subject: [PATCH 151/816] refactor: simplify internal error handling (#968) --- src/openai/_base_client.py | 102 +++++++------- tests/test_client.py | 268 +++++++++++-------------------------- 2 files changed, 124 insertions(+), 246 deletions(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 04a20bfd91..92189617b5 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -873,40 +873,25 @@ def _request( request = self._build_request(options) self._prepare_request(request) - response = None - try: response = self._client.send( request, auth=self.custom_auth, stream=stream or self._should_stream_response_body(request=request), ) - log.debug( - 'HTTP Request: %s %s "%i %s"', request.method, request.url, response.status_code, response.reason_phrase - ) - response.raise_for_status() - except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code - if retries > 0 and self._should_retry(err.response): - err.response.close() + except httpx.TimeoutException as err: + if retries > 0: return self._retry_request( options, cast_to, retries, - err.response.headers, stream=stream, stream_cls=stream_cls, + response_headers=None, ) - # If the response is streamed then we need to explicitly read the response - # to completion before attempting to access the response text. - if not err.response.is_closed: - err.response.read() - - raise self._make_status_error_from_response(err.response) from None - except httpx.TimeoutException as err: - if response is not None: - response.close() - + raise APITimeoutError(request=request) from err + except Exception as err: if retries > 0: return self._retry_request( options, @@ -914,25 +899,35 @@ def _request( retries, stream=stream, stream_cls=stream_cls, - response_headers=response.headers if response is not None else None, + response_headers=None, ) - raise APITimeoutError(request=request) from err - except Exception as err: - if response is not None: - response.close() + raise APIConnectionError(request=request) from err - if retries > 0: + log.debug( + 'HTTP Request: %s %s "%i %s"', request.method, request.url, response.status_code, response.reason_phrase + ) + + try: + response.raise_for_status() + except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code + if retries > 0 and self._should_retry(err.response): + err.response.close() return self._retry_request( options, cast_to, retries, + err.response.headers, stream=stream, stream_cls=stream_cls, - response_headers=response.headers if response is not None else None, ) - raise APIConnectionError(request=request) from err + # If the response is streamed then we need to explicitly read the response + # to completion before attempting to access the response text. + if not err.response.is_closed: + err.response.read() + + raise self._make_status_error_from_response(err.response) from None return self._process_response( cast_to=cast_to, @@ -1340,40 +1335,25 @@ async def _request( request = self._build_request(options) await self._prepare_request(request) - response = None - try: response = await self._client.send( request, auth=self.custom_auth, stream=stream or self._should_stream_response_body(request=request), ) - log.debug( - 'HTTP Request: %s %s "%i %s"', request.method, request.url, response.status_code, response.reason_phrase - ) - response.raise_for_status() - except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code - if retries > 0 and self._should_retry(err.response): - await err.response.aclose() + except httpx.TimeoutException as err: + if retries > 0: return await self._retry_request( options, cast_to, retries, - err.response.headers, stream=stream, stream_cls=stream_cls, + response_headers=None, ) - # If the response is streamed then we need to explicitly read the response - # to completion before attempting to access the response text. - if not err.response.is_closed: - await err.response.aread() - - raise self._make_status_error_from_response(err.response) from None - except httpx.TimeoutException as err: - if response is not None: - await response.aclose() - + raise APITimeoutError(request=request) from err + except Exception as err: if retries > 0: return await self._retry_request( options, @@ -1381,25 +1361,35 @@ async def _request( retries, stream=stream, stream_cls=stream_cls, - response_headers=response.headers if response is not None else None, + response_headers=None, ) - raise APITimeoutError(request=request) from err - except Exception as err: - if response is not None: - await response.aclose() + raise APIConnectionError(request=request) from err - if retries > 0: + log.debug( + 'HTTP Request: %s %s "%i %s"', request.method, request.url, response.status_code, response.reason_phrase + ) + + try: + response.raise_for_status() + except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code + if retries > 0 and self._should_retry(err.response): + await err.response.aclose() return await self._retry_request( options, cast_to, retries, + err.response.headers, stream=stream, stream_cls=stream_cls, - response_headers=response.headers if response is not None else None, ) - raise APIConnectionError(request=request) from err + # If the response is streamed then we need to explicitly read the response + # to completion before attempting to access the response text. + if not err.response.is_closed: + await err.response.aread() + + raise self._make_status_error_from_response(err.response) from None return self._process_response( cast_to=cast_to, diff --git a/tests/test_client.py b/tests/test_client.py index 92998769d8..0959185df2 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -24,7 +24,6 @@ OpenAIError, APIStatusError, APITimeoutError, - APIConnectionError, APIResponseValidationError, ) from openai._base_client import ( @@ -46,14 +45,8 @@ def _get_params(client: BaseClient[Any, Any]) -> dict[str, str]: return dict(url.params) -_original_response_init = cast(Any, httpx.Response.__init__) # type: ignore - - -def _low_retry_response_init(*args: Any, **kwargs: Any) -> Any: - headers = cast("list[tuple[bytes, bytes]]", kwargs["headers"]) - headers.append((b"retry-after", b"0.1")) - - return _original_response_init(*args, **kwargs) +def _low_retry_timeout(*_args: Any, **_kwargs: Any) -> float: + return 0.1 def _get_open_connections(client: OpenAI | AsyncOpenAI) -> int: @@ -678,103 +671,51 @@ def test_parse_retry_after_header(self, remaining_retries: int, retry_after: str calculated = client._calculate_retry_timeout(remaining_retries, options, headers) assert calculated == pytest.approx(timeout, 0.5 * 0.875) # pyright: ignore[reportUnknownMemberType] - @mock.patch("httpx.Response.__init__", _low_retry_response_init) - def test_retrying_timeout_errors_doesnt_leak(self) -> None: - def raise_for_status(response: httpx.Response) -> None: - raise httpx.TimeoutException("Test timeout error", request=response.request) - - with mock.patch("httpx.Response.raise_for_status", raise_for_status): - with pytest.raises(APITimeoutError): - self.client.post( - "/chat/completions", - body=dict( - messages=[ - { - "role": "user", - "content": "Say this is a test", - } - ], - model="gpt-3.5-turbo", - ), - cast_to=httpx.Response, - options={"headers": {"X-Stainless-Streamed-Raw-Response": "true"}}, - ) - - assert _get_open_connections(self.client) == 0 - - @mock.patch("httpx.Response.__init__", _low_retry_response_init) - def test_retrying_runtime_errors_doesnt_leak(self) -> None: - def raise_for_status(_response: httpx.Response) -> None: - raise RuntimeError("Test error") - - with mock.patch("httpx.Response.raise_for_status", raise_for_status): - with pytest.raises(APIConnectionError): - self.client.post( - "/chat/completions", - body=dict( - messages=[ - { - "role": "user", - "content": "Say this is a test", - } - ], - model="gpt-3.5-turbo", - ), - cast_to=httpx.Response, - options={"headers": {"X-Stainless-Streamed-Raw-Response": "true"}}, - ) - - assert _get_open_connections(self.client) == 0 - - @mock.patch("httpx.Response.__init__", _low_retry_response_init) - def test_retrying_status_errors_doesnt_leak(self) -> None: - def raise_for_status(response: httpx.Response) -> None: - response.status_code = 500 - raise httpx.HTTPStatusError("Test 500 error", response=response, request=response.request) - - with mock.patch("httpx.Response.raise_for_status", raise_for_status): - with pytest.raises(APIStatusError): - self.client.post( - "/chat/completions", - body=dict( - messages=[ - { - "role": "user", - "content": "Say this is a test", - } - ], - model="gpt-3.5-turbo", - ), - cast_to=httpx.Response, - options={"headers": {"X-Stainless-Streamed-Raw-Response": "true"}}, - ) + @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) + @pytest.mark.respx(base_url=base_url) + def test_retrying_timeout_errors_doesnt_leak(self, respx_mock: MockRouter) -> None: + respx_mock.post("/chat/completions").mock(side_effect=httpx.TimeoutException("Test timeout error")) + + with pytest.raises(APITimeoutError): + self.client.post( + "/chat/completions", + body=dict( + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-3.5-turbo", + ), + cast_to=httpx.Response, + options={"headers": {"X-Stainless-Streamed-Raw-Response": "true"}}, + ) assert _get_open_connections(self.client) == 0 + @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) @pytest.mark.respx(base_url=base_url) - def test_status_error_within_httpx(self, respx_mock: MockRouter) -> None: - respx_mock.post("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + def test_retrying_status_errors_doesnt_leak(self, respx_mock: MockRouter) -> None: + respx_mock.post("/chat/completions").mock(return_value=httpx.Response(500)) - def on_response(response: httpx.Response) -> None: - raise httpx.HTTPStatusError( - "Simulating an error inside httpx", - response=response, - request=response.request, + with pytest.raises(APIStatusError): + self.client.post( + "/chat/completions", + body=dict( + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-3.5-turbo", + ), + cast_to=httpx.Response, + options={"headers": {"X-Stainless-Streamed-Raw-Response": "true"}}, ) - client = OpenAI( - base_url=base_url, - api_key=api_key, - _strict_response_validation=True, - http_client=httpx.Client( - event_hooks={ - "response": [on_response], - } - ), - max_retries=0, - ) - with pytest.raises(APIStatusError): - client.post("/foo", cast_to=httpx.Response) + assert _get_open_connections(self.client) == 0 class TestAsyncOpenAI: @@ -1408,101 +1349,48 @@ async def test_parse_retry_after_header(self, remaining_retries: int, retry_afte calculated = client._calculate_retry_timeout(remaining_retries, options, headers) assert calculated == pytest.approx(timeout, 0.5 * 0.875) # pyright: ignore[reportUnknownMemberType] - @mock.patch("httpx.Response.__init__", _low_retry_response_init) - async def test_retrying_timeout_errors_doesnt_leak(self) -> None: - def raise_for_status(response: httpx.Response) -> None: - raise httpx.TimeoutException("Test timeout error", request=response.request) - - with mock.patch("httpx.Response.raise_for_status", raise_for_status): - with pytest.raises(APITimeoutError): - await self.client.post( - "/chat/completions", - body=dict( - messages=[ - { - "role": "user", - "content": "Say this is a test", - } - ], - model="gpt-3.5-turbo", - ), - cast_to=httpx.Response, - options={"headers": {"X-Stainless-Streamed-Raw-Response": "true"}}, - ) - - assert _get_open_connections(self.client) == 0 - - @mock.patch("httpx.Response.__init__", _low_retry_response_init) - async def test_retrying_runtime_errors_doesnt_leak(self) -> None: - def raise_for_status(_response: httpx.Response) -> None: - raise RuntimeError("Test error") - - with mock.patch("httpx.Response.raise_for_status", raise_for_status): - with pytest.raises(APIConnectionError): - await self.client.post( - "/chat/completions", - body=dict( - messages=[ - { - "role": "user", - "content": "Say this is a test", - } - ], - model="gpt-3.5-turbo", - ), - cast_to=httpx.Response, - options={"headers": {"X-Stainless-Streamed-Raw-Response": "true"}}, - ) - - assert _get_open_connections(self.client) == 0 - - @mock.patch("httpx.Response.__init__", _low_retry_response_init) - async def test_retrying_status_errors_doesnt_leak(self) -> None: - def raise_for_status(response: httpx.Response) -> None: - response.status_code = 500 - raise httpx.HTTPStatusError("Test 500 error", response=response, request=response.request) - - with mock.patch("httpx.Response.raise_for_status", raise_for_status): - with pytest.raises(APIStatusError): - await self.client.post( - "/chat/completions", - body=dict( - messages=[ - { - "role": "user", - "content": "Say this is a test", - } - ], - model="gpt-3.5-turbo", - ), - cast_to=httpx.Response, - options={"headers": {"X-Stainless-Streamed-Raw-Response": "true"}}, - ) + @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) + @pytest.mark.respx(base_url=base_url) + async def test_retrying_timeout_errors_doesnt_leak(self, respx_mock: MockRouter) -> None: + respx_mock.post("/chat/completions").mock(side_effect=httpx.TimeoutException("Test timeout error")) + + with pytest.raises(APITimeoutError): + await self.client.post( + "/chat/completions", + body=dict( + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-3.5-turbo", + ), + cast_to=httpx.Response, + options={"headers": {"X-Stainless-Streamed-Raw-Response": "true"}}, + ) assert _get_open_connections(self.client) == 0 + @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) @pytest.mark.respx(base_url=base_url) - @pytest.mark.asyncio - async def test_status_error_within_httpx(self, respx_mock: MockRouter) -> None: - respx_mock.post("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + async def test_retrying_status_errors_doesnt_leak(self, respx_mock: MockRouter) -> None: + respx_mock.post("/chat/completions").mock(return_value=httpx.Response(500)) - def on_response(response: httpx.Response) -> None: - raise httpx.HTTPStatusError( - "Simulating an error inside httpx", - response=response, - request=response.request, + with pytest.raises(APIStatusError): + await self.client.post( + "/chat/completions", + body=dict( + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-3.5-turbo", + ), + cast_to=httpx.Response, + options={"headers": {"X-Stainless-Streamed-Raw-Response": "true"}}, ) - client = AsyncOpenAI( - base_url=base_url, - api_key=api_key, - _strict_response_validation=True, - http_client=httpx.AsyncClient( - event_hooks={ - "response": [on_response], - } - ), - max_retries=0, - ) - with pytest.raises(APIStatusError): - await client.post("/foo", cast_to=httpx.Response) + assert _get_open_connections(self.client) == 0 From 9e6e1a284eeb2c20c05a03831e5566a4e9eaba50 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 12 Dec 2023 18:18:06 -0500 Subject: [PATCH 152/816] release: 1.3.9 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 16 ++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 19 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index c2f2ae6bbd..d19f910446 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.3.8" + ".": "1.3.9" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 1cb12572d1..372f3ccaa3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## 1.3.9 (2023-12-12) + +Full Changelog: [v1.3.8...v1.3.9](https://github.com/openai/openai-python/compare/v1.3.8...v1.3.9) + +### Documentation + +* improve README timeout comment ([#964](https://github.com/openai/openai-python/issues/964)) ([3c3ed5e](https://github.com/openai/openai-python/commit/3c3ed5edd938a9333e8d2fa47cb4b44178eef89a)) +* small Improvement in the async chat response code ([#959](https://github.com/openai/openai-python/issues/959)) ([fb9d0a3](https://github.com/openai/openai-python/commit/fb9d0a358fa232043d9d5c149b6a888d50127c7b)) +* small streaming readme improvements ([#962](https://github.com/openai/openai-python/issues/962)) ([f3be2e5](https://github.com/openai/openai-python/commit/f3be2e5cc24988471e6cedb3e34bdfd3123edc63)) + + +### Refactors + +* **client:** simplify cleanup ([#966](https://github.com/openai/openai-python/issues/966)) ([5c138f4](https://github.com/openai/openai-python/commit/5c138f4a7947e5b4aae8779fae78ca51269b355a)) +* simplify internal error handling ([#968](https://github.com/openai/openai-python/issues/968)) ([d187f6b](https://github.com/openai/openai-python/commit/d187f6b6e4e646cca39c6ca35c618aa5c1bfbd61)) + ## 1.3.8 (2023-12-08) Full Changelog: [v1.3.7...v1.3.8](https://github.com/openai/openai-python/compare/v1.3.7...v1.3.8) diff --git a/pyproject.toml b/pyproject.toml index 57fe2afc6d..99d537d22e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.3.8" +version = "1.3.9" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 7c90447cbc..3c646d4ffe 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.3.8" # x-release-please-version +__version__ = "1.3.9" # x-release-please-version From d1616886b57db690dad97c046836b138b87adb45 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 14 Dec 2023 22:04:39 -0500 Subject: [PATCH 153/816] feat(api): add optional `name` argument + improve docs (#972) --- src/openai/resources/audio/speech.py | 8 +- src/openai/resources/chat/completions.py | 112 ++++++++++-------- src/openai/resources/completions.py | 24 ++-- src/openai/resources/embeddings.py | 6 +- src/openai/resources/files.py | 16 +-- .../types/audio/speech_create_params.py | 2 + ...chat_completion_assistant_message_param.py | 16 ++- ...hat_completion_content_part_image_param.py | 6 +- .../chat_completion_function_message_param.py | 5 +- ...chat_completion_named_tool_choice_param.py | 4 +- .../chat_completion_system_message_param.py | 10 +- .../chat_completion_tool_message_param.py | 3 +- .../chat_completion_user_message_param.py | 9 +- .../types/chat/completion_create_params.py | 52 ++++---- src/openai/types/completion_create_params.py | 4 +- src/openai/types/embedding_create_params.py | 3 +- .../types/shared/function_definition.py | 20 ++-- .../shared_params/function_definition.py | 20 ++-- .../beta/assistants/test_files.py | 8 +- .../beta/threads/messages/test_files.py | 24 ++-- tests/api_resources/chat/test_completions.py | 4 + 21 files changed, 205 insertions(+), 151 deletions(-) diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index 458843866f..aadb00bd02 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -53,7 +53,9 @@ def create( `tts-1` or `tts-1-hd` voice: The voice to use when generating the audio. Supported voices are `alloy`, - `echo`, `fable`, `onyx`, `nova`, and `shimmer`. + `echo`, `fable`, `onyx`, `nova`, and `shimmer`. Previews of the voices are + available in the + [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech/voice-options). response_format: The format to audio in. Supported formats are `mp3`, `opus`, `aac`, and `flac`. @@ -120,7 +122,9 @@ async def create( `tts-1` or `tts-1-hd` voice: The voice to use when generating the audio. Supported voices are `alloy`, - `echo`, `fable`, `onyx`, `nova`, and `shimmer`. + `echo`, `fable`, `onyx`, `nova`, and `shimmer`. Previews of the voices are + available in the + [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech/voice-options). response_format: The format to audio in. Supported formats are `mp3`, `opus`, `aac`, and `flac`. diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index d0657b2f73..db7715c5dc 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -51,11 +51,11 @@ def create( "gpt-4-32k", "gpt-4-32k-0314", "gpt-4-32k-0613", - "gpt-3.5-turbo-1106", "gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0301", "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", "gpt-3.5-turbo-16k-0613", ], ], @@ -97,7 +97,7 @@ def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) function_call: Deprecated in favor of `tool_choice`. @@ -130,13 +130,15 @@ def create( [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. - n: How many chat completion choices to generate for each input message. + n: How many chat completion choices to generate for each input message. Note that + you will be charged based on the number of generated tokens across all of the + choices. Keep `n` as `1` to minimize costs. presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) response_format: An object specifying the format that the model must output. @@ -146,10 +148,10 @@ def create( **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token - limit, resulting in increased latency and appearance of a "stuck" request. Also - note that the message content may be partially cut off if - `finish_reason="length"`, which indicates the generation exceeded `max_tokens` - or the conversation exceeded the max context length. + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. seed: This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and @@ -222,11 +224,11 @@ def create( "gpt-4-32k", "gpt-4-32k-0314", "gpt-4-32k-0613", - "gpt-3.5-turbo-1106", "gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0301", "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", "gpt-3.5-turbo-16k-0613", ], ], @@ -275,7 +277,7 @@ def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) function_call: Deprecated in favor of `tool_choice`. @@ -308,13 +310,15 @@ def create( [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. - n: How many chat completion choices to generate for each input message. + n: How many chat completion choices to generate for each input message. Note that + you will be charged based on the number of generated tokens across all of the + choices. Keep `n` as `1` to minimize costs. presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) response_format: An object specifying the format that the model must output. @@ -324,10 +328,10 @@ def create( **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token - limit, resulting in increased latency and appearance of a "stuck" request. Also - note that the message content may be partially cut off if - `finish_reason="length"`, which indicates the generation exceeded `max_tokens` - or the conversation exceeded the max context length. + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. seed: This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and @@ -393,11 +397,11 @@ def create( "gpt-4-32k", "gpt-4-32k-0314", "gpt-4-32k-0613", - "gpt-3.5-turbo-1106", "gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0301", "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", "gpt-3.5-turbo-16k-0613", ], ], @@ -446,7 +450,7 @@ def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) function_call: Deprecated in favor of `tool_choice`. @@ -479,13 +483,15 @@ def create( [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. - n: How many chat completion choices to generate for each input message. + n: How many chat completion choices to generate for each input message. Note that + you will be charged based on the number of generated tokens across all of the + choices. Keep `n` as `1` to minimize costs. presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) response_format: An object specifying the format that the model must output. @@ -495,10 +501,10 @@ def create( **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token - limit, resulting in increased latency and appearance of a "stuck" request. Also - note that the message content may be partially cut off if - `finish_reason="length"`, which indicates the generation exceeded `max_tokens` - or the conversation exceeded the max context length. + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. seed: This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and @@ -564,11 +570,11 @@ def create( "gpt-4-32k", "gpt-4-32k-0314", "gpt-4-32k-0613", - "gpt-3.5-turbo-1106", "gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0301", "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", "gpt-3.5-turbo-16k-0613", ], ], @@ -652,11 +658,11 @@ async def create( "gpt-4-32k", "gpt-4-32k-0314", "gpt-4-32k-0613", - "gpt-3.5-turbo-1106", "gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0301", "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", "gpt-3.5-turbo-16k-0613", ], ], @@ -698,7 +704,7 @@ async def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) function_call: Deprecated in favor of `tool_choice`. @@ -731,13 +737,15 @@ async def create( [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. - n: How many chat completion choices to generate for each input message. + n: How many chat completion choices to generate for each input message. Note that + you will be charged based on the number of generated tokens across all of the + choices. Keep `n` as `1` to minimize costs. presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) response_format: An object specifying the format that the model must output. @@ -747,10 +755,10 @@ async def create( **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token - limit, resulting in increased latency and appearance of a "stuck" request. Also - note that the message content may be partially cut off if - `finish_reason="length"`, which indicates the generation exceeded `max_tokens` - or the conversation exceeded the max context length. + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. seed: This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and @@ -823,11 +831,11 @@ async def create( "gpt-4-32k", "gpt-4-32k-0314", "gpt-4-32k-0613", - "gpt-3.5-turbo-1106", "gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0301", "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", "gpt-3.5-turbo-16k-0613", ], ], @@ -876,7 +884,7 @@ async def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) function_call: Deprecated in favor of `tool_choice`. @@ -909,13 +917,15 @@ async def create( [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. - n: How many chat completion choices to generate for each input message. + n: How many chat completion choices to generate for each input message. Note that + you will be charged based on the number of generated tokens across all of the + choices. Keep `n` as `1` to minimize costs. presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) response_format: An object specifying the format that the model must output. @@ -925,10 +935,10 @@ async def create( **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token - limit, resulting in increased latency and appearance of a "stuck" request. Also - note that the message content may be partially cut off if - `finish_reason="length"`, which indicates the generation exceeded `max_tokens` - or the conversation exceeded the max context length. + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. seed: This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and @@ -994,11 +1004,11 @@ async def create( "gpt-4-32k", "gpt-4-32k-0314", "gpt-4-32k-0613", - "gpt-3.5-turbo-1106", "gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0301", "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", "gpt-3.5-turbo-16k-0613", ], ], @@ -1047,7 +1057,7 @@ async def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) function_call: Deprecated in favor of `tool_choice`. @@ -1080,13 +1090,15 @@ async def create( [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. - n: How many chat completion choices to generate for each input message. + n: How many chat completion choices to generate for each input message. Note that + you will be charged based on the number of generated tokens across all of the + choices. Keep `n` as `1` to minimize costs. presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) response_format: An object specifying the format that the model must output. @@ -1096,10 +1108,10 @@ async def create( **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token - limit, resulting in increased latency and appearance of a "stuck" request. Also - note that the message content may be partially cut off if - `finish_reason="length"`, which indicates the generation exceeded `max_tokens` - or the conversation exceeded the max context length. + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. seed: This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and @@ -1165,11 +1177,11 @@ async def create( "gpt-4-32k", "gpt-4-32k-0314", "gpt-4-32k-0613", - "gpt-3.5-turbo-1106", "gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0301", "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", "gpt-3.5-turbo-16k-0613", ], ], diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index baf6f04fef..93e1155a91 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -103,7 +103,7 @@ def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) logit_bias: Modify the likelihood of specified tokens appearing in the completion. @@ -143,7 +143,7 @@ def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) seed: If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return @@ -272,7 +272,7 @@ def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) logit_bias: Modify the likelihood of specified tokens appearing in the completion. @@ -312,7 +312,7 @@ def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) seed: If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return @@ -434,7 +434,7 @@ def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) logit_bias: Modify the likelihood of specified tokens appearing in the completion. @@ -474,7 +474,7 @@ def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) seed: If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return @@ -671,7 +671,7 @@ async def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) logit_bias: Modify the likelihood of specified tokens appearing in the completion. @@ -711,7 +711,7 @@ async def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) seed: If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return @@ -840,7 +840,7 @@ async def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) logit_bias: Modify the likelihood of specified tokens appearing in the completion. @@ -880,7 +880,7 @@ async def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) seed: If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return @@ -1002,7 +1002,7 @@ async def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) logit_bias: Modify the likelihood of specified tokens appearing in the completion. @@ -1042,7 +1042,7 @@ async def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) seed: If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return diff --git a/src/openai/resources/embeddings.py b/src/openai/resources/embeddings.py index c31ad9d931..978d239774 100644 --- a/src/openai/resources/embeddings.py +++ b/src/openai/resources/embeddings.py @@ -51,7 +51,8 @@ def create( input: Input text to embed, encoded as a string or array of tokens. To embed multiple inputs in a single request, pass an array of strings or array of token arrays. The input must not exceed the max input tokens for the model (8192 tokens for - `text-embedding-ada-002`) and cannot be an empty string. + `text-embedding-ada-002`), cannot be an empty string, and any array must be 2048 + dimensions or less. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. @@ -144,7 +145,8 @@ async def create( input: Input text to embed, encoded as a string or array of tokens. To embed multiple inputs in a single request, pass an array of strings or array of token arrays. The input must not exceed the max input tokens for the model (8192 tokens for - `text-embedding-ada-002`) and cannot be an empty string. + `text-embedding-ada-002`), cannot be an empty string, and any array must be 2048 + dimensions or less. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index a6f75e5a4c..ed52bc3d51 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -46,12 +46,12 @@ def create( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> FileObject: - """Upload a file that can be used across various endpoints/features. + """Upload a file that can be used across various endpoints. - The size of - all the files uploaded by one organization can be up to 100 GB. + The size of all the + files uploaded by one organization can be up to 100 GB. - The size of individual files for can be a maximum of 512MB. See the + The size of individual files can be a maximum of 512 MB. See the [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) to learn more about the types of files supported. The Fine-tuning API only supports `.jsonl` files. @@ -309,12 +309,12 @@ async def create( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> FileObject: - """Upload a file that can be used across various endpoints/features. + """Upload a file that can be used across various endpoints. - The size of - all the files uploaded by one organization can be up to 100 GB. + The size of all the + files uploaded by one organization can be up to 100 GB. - The size of individual files for can be a maximum of 512MB. See the + The size of individual files can be a maximum of 512 MB. See the [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) to learn more about the types of files supported. The Fine-tuning API only supports `.jsonl` files. diff --git a/src/openai/types/audio/speech_create_params.py b/src/openai/types/audio/speech_create_params.py index 06bea01746..6a302dd3c8 100644 --- a/src/openai/types/audio/speech_create_params.py +++ b/src/openai/types/audio/speech_create_params.py @@ -22,6 +22,8 @@ class SpeechCreateParams(TypedDict, total=False): """The voice to use when generating the audio. Supported voices are `alloy`, `echo`, `fable`, `onyx`, `nova`, and `shimmer`. + Previews of the voices are available in the + [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech/voice-options). """ response_format: Literal["mp3", "opus", "aac", "flac"] diff --git a/src/openai/types/chat/chat_completion_assistant_message_param.py b/src/openai/types/chat/chat_completion_assistant_message_param.py index abdd87c991..72a5bff83b 100644 --- a/src/openai/types/chat/chat_completion_assistant_message_param.py +++ b/src/openai/types/chat/chat_completion_assistant_message_param.py @@ -24,12 +24,15 @@ class FunctionCall(TypedDict, total=False): class ChatCompletionAssistantMessageParam(TypedDict, total=False): - content: Required[Optional[str]] - """The contents of the assistant message.""" - role: Required[Literal["assistant"]] """The role of the messages author, in this case `assistant`.""" + content: Optional[str] + """The contents of the assistant message. + + Required unless `tool_calls` or `function_call` is specified. + """ + function_call: FunctionCall """Deprecated and replaced by `tool_calls`. @@ -37,5 +40,12 @@ class ChatCompletionAssistantMessageParam(TypedDict, total=False): model. """ + name: str + """An optional name for the participant. + + Provides the model information to differentiate between participants of the same + role. + """ + tool_calls: List[ChatCompletionMessageToolCallParam] """The tool calls generated by the model, such as function calls.""" diff --git a/src/openai/types/chat/chat_completion_content_part_image_param.py b/src/openai/types/chat/chat_completion_content_part_image_param.py index eb9bd52689..e6732185ef 100644 --- a/src/openai/types/chat/chat_completion_content_part_image_param.py +++ b/src/openai/types/chat/chat_completion_content_part_image_param.py @@ -12,7 +12,11 @@ class ImageURL(TypedDict, total=False): """Either a URL of the image or the base64 encoded image data.""" detail: Literal["auto", "low", "high"] - """Specifies the detail level of the image.""" + """Specifies the detail level of the image. + + Learn more in the + [Vision guide](https://platform.openai.com/docs/guides/vision/low-or-high-fidelity-image-understanding). + """ class ChatCompletionContentPartImageParam(TypedDict, total=False): diff --git a/src/openai/types/chat/chat_completion_function_message_param.py b/src/openai/types/chat/chat_completion_function_message_param.py index 1a16c5f5eb..593571c0d2 100644 --- a/src/openai/types/chat/chat_completion_function_message_param.py +++ b/src/openai/types/chat/chat_completion_function_message_param.py @@ -2,15 +2,14 @@ from __future__ import annotations -from typing import Optional from typing_extensions import Literal, Required, TypedDict __all__ = ["ChatCompletionFunctionMessageParam"] class ChatCompletionFunctionMessageParam(TypedDict, total=False): - content: Required[Optional[str]] - """The return value from the function call, to return to the model.""" + content: Required[str] + """The contents of the function message.""" name: Required[str] """The name of the function to call.""" diff --git a/src/openai/types/chat/chat_completion_named_tool_choice_param.py b/src/openai/types/chat/chat_completion_named_tool_choice_param.py index 4c6f20d2f1..0b5ffde37b 100644 --- a/src/openai/types/chat/chat_completion_named_tool_choice_param.py +++ b/src/openai/types/chat/chat_completion_named_tool_choice_param.py @@ -13,7 +13,7 @@ class Function(TypedDict, total=False): class ChatCompletionNamedToolChoiceParam(TypedDict, total=False): - function: Function + function: Required[Function] - type: Literal["function"] + type: Required[Literal["function"]] """The type of the tool. Currently, only `function` is supported.""" diff --git a/src/openai/types/chat/chat_completion_system_message_param.py b/src/openai/types/chat/chat_completion_system_message_param.py index ec08e00350..6e862e75c7 100644 --- a/src/openai/types/chat/chat_completion_system_message_param.py +++ b/src/openai/types/chat/chat_completion_system_message_param.py @@ -2,15 +2,21 @@ from __future__ import annotations -from typing import Optional from typing_extensions import Literal, Required, TypedDict __all__ = ["ChatCompletionSystemMessageParam"] class ChatCompletionSystemMessageParam(TypedDict, total=False): - content: Required[Optional[str]] + content: Required[str] """The contents of the system message.""" role: Required[Literal["system"]] """The role of the messages author, in this case `system`.""" + + name: str + """An optional name for the participant. + + Provides the model information to differentiate between participants of the same + role. + """ diff --git a/src/openai/types/chat/chat_completion_tool_message_param.py b/src/openai/types/chat/chat_completion_tool_message_param.py index 51759a9a99..373c5b88f4 100644 --- a/src/openai/types/chat/chat_completion_tool_message_param.py +++ b/src/openai/types/chat/chat_completion_tool_message_param.py @@ -2,14 +2,13 @@ from __future__ import annotations -from typing import Optional from typing_extensions import Literal, Required, TypedDict __all__ = ["ChatCompletionToolMessageParam"] class ChatCompletionToolMessageParam(TypedDict, total=False): - content: Required[Optional[str]] + content: Required[str] """The contents of the tool message.""" role: Required[Literal["tool"]] diff --git a/src/openai/types/chat/chat_completion_user_message_param.py b/src/openai/types/chat/chat_completion_user_message_param.py index 6f0cf34623..07be67c405 100644 --- a/src/openai/types/chat/chat_completion_user_message_param.py +++ b/src/openai/types/chat/chat_completion_user_message_param.py @@ -11,8 +11,15 @@ class ChatCompletionUserMessageParam(TypedDict, total=False): - content: Required[Union[str, List[ChatCompletionContentPartParam], None]] + content: Required[Union[str, List[ChatCompletionContentPartParam]]] """The contents of the user message.""" role: Required[Literal["user"]] """The role of the messages author, in this case `user`.""" + + name: str + """An optional name for the participant. + + Provides the model information to differentiate between participants of the same + role. + """ diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 69fe250eca..e8098f7b77 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -44,11 +44,11 @@ class CompletionCreateParamsBase(TypedDict, total=False): "gpt-4-32k", "gpt-4-32k-0314", "gpt-4-32k-0613", - "gpt-3.5-turbo-1106", "gpt-3.5-turbo", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0301", "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", "gpt-3.5-turbo-16k-0613", ], ] @@ -66,7 +66,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) """ function_call: FunctionCall @@ -109,7 +109,11 @@ class CompletionCreateParamsBase(TypedDict, total=False): """ n: Optional[int] - """How many chat completion choices to generate for each input message.""" + """How many chat completion choices to generate for each input message. + + Note that you will be charged based on the number of generated tokens across all + of the choices. Keep `n` as `1` to minimize costs. + """ presence_penalty: Optional[float] """Number between -2.0 and 2.0. @@ -117,7 +121,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) """ response_format: ResponseFormat @@ -129,19 +133,19 @@ class CompletionCreateParamsBase(TypedDict, total=False): **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token - limit, resulting in increased latency and appearance of a "stuck" request. Also - note that the message content may be partially cut off if - `finish_reason="length"`, which indicates the generation exceeded `max_tokens` - or the conversation exceeded the max context length. + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. """ seed: Optional[int] - """This feature is in Beta. - - If specified, our system will make a best effort to sample deterministically, - such that repeated requests with the same `seed` and parameters should return - the same result. Determinism is not guaranteed, and you should refer to the - `system_fingerprint` response parameter to monitor changes in the backend. + """ + This feature is in Beta. If specified, our system will make a best effort to + sample deterministically, such that repeated requests with the same `seed` and + parameters should return the same result. Determinism is not guaranteed, and you + should refer to the `system_fingerprint` response parameter to monitor changes + in the backend. """ stop: Union[Optional[str], List[str]] @@ -204,22 +208,22 @@ class Function(TypedDict, total=False): of 64. """ - parameters: Required[shared_params.FunctionParameters] + description: str + """ + A description of what the function does, used by the model to choose when and + how to call the function. + """ + + parameters: shared_params.FunctionParameters """The parameters the functions accepts, described as a JSON Schema object. - See the [guide](https://platform.openai.com/docs/guides/gpt/function-calling) + See the + [guide](https://platform.openai.com/docs/guides/text-generation/function-calling) for examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format. - To describe a function that accepts no parameters, provide the value - `{"type": "object", "properties": {}}`. - """ - - description: str - """ - A description of what the function does, used by the model to choose when and - how to call the function. + Omitting `parameters` defines a function with an empty parameter list. """ diff --git a/src/openai/types/completion_create_params.py b/src/openai/types/completion_create_params.py index 3e56d4f7bf..488fe34893 100644 --- a/src/openai/types/completion_create_params.py +++ b/src/openai/types/completion_create_params.py @@ -67,7 +67,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) """ logit_bias: Optional[Dict[str, int]] @@ -119,7 +119,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/gpt/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) """ seed: Optional[int] diff --git a/src/openai/types/embedding_create_params.py b/src/openai/types/embedding_create_params.py index bc8535f880..fd2fc5b48d 100644 --- a/src/openai/types/embedding_create_params.py +++ b/src/openai/types/embedding_create_params.py @@ -14,7 +14,8 @@ class EmbeddingCreateParams(TypedDict, total=False): To embed multiple inputs in a single request, pass an array of strings or array of token arrays. The input must not exceed the max input tokens for the model - (8192 tokens for `text-embedding-ada-002`) and cannot be an empty string. + (8192 tokens for `text-embedding-ada-002`), cannot be an empty string, and any + array must be 2048 dimensions or less. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. """ diff --git a/src/openai/types/shared/function_definition.py b/src/openai/types/shared/function_definition.py index bfcee50c85..32658220fa 100644 --- a/src/openai/types/shared/function_definition.py +++ b/src/openai/types/shared/function_definition.py @@ -16,20 +16,20 @@ class FunctionDefinition(BaseModel): of 64. """ - parameters: FunctionParameters + description: Optional[str] = None + """ + A description of what the function does, used by the model to choose when and + how to call the function. + """ + + parameters: Optional[FunctionParameters] = None """The parameters the functions accepts, described as a JSON Schema object. - See the [guide](https://platform.openai.com/docs/guides/gpt/function-calling) + See the + [guide](https://platform.openai.com/docs/guides/text-generation/function-calling) for examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format. - To describe a function that accepts no parameters, provide the value - `{"type": "object", "properties": {}}`. - """ - - description: Optional[str] = None - """ - A description of what the function does, used by the model to choose when and - how to call the function. + Omitting `parameters` defines a function with an empty parameter list. """ diff --git a/src/openai/types/shared_params/function_definition.py b/src/openai/types/shared_params/function_definition.py index 6bb6fa6ff2..8e89bd41dd 100644 --- a/src/openai/types/shared_params/function_definition.py +++ b/src/openai/types/shared_params/function_definition.py @@ -17,20 +17,20 @@ class FunctionDefinition(TypedDict, total=False): of 64. """ - parameters: Required[shared_params.FunctionParameters] + description: str + """ + A description of what the function does, used by the model to choose when and + how to call the function. + """ + + parameters: shared_params.FunctionParameters """The parameters the functions accepts, described as a JSON Schema object. - See the [guide](https://platform.openai.com/docs/guides/gpt/function-calling) + See the + [guide](https://platform.openai.com/docs/guides/text-generation/function-calling) for examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format. - To describe a function that accepts no parameters, provide the value - `{"type": "object", "properties": {}}`. - """ - - description: str - """ - A description of what the function does, used by the model to choose when and - how to call the function. + Omitting `parameters` defines a function with an empty parameter list. """ diff --git a/tests/api_resources/beta/assistants/test_files.py b/tests/api_resources/beta/assistants/test_files.py index 2545640c57..27c12e4475 100644 --- a/tests/api_resources/beta/assistants/test_files.py +++ b/tests/api_resources/beta/assistants/test_files.py @@ -24,7 +24,7 @@ class TestFiles: @parametrize def test_method_create(self, client: OpenAI) -> None: file = client.beta.assistants.files.create( - "file-AF1WoRqd3aJAHsqc9NY7iL8F", + "file-abc123", file_id="string", ) assert_matches_type(AssistantFile, file, path=["response"]) @@ -32,7 +32,7 @@ def test_method_create(self, client: OpenAI) -> None: @parametrize def test_raw_response_create(self, client: OpenAI) -> None: response = client.beta.assistants.files.with_raw_response.create( - "file-AF1WoRqd3aJAHsqc9NY7iL8F", + "file-abc123", file_id="string", ) assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -111,7 +111,7 @@ class TestAsyncFiles: @parametrize async def test_method_create(self, client: AsyncOpenAI) -> None: file = await client.beta.assistants.files.create( - "file-AF1WoRqd3aJAHsqc9NY7iL8F", + "file-abc123", file_id="string", ) assert_matches_type(AssistantFile, file, path=["response"]) @@ -119,7 +119,7 @@ async def test_method_create(self, client: AsyncOpenAI) -> None: @parametrize async def test_raw_response_create(self, client: AsyncOpenAI) -> None: response = await client.beta.assistants.files.with_raw_response.create( - "file-AF1WoRqd3aJAHsqc9NY7iL8F", + "file-abc123", file_id="string", ) assert response.http_request.headers.get("X-Stainless-Lang") == "python" diff --git a/tests/api_resources/beta/threads/messages/test_files.py b/tests/api_resources/beta/threads/messages/test_files.py index a5b68713e6..b97e4debd5 100644 --- a/tests/api_resources/beta/threads/messages/test_files.py +++ b/tests/api_resources/beta/threads/messages/test_files.py @@ -24,18 +24,18 @@ class TestFiles: @parametrize def test_method_retrieve(self, client: OpenAI) -> None: file = client.beta.threads.messages.files.retrieve( - "file-AF1WoRqd3aJAHsqc9NY7iL8F", - thread_id="thread_AF1WoRqd3aJAHsqc9NY7iL8F", - message_id="msg_AF1WoRqd3aJAHsqc9NY7iL8F", + "file-abc123", + thread_id="thread_abc123", + message_id="msg_abc123", ) assert_matches_type(MessageFile, file, path=["response"]) @parametrize def test_raw_response_retrieve(self, client: OpenAI) -> None: response = client.beta.threads.messages.files.with_raw_response.retrieve( - "file-AF1WoRqd3aJAHsqc9NY7iL8F", - thread_id="thread_AF1WoRqd3aJAHsqc9NY7iL8F", - message_id="msg_AF1WoRqd3aJAHsqc9NY7iL8F", + "file-abc123", + thread_id="thread_abc123", + message_id="msg_abc123", ) assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() @@ -80,18 +80,18 @@ class TestAsyncFiles: @parametrize async def test_method_retrieve(self, client: AsyncOpenAI) -> None: file = await client.beta.threads.messages.files.retrieve( - "file-AF1WoRqd3aJAHsqc9NY7iL8F", - thread_id="thread_AF1WoRqd3aJAHsqc9NY7iL8F", - message_id="msg_AF1WoRqd3aJAHsqc9NY7iL8F", + "file-abc123", + thread_id="thread_abc123", + message_id="msg_abc123", ) assert_matches_type(MessageFile, file, path=["response"]) @parametrize async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: response = await client.beta.threads.messages.files.with_raw_response.retrieve( - "file-AF1WoRqd3aJAHsqc9NY7iL8F", - thread_id="thread_AF1WoRqd3aJAHsqc9NY7iL8F", - message_id="msg_AF1WoRqd3aJAHsqc9NY7iL8F", + "file-abc123", + thread_id="thread_abc123", + message_id="msg_abc123", ) assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index 132e00039b..0b58a4109d 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -40,6 +40,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: { "content": "string", "role": "system", + "name": "string", } ], model="gpt-3.5-turbo", @@ -128,6 +129,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: { "content": "string", "role": "system", + "name": "string", } ], model="gpt-3.5-turbo", @@ -221,6 +223,7 @@ async def test_method_create_with_all_params_overload_1(self, client: AsyncOpenA { "content": "string", "role": "system", + "name": "string", } ], model="gpt-3.5-turbo", @@ -309,6 +312,7 @@ async def test_method_create_with_all_params_overload_2(self, client: AsyncOpenA { "content": "string", "role": "system", + "name": "string", } ], model="gpt-3.5-turbo", From 1fa164d2d86cd870526463e45c5998482e90fb1d Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 14 Dec 2023 22:05:22 -0500 Subject: [PATCH 154/816] release: 1.4.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index d19f910446..3e9af1b3ae 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.3.9" + ".": "1.4.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 372f3ccaa3..fc6366c4ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.4.0 (2023-12-15) + +Full Changelog: [v1.3.9...v1.4.0](https://github.com/openai/openai-python/compare/v1.3.9...v1.4.0) + +### Features + +* **api:** add optional `name` argument + improve docs ([#972](https://github.com/openai/openai-python/issues/972)) ([7972010](https://github.com/openai/openai-python/commit/7972010615820099f662c02821cfbd59e7d6ea44)) + ## 1.3.9 (2023-12-12) Full Changelog: [v1.3.8...v1.3.9](https://github.com/openai/openai-python/compare/v1.3.8...v1.3.9) diff --git a/pyproject.toml b/pyproject.toml index 99d537d22e..f96442aaa4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.3.9" +version = "1.4.0" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 3c646d4ffe..e43b6069a8 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.3.9" # x-release-please-version +__version__ = "1.4.0" # x-release-please-version From eafe8f938bd7b1a36dc2857fe8948b0cf355b159 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Sat, 16 Dec 2023 19:39:38 -0500 Subject: [PATCH 155/816] chore(ci): run release workflow once per day (#978) --- .github/workflows/create-releases.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/create-releases.yml b/.github/workflows/create-releases.yml index 7dbae006c0..c8c94db105 100644 --- a/.github/workflows/create-releases.yml +++ b/.github/workflows/create-releases.yml @@ -1,5 +1,7 @@ name: Create releases on: + schedule: + - cron: '0 5 * * *' # every day at 5am UTC push: branches: - main From ccae821bd90110161dd061945d4ecfb410531836 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Sat, 16 Dec 2023 19:47:42 -0500 Subject: [PATCH 156/816] feat(api): add token logprobs to chat completions (#980) --- api.md | 1 + src/openai/resources/chat/completions.py | 122 +++++++++++++++--- src/openai/resources/completions.py | 66 +++++----- src/openai/resources/files.py | 6 +- .../runs/message_creation_step_details.py | 2 +- .../types/beta/threads/runs/run_step.py | 2 +- src/openai/types/chat/__init__.py | 3 + src/openai/types/chat/chat_completion.py | 11 +- .../types/chat/chat_completion_chunk.py | 10 ++ .../chat_completion_function_message_param.py | 3 +- .../chat/chat_completion_token_logprob.py | 47 +++++++ .../types/chat/completion_create_params.py | 23 +++- src/openai/types/completion_create_params.py | 12 +- tests/api_resources/chat/test_completions.py | 8 ++ 14 files changed, 255 insertions(+), 61 deletions(-) create mode 100644 src/openai/types/chat/chat_completion_token_logprob.py diff --git a/api.md b/api.md index a7ee177411..9d9993105b 100644 --- a/api.md +++ b/api.md @@ -38,6 +38,7 @@ from openai.types.chat import ( ChatCompletionNamedToolChoice, ChatCompletionRole, ChatCompletionSystemMessageParam, + ChatCompletionTokenLogprob, ChatCompletionTool, ChatCompletionToolChoiceOption, ChatCompletionToolMessageParam, diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index db7715c5dc..5aac234227 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -63,6 +63,7 @@ def create( function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: List[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -73,6 +74,7 @@ def create( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, tools: List[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, + top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -107,7 +109,7 @@ def create( particular function via `{"name": "my_function"}` forces the model to call that function. - `none` is the default when no functions are present. `auto`` is the default if + `none` is the default when no functions are present. `auto` is the default if functions are present. functions: Deprecated in favor of `tools`. @@ -123,7 +125,13 @@ def create( increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. - max_tokens: The maximum number of [tokens](/tokenizer) to generate in the chat completion. + logprobs: Whether to return log probabilities of the output tokens or not. If true, + returns the log probabilities of each output token returned in the `content` of + `message`. This option is currently not available on the `gpt-4-vision-preview` + model. + + max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the chat + completion. The total length of input tokens and generated tokens is limited by the model's context length. @@ -140,7 +148,8 @@ def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) - response_format: An object specifying the format that the model must output. + response_format: An object specifying the format that the model must output. Compatible with + `gpt-4-1106-preview` and `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -188,6 +197,10 @@ def create( tool. Use this to provide a list of functions the model may generate JSON inputs for. + top_logprobs: An integer between 0 and 5 specifying the number of most likely tokens to return + at each token position, each with an associated log probability. `logprobs` must + be set to `true` if this parameter is used. + top_p: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. @@ -237,6 +250,7 @@ def create( function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: List[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -246,6 +260,7 @@ def create( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, tools: List[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, + top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -287,7 +302,7 @@ def create( particular function via `{"name": "my_function"}` forces the model to call that function. - `none` is the default when no functions are present. `auto`` is the default if + `none` is the default when no functions are present. `auto` is the default if functions are present. functions: Deprecated in favor of `tools`. @@ -303,7 +318,13 @@ def create( increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. - max_tokens: The maximum number of [tokens](/tokenizer) to generate in the chat completion. + logprobs: Whether to return log probabilities of the output tokens or not. If true, + returns the log probabilities of each output token returned in the `content` of + `message`. This option is currently not available on the `gpt-4-vision-preview` + model. + + max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the chat + completion. The total length of input tokens and generated tokens is limited by the model's context length. @@ -320,7 +341,8 @@ def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) - response_format: An object specifying the format that the model must output. + response_format: An object specifying the format that the model must output. Compatible with + `gpt-4-1106-preview` and `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -361,6 +383,10 @@ def create( tool. Use this to provide a list of functions the model may generate JSON inputs for. + top_logprobs: An integer between 0 and 5 specifying the number of most likely tokens to return + at each token position, each with an associated log probability. `logprobs` must + be set to `true` if this parameter is used. + top_p: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. @@ -410,6 +436,7 @@ def create( function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: List[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -419,6 +446,7 @@ def create( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, tools: List[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, + top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -460,7 +488,7 @@ def create( particular function via `{"name": "my_function"}` forces the model to call that function. - `none` is the default when no functions are present. `auto`` is the default if + `none` is the default when no functions are present. `auto` is the default if functions are present. functions: Deprecated in favor of `tools`. @@ -476,7 +504,13 @@ def create( increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. - max_tokens: The maximum number of [tokens](/tokenizer) to generate in the chat completion. + logprobs: Whether to return log probabilities of the output tokens or not. If true, + returns the log probabilities of each output token returned in the `content` of + `message`. This option is currently not available on the `gpt-4-vision-preview` + model. + + max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the chat + completion. The total length of input tokens and generated tokens is limited by the model's context length. @@ -493,7 +527,8 @@ def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) - response_format: An object specifying the format that the model must output. + response_format: An object specifying the format that the model must output. Compatible with + `gpt-4-1106-preview` and `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -534,6 +569,10 @@ def create( tool. Use this to provide a list of functions the model may generate JSON inputs for. + top_logprobs: An integer between 0 and 5 specifying the number of most likely tokens to return + at each token position, each with an associated log probability. `logprobs` must + be set to `true` if this parameter is used. + top_p: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. @@ -582,6 +621,7 @@ def create( function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: List[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -592,6 +632,7 @@ def create( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, tools: List[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, + top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -611,6 +652,7 @@ def create( "function_call": function_call, "functions": functions, "logit_bias": logit_bias, + "logprobs": logprobs, "max_tokens": max_tokens, "n": n, "presence_penalty": presence_penalty, @@ -621,6 +663,7 @@ def create( "temperature": temperature, "tool_choice": tool_choice, "tools": tools, + "top_logprobs": top_logprobs, "top_p": top_p, "user": user, }, @@ -670,6 +713,7 @@ async def create( function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: List[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -680,6 +724,7 @@ async def create( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, tools: List[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, + top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -714,7 +759,7 @@ async def create( particular function via `{"name": "my_function"}` forces the model to call that function. - `none` is the default when no functions are present. `auto`` is the default if + `none` is the default when no functions are present. `auto` is the default if functions are present. functions: Deprecated in favor of `tools`. @@ -730,7 +775,13 @@ async def create( increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. - max_tokens: The maximum number of [tokens](/tokenizer) to generate in the chat completion. + logprobs: Whether to return log probabilities of the output tokens or not. If true, + returns the log probabilities of each output token returned in the `content` of + `message`. This option is currently not available on the `gpt-4-vision-preview` + model. + + max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the chat + completion. The total length of input tokens and generated tokens is limited by the model's context length. @@ -747,7 +798,8 @@ async def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) - response_format: An object specifying the format that the model must output. + response_format: An object specifying the format that the model must output. Compatible with + `gpt-4-1106-preview` and `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -795,6 +847,10 @@ async def create( tool. Use this to provide a list of functions the model may generate JSON inputs for. + top_logprobs: An integer between 0 and 5 specifying the number of most likely tokens to return + at each token position, each with an associated log probability. `logprobs` must + be set to `true` if this parameter is used. + top_p: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. @@ -844,6 +900,7 @@ async def create( function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: List[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -853,6 +910,7 @@ async def create( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, tools: List[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, + top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -894,7 +952,7 @@ async def create( particular function via `{"name": "my_function"}` forces the model to call that function. - `none` is the default when no functions are present. `auto`` is the default if + `none` is the default when no functions are present. `auto` is the default if functions are present. functions: Deprecated in favor of `tools`. @@ -910,7 +968,13 @@ async def create( increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. - max_tokens: The maximum number of [tokens](/tokenizer) to generate in the chat completion. + logprobs: Whether to return log probabilities of the output tokens or not. If true, + returns the log probabilities of each output token returned in the `content` of + `message`. This option is currently not available on the `gpt-4-vision-preview` + model. + + max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the chat + completion. The total length of input tokens and generated tokens is limited by the model's context length. @@ -927,7 +991,8 @@ async def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) - response_format: An object specifying the format that the model must output. + response_format: An object specifying the format that the model must output. Compatible with + `gpt-4-1106-preview` and `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -968,6 +1033,10 @@ async def create( tool. Use this to provide a list of functions the model may generate JSON inputs for. + top_logprobs: An integer between 0 and 5 specifying the number of most likely tokens to return + at each token position, each with an associated log probability. `logprobs` must + be set to `true` if this parameter is used. + top_p: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. @@ -1017,6 +1086,7 @@ async def create( function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: List[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -1026,6 +1096,7 @@ async def create( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, tools: List[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, + top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -1067,7 +1138,7 @@ async def create( particular function via `{"name": "my_function"}` forces the model to call that function. - `none` is the default when no functions are present. `auto`` is the default if + `none` is the default when no functions are present. `auto` is the default if functions are present. functions: Deprecated in favor of `tools`. @@ -1083,7 +1154,13 @@ async def create( increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token. - max_tokens: The maximum number of [tokens](/tokenizer) to generate in the chat completion. + logprobs: Whether to return log probabilities of the output tokens or not. If true, + returns the log probabilities of each output token returned in the `content` of + `message`. This option is currently not available on the `gpt-4-vision-preview` + model. + + max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the chat + completion. The total length of input tokens and generated tokens is limited by the model's context length. @@ -1100,7 +1177,8 @@ async def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) - response_format: An object specifying the format that the model must output. + response_format: An object specifying the format that the model must output. Compatible with + `gpt-4-1106-preview` and `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -1141,6 +1219,10 @@ async def create( tool. Use this to provide a list of functions the model may generate JSON inputs for. + top_logprobs: An integer between 0 and 5 specifying the number of most likely tokens to return + at each token position, each with an associated log probability. `logprobs` must + be set to `true` if this parameter is used. + top_p: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. @@ -1189,6 +1271,7 @@ async def create( function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: List[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -1199,6 +1282,7 @@ async def create( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, tools: List[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, + top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -1218,6 +1302,7 @@ async def create( "function_call": function_call, "functions": functions, "logit_bias": logit_bias, + "logprobs": logprobs, "max_tokens": max_tokens, "n": n, "presence_penalty": presence_penalty, @@ -1228,6 +1313,7 @@ async def create( "temperature": temperature, "tool_choice": tool_choice, "tools": tools, + "top_logprobs": top_logprobs, "top_p": top_p, "user": user, }, diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index 93e1155a91..d22e288054 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -119,14 +119,15 @@ def create( As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token from being generated. - logprobs: Include the log probabilities on the `logprobs` most likely tokens, as well the - chosen tokens. For example, if `logprobs` is 5, the API will return a list of - the 5 most likely tokens. The API will always return the `logprob` of the - sampled token, so there may be up to `logprobs+1` elements in the response. + logprobs: Include the log probabilities on the `logprobs` most likely output tokens, as + well the chosen tokens. For example, if `logprobs` is 5, the API will return a + list of the 5 most likely tokens. The API will always return the `logprob` of + the sampled token, so there may be up to `logprobs+1` elements in the response. The maximum value for `logprobs` is 5. - max_tokens: The maximum number of [tokens](/tokenizer) to generate in the completion. + max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the + completion. The token count of your prompt plus `max_tokens` cannot exceed the model's context length. @@ -288,14 +289,15 @@ def create( As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token from being generated. - logprobs: Include the log probabilities on the `logprobs` most likely tokens, as well the - chosen tokens. For example, if `logprobs` is 5, the API will return a list of - the 5 most likely tokens. The API will always return the `logprob` of the - sampled token, so there may be up to `logprobs+1` elements in the response. + logprobs: Include the log probabilities on the `logprobs` most likely output tokens, as + well the chosen tokens. For example, if `logprobs` is 5, the API will return a + list of the 5 most likely tokens. The API will always return the `logprob` of + the sampled token, so there may be up to `logprobs+1` elements in the response. The maximum value for `logprobs` is 5. - max_tokens: The maximum number of [tokens](/tokenizer) to generate in the completion. + max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the + completion. The token count of your prompt plus `max_tokens` cannot exceed the model's context length. @@ -450,14 +452,15 @@ def create( As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token from being generated. - logprobs: Include the log probabilities on the `logprobs` most likely tokens, as well the - chosen tokens. For example, if `logprobs` is 5, the API will return a list of - the 5 most likely tokens. The API will always return the `logprob` of the - sampled token, so there may be up to `logprobs+1` elements in the response. + logprobs: Include the log probabilities on the `logprobs` most likely output tokens, as + well the chosen tokens. For example, if `logprobs` is 5, the API will return a + list of the 5 most likely tokens. The API will always return the `logprob` of + the sampled token, so there may be up to `logprobs+1` elements in the response. The maximum value for `logprobs` is 5. - max_tokens: The maximum number of [tokens](/tokenizer) to generate in the completion. + max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the + completion. The token count of your prompt plus `max_tokens` cannot exceed the model's context length. @@ -687,14 +690,15 @@ async def create( As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token from being generated. - logprobs: Include the log probabilities on the `logprobs` most likely tokens, as well the - chosen tokens. For example, if `logprobs` is 5, the API will return a list of - the 5 most likely tokens. The API will always return the `logprob` of the - sampled token, so there may be up to `logprobs+1` elements in the response. + logprobs: Include the log probabilities on the `logprobs` most likely output tokens, as + well the chosen tokens. For example, if `logprobs` is 5, the API will return a + list of the 5 most likely tokens. The API will always return the `logprob` of + the sampled token, so there may be up to `logprobs+1` elements in the response. The maximum value for `logprobs` is 5. - max_tokens: The maximum number of [tokens](/tokenizer) to generate in the completion. + max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the + completion. The token count of your prompt plus `max_tokens` cannot exceed the model's context length. @@ -856,14 +860,15 @@ async def create( As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token from being generated. - logprobs: Include the log probabilities on the `logprobs` most likely tokens, as well the - chosen tokens. For example, if `logprobs` is 5, the API will return a list of - the 5 most likely tokens. The API will always return the `logprob` of the - sampled token, so there may be up to `logprobs+1` elements in the response. + logprobs: Include the log probabilities on the `logprobs` most likely output tokens, as + well the chosen tokens. For example, if `logprobs` is 5, the API will return a + list of the 5 most likely tokens. The API will always return the `logprob` of + the sampled token, so there may be up to `logprobs+1` elements in the response. The maximum value for `logprobs` is 5. - max_tokens: The maximum number of [tokens](/tokenizer) to generate in the completion. + max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the + completion. The token count of your prompt plus `max_tokens` cannot exceed the model's context length. @@ -1018,14 +1023,15 @@ async def create( As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token from being generated. - logprobs: Include the log probabilities on the `logprobs` most likely tokens, as well the - chosen tokens. For example, if `logprobs` is 5, the API will return a list of - the 5 most likely tokens. The API will always return the `logprob` of the - sampled token, so there may be up to `logprobs+1` elements in the response. + logprobs: Include the log probabilities on the `logprobs` most likely output tokens, as + well the chosen tokens. For example, if `logprobs` is 5, the API will return a + list of the 5 most likely tokens. The API will always return the `logprob` of + the sampled token, so there may be up to `logprobs+1` elements in the response. The maximum value for `logprobs` is 5. - max_tokens: The maximum number of [tokens](/tokenizer) to generate in the completion. + max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the + completion. The token count of your prompt plus `max_tokens` cannot exceed the model's context length. diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index ed52bc3d51..e4d978d3af 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -51,7 +51,8 @@ def create( The size of all the files uploaded by one organization can be up to 100 GB. - The size of individual files can be a maximum of 512 MB. See the + The size of individual files can be a maximum of 512 MB or 2 million tokens for + Assistants. See the [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) to learn more about the types of files supported. The Fine-tuning API only supports `.jsonl` files. @@ -314,7 +315,8 @@ async def create( The size of all the files uploaded by one organization can be up to 100 GB. - The size of individual files can be a maximum of 512 MB. See the + The size of individual files can be a maximum of 512 MB or 2 million tokens for + Assistants. See the [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) to learn more about the types of files supported. The Fine-tuning API only supports `.jsonl` files. diff --git a/src/openai/types/beta/threads/runs/message_creation_step_details.py b/src/openai/types/beta/threads/runs/message_creation_step_details.py index 29f9106ec0..13f9398515 100644 --- a/src/openai/types/beta/threads/runs/message_creation_step_details.py +++ b/src/openai/types/beta/threads/runs/message_creation_step_details.py @@ -16,4 +16,4 @@ class MessageCreationStepDetails(BaseModel): message_creation: MessageCreation type: Literal["message_creation"] - """Always `message_creation``.""" + """Always `message_creation`.""" diff --git a/src/openai/types/beta/threads/runs/run_step.py b/src/openai/types/beta/threads/runs/run_step.py index 536cf04ab1..5f8723b71a 100644 --- a/src/openai/types/beta/threads/runs/run_step.py +++ b/src/openai/types/beta/threads/runs/run_step.py @@ -66,7 +66,7 @@ class RunStep(BaseModel): """ object: Literal["thread.run.step"] - """The object type, which is always `thread.run.step``.""" + """The object type, which is always `thread.run.step`.""" run_id: str """ diff --git a/src/openai/types/chat/__init__.py b/src/openai/types/chat/__init__.py index 5fe182f41e..ba21982a2b 100644 --- a/src/openai/types/chat/__init__.py +++ b/src/openai/types/chat/__init__.py @@ -13,6 +13,9 @@ from .chat_completion_message_param import ( ChatCompletionMessageParam as ChatCompletionMessageParam, ) +from .chat_completion_token_logprob import ( + ChatCompletionTokenLogprob as ChatCompletionTokenLogprob, +) from .chat_completion_message_tool_call import ( ChatCompletionMessageToolCall as ChatCompletionMessageToolCall, ) diff --git a/src/openai/types/chat/chat_completion.py b/src/openai/types/chat/chat_completion.py index da12ee7c07..055280c347 100644 --- a/src/openai/types/chat/chat_completion.py +++ b/src/openai/types/chat/chat_completion.py @@ -6,8 +6,14 @@ from ..._models import BaseModel from ..completion_usage import CompletionUsage from .chat_completion_message import ChatCompletionMessage +from .chat_completion_token_logprob import ChatCompletionTokenLogprob -__all__ = ["ChatCompletion", "Choice"] +__all__ = ["ChatCompletion", "Choice", "ChoiceLogprobs"] + + +class ChoiceLogprobs(BaseModel): + content: Optional[List[ChatCompletionTokenLogprob]] + """A list of message content tokens with log probability information.""" class Choice(BaseModel): @@ -24,6 +30,9 @@ class Choice(BaseModel): index: int """The index of the choice in the list of choices.""" + logprobs: Optional[ChoiceLogprobs] + """Log probability information for the choice.""" + message: ChatCompletionMessage """A chat completion message generated by the model.""" diff --git a/src/openai/types/chat/chat_completion_chunk.py b/src/openai/types/chat/chat_completion_chunk.py index 6be046b01e..ccc7ad79ec 100644 --- a/src/openai/types/chat/chat_completion_chunk.py +++ b/src/openai/types/chat/chat_completion_chunk.py @@ -4,6 +4,7 @@ from typing_extensions import Literal from ..._models import BaseModel +from .chat_completion_token_logprob import ChatCompletionTokenLogprob __all__ = [ "ChatCompletionChunk", @@ -12,6 +13,7 @@ "ChoiceDeltaFunctionCall", "ChoiceDeltaToolCall", "ChoiceDeltaToolCallFunction", + "ChoiceLogprobs", ] @@ -70,6 +72,11 @@ class ChoiceDelta(BaseModel): tool_calls: Optional[List[ChoiceDeltaToolCall]] = None +class ChoiceLogprobs(BaseModel): + content: Optional[List[ChatCompletionTokenLogprob]] + """A list of message content tokens with log probability information.""" + + class Choice(BaseModel): delta: ChoiceDelta """A chat completion delta generated by streamed model responses.""" @@ -87,6 +94,9 @@ class Choice(BaseModel): index: int """The index of the choice in the list of choices.""" + logprobs: Optional[ChoiceLogprobs] = None + """Log probability information for the choice.""" + class ChatCompletionChunk(BaseModel): id: str diff --git a/src/openai/types/chat/chat_completion_function_message_param.py b/src/openai/types/chat/chat_completion_function_message_param.py index 593571c0d2..3f9a1a9039 100644 --- a/src/openai/types/chat/chat_completion_function_message_param.py +++ b/src/openai/types/chat/chat_completion_function_message_param.py @@ -2,13 +2,14 @@ from __future__ import annotations +from typing import Optional from typing_extensions import Literal, Required, TypedDict __all__ = ["ChatCompletionFunctionMessageParam"] class ChatCompletionFunctionMessageParam(TypedDict, total=False): - content: Required[str] + content: Required[Optional[str]] """The contents of the function message.""" name: Required[str] diff --git a/src/openai/types/chat/chat_completion_token_logprob.py b/src/openai/types/chat/chat_completion_token_logprob.py new file mode 100644 index 0000000000..8896da8b85 --- /dev/null +++ b/src/openai/types/chat/chat_completion_token_logprob.py @@ -0,0 +1,47 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import List, Optional + +from ..._models import BaseModel + +__all__ = ["ChatCompletionTokenLogprob", "TopLogprob"] + + +class TopLogprob(BaseModel): + token: str + """The token.""" + + bytes: Optional[List[int]] + """A list of integers representing the UTF-8 bytes representation of the token. + + Useful in instances where characters are represented by multiple tokens and + their byte representations must be combined to generate the correct text + representation. Can be `null` if there is no bytes representation for the token. + """ + + logprob: float + """The log probability of this token.""" + + +class ChatCompletionTokenLogprob(BaseModel): + token: str + """The token.""" + + bytes: Optional[List[int]] + """A list of integers representing the UTF-8 bytes representation of the token. + + Useful in instances where characters are represented by multiple tokens and + their byte representations must be combined to generate the correct text + representation. Can be `null` if there is no bytes representation for the token. + """ + + logprob: float + """The log probability of this token.""" + + top_logprobs: List[TopLogprob] + """List of the most likely tokens and their log probability, at this token + position. + + In rare cases, there may be fewer than the number of requested `top_logprobs` + returned. + """ diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index e8098f7b77..41b71efa04 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -78,7 +78,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): particular function via `{"name": "my_function"}` forces the model to call that function. - `none` is the default when no functions are present. `auto`` is the default if + `none` is the default when no functions are present. `auto` is the default if functions are present. """ @@ -99,8 +99,18 @@ class CompletionCreateParamsBase(TypedDict, total=False): or exclusive selection of the relevant token. """ + logprobs: Optional[bool] + """Whether to return log probabilities of the output tokens or not. + + If true, returns the log probabilities of each output token returned in the + `content` of `message`. This option is currently not available on the + `gpt-4-vision-preview` model. + """ + max_tokens: Optional[int] - """The maximum number of [tokens](/tokenizer) to generate in the chat completion. + """ + The maximum number of [tokens](/tokenizer) that can be generated in the chat + completion. The total length of input tokens and generated tokens is limited by the model's context length. @@ -127,6 +137,8 @@ class CompletionCreateParamsBase(TypedDict, total=False): response_format: ResponseFormat """An object specifying the format that the model must output. + Compatible with `gpt-4-1106-preview` and `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -180,6 +192,13 @@ class CompletionCreateParamsBase(TypedDict, total=False): functions the model may generate JSON inputs for. """ + top_logprobs: Optional[int] + """ + An integer between 0 and 5 specifying the number of most likely tokens to return + at each token position, each with an associated log probability. `logprobs` must + be set to `true` if this parameter is used. + """ + top_p: Optional[float] """ An alternative to sampling with temperature, called nucleus sampling, where the diff --git a/src/openai/types/completion_create_params.py b/src/openai/types/completion_create_params.py index 488fe34893..ab6609a06b 100644 --- a/src/openai/types/completion_create_params.py +++ b/src/openai/types/completion_create_params.py @@ -88,16 +88,18 @@ class CompletionCreateParamsBase(TypedDict, total=False): logprobs: Optional[int] """ - Include the log probabilities on the `logprobs` most likely tokens, as well the - chosen tokens. For example, if `logprobs` is 5, the API will return a list of - the 5 most likely tokens. The API will always return the `logprob` of the - sampled token, so there may be up to `logprobs+1` elements in the response. + Include the log probabilities on the `logprobs` most likely output tokens, as + well the chosen tokens. For example, if `logprobs` is 5, the API will return a + list of the 5 most likely tokens. The API will always return the `logprob` of + the sampled token, so there may be up to `logprobs+1` elements in the response. The maximum value for `logprobs` is 5. """ max_tokens: Optional[int] - """The maximum number of [tokens](/tokenizer) to generate in the completion. + """ + The maximum number of [tokens](/tokenizer) that can be generated in the + completion. The token count of your prompt plus `max_tokens` cannot exceed the model's context length. diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index 0b58a4109d..985d5f1c04 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -54,6 +54,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: } ], logit_bias={"foo": 0}, + logprobs=True, max_tokens=0, n=1, presence_penalty=-2, @@ -89,6 +90,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: }, }, ], + top_logprobs=0, top_p=1, user="user-1234", ) @@ -144,6 +146,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: } ], logit_bias={"foo": 0}, + logprobs=True, max_tokens=0, n=1, presence_penalty=-2, @@ -178,6 +181,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: }, }, ], + top_logprobs=0, top_p=1, user="user-1234", ) @@ -237,6 +241,7 @@ async def test_method_create_with_all_params_overload_1(self, client: AsyncOpenA } ], logit_bias={"foo": 0}, + logprobs=True, max_tokens=0, n=1, presence_penalty=-2, @@ -272,6 +277,7 @@ async def test_method_create_with_all_params_overload_1(self, client: AsyncOpenA }, }, ], + top_logprobs=0, top_p=1, user="user-1234", ) @@ -327,6 +333,7 @@ async def test_method_create_with_all_params_overload_2(self, client: AsyncOpenA } ], logit_bias={"foo": 0}, + logprobs=True, max_tokens=0, n=1, presence_penalty=-2, @@ -361,6 +368,7 @@ async def test_method_create_with_all_params_overload_2(self, client: AsyncOpenA }, }, ], + top_logprobs=0, top_p=1, user="user-1234", ) From 15d3aba42ed40713ef2d2757462d19846049523a Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Sat, 16 Dec 2023 19:48:23 -0500 Subject: [PATCH 157/816] release: 1.5.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 3e9af1b3ae..fbd9082d71 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.4.0" + ".": "1.5.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index fc6366c4ff..757d79af62 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.5.0 (2023-12-17) + +Full Changelog: [v1.4.0...v1.5.0](https://github.com/openai/openai-python/compare/v1.4.0...v1.5.0) + +### Features + +* **api:** add token logprobs to chat completions ([#980](https://github.com/openai/openai-python/issues/980)) ([f50e962](https://github.com/openai/openai-python/commit/f50e962b930bd682a4299143b2995337e8571273)) + + +### Chores + +* **ci:** run release workflow once per day ([#978](https://github.com/openai/openai-python/issues/978)) ([215476a](https://github.com/openai/openai-python/commit/215476a0b99e0c92ab3e44ddd25de207af32d160)) + ## 1.4.0 (2023-12-15) Full Changelog: [v1.3.9...v1.4.0](https://github.com/openai/openai-python/compare/v1.3.9...v1.4.0) diff --git a/pyproject.toml b/pyproject.toml index f96442aaa4..0cf709a726 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.4.0" +version = "1.5.0" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index e43b6069a8..9dbb5b1401 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.4.0" # x-release-please-version +__version__ = "1.5.0" # x-release-please-version From 7367256070a975921ed4430f55d17dc0a9319f21 Mon Sep 17 00:00:00 2001 From: franz101 Date: Mon, 18 Dec 2023 10:57:23 -0500 Subject: [PATCH 158/816] Upgrade examples to latest version (no legacy models) (#697) * Update streaming.py Removed legacy model * Update streaming.py * more upgrades --- examples/async_demo.py | 2 +- examples/streaming.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/async_demo.py b/examples/async_demo.py index 92c267c38f..793b4e43fb 100755 --- a/examples/async_demo.py +++ b/examples/async_demo.py @@ -10,7 +10,7 @@ async def main() -> None: stream = await client.completions.create( - model="text-davinci-003", + model="gpt-3.5-turbo-instruct", prompt="Say this is a test", stream=True, ) diff --git a/examples/streaming.py b/examples/streaming.py index 168877dfc5..368fa5f911 100755 --- a/examples/streaming.py +++ b/examples/streaming.py @@ -13,7 +13,7 @@ def sync_main() -> None: client = OpenAI() response = client.completions.create( - model="text-davinci-002", + model="gpt-3.5-turbo-instruct", prompt="1,2,3,", max_tokens=5, temperature=0, @@ -33,7 +33,7 @@ def sync_main() -> None: async def async_main() -> None: client = AsyncOpenAI() response = await client.completions.create( - model="text-davinci-002", + model="gpt-3.5-turbo-instruct", prompt="1,2,3,", max_tokens=5, temperature=0, From b56cf7230a69d657274dacd65340578d3307e9ac Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 18 Dec 2023 09:06:05 -0500 Subject: [PATCH 159/816] chore(internal): fix binary response tests (#983) --- tests/api_resources/audio/test_speech.py | 6 ++---- tests/api_resources/test_files.py | 12 ++++-------- 2 files changed, 6 insertions(+), 12 deletions(-) diff --git a/tests/api_resources/audio/test_speech.py b/tests/api_resources/audio/test_speech.py index 50b00b73b4..23f5303153 100644 --- a/tests/api_resources/audio/test_speech.py +++ b/tests/api_resources/audio/test_speech.py @@ -39,8 +39,7 @@ def test_method_create(self, client: OpenAI, respx_mock: MockRouter) -> None: @pytest.mark.respx(base_url=base_url) def test_method_create_with_all_params(self, client: OpenAI, respx_mock: MockRouter) -> None: respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) - speech = respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) - client.audio.speech.create( + speech = client.audio.speech.create( input="string", model="string", voice="alloy", @@ -89,8 +88,7 @@ async def test_method_create(self, client: AsyncOpenAI, respx_mock: MockRouter) @pytest.mark.respx(base_url=base_url) async def test_method_create_with_all_params(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) - speech = respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) - await client.audio.speech.create( + speech = await client.audio.speech.create( input="string", model="string", voice="alloy", diff --git a/tests/api_resources/test_files.py b/tests/api_resources/test_files.py index e4cf493319..13ffca9773 100644 --- a/tests/api_resources/test_files.py +++ b/tests/api_resources/test_files.py @@ -95,22 +95,20 @@ def test_raw_response_delete(self, client: OpenAI) -> None: file = response.parse() assert_matches_type(FileDeleted, file, path=["response"]) - @pytest.mark.skip(reason="mocked response isn't working yet") @parametrize @pytest.mark.respx(base_url=base_url) def test_method_content(self, client: OpenAI, respx_mock: MockRouter) -> None: - respx_mock.get("/files/{file_id}/content").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + respx_mock.get("/files/string/content").mock(return_value=httpx.Response(200, json={"foo": "bar"})) file = client.files.content( "string", ) assert isinstance(file, BinaryResponseContent) assert file.json() == {"foo": "bar"} - @pytest.mark.skip(reason="mocked response isn't working yet") @parametrize @pytest.mark.respx(base_url=base_url) def test_raw_response_content(self, client: OpenAI, respx_mock: MockRouter) -> None: - respx_mock.get("/files/{file_id}/content").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + respx_mock.get("/files/string/content").mock(return_value=httpx.Response(200, json={"foo": "bar"})) response = client.files.with_raw_response.content( "string", ) @@ -212,22 +210,20 @@ async def test_raw_response_delete(self, client: AsyncOpenAI) -> None: file = response.parse() assert_matches_type(FileDeleted, file, path=["response"]) - @pytest.mark.skip(reason="mocked response isn't working yet") @parametrize @pytest.mark.respx(base_url=base_url) async def test_method_content(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: - respx_mock.get("/files/{file_id}/content").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + respx_mock.get("/files/string/content").mock(return_value=httpx.Response(200, json={"foo": "bar"})) file = await client.files.content( "string", ) assert isinstance(file, BinaryResponseContent) assert file.json() == {"foo": "bar"} - @pytest.mark.skip(reason="mocked response isn't working yet") @parametrize @pytest.mark.respx(base_url=base_url) async def test_raw_response_content(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: - respx_mock.get("/files/{file_id}/content").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + respx_mock.get("/files/string/content").mock(return_value=httpx.Response(200, json={"foo": "bar"})) response = await client.files.with_raw_response.content( "string", ) From af20c30c78765f4ab6f4a11d0a4093c637eeba2c Mon Sep 17 00:00:00 2001 From: Logan Kilpatrick Date: Tue, 19 Dec 2023 00:53:24 +0900 Subject: [PATCH 160/816] chore(cli): fix typo in completions (#985) --- src/openai/cli/_api/completions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/openai/cli/_api/completions.py b/src/openai/cli/_api/completions.py index ce1036b224..cbdb35bf3a 100644 --- a/src/openai/cli/_api/completions.py +++ b/src/openai/cli/_api/completions.py @@ -57,7 +57,7 @@ def register(subparser: _SubParsersAction[ArgumentParser]) -> None: ) sub.add_argument( "--logprobs", - help="Include the log probabilites on the `logprobs` most likely tokens, as well the chosen tokens. So for example, if `logprobs` is 10, the API will return a list of the 10 most likely tokens. If `logprobs` is 0, only the chosen tokens will have logprobs returned.", + help="Include the log probabilities on the `logprobs` most likely tokens, as well the chosen tokens. So for example, if `logprobs` is 10, the API will return a list of the 10 most likely tokens. If `logprobs` is 0, only the chosen tokens will have logprobs returned.", type=int, ) sub.add_argument( From e847023b8171f6e7fcb8535a634e5107f6672945 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 18 Dec 2023 11:31:14 -0500 Subject: [PATCH 161/816] chore(cli): fix typo in completions (#986) --- examples/async_demo.py | 2 +- examples/streaming.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/async_demo.py b/examples/async_demo.py index 793b4e43fb..92c267c38f 100755 --- a/examples/async_demo.py +++ b/examples/async_demo.py @@ -10,7 +10,7 @@ async def main() -> None: stream = await client.completions.create( - model="gpt-3.5-turbo-instruct", + model="text-davinci-003", prompt="Say this is a test", stream=True, ) diff --git a/examples/streaming.py b/examples/streaming.py index 368fa5f911..168877dfc5 100755 --- a/examples/streaming.py +++ b/examples/streaming.py @@ -13,7 +13,7 @@ def sync_main() -> None: client = OpenAI() response = client.completions.create( - model="gpt-3.5-turbo-instruct", + model="text-davinci-002", prompt="1,2,3,", max_tokens=5, temperature=0, @@ -33,7 +33,7 @@ def sync_main() -> None: async def async_main() -> None: client = AsyncOpenAI() response = await client.completions.create( - model="gpt-3.5-turbo-instruct", + model="text-davinci-002", prompt="1,2,3,", max_tokens=5, temperature=0, From a045ef843ef218790cb704dd8acfaf4dc270f1e5 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 18 Dec 2023 22:33:10 -0500 Subject: [PATCH 162/816] docs: upgrade models in examples to latest version (#989) --- examples/async_demo.py | 2 +- examples/streaming.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/async_demo.py b/examples/async_demo.py index 92c267c38f..793b4e43fb 100755 --- a/examples/async_demo.py +++ b/examples/async_demo.py @@ -10,7 +10,7 @@ async def main() -> None: stream = await client.completions.create( - model="text-davinci-003", + model="gpt-3.5-turbo-instruct", prompt="Say this is a test", stream=True, ) diff --git a/examples/streaming.py b/examples/streaming.py index 168877dfc5..368fa5f911 100755 --- a/examples/streaming.py +++ b/examples/streaming.py @@ -13,7 +13,7 @@ def sync_main() -> None: client = OpenAI() response = client.completions.create( - model="text-davinci-002", + model="gpt-3.5-turbo-instruct", prompt="1,2,3,", max_tokens=5, temperature=0, @@ -33,7 +33,7 @@ def sync_main() -> None: async def async_main() -> None: client = AsyncOpenAI() response = await client.completions.create( - model="text-davinci-002", + model="gpt-3.5-turbo-instruct", prompt="1,2,3,", max_tokens=5, temperature=0, From 3d6ca3e7fb5fea5e987b62e398cfff9effc48382 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 19 Dec 2023 07:30:56 -0500 Subject: [PATCH 163/816] chore(streaming): update constructor to use direct client names (#991) --- src/openai/_streaming.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/openai/_streaming.py b/src/openai/_streaming.py index e48324fc78..e323c59ac0 100644 --- a/src/openai/_streaming.py +++ b/src/openai/_streaming.py @@ -12,7 +12,7 @@ from ._exceptions import APIError if TYPE_CHECKING: - from ._base_client import SyncAPIClient, AsyncAPIClient + from ._client import OpenAI, AsyncOpenAI class Stream(Generic[ResponseT]): @@ -25,7 +25,7 @@ def __init__( *, cast_to: type[ResponseT], response: httpx.Response, - client: SyncAPIClient, + client: OpenAI, ) -> None: self.response = response self._cast_to = cast_to @@ -79,7 +79,7 @@ def __init__( *, cast_to: type[ResponseT], response: httpx.Response, - client: AsyncAPIClient, + client: AsyncOpenAI, ) -> None: self.response = response self._cast_to = cast_to From 052e611a7f75a0c82eed56f88333d0cf7d599da7 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 19 Dec 2023 11:23:44 -0500 Subject: [PATCH 164/816] chore(internal): minor utils restructuring (#992) --- src/openai/_response.py | 17 +++---- src/openai/_streaming.py | 71 ++++++++++++++++++++++------- src/openai/_types.py | 14 ++++++ src/openai/_utils/__init__.py | 15 ++++--- src/openai/_utils/_streams.py | 12 +++++ src/openai/_utils/_transform.py | 5 +-- src/openai/_utils/_typing.py | 80 +++++++++++++++++++++++++++++++++ src/openai/_utils/_utils.py | 35 +-------------- 8 files changed, 183 insertions(+), 66 deletions(-) create mode 100644 src/openai/_utils/_streams.py create mode 100644 src/openai/_utils/_typing.py diff --git a/src/openai/_response.py b/src/openai/_response.py index 933c37525e..6b7c86e544 100644 --- a/src/openai/_response.py +++ b/src/openai/_response.py @@ -5,12 +5,12 @@ import datetime import functools from typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, cast -from typing_extensions import Awaitable, ParamSpec, get_args, override, get_origin +from typing_extensions import Awaitable, ParamSpec, override, get_origin import httpx from ._types import NoneType, UnknownResponse, BinaryResponseContent -from ._utils import is_given +from ._utils import is_given, extract_type_var_from_base from ._models import BaseModel, is_basemodel from ._constants import RAW_RESPONSE_HEADER from ._exceptions import APIResponseValidationError @@ -221,12 +221,13 @@ def __init__(self) -> None: def _extract_stream_chunk_type(stream_cls: type) -> type: - args = get_args(stream_cls) - if not args: - raise TypeError( - f"Expected stream_cls to have been given a generic type argument, e.g. Stream[Foo] but received {stream_cls}", - ) - return cast(type, args[0]) + from ._base_client import Stream, AsyncStream + + return extract_type_var_from_base( + stream_cls, + index=0, + generic_bases=cast("tuple[type, ...]", (Stream, AsyncStream)), + ) def to_raw_response_wrapper(func: Callable[P, R]) -> Callable[P, APIResponse[R]]: diff --git a/src/openai/_streaming.py b/src/openai/_streaming.py index e323c59ac0..f1896a242a 100644 --- a/src/openai/_streaming.py +++ b/src/openai/_streaming.py @@ -2,12 +2,12 @@ from __future__ import annotations import json -from typing import TYPE_CHECKING, Any, Generic, Iterator, AsyncIterator -from typing_extensions import override +from types import TracebackType +from typing import TYPE_CHECKING, Any, Generic, TypeVar, Iterator, AsyncIterator, cast +from typing_extensions import Self, override import httpx -from ._types import ResponseT from ._utils import is_mapping from ._exceptions import APIError @@ -15,7 +15,10 @@ from ._client import OpenAI, AsyncOpenAI -class Stream(Generic[ResponseT]): +_T = TypeVar("_T") + + +class Stream(Generic[_T]): """Provides the core interface to iterate over a synchronous stream response.""" response: httpx.Response @@ -23,7 +26,7 @@ class Stream(Generic[ResponseT]): def __init__( self, *, - cast_to: type[ResponseT], + cast_to: type[_T], response: httpx.Response, client: OpenAI, ) -> None: @@ -33,18 +36,18 @@ def __init__( self._decoder = SSEDecoder() self._iterator = self.__stream__() - def __next__(self) -> ResponseT: + def __next__(self) -> _T: return self._iterator.__next__() - def __iter__(self) -> Iterator[ResponseT]: + def __iter__(self) -> Iterator[_T]: for item in self._iterator: yield item def _iter_events(self) -> Iterator[ServerSentEvent]: yield from self._decoder.iter(self.response.iter_lines()) - def __stream__(self) -> Iterator[ResponseT]: - cast_to = self._cast_to + def __stream__(self) -> Iterator[_T]: + cast_to = cast(Any, self._cast_to) response = self.response process_data = self._client._process_response_data iterator = self._iter_events() @@ -68,8 +71,27 @@ def __stream__(self) -> Iterator[ResponseT]: for _sse in iterator: ... + def __enter__(self) -> Self: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.close() + + def close(self) -> None: + """ + Close the response and release the connection. + + Automatically called if the response body is read to completion. + """ + self.response.close() -class AsyncStream(Generic[ResponseT]): + +class AsyncStream(Generic[_T]): """Provides the core interface to iterate over an asynchronous stream response.""" response: httpx.Response @@ -77,7 +99,7 @@ class AsyncStream(Generic[ResponseT]): def __init__( self, *, - cast_to: type[ResponseT], + cast_to: type[_T], response: httpx.Response, client: AsyncOpenAI, ) -> None: @@ -87,10 +109,10 @@ def __init__( self._decoder = SSEDecoder() self._iterator = self.__stream__() - async def __anext__(self) -> ResponseT: + async def __anext__(self) -> _T: return await self._iterator.__anext__() - async def __aiter__(self) -> AsyncIterator[ResponseT]: + async def __aiter__(self) -> AsyncIterator[_T]: async for item in self._iterator: yield item @@ -98,8 +120,8 @@ async def _iter_events(self) -> AsyncIterator[ServerSentEvent]: async for sse in self._decoder.aiter(self.response.aiter_lines()): yield sse - async def __stream__(self) -> AsyncIterator[ResponseT]: - cast_to = self._cast_to + async def __stream__(self) -> AsyncIterator[_T]: + cast_to = cast(Any, self._cast_to) response = self.response process_data = self._client._process_response_data iterator = self._iter_events() @@ -123,6 +145,25 @@ async def __stream__(self) -> AsyncIterator[ResponseT]: async for _sse in iterator: ... + async def __aenter__(self) -> Self: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + await self.close() + + async def close(self) -> None: + """ + Close the response and release the connection. + + Automatically called if the response body is read to completion. + """ + await self.response.aclose() + class ServerSentEvent: def __init__( diff --git a/src/openai/_types.py b/src/openai/_types.py index 8d543171eb..a20a4b4c1b 100644 --- a/src/openai/_types.py +++ b/src/openai/_types.py @@ -353,3 +353,17 @@ def get(self, __key: str) -> str | None: IncEx: TypeAlias = "set[int] | set[str] | dict[int, Any] | dict[str, Any] | None" PostParser = Callable[[Any], Any] + + +@runtime_checkable +class InheritsGeneric(Protocol): + """Represents a type that has inherited from `Generic` + The `__orig_bases__` property can be used to determine the resolved + type variable for a given base class. + """ + + __orig_bases__: tuple[_GenericAlias] + + +class _GenericAlias(Protocol): + __origin__: type[object] diff --git a/src/openai/_utils/__init__.py b/src/openai/_utils/__init__.py index 400ca9b828..a43201d3c7 100644 --- a/src/openai/_utils/__init__.py +++ b/src/openai/_utils/__init__.py @@ -9,13 +9,11 @@ from ._utils import parse_date as parse_date from ._utils import is_sequence as is_sequence from ._utils import coerce_float as coerce_float -from ._utils import is_list_type as is_list_type from ._utils import is_mapping_t as is_mapping_t from ._utils import removeprefix as removeprefix from ._utils import removesuffix as removesuffix from ._utils import extract_files as extract_files from ._utils import is_sequence_t as is_sequence_t -from ._utils import is_union_type as is_union_type from ._utils import required_args as required_args from ._utils import coerce_boolean as coerce_boolean from ._utils import coerce_integer as coerce_integer @@ -23,15 +21,20 @@ from ._utils import parse_datetime as parse_datetime from ._utils import strip_not_given as strip_not_given from ._utils import deepcopy_minimal as deepcopy_minimal -from ._utils import extract_type_arg as extract_type_arg -from ._utils import is_required_type as is_required_type from ._utils import get_async_library as get_async_library -from ._utils import is_annotated_type as is_annotated_type from ._utils import maybe_coerce_float as maybe_coerce_float from ._utils import get_required_header as get_required_header from ._utils import maybe_coerce_boolean as maybe_coerce_boolean from ._utils import maybe_coerce_integer as maybe_coerce_integer -from ._utils import strip_annotated_type as strip_annotated_type +from ._typing import is_list_type as is_list_type +from ._typing import is_union_type as is_union_type +from ._typing import extract_type_arg as extract_type_arg +from ._typing import is_required_type as is_required_type +from ._typing import is_annotated_type as is_annotated_type +from ._typing import strip_annotated_type as strip_annotated_type +from ._typing import extract_type_var_from_base as extract_type_var_from_base +from ._streams import consume_sync_iterator as consume_sync_iterator +from ._streams import consume_async_iterator as consume_async_iterator from ._transform import PropertyInfo as PropertyInfo from ._transform import transform as transform from ._transform import maybe_transform as maybe_transform diff --git a/src/openai/_utils/_streams.py b/src/openai/_utils/_streams.py new file mode 100644 index 0000000000..f4a0208f01 --- /dev/null +++ b/src/openai/_utils/_streams.py @@ -0,0 +1,12 @@ +from typing import Any +from typing_extensions import Iterator, AsyncIterator + + +def consume_sync_iterator(iterator: Iterator[Any]) -> None: + for _ in iterator: + ... + + +async def consume_async_iterator(iterator: AsyncIterator[Any]) -> None: + async for _ in iterator: + ... diff --git a/src/openai/_utils/_transform.py b/src/openai/_utils/_transform.py index 769f7362b9..9117559064 100644 --- a/src/openai/_utils/_transform.py +++ b/src/openai/_utils/_transform.py @@ -6,9 +6,8 @@ import pydantic -from ._utils import ( - is_list, - is_mapping, +from ._utils import is_list, is_mapping +from ._typing import ( is_list_type, is_union_type, extract_type_arg, diff --git a/src/openai/_utils/_typing.py b/src/openai/_utils/_typing.py new file mode 100644 index 0000000000..b5e2c2e397 --- /dev/null +++ b/src/openai/_utils/_typing.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +from typing import Any, cast +from typing_extensions import Required, Annotated, get_args, get_origin + +from .._types import InheritsGeneric +from .._compat import is_union as _is_union + + +def is_annotated_type(typ: type) -> bool: + return get_origin(typ) == Annotated + + +def is_list_type(typ: type) -> bool: + return (get_origin(typ) or typ) == list + + +def is_union_type(typ: type) -> bool: + return _is_union(get_origin(typ)) + + +def is_required_type(typ: type) -> bool: + return get_origin(typ) == Required + + +# Extracts T from Annotated[T, ...] or from Required[Annotated[T, ...]] +def strip_annotated_type(typ: type) -> type: + if is_required_type(typ) or is_annotated_type(typ): + return strip_annotated_type(cast(type, get_args(typ)[0])) + + return typ + + +def extract_type_arg(typ: type, index: int) -> type: + args = get_args(typ) + try: + return cast(type, args[index]) + except IndexError as err: + raise RuntimeError(f"Expected type {typ} to have a type argument at index {index} but it did not") from err + + +def extract_type_var_from_base(typ: type, *, generic_bases: tuple[type, ...], index: int) -> type: + """Given a type like `Foo[T]`, returns the generic type variable `T`. + + This also handles the case where a concrete subclass is given, e.g. + ```py + class MyResponse(Foo[bytes]): + ... + + extract_type_var(MyResponse, bases=(Foo,), index=0) -> bytes + ``` + """ + cls = cast(object, get_origin(typ) or typ) + if cls in generic_bases: + # we're given the class directly + return extract_type_arg(typ, index) + + # if a subclass is given + # --- + # this is needed as __orig_bases__ is not present in the typeshed stubs + # because it is intended to be for internal use only, however there does + # not seem to be a way to resolve generic TypeVars for inherited subclasses + # without using it. + if isinstance(cls, InheritsGeneric): + target_base_class: Any | None = None + for base in cls.__orig_bases__: + if base.__origin__ in generic_bases: + target_base_class = base + break + + if target_base_class is None: + raise RuntimeError( + "Could not find the generic base class;\n" + "This should never happen;\n" + f"Does {cls} inherit from one of {generic_bases} ?" + ) + + return extract_type_arg(target_base_class, index) + + raise RuntimeError(f"Could not resolve inner type variable at index {index} for {typ}") diff --git a/src/openai/_utils/_utils.py b/src/openai/_utils/_utils.py index c874d3682d..993462a66b 100644 --- a/src/openai/_utils/_utils.py +++ b/src/openai/_utils/_utils.py @@ -16,12 +16,11 @@ overload, ) from pathlib import Path -from typing_extensions import Required, Annotated, TypeGuard, get_args, get_origin +from typing_extensions import TypeGuard import sniffio from .._types import Headers, NotGiven, FileTypes, NotGivenOr, HeadersLike -from .._compat import is_union as _is_union from .._compat import parse_date as parse_date from .._compat import parse_datetime as parse_datetime @@ -166,38 +165,6 @@ def is_list(obj: object) -> TypeGuard[list[object]]: return isinstance(obj, list) -def is_annotated_type(typ: type) -> bool: - return get_origin(typ) == Annotated - - -def is_list_type(typ: type) -> bool: - return (get_origin(typ) or typ) == list - - -def is_union_type(typ: type) -> bool: - return _is_union(get_origin(typ)) - - -def is_required_type(typ: type) -> bool: - return get_origin(typ) == Required - - -# Extracts T from Annotated[T, ...] or from Required[Annotated[T, ...]] -def strip_annotated_type(typ: type) -> type: - if is_required_type(typ) or is_annotated_type(typ): - return strip_annotated_type(cast(type, get_args(typ)[0])) - - return typ - - -def extract_type_arg(typ: type, index: int) -> type: - args = get_args(typ) - try: - return cast(type, args[index]) - except IndexError as err: - raise RuntimeError(f"Expected type {typ} to have a type argument at index {index} but it did not") from err - - def deepcopy_minimal(item: _T) -> _T: """Minimal reimplementation of copy.deepcopy() that will only copy certain object types: From 00ef2f47d1492ecfcff2243cf2c054053dd62d04 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 19 Dec 2023 13:22:14 -0500 Subject: [PATCH 165/816] chore(internal): fix typos (#993) --- src/openai/_base_client.py | 2 +- src/openai/_streaming.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 92189617b5..481171a447 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -107,7 +107,7 @@ class PageInfo: - """Stores the necesary information to build the request to retrieve the next page. + """Stores the necessary information to build the request to retrieve the next page. Either `url` or `params` must be set. """ diff --git a/src/openai/_streaming.py b/src/openai/_streaming.py index f1896a242a..85cec70c11 100644 --- a/src/openai/_streaming.py +++ b/src/openai/_streaming.py @@ -60,7 +60,7 @@ def __stream__(self) -> Iterator[_T]: data = sse.json() if is_mapping(data) and data.get("error"): raise APIError( - message="An error ocurred during streaming", + message="An error occurred during streaming", request=self.response.request, body=data["error"], ) @@ -134,7 +134,7 @@ async def __stream__(self) -> AsyncIterator[_T]: data = sse.json() if is_mapping(data) and data.get("error"): raise APIError( - message="An error ocurred during streaming", + message="An error occurred during streaming", request=self.response.request, body=data["error"], ) From a893a19f82caef5ed7078a1bcf1e1b954e8e72b4 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 19 Dec 2023 14:05:05 -0500 Subject: [PATCH 166/816] chore(package): bump minimum typing-extensions to 4.7 (#994) --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 0cf709a726..24498b18fe 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -10,7 +10,7 @@ authors = [ dependencies = [ "httpx>=0.23.0, <1", "pydantic>=1.9.0, <3", - "typing-extensions>=4.5, <5", + "typing-extensions>=4.7, <5", "anyio>=3.5.0, <5", "distro>=1.7.0, <2", "sniffio", From 53bca49e184091c4d71eeee86aacf7e974ff6c46 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 19 Dec 2023 18:17:29 -0500 Subject: [PATCH 167/816] feat(api): add additional instructions for runs (#995) --- .../resources/beta/threads/runs/runs.py | 22 +++++++++++++++---- .../types/beta/threads/run_create_params.py | 14 +++++++++--- tests/api_resources/beta/threads/test_runs.py | 2 ++ 3 files changed, 31 insertions(+), 7 deletions(-) diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 969bfab70a..aea3b8cefc 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -42,6 +42,7 @@ def create( thread_id: str, *, assistant_id: str, + additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, @@ -61,8 +62,13 @@ def create( [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run. - instructions: Override the default system message of the assistant. This is useful for - modifying the behavior on a per-run basis. + additional_instructions: Appends additional instructions at the end of the instructions for the run. This + is useful for modifying the behavior on a per-run basis without overriding other + instructions. + + instructions: Overrides the + [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) + of the assistant. This is useful for modifying the behavior on a per-run basis. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys @@ -91,6 +97,7 @@ def create( body=maybe_transform( { "assistant_id": assistant_id, + "additional_instructions": additional_instructions, "instructions": instructions, "metadata": metadata, "model": model, @@ -332,6 +339,7 @@ async def create( thread_id: str, *, assistant_id: str, + additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, @@ -351,8 +359,13 @@ async def create( [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run. - instructions: Override the default system message of the assistant. This is useful for - modifying the behavior on a per-run basis. + additional_instructions: Appends additional instructions at the end of the instructions for the run. This + is useful for modifying the behavior on a per-run basis without overriding other + instructions. + + instructions: Overrides the + [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) + of the assistant. This is useful for modifying the behavior on a per-run basis. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys @@ -381,6 +394,7 @@ async def create( body=maybe_transform( { "assistant_id": assistant_id, + "additional_instructions": additional_instructions, "instructions": instructions, "metadata": metadata, "model": model, diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index df92f4fd2c..a4f41a9338 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -24,10 +24,18 @@ class RunCreateParams(TypedDict, total=False): execute this run. """ - instructions: Optional[str] - """Override the default system message of the assistant. + additional_instructions: Optional[str] + """Appends additional instructions at the end of the instructions for the run. - This is useful for modifying the behavior on a per-run basis. + This is useful for modifying the behavior on a per-run basis without overriding + other instructions. + """ + + instructions: Optional[str] + """ + Overrides the + [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) + of the assistant. This is useful for modifying the behavior on a per-run basis. """ metadata: Optional[object] diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index d323dfc354..494cae2656 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -34,6 +34,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: run = client.beta.threads.runs.create( "string", assistant_id="string", + additional_instructions="string", instructions="string", metadata={}, model="string", @@ -180,6 +181,7 @@ async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: run = await client.beta.threads.runs.create( "string", assistant_id="string", + additional_instructions="string", instructions="string", metadata={}, model="string", From 3ad4e8bc9d89d7a81586bf598289ff62b0a339b9 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 19 Dec 2023 18:18:08 -0500 Subject: [PATCH 168/816] release: 1.6.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 24 ++++++++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 27 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index fbd9082d71..7deae33804 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.5.0" + ".": "1.6.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 757d79af62..399e3aaebd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,29 @@ # Changelog +## 1.6.0 (2023-12-19) + +Full Changelog: [v1.5.0...v1.6.0](https://github.com/openai/openai-python/compare/v1.5.0...v1.6.0) + +### Features + +* **api:** add additional instructions for runs ([#995](https://github.com/openai/openai-python/issues/995)) ([7bf9b75](https://github.com/openai/openai-python/commit/7bf9b75067905449e83e828c12eb384022cff6ca)) + + +### Chores + +* **cli:** fix typo in completions ([#985](https://github.com/openai/openai-python/issues/985)) ([d1e9e8f](https://github.com/openai/openai-python/commit/d1e9e8f24df366bb7b796c55a98247c025d229f5)) +* **cli:** fix typo in completions ([#986](https://github.com/openai/openai-python/issues/986)) ([626bc34](https://github.com/openai/openai-python/commit/626bc34d82a7057bac99f8b556f9e5f60c261ee7)) +* **internal:** fix binary response tests ([#983](https://github.com/openai/openai-python/issues/983)) ([cfb7e30](https://github.com/openai/openai-python/commit/cfb7e308393f2e912e959dd10d68096dd5b3ab9c)) +* **internal:** fix typos ([#993](https://github.com/openai/openai-python/issues/993)) ([3b338a4](https://github.com/openai/openai-python/commit/3b338a401b206618774291ff8137deb0cc5f6b4c)) +* **internal:** minor utils restructuring ([#992](https://github.com/openai/openai-python/issues/992)) ([5ba576a](https://github.com/openai/openai-python/commit/5ba576ae38d2c4c4d32a21933e0d68e0bc2f0d49)) +* **package:** bump minimum typing-extensions to 4.7 ([#994](https://github.com/openai/openai-python/issues/994)) ([0c2da84](https://github.com/openai/openai-python/commit/0c2da84badf416f8b2213983f68bd2b6f9e52f2b)) +* **streaming:** update constructor to use direct client names ([#991](https://github.com/openai/openai-python/issues/991)) ([6c3427d](https://github.com/openai/openai-python/commit/6c3427dac8c414658516aeb4caf5d5fd8b11097b)) + + +### Documentation + +* upgrade models in examples to latest version ([#989](https://github.com/openai/openai-python/issues/989)) ([cedd574](https://github.com/openai/openai-python/commit/cedd574e5611f3e71e92b523a72ba87bcfe546f1)) + ## 1.5.0 (2023-12-17) Full Changelog: [v1.4.0...v1.5.0](https://github.com/openai/openai-python/compare/v1.4.0...v1.5.0) diff --git a/pyproject.toml b/pyproject.toml index 24498b18fe..91d3d79219 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.5.0" +version = "1.6.0" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 9dbb5b1401..9b01b6fcb1 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.5.0" # x-release-please-version +__version__ = "1.6.0" # x-release-please-version From d58c2ef8606264e7b69cebcdfd379c77210f8975 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 21 Dec 2023 07:40:30 -0500 Subject: [PATCH 169/816] chore(internal): add bin script (#1001) --- bin/check-env-state.py | 40 ++++++++++++++++++++++++++++++++++++++++ pyproject.toml | 1 + requirements-dev.lock | 10 ++++++---- 3 files changed, 47 insertions(+), 4 deletions(-) create mode 100644 bin/check-env-state.py diff --git a/bin/check-env-state.py b/bin/check-env-state.py new file mode 100644 index 0000000000..e1b8b6cb39 --- /dev/null +++ b/bin/check-env-state.py @@ -0,0 +1,40 @@ +"""Script that exits 1 if the current environment is not +in sync with the `requirements-dev.lock` file. +""" + +from pathlib import Path + +import importlib_metadata + + +def should_run_sync() -> bool: + dev_lock = Path(__file__).parent.parent.joinpath("requirements-dev.lock") + + for line in dev_lock.read_text().splitlines(): + if not line or line.startswith("#") or line.startswith("-e"): + continue + + dep, lock_version = line.split("==") + + try: + version = importlib_metadata.version(dep) + + if lock_version != version: + print(f"mismatch for {dep} current={version} lock={lock_version}") + return True + except Exception: + print(f"could not import {dep}") + return True + + return False + + +def main() -> None: + if should_run_sync(): + exit(1) + else: + exit(0) + + +if __name__ == "__main__": + main() diff --git a/pyproject.toml b/pyproject.toml index 91d3d79219..a9860b29ef 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -60,6 +60,7 @@ dev-dependencies = [ "time-machine", "nox", "dirty-equals>=0.6.0", + "importlib-metadata>=6.7.0", "azure-identity >=1.14.1", "types-tqdm > 4" ] diff --git a/requirements-dev.lock b/requirements-dev.lock index 6df8805579..3e480ada33 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -11,7 +11,7 @@ annotated-types==0.6.0 anyio==4.1.0 argcomplete==3.1.2 attrs==23.1.0 -azure-core==1.29.5 +azure-core==1.29.6 azure-identity==1.15.0 black==23.3.0 certifi==2023.7.22 @@ -29,18 +29,19 @@ h11==0.14.0 httpcore==1.0.2 httpx==0.25.2 idna==3.4 +importlib-metadata==7.0.0 iniconfig==2.0.0 isort==5.10.1 msal==1.26.0 -msal-extensions==1.0.0 +msal-extensions==1.1.0 mypy==1.7.1 mypy-extensions==1.0.0 nodeenv==1.8.0 nox==2023.4.22 numpy==1.26.2 packaging==23.2 -pandas==2.1.3 -pandas-stubs==2.1.1.230928 +pandas==2.1.4 +pandas-stubs==2.1.4.231218 pathspec==0.11.2 platformdirs==3.11.0 pluggy==1.3.0 @@ -69,5 +70,6 @@ typing-extensions==4.8.0 tzdata==2023.3 urllib3==2.1.0 virtualenv==20.24.5 +zipp==3.17.0 # The following packages are considered to be unsafe in a requirements file: setuptools==68.2.2 From 819ae68d990dc5df68921257213971caf1afb369 Mon Sep 17 00:00:00 2001 From: JackYu Date: Thu, 21 Dec 2023 22:52:19 +0800 Subject: [PATCH 170/816] Fix missing comma in README code example (#1000) The previous version of the README contained a code example with a missing comma, which could lead to syntax errors. This commit corrects that issue by adding the missing comma. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f89d0bdb28..f644cdeefe 100644 --- a/README.md +++ b/README.md @@ -475,7 +475,7 @@ from openai import AzureOpenAI # gets the API Key from environment variable AZURE_OPENAI_API_KEY client = AzureOpenAI( # https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#rest-api-versioning - api_version="2023-07-01-preview" + api_version="2023-07-01-preview", # https://learn.microsoft.com/en-us/azure/cognitive-services/openai/how-to/create-resource?pivots=web-portal#create-a-resource azure_endpoint="https://example-endpoint.openai.azure.com/", ) From ce04ec285c86ff91b584a0105d8559a3f94b282f Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 21 Dec 2023 22:48:12 -0500 Subject: [PATCH 171/816] test: run the garbage collector less often (#1003) --- tests/test_client.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_client.py b/tests/test_client.py index 0959185df2..ffa779fb38 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -208,8 +208,8 @@ def build_request(options: FinalRequestOptions) -> None: ITERATIONS = 10 for _ in range(ITERATIONS): build_request(options) - gc.collect() + gc.collect() snapshot_after = tracemalloc.take_snapshot() tracemalloc.stop() @@ -871,8 +871,8 @@ def build_request(options: FinalRequestOptions) -> None: ITERATIONS = 10 for _ in range(ITERATIONS): build_request(options) - gc.collect() + gc.collect() snapshot_after = tracemalloc.take_snapshot() tracemalloc.stop() From e1b60b22915c34464faeca63e6034524d50a70d7 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 22 Dec 2023 05:45:53 -0500 Subject: [PATCH 172/816] chore(internal): use ruff instead of black for formatting (#1008) --- bin/{blacken-docs.py => ruffen-docs.py} | 130 +++++------------------- pyproject.toml | 12 ++- requirements-dev.lock | 5 +- src/openai/_models.py | 2 +- src/openai/_types.py | 16 +-- src/openai/_utils/_transform.py | 5 +- src/openai/_utils/_utils.py | 4 +- tests/test_transform.py | 4 +- 8 files changed, 50 insertions(+), 128 deletions(-) rename bin/{blacken-docs.py => ruffen-docs.py} (52%) diff --git a/bin/blacken-docs.py b/bin/ruffen-docs.py similarity index 52% rename from bin/blacken-docs.py rename to bin/ruffen-docs.py index 45d0ad1225..37b3d94f0f 100644 --- a/bin/blacken-docs.py +++ b/bin/ruffen-docs.py @@ -1,16 +1,14 @@ -# fork of https://github.com/asottile/blacken-docs implementing https://github.com/asottile/blacken-docs/issues/170 +# fork of https://github.com/asottile/blacken-docs adapted for ruff from __future__ import annotations import re +import sys import argparse import textwrap import contextlib +import subprocess from typing import Match, Optional, Sequence, Generator, NamedTuple, cast -import black -from black.mode import TargetVersion -from black.const import DEFAULT_LINE_LENGTH - MD_RE = re.compile( r"(?P^(?P *)```\s*python\n)" r"(?P.*?)" r"(?P^(?P=indent)```\s*$)", re.DOTALL | re.MULTILINE, @@ -19,55 +17,12 @@ r"(?P^(?P *)```\s*pycon\n)" r"(?P.*?)" r"(?P^(?P=indent)```.*$)", re.DOTALL | re.MULTILINE, ) -RST_PY_LANGS = frozenset(("python", "py", "sage", "python3", "py3", "numpy")) -BLOCK_TYPES = "(code|code-block|sourcecode|ipython)" -DOCTEST_TYPES = "(testsetup|testcleanup|testcode)" -RST_RE = re.compile( - rf"(?P" - rf"^(?P *)\.\. (" - rf"jupyter-execute::|" - rf"{BLOCK_TYPES}:: (?P\w+)|" - rf"{DOCTEST_TYPES}::.*" - rf")\n" - rf"((?P=indent) +:.*\n)*" - rf"\n*" - rf")" - rf"(?P(^((?P=indent) +.*)?\n)+)", - re.MULTILINE, -) -RST_PYCON_RE = re.compile( - r"(?P" - r"(?P *)\.\. ((code|code-block):: pycon|doctest::.*)\n" - r"((?P=indent) +:.*\n)*" - r"\n*" - r")" - r"(?P(^((?P=indent) +.*)?(\n|$))+)", - re.MULTILINE, -) PYCON_PREFIX = ">>> " PYCON_CONTINUATION_PREFIX = "..." PYCON_CONTINUATION_RE = re.compile( rf"^{re.escape(PYCON_CONTINUATION_PREFIX)}( |$)", ) -LATEX_RE = re.compile( - r"(?P^(?P *)\\begin{minted}{python}\n)" - r"(?P.*?)" - r"(?P^(?P=indent)\\end{minted}\s*$)", - re.DOTALL | re.MULTILINE, -) -LATEX_PYCON_RE = re.compile( - r"(?P^(?P *)\\begin{minted}{pycon}\n)" r"(?P.*?)" r"(?P^(?P=indent)\\end{minted}\s*$)", - re.DOTALL | re.MULTILINE, -) -PYTHONTEX_LANG = r"(?Ppyblock|pycode|pyconsole|pyverbatim)" -PYTHONTEX_RE = re.compile( - rf"(?P^(?P *)\\begin{{{PYTHONTEX_LANG}}}\n)" - rf"(?P.*?)" - rf"(?P^(?P=indent)\\end{{(?P=lang)}}\s*$)", - re.DOTALL | re.MULTILINE, -) -INDENT_RE = re.compile("^ +(?=[^ ])", re.MULTILINE) -TRAILING_NL_RE = re.compile(r"\n+\Z", re.MULTILINE) +DEFAULT_LINE_LENGTH = 100 class CodeBlockError(NamedTuple): @@ -77,7 +32,6 @@ class CodeBlockError(NamedTuple): def format_str( src: str, - black_mode: black.FileMode, ) -> tuple[str, Sequence[CodeBlockError]]: errors: list[CodeBlockError] = [] @@ -91,24 +45,10 @@ def _collect_error(match: Match[str]) -> Generator[None, None, None]: def _md_match(match: Match[str]) -> str: code = textwrap.dedent(match["code"]) with _collect_error(match): - code = black.format_str(code, mode=black_mode) + code = format_code_block(code) code = textwrap.indent(code, match["indent"]) return f'{match["before"]}{code}{match["after"]}' - def _rst_match(match: Match[str]) -> str: - lang = match["lang"] - if lang is not None and lang not in RST_PY_LANGS: - return match[0] - min_indent = min(INDENT_RE.findall(match["code"])) - trailing_ws_match = TRAILING_NL_RE.search(match["code"]) - assert trailing_ws_match - trailing_ws = trailing_ws_match.group() - code = textwrap.dedent(match["code"]) - with _collect_error(match): - code = black.format_str(code, mode=black_mode) - code = textwrap.indent(code, min_indent) - return f'{match["before"]}{code.rstrip()}{trailing_ws}' - def _pycon_match(match: Match[str]) -> str: code = "" fragment = cast(Optional[str], None) @@ -119,7 +59,7 @@ def finish_fragment() -> None: if fragment is not None: with _collect_error(match): - fragment = black.format_str(fragment, mode=black_mode) + fragment = format_code_block(fragment) fragment_lines = fragment.splitlines() code += f"{PYCON_PREFIX}{fragment_lines[0]}\n" for line in fragment_lines[1:]: @@ -159,42 +99,33 @@ def _md_pycon_match(match: Match[str]) -> str: code = textwrap.indent(code, match["indent"]) return f'{match["before"]}{code}{match["after"]}' - def _rst_pycon_match(match: Match[str]) -> str: - code = _pycon_match(match) - min_indent = min(INDENT_RE.findall(match["code"])) - code = textwrap.indent(code, min_indent) - return f'{match["before"]}{code}' - - def _latex_match(match: Match[str]) -> str: - code = textwrap.dedent(match["code"]) - with _collect_error(match): - code = black.format_str(code, mode=black_mode) - code = textwrap.indent(code, match["indent"]) - return f'{match["before"]}{code}{match["after"]}' - - def _latex_pycon_match(match: Match[str]) -> str: - code = _pycon_match(match) - code = textwrap.indent(code, match["indent"]) - return f'{match["before"]}{code}{match["after"]}' - src = MD_RE.sub(_md_match, src) src = MD_PYCON_RE.sub(_md_pycon_match, src) - src = RST_RE.sub(_rst_match, src) - src = RST_PYCON_RE.sub(_rst_pycon_match, src) - src = LATEX_RE.sub(_latex_match, src) - src = LATEX_PYCON_RE.sub(_latex_pycon_match, src) - src = PYTHONTEX_RE.sub(_latex_match, src) return src, errors +def format_code_block(code: str) -> str: + return subprocess.check_output( + [ + sys.executable, + "-m", + "ruff", + "format", + "--stdin-filename=script.py", + f"--line-length={DEFAULT_LINE_LENGTH}", + ], + encoding="utf-8", + input=code, + ) + + def format_file( filename: str, - black_mode: black.FileMode, skip_errors: bool, ) -> int: with open(filename, encoding="UTF-8") as f: contents = f.read() - new_contents, errors = format_str(contents, black_mode) + new_contents, errors = format_str(contents) for error in errors: lineno = contents[: error.offset].count("\n") + 1 print(f"{filename}:{lineno}: code block parse error {error.exc}") @@ -217,15 +148,6 @@ def main(argv: Sequence[str] | None = None) -> int: type=int, default=DEFAULT_LINE_LENGTH, ) - parser.add_argument( - "-t", - "--target-version", - action="http://github.com/append", - type=lambda v: TargetVersion[v.upper()], - default=[], - help=f"choices: {[v.name.lower() for v in TargetVersion]}", - dest="target_versions", - ) parser.add_argument( "-S", "--skip-string-normalization", @@ -235,15 +157,9 @@ def main(argv: Sequence[str] | None = None) -> int: parser.add_argument("filenames", nargs="*") args = parser.parse_args(argv) - black_mode = black.FileMode( - target_versions=set(args.target_versions), - line_length=args.line_length, - string_normalization=not args.skip_string_normalization, - ) - retv = 0 for filename in args.filenames: - retv |= format_file(filename, black_mode, skip_errors=args.skip_errors) + retv |= format_file(filename, skip_errors=args.skip_errors) return retv diff --git a/pyproject.toml b/pyproject.toml index a9860b29ef..f1d1a66fef 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -51,7 +51,6 @@ managed = true dev-dependencies = [ "pyright", "mypy", - "black", "respx", "pytest", "pytest-asyncio", @@ -67,17 +66,18 @@ dev-dependencies = [ [tool.rye.scripts] format = { chain = [ - "format:black", - "format:docs", "format:ruff", + "format:docs", + "fix:ruff", "format:isort", ]} "format:black" = "black ." -"format:docs" = "python bin/blacken-docs.py README.md api.md" -"format:ruff" = "ruff --fix ." +"format:docs" = "python bin/ruffen-docs.py README.md api.md" +"format:ruff" = "ruff format" "format:isort" = "isort ." "check:ruff" = "ruff ." +"fix:ruff" = "ruff --fix ." typecheck = { chain = [ "typecheck:pyright", @@ -163,6 +163,8 @@ unfixable = [ ] ignore-init-module-imports = true +[tool.ruff.format] +docstring-code-format = true [tool.ruff.per-file-ignores] "bin/**.py" = ["T201", "T203"] diff --git a/requirements-dev.lock b/requirements-dev.lock index 3e480ada33..53763f2aa9 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -13,11 +13,9 @@ argcomplete==3.1.2 attrs==23.1.0 azure-core==1.29.6 azure-identity==1.15.0 -black==23.3.0 certifi==2023.7.22 cffi==1.16.0 charset-normalizer==3.3.2 -click==8.1.7 colorlog==6.7.0 cryptography==41.0.7 dirty-equals==0.6.0 @@ -42,7 +40,6 @@ numpy==1.26.2 packaging==23.2 pandas==2.1.4 pandas-stubs==2.1.4.231218 -pathspec==0.11.2 platformdirs==3.11.0 pluggy==1.3.0 portalocker==2.8.2 @@ -58,7 +55,7 @@ python-dateutil==2.8.2 pytz==2023.3.post1 requests==2.31.0 respx==0.20.2 -ruff==0.1.7 +ruff==0.1.9 six==1.16.0 sniffio==1.3.0 time-machine==2.9.0 diff --git a/src/openai/_models.py b/src/openai/_models.py index 5b8c96010f..330a2064d8 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -382,7 +382,7 @@ class RootModel(GenericModel, Generic[_T]): For example: ```py - validated = RootModel[int](__root__='5').__root__ + validated = RootModel[int](__root__="5").__root__ # validated: 5 ``` """ diff --git a/src/openai/_types.py b/src/openai/_types.py index a20a4b4c1b..fc26d5458a 100644 --- a/src/openai/_types.py +++ b/src/openai/_types.py @@ -278,11 +278,13 @@ class NotGiven: For example: ```py - def get(timeout: Union[int, NotGiven, None] = NotGiven()) -> Response: ... + def get(timeout: Union[int, NotGiven, None] = NotGiven()) -> Response: + ... + - get(timeout=1) # 1s timeout - get(timeout=None) # No timeout - get() # Default timeout behavior, which may not be statically known at the method definition. + get(timeout=1) # 1s timeout + get(timeout=None) # No timeout + get() # Default timeout behavior, which may not be statically known at the method definition. ``` """ @@ -304,14 +306,14 @@ class Omit: ```py # as the default `Content-Type` header is `application/json` that will be sent - client.post('/upload/files', files={'file': b'my raw file content'}) + client.post("/upload/files", files={"file": b"my raw file content"}) # you can't explicitly override the header as it has to be dynamically generated # to look something like: 'multipart/form-data; boundary=0d8382fcf5f8c3be01ca2e11002d2983' - client.post(..., headers={'Content-Type': 'multipart/form-data'}) + client.post(..., headers={"Content-Type": "multipart/form-data"}) # instead you can remove the default `application/json` header by passing Omit - client.post(..., headers={'Content-Type': Omit()}) + client.post(..., headers={"Content-Type": Omit()}) ``` """ diff --git a/src/openai/_utils/_transform.py b/src/openai/_utils/_transform.py index 9117559064..342b52416a 100644 --- a/src/openai/_utils/_transform.py +++ b/src/openai/_utils/_transform.py @@ -80,9 +80,10 @@ def transform( ```py class Params(TypedDict, total=False): - card_id: Required[Annotated[str, PropertyInfo(alias='cardID')]] + card_id: Required[Annotated[str, PropertyInfo(alias="cardID")]] - transformed = transform({'card_id': ''}, Params) + + transformed = transform({"card_id": ""}, Params) # {'cardID': ''} ``` diff --git a/src/openai/_utils/_utils.py b/src/openai/_utils/_utils.py index 993462a66b..cc624b0ce1 100644 --- a/src/openai/_utils/_utils.py +++ b/src/openai/_utils/_utils.py @@ -211,13 +211,15 @@ def required_args(*variants: Sequence[str]) -> Callable[[CallableT], CallableT]: def foo(*, a: str) -> str: ... + @overload def foo(*, b: bool) -> str: ... + # This enforces the same constraints that a static type checker would # i.e. that either a or b must be passed to the function - @required_args(['a'], ['b']) + @required_args(["a"], ["b"]) def foo(*, a: str | None = None, b: bool | None = None) -> str: ... ``` diff --git a/tests/test_transform.py b/tests/test_transform.py index 5e15385f4d..c4dffb3bb0 100644 --- a/tests/test_transform.py +++ b/tests/test_transform.py @@ -189,7 +189,9 @@ class DateDictWithRequiredAlias(TypedDict, total=False): def test_datetime_with_alias() -> None: assert transform({"required_prop": None}, DateDictWithRequiredAlias) == {"prop": None} # type: ignore[comparison-overlap] - assert transform({"required_prop": date.fromisoformat("2023-02-23")}, DateDictWithRequiredAlias) == {"prop": "2023-02-23"} # type: ignore[comparison-overlap] + assert transform({"required_prop": date.fromisoformat("2023-02-23")}, DateDictWithRequiredAlias) == { + "prop": "2023-02-23" + } # type: ignore[comparison-overlap] class MyModel(BaseModel): From f1c7d714914e3321ca2e72839fe2d132a8646e7f Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 22 Dec 2023 05:46:35 -0500 Subject: [PATCH 173/816] release: 1.6.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 9 +++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 7deae33804..59565e8e31 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.6.0" + ".": "1.6.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 399e3aaebd..83bf20f775 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 1.6.1 (2023-12-22) + +Full Changelog: [v1.6.0...v1.6.1](https://github.com/openai/openai-python/compare/v1.6.0...v1.6.1) + +### Chores + +* **internal:** add bin script ([#1001](https://github.com/openai/openai-python/issues/1001)) ([99ffbda](https://github.com/openai/openai-python/commit/99ffbda279bf4c159511fb96b1d5bb688af25437)) +* **internal:** use ruff instead of black for formatting ([#1008](https://github.com/openai/openai-python/issues/1008)) ([ceaf9a0](https://github.com/openai/openai-python/commit/ceaf9a06fbd1a846756bb72cce50a69c8cc20bd3)) + ## 1.6.0 (2023-12-19) Full Changelog: [v1.5.0...v1.6.0](https://github.com/openai/openai-python/compare/v1.5.0...v1.6.0) diff --git a/pyproject.toml b/pyproject.toml index f1d1a66fef..f39cfb8f15 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.6.0" +version = "1.6.1" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 9b01b6fcb1..9ab131d176 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.6.0" # x-release-please-version +__version__ = "1.6.1" # x-release-please-version From acbe5ffa2b6322aef5ed424b489bf419b48d4aec Mon Sep 17 00:00:00 2001 From: Davor Runje Date: Sun, 24 Dec 2023 00:22:43 +0100 Subject: [PATCH 174/816] added default value to logprobs (#1007) --- src/openai/types/chat/chat_completion.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/openai/types/chat/chat_completion.py b/src/openai/types/chat/chat_completion.py index 055280c347..b2e98a3144 100644 --- a/src/openai/types/chat/chat_completion.py +++ b/src/openai/types/chat/chat_completion.py @@ -30,7 +30,7 @@ class Choice(BaseModel): index: int """The index of the choice in the list of choices.""" - logprobs: Optional[ChoiceLogprobs] + logprobs: Optional[ChoiceLogprobs] = None """Log probability information for the choice.""" message: ChatCompletionMessage From ecc3b441290141031b765a0b4dd1bba10e65535a Mon Sep 17 00:00:00 2001 From: vuittont60 <81072379+vuittont60@users.noreply.github.com> Date: Sun, 24 Dec 2023 07:23:41 +0800 Subject: [PATCH 175/816] chore(src): fix typos (#988) --- src/openai/resources/beta/assistants/assistants.py | 4 ++-- src/openai/types/beta/assistant_update_params.py | 2 +- src/openai/types/moderation.py | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/openai/resources/beta/assistants/assistants.py b/src/openai/resources/beta/assistants/assistants.py index efa711ecf4..8854c8b867 100644 --- a/src/openai/resources/beta/assistants/assistants.py +++ b/src/openai/resources/beta/assistants/assistants.py @@ -172,7 +172,7 @@ def update( file_ids: A list of [File](https://platform.openai.com/docs/api-reference/files) IDs attached to this assistant. There can be a maximum of 20 files attached to the assistant. Files are ordered by their creation date in ascending order. If a - file was previosuly attached to the list but does not show up in the list, it + file was previously attached to the list but does not show up in the list, it will be deleted from the assistant. instructions: The system instructions that the assistant uses. The maximum length is 32768 @@ -465,7 +465,7 @@ async def update( file_ids: A list of [File](https://platform.openai.com/docs/api-reference/files) IDs attached to this assistant. There can be a maximum of 20 files attached to the assistant. Files are ordered by their creation date in ascending order. If a - file was previosuly attached to the list but does not show up in the list, it + file was previously attached to the list but does not show up in the list, it will be deleted from the assistant. instructions: The system instructions that the assistant uses. The maximum length is 32768 diff --git a/src/openai/types/beta/assistant_update_params.py b/src/openai/types/beta/assistant_update_params.py index a0efd96ecd..dfb5d4c553 100644 --- a/src/openai/types/beta/assistant_update_params.py +++ b/src/openai/types/beta/assistant_update_params.py @@ -25,7 +25,7 @@ class AssistantUpdateParams(TypedDict, total=False): A list of [File](https://platform.openai.com/docs/api-reference/files) IDs attached to this assistant. There can be a maximum of 20 files attached to the assistant. Files are ordered by their creation date in ascending order. If a - file was previosuly attached to the list but does not show up in the list, it + file was previously attached to the list but does not show up in the list, it will be deleted from the assistant. """ diff --git a/src/openai/types/moderation.py b/src/openai/types/moderation.py index 3602a46985..09c9a6058b 100644 --- a/src/openai/types/moderation.py +++ b/src/openai/types/moderation.py @@ -25,7 +25,7 @@ class Categories(BaseModel): Content that expresses, incites, or promotes hate based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste. Hateful content aimed at non-protected groups (e.g., chess players) is - harrassment. + harassment. """ hate_threatening: bool = FieldInfo(alias="hate/threatening") From 47f35921a21c0c6eb21084356f198c0fcb87ed7a Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Sat, 23 Dec 2023 18:40:55 -0500 Subject: [PATCH 176/816] docs: improve audio example to show how to stream to a file (#1017) --- src/openai/resources/beta/assistants/assistants.py | 4 ++-- src/openai/types/beta/assistant_update_params.py | 2 +- src/openai/types/chat/chat_completion.py | 2 +- src/openai/types/moderation.py | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/openai/resources/beta/assistants/assistants.py b/src/openai/resources/beta/assistants/assistants.py index 8854c8b867..efa711ecf4 100644 --- a/src/openai/resources/beta/assistants/assistants.py +++ b/src/openai/resources/beta/assistants/assistants.py @@ -172,7 +172,7 @@ def update( file_ids: A list of [File](https://platform.openai.com/docs/api-reference/files) IDs attached to this assistant. There can be a maximum of 20 files attached to the assistant. Files are ordered by their creation date in ascending order. If a - file was previously attached to the list but does not show up in the list, it + file was previosuly attached to the list but does not show up in the list, it will be deleted from the assistant. instructions: The system instructions that the assistant uses. The maximum length is 32768 @@ -465,7 +465,7 @@ async def update( file_ids: A list of [File](https://platform.openai.com/docs/api-reference/files) IDs attached to this assistant. There can be a maximum of 20 files attached to the assistant. Files are ordered by their creation date in ascending order. If a - file was previously attached to the list but does not show up in the list, it + file was previosuly attached to the list but does not show up in the list, it will be deleted from the assistant. instructions: The system instructions that the assistant uses. The maximum length is 32768 diff --git a/src/openai/types/beta/assistant_update_params.py b/src/openai/types/beta/assistant_update_params.py index dfb5d4c553..a0efd96ecd 100644 --- a/src/openai/types/beta/assistant_update_params.py +++ b/src/openai/types/beta/assistant_update_params.py @@ -25,7 +25,7 @@ class AssistantUpdateParams(TypedDict, total=False): A list of [File](https://platform.openai.com/docs/api-reference/files) IDs attached to this assistant. There can be a maximum of 20 files attached to the assistant. Files are ordered by their creation date in ascending order. If a - file was previously attached to the list but does not show up in the list, it + file was previosuly attached to the list but does not show up in the list, it will be deleted from the assistant. """ diff --git a/src/openai/types/chat/chat_completion.py b/src/openai/types/chat/chat_completion.py index b2e98a3144..055280c347 100644 --- a/src/openai/types/chat/chat_completion.py +++ b/src/openai/types/chat/chat_completion.py @@ -30,7 +30,7 @@ class Choice(BaseModel): index: int """The index of the choice in the list of choices.""" - logprobs: Optional[ChoiceLogprobs] = None + logprobs: Optional[ChoiceLogprobs] """Log probability information for the choice.""" message: ChatCompletionMessage diff --git a/src/openai/types/moderation.py b/src/openai/types/moderation.py index 09c9a6058b..3602a46985 100644 --- a/src/openai/types/moderation.py +++ b/src/openai/types/moderation.py @@ -25,7 +25,7 @@ class Categories(BaseModel): Content that expresses, incites, or promotes hate based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste. Hateful content aimed at non-protected groups (e.g., chess players) is - harassment. + harrassment. """ hate_threatening: bool = FieldInfo(alias="hate/threatening") From ade28c4f6ce0f4eed6c6a344f069b63f4571ed3b Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 25 Dec 2023 02:10:30 -0500 Subject: [PATCH 177/816] docs: fix docstring typos (#1022) --- src/openai/resources/beta/assistants/assistants.py | 4 ++-- src/openai/types/beta/assistant_update_params.py | 2 +- src/openai/types/moderation.py | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/openai/resources/beta/assistants/assistants.py b/src/openai/resources/beta/assistants/assistants.py index efa711ecf4..8854c8b867 100644 --- a/src/openai/resources/beta/assistants/assistants.py +++ b/src/openai/resources/beta/assistants/assistants.py @@ -172,7 +172,7 @@ def update( file_ids: A list of [File](https://platform.openai.com/docs/api-reference/files) IDs attached to this assistant. There can be a maximum of 20 files attached to the assistant. Files are ordered by their creation date in ascending order. If a - file was previosuly attached to the list but does not show up in the list, it + file was previously attached to the list but does not show up in the list, it will be deleted from the assistant. instructions: The system instructions that the assistant uses. The maximum length is 32768 @@ -465,7 +465,7 @@ async def update( file_ids: A list of [File](https://platform.openai.com/docs/api-reference/files) IDs attached to this assistant. There can be a maximum of 20 files attached to the assistant. Files are ordered by their creation date in ascending order. If a - file was previosuly attached to the list but does not show up in the list, it + file was previously attached to the list but does not show up in the list, it will be deleted from the assistant. instructions: The system instructions that the assistant uses. The maximum length is 32768 diff --git a/src/openai/types/beta/assistant_update_params.py b/src/openai/types/beta/assistant_update_params.py index a0efd96ecd..dfb5d4c553 100644 --- a/src/openai/types/beta/assistant_update_params.py +++ b/src/openai/types/beta/assistant_update_params.py @@ -25,7 +25,7 @@ class AssistantUpdateParams(TypedDict, total=False): A list of [File](https://platform.openai.com/docs/api-reference/files) IDs attached to this assistant. There can be a maximum of 20 files attached to the assistant. Files are ordered by their creation date in ascending order. If a - file was previosuly attached to the list but does not show up in the list, it + file was previously attached to the list but does not show up in the list, it will be deleted from the assistant. """ diff --git a/src/openai/types/moderation.py b/src/openai/types/moderation.py index 3602a46985..09c9a6058b 100644 --- a/src/openai/types/moderation.py +++ b/src/openai/types/moderation.py @@ -25,7 +25,7 @@ class Categories(BaseModel): Content that expresses, incites, or promotes hate based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste. Hateful content aimed at non-protected groups (e.g., chess players) is - harrassment. + harassment. """ hate_threatening: bool = FieldInfo(alias="hate/threatening") From 6279b267be1f8d28c080d0282d029e7f0b50948a Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 27 Dec 2023 21:19:05 -0500 Subject: [PATCH 178/816] fix(client): correctly use custom http client auth (#1028) --- src/openai/_base_client.py | 13 +++++++++++-- src/openai/_types.py | 5 +++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 481171a447..53a53d8016 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -58,6 +58,7 @@ PostParser, ProxiesTypes, RequestFiles, + HttpxSendArgs, AsyncTransport, RequestOptions, UnknownResponse, @@ -873,11 +874,15 @@ def _request( request = self._build_request(options) self._prepare_request(request) + kwargs: HttpxSendArgs = {} + if self.custom_auth is not None: + kwargs["auth"] = self.custom_auth + try: response = self._client.send( request, - auth=self.custom_auth, stream=stream or self._should_stream_response_body(request=request), + **kwargs, ) except httpx.TimeoutException as err: if retries > 0: @@ -1335,11 +1340,15 @@ async def _request( request = self._build_request(options) await self._prepare_request(request) + kwargs: HttpxSendArgs = {} + if self.custom_auth is not None: + kwargs["auth"] = self.custom_auth + try: response = await self._client.send( request, - auth=self.custom_auth, stream=stream or self._should_stream_response_body(request=request), + **kwargs, ) except httpx.TimeoutException as err: if retries > 0: diff --git a/src/openai/_types.py b/src/openai/_types.py index fc26d5458a..061e5c97f5 100644 --- a/src/openai/_types.py +++ b/src/openai/_types.py @@ -28,6 +28,7 @@ runtime_checkable, ) +import httpx import pydantic from httpx import URL, Proxy, Timeout, Response, BaseTransport, AsyncBaseTransport @@ -369,3 +370,7 @@ class InheritsGeneric(Protocol): class _GenericAlias(Protocol): __origin__: type[object] + + +class HttpxSendArgs(TypedDict, total=False): + auth: httpx.Auth From bba23438a63121102fe066982c91771fcca19c80 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 2 Jan 2024 05:36:02 -0500 Subject: [PATCH 179/816] chore(internal): bump license (#1037) --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index 7b1b36a644..621a6becfb 100644 --- a/LICENSE +++ b/LICENSE @@ -186,7 +186,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright 2023 OpenAI + Copyright 2024 OpenAI Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. From bcc54ea9ab77ee4c37489ecf095db563ca9c35a3 Mon Sep 17 00:00:00 2001 From: Christian Malpass Date: Wed, 3 Jan 2024 18:52:30 +0200 Subject: [PATCH 180/816] Add Picture API file example to the Examples Folder (#977) * Added a file to the examples folder to provide a simple example of retrieving and printing a picture to the console using the new API. Previously, no examples were provided for images, making it unclear. * Update picture.py --------- Co-authored-by: Logan Kilpatrick <23kilpatrick23@gmail.com> --- examples/picture.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 examples/picture.py diff --git a/examples/picture.py b/examples/picture.py new file mode 100644 index 0000000000..7bf22aa790 --- /dev/null +++ b/examples/picture.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python + +from openai import OpenAI + +# gets OPENAI_API_KEY from your environment variables +openai = OpenAI() + +prompt = "An astronaut lounging in a tropical resort in space, pixel art" +model = "dall-e-3" + +def main() -> None: + # Generate an image based on the prompt + response = openai.images.generate(prompt=prompt, model=model) + + # Prints response containing a URL link to image + print(response) + +if __name__ == "__main__": + main() From 6f1adfec053ddca20777e9f7959dcbd3f34a6da0 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 3 Jan 2024 14:04:23 -0500 Subject: [PATCH 181/816] chore(internal): update formatting (#1041) --- examples/picture.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/examples/picture.py b/examples/picture.py index 7bf22aa790..c27b52b0da 100644 --- a/examples/picture.py +++ b/examples/picture.py @@ -8,12 +8,14 @@ prompt = "An astronaut lounging in a tropical resort in space, pixel art" model = "dall-e-3" + def main() -> None: # Generate an image based on the prompt response = openai.images.generate(prompt=prompt, model=model) - + # Prints response containing a URL link to image print(response) - + + if __name__ == "__main__": main() From a47375b7e20d411489991bf05b3c10431503141d Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 3 Jan 2024 17:13:18 -0500 Subject: [PATCH 182/816] chore(internal): replace isort with ruff (#1042) --- pyproject.toml | 16 ++-- requirements-dev.lock | 7 +- src/openai/__init__.py | 41 ++++----- src/openai/_client.py | 15 +++- src/openai/_compat.py | 30 +++---- src/openai/_extras/__init__.py | 3 +- src/openai/_models.py | 14 +--- src/openai/_types.py | 9 +- src/openai/_utils/__init__.py | 83 ++++++++++--------- src/openai/_utils/_transform.py | 5 +- src/openai/_utils/_utils.py | 3 +- src/openai/resources/__init__.py | 49 ++--------- src/openai/resources/audio/__init__.py | 14 +--- src/openai/resources/audio/audio.py | 14 +--- src/openai/resources/audio/speech.py | 13 ++- src/openai/resources/audio/transcriptions.py | 13 ++- src/openai/resources/audio/translations.py | 13 ++- src/openai/resources/beta/__init__.py | 14 +--- .../resources/beta/assistants/__init__.py | 7 +- .../resources/beta/assistants/assistants.py | 13 ++- src/openai/resources/beta/assistants/files.py | 13 ++- src/openai/resources/beta/beta.py | 14 +--- src/openai/resources/beta/threads/__init__.py | 14 +--- .../beta/threads/messages/__init__.py | 7 +- .../resources/beta/threads/messages/files.py | 13 ++- .../beta/threads/messages/messages.py | 13 ++- .../resources/beta/threads/runs/runs.py | 13 ++- .../resources/beta/threads/runs/steps.py | 13 ++- src/openai/resources/beta/threads/threads.py | 17 ++-- src/openai/resources/chat/__init__.py | 7 +- src/openai/resources/chat/chat.py | 7 +- src/openai/resources/chat/completions.py | 12 ++- src/openai/resources/completions.py | 12 ++- src/openai/resources/edits.py | 12 ++- src/openai/resources/embeddings.py | 15 +++- src/openai/resources/files.py | 16 +++- src/openai/resources/fine_tunes.py | 13 ++- src/openai/resources/fine_tuning/__init__.py | 7 +- src/openai/resources/fine_tuning/jobs.py | 13 ++- src/openai/resources/images.py | 13 ++- src/openai/resources/models.py | 13 ++- src/openai/resources/moderations.py | 12 ++- src/openai/types/__init__.py | 23 ++--- src/openai/types/audio/__init__.py | 8 +- src/openai/types/beta/__init__.py | 4 +- src/openai/types/beta/threads/__init__.py | 12 +-- .../types/beta/threads/runs/__init__.py | 4 +- src/openai/types/chat/__init__.py | 32 ++----- .../chat_completion_content_part_param.py | 4 +- .../types/chat/completion_create_params.py | 8 +- tests/api_resources/beta/test_assistants.py | 5 +- tests/api_resources/beta/test_threads.py | 5 +- tests/api_resources/beta/threads/test_runs.py | 4 +- tests/api_resources/fine_tuning/test_jobs.py | 5 +- tests/test_client.py | 14 +--- tests/utils.py | 7 +- 56 files changed, 397 insertions(+), 383 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index f39cfb8f15..a4eba4a0d9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -55,7 +55,6 @@ dev-dependencies = [ "pytest", "pytest-asyncio", "ruff", - "isort", "time-machine", "nox", "dirty-equals>=0.6.0", @@ -69,7 +68,6 @@ format = { chain = [ "format:ruff", "format:docs", "fix:ruff", - "format:isort", ]} "format:black" = "black ." "format:docs" = "python bin/ruffen-docs.py README.md api.md" @@ -130,16 +128,13 @@ reportImplicitOverride = true reportImportCycles = false reportPrivateUsage = false -[tool.isort] -profile = "black" -length_sort = true -extra_standard_library = ["typing_extensions"] - [tool.ruff] line-length = 120 output-format = "grouped" target-version = "py37" select = [ + # isort + "I", # bugbear rules "B", # remove unused imports @@ -166,6 +161,13 @@ ignore-init-module-imports = true [tool.ruff.format] docstring-code-format = true +[tool.ruff.lint.isort] +length-sort = true +length-sort-straight = true +combine-as-imports = true +extra-standard-library = ["typing_extensions"] +known-first-party = ["openai", "tests"] + [tool.ruff.per-file-ignores] "bin/**.py" = ["T201", "T203"] "tests/**.py" = ["T201", "T203"] diff --git a/requirements-dev.lock b/requirements-dev.lock index 53763f2aa9..088cb2bd98 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -29,17 +29,16 @@ httpx==0.25.2 idna==3.4 importlib-metadata==7.0.0 iniconfig==2.0.0 -isort==5.10.1 msal==1.26.0 msal-extensions==1.1.0 mypy==1.7.1 mypy-extensions==1.0.0 nodeenv==1.8.0 nox==2023.4.22 -numpy==1.26.2 +numpy==1.26.3 packaging==23.2 pandas==2.1.4 -pandas-stubs==2.1.4.231218 +pandas-stubs==2.1.4.231227 platformdirs==3.11.0 pluggy==1.3.0 portalocker==2.8.2 @@ -64,7 +63,7 @@ tqdm==4.66.1 types-pytz==2023.3.1.1 types-tqdm==4.66.0.2 typing-extensions==4.8.0 -tzdata==2023.3 +tzdata==2023.4 urllib3==2.1.0 virtualenv==20.24.5 zipp==3.17.0 diff --git a/src/openai/__init__.py b/src/openai/__init__.py index 0d66b3c682..ee96f06919 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -8,17 +8,7 @@ from . import types from ._types import NoneType, Transport, ProxiesTypes from ._utils import file_from_path -from ._client import ( - Client, - OpenAI, - Stream, - Timeout, - Transport, - AsyncClient, - AsyncOpenAI, - AsyncStream, - RequestOptions, -) +from ._client import Client, OpenAI, Stream, Timeout, Transport, AsyncClient, AsyncOpenAI, AsyncStream, RequestOptions from ._version import __title__, __version__ from ._exceptions import ( APIError, @@ -72,8 +62,7 @@ from .lib import azure as _azure from .version import VERSION as VERSION -from .lib.azure import AzureOpenAI as AzureOpenAI -from .lib.azure import AsyncAzureOpenAI as AsyncAzureOpenAI +from .lib.azure import AzureOpenAI as AzureOpenAI, AsyncAzureOpenAI as AsyncAzureOpenAI from .lib._old_api import * _setup_logging() @@ -323,15 +312,17 @@ def _reset_client() -> None: # type: ignore[reportUnusedFunction] _client = None -from ._module_client import beta as beta -from ._module_client import chat as chat -from ._module_client import audio as audio -from ._module_client import edits as edits -from ._module_client import files as files -from ._module_client import images as images -from ._module_client import models as models -from ._module_client import embeddings as embeddings -from ._module_client import fine_tunes as fine_tunes -from ._module_client import completions as completions -from ._module_client import fine_tuning as fine_tuning -from ._module_client import moderations as moderations +from ._module_client import ( + beta as beta, + chat as chat, + audio as audio, + edits as edits, + files as files, + images as images, + models as models, + embeddings as embeddings, + fine_tunes as fine_tunes, + completions as completions, + fine_tuning as fine_tuning, + moderations as moderations, +) diff --git a/src/openai/_client.py b/src/openai/_client.py index dacadf5aff..9eb6888909 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -19,12 +19,19 @@ ProxiesTypes, RequestOptions, ) -from ._utils import is_given, is_mapping, get_async_library +from ._utils import ( + is_given, + is_mapping, + get_async_library, +) from ._version import __version__ -from ._streaming import Stream as Stream -from ._streaming import AsyncStream as AsyncStream +from ._streaming import Stream as Stream, AsyncStream as AsyncStream from ._exceptions import OpenAIError, APIStatusError -from ._base_client import DEFAULT_MAX_RETRIES, SyncAPIClient, AsyncAPIClient +from ._base_client import ( + DEFAULT_MAX_RETRIES, + SyncAPIClient, + AsyncAPIClient, +) __all__ = [ "Timeout", diff --git a/src/openai/_compat.py b/src/openai/_compat.py index 34323c9b7e..d95db8ed1e 100644 --- a/src/openai/_compat.py +++ b/src/openai/_compat.py @@ -43,21 +43,23 @@ def is_typeddict(type_: type[Any]) -> bool: # noqa: ARG001 else: if PYDANTIC_V2: - from pydantic.v1.typing import get_args as get_args - from pydantic.v1.typing import is_union as is_union - from pydantic.v1.typing import get_origin as get_origin - from pydantic.v1.typing import is_typeddict as is_typeddict - from pydantic.v1.typing import is_literal_type as is_literal_type - from pydantic.v1.datetime_parse import parse_date as parse_date - from pydantic.v1.datetime_parse import parse_datetime as parse_datetime + from pydantic.v1.typing import ( + get_args as get_args, + is_union as is_union, + get_origin as get_origin, + is_typeddict as is_typeddict, + is_literal_type as is_literal_type, + ) + from pydantic.v1.datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime else: - from pydantic.typing import get_args as get_args - from pydantic.typing import is_union as is_union - from pydantic.typing import get_origin as get_origin - from pydantic.typing import is_typeddict as is_typeddict - from pydantic.typing import is_literal_type as is_literal_type - from pydantic.datetime_parse import parse_date as parse_date - from pydantic.datetime_parse import parse_datetime as parse_datetime + from pydantic.typing import ( + get_args as get_args, + is_union as is_union, + get_origin as get_origin, + is_typeddict as is_typeddict, + is_literal_type as is_literal_type, + ) + from pydantic.datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime # refactored config diff --git a/src/openai/_extras/__init__.py b/src/openai/_extras/__init__.py index dc6625c5dc..864dac4171 100644 --- a/src/openai/_extras/__init__.py +++ b/src/openai/_extras/__init__.py @@ -1,3 +1,2 @@ -from .numpy_proxy import numpy as numpy -from .numpy_proxy import has_numpy as has_numpy +from .numpy_proxy import numpy as numpy, has_numpy as has_numpy from .pandas_proxy import pandas as pandas diff --git a/src/openai/_models.py b/src/openai/_models.py index 330a2064d8..48d5624f64 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -30,17 +30,11 @@ AnyMapping, HttpxRequestFiles, ) -from ._utils import ( - is_list, - is_given, - is_mapping, - parse_date, - parse_datetime, - strip_not_given, -) -from ._compat import PYDANTIC_V2, ConfigDict -from ._compat import GenericModel as BaseGenericModel +from ._utils import is_list, is_given, is_mapping, parse_date, parse_datetime, strip_not_given from ._compat import ( + PYDANTIC_V2, + ConfigDict, + GenericModel as BaseGenericModel, get_args, is_union, parse_obj, diff --git a/src/openai/_types.py b/src/openai/_types.py index 061e5c97f5..b52af6882f 100644 --- a/src/openai/_types.py +++ b/src/openai/_types.py @@ -19,14 +19,7 @@ Sequence, AsyncIterator, ) -from typing_extensions import ( - Literal, - Protocol, - TypeAlias, - TypedDict, - override, - runtime_checkable, -) +from typing_extensions import Literal, Protocol, TypeAlias, TypedDict, override, runtime_checkable import httpx import pydantic diff --git a/src/openai/_utils/__init__.py b/src/openai/_utils/__init__.py index a43201d3c7..2dcfc122f1 100644 --- a/src/openai/_utils/__init__.py +++ b/src/openai/_utils/__init__.py @@ -1,40 +1,45 @@ from ._proxy import LazyProxy as LazyProxy -from ._utils import flatten as flatten -from ._utils import is_dict as is_dict -from ._utils import is_list as is_list -from ._utils import is_given as is_given -from ._utils import is_tuple as is_tuple -from ._utils import is_mapping as is_mapping -from ._utils import is_tuple_t as is_tuple_t -from ._utils import parse_date as parse_date -from ._utils import is_sequence as is_sequence -from ._utils import coerce_float as coerce_float -from ._utils import is_mapping_t as is_mapping_t -from ._utils import removeprefix as removeprefix -from ._utils import removesuffix as removesuffix -from ._utils import extract_files as extract_files -from ._utils import is_sequence_t as is_sequence_t -from ._utils import required_args as required_args -from ._utils import coerce_boolean as coerce_boolean -from ._utils import coerce_integer as coerce_integer -from ._utils import file_from_path as file_from_path -from ._utils import parse_datetime as parse_datetime -from ._utils import strip_not_given as strip_not_given -from ._utils import deepcopy_minimal as deepcopy_minimal -from ._utils import get_async_library as get_async_library -from ._utils import maybe_coerce_float as maybe_coerce_float -from ._utils import get_required_header as get_required_header -from ._utils import maybe_coerce_boolean as maybe_coerce_boolean -from ._utils import maybe_coerce_integer as maybe_coerce_integer -from ._typing import is_list_type as is_list_type -from ._typing import is_union_type as is_union_type -from ._typing import extract_type_arg as extract_type_arg -from ._typing import is_required_type as is_required_type -from ._typing import is_annotated_type as is_annotated_type -from ._typing import strip_annotated_type as strip_annotated_type -from ._typing import extract_type_var_from_base as extract_type_var_from_base -from ._streams import consume_sync_iterator as consume_sync_iterator -from ._streams import consume_async_iterator as consume_async_iterator -from ._transform import PropertyInfo as PropertyInfo -from ._transform import transform as transform -from ._transform import maybe_transform as maybe_transform +from ._utils import ( + flatten as flatten, + is_dict as is_dict, + is_list as is_list, + is_given as is_given, + is_tuple as is_tuple, + is_mapping as is_mapping, + is_tuple_t as is_tuple_t, + parse_date as parse_date, + is_sequence as is_sequence, + coerce_float as coerce_float, + is_mapping_t as is_mapping_t, + removeprefix as removeprefix, + removesuffix as removesuffix, + extract_files as extract_files, + is_sequence_t as is_sequence_t, + required_args as required_args, + coerce_boolean as coerce_boolean, + coerce_integer as coerce_integer, + file_from_path as file_from_path, + parse_datetime as parse_datetime, + strip_not_given as strip_not_given, + deepcopy_minimal as deepcopy_minimal, + get_async_library as get_async_library, + maybe_coerce_float as maybe_coerce_float, + get_required_header as get_required_header, + maybe_coerce_boolean as maybe_coerce_boolean, + maybe_coerce_integer as maybe_coerce_integer, +) +from ._typing import ( + is_list_type as is_list_type, + is_union_type as is_union_type, + extract_type_arg as extract_type_arg, + is_required_type as is_required_type, + is_annotated_type as is_annotated_type, + strip_annotated_type as strip_annotated_type, + extract_type_var_from_base as extract_type_var_from_base, +) +from ._streams import consume_sync_iterator as consume_sync_iterator, consume_async_iterator as consume_async_iterator +from ._transform import ( + PropertyInfo as PropertyInfo, + transform as transform, + maybe_transform as maybe_transform, +) diff --git a/src/openai/_utils/_transform.py b/src/openai/_utils/_transform.py index 342b52416a..3a1c14969b 100644 --- a/src/openai/_utils/_transform.py +++ b/src/openai/_utils/_transform.py @@ -6,7 +6,10 @@ import pydantic -from ._utils import is_list, is_mapping +from ._utils import ( + is_list, + is_mapping, +) from ._typing import ( is_list_type, is_union_type, diff --git a/src/openai/_utils/_utils.py b/src/openai/_utils/_utils.py index cc624b0ce1..1c5c21a8ea 100644 --- a/src/openai/_utils/_utils.py +++ b/src/openai/_utils/_utils.py @@ -21,8 +21,7 @@ import sniffio from .._types import Headers, NotGiven, FileTypes, NotGivenOr, HeadersLike -from .._compat import parse_date as parse_date -from .._compat import parse_datetime as parse_datetime +from .._compat import parse_date as parse_date, parse_datetime as parse_datetime _T = TypeVar("_T") _TupleT = TypeVar("_TupleT", bound=Tuple[object, ...]) diff --git a/src/openai/resources/__init__.py b/src/openai/resources/__init__.py index e0f4f08d5c..2cdbeb6ae1 100644 --- a/src/openai/resources/__init__.py +++ b/src/openai/resources/__init__.py @@ -5,48 +5,13 @@ from .audio import Audio, AsyncAudio, AudioWithRawResponse, AsyncAudioWithRawResponse from .edits import Edits, AsyncEdits, EditsWithRawResponse, AsyncEditsWithRawResponse from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from .images import ( - Images, - AsyncImages, - ImagesWithRawResponse, - AsyncImagesWithRawResponse, -) -from .models import ( - Models, - AsyncModels, - ModelsWithRawResponse, - AsyncModelsWithRawResponse, -) -from .embeddings import ( - Embeddings, - AsyncEmbeddings, - EmbeddingsWithRawResponse, - AsyncEmbeddingsWithRawResponse, -) -from .fine_tunes import ( - FineTunes, - AsyncFineTunes, - FineTunesWithRawResponse, - AsyncFineTunesWithRawResponse, -) -from .completions import ( - Completions, - AsyncCompletions, - CompletionsWithRawResponse, - AsyncCompletionsWithRawResponse, -) -from .fine_tuning import ( - FineTuning, - AsyncFineTuning, - FineTuningWithRawResponse, - AsyncFineTuningWithRawResponse, -) -from .moderations import ( - Moderations, - AsyncModerations, - ModerationsWithRawResponse, - AsyncModerationsWithRawResponse, -) +from .images import Images, AsyncImages, ImagesWithRawResponse, AsyncImagesWithRawResponse +from .models import Models, AsyncModels, ModelsWithRawResponse, AsyncModelsWithRawResponse +from .embeddings import Embeddings, AsyncEmbeddings, EmbeddingsWithRawResponse, AsyncEmbeddingsWithRawResponse +from .fine_tunes import FineTunes, AsyncFineTunes, FineTunesWithRawResponse, AsyncFineTunesWithRawResponse +from .completions import Completions, AsyncCompletions, CompletionsWithRawResponse, AsyncCompletionsWithRawResponse +from .fine_tuning import FineTuning, AsyncFineTuning, FineTuningWithRawResponse, AsyncFineTuningWithRawResponse +from .moderations import Moderations, AsyncModerations, ModerationsWithRawResponse, AsyncModerationsWithRawResponse __all__ = [ "Completions", diff --git a/src/openai/resources/audio/__init__.py b/src/openai/resources/audio/__init__.py index 76547b5f34..b6ff4322d4 100644 --- a/src/openai/resources/audio/__init__.py +++ b/src/openai/resources/audio/__init__.py @@ -1,18 +1,8 @@ # File generated from our OpenAPI spec by Stainless. from .audio import Audio, AsyncAudio, AudioWithRawResponse, AsyncAudioWithRawResponse -from .speech import ( - Speech, - AsyncSpeech, - SpeechWithRawResponse, - AsyncSpeechWithRawResponse, -) -from .translations import ( - Translations, - AsyncTranslations, - TranslationsWithRawResponse, - AsyncTranslationsWithRawResponse, -) +from .speech import Speech, AsyncSpeech, SpeechWithRawResponse, AsyncSpeechWithRawResponse +from .translations import Translations, AsyncTranslations, TranslationsWithRawResponse, AsyncTranslationsWithRawResponse from .transcriptions import ( Transcriptions, AsyncTranscriptions, diff --git a/src/openai/resources/audio/audio.py b/src/openai/resources/audio/audio.py index 6f7226ee59..6b9242f0c2 100644 --- a/src/openai/resources/audio/audio.py +++ b/src/openai/resources/audio/audio.py @@ -4,19 +4,9 @@ from typing import TYPE_CHECKING -from .speech import ( - Speech, - AsyncSpeech, - SpeechWithRawResponse, - AsyncSpeechWithRawResponse, -) +from .speech import Speech, AsyncSpeech, SpeechWithRawResponse, AsyncSpeechWithRawResponse from ..._resource import SyncAPIResource, AsyncAPIResource -from .translations import ( - Translations, - AsyncTranslations, - TranslationsWithRawResponse, - AsyncTranslationsWithRawResponse, -) +from .translations import Translations, AsyncTranslations, TranslationsWithRawResponse, AsyncTranslationsWithRawResponse from .transcriptions import ( Transcriptions, AsyncTranscriptions, diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index aadb00bd02..7ae552c12f 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -7,12 +7,21 @@ import httpx -from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ..._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ..._utils import maybe_transform from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ...types.audio import speech_create_params -from ..._base_client import HttpxBinaryResponseContent, make_request_options +from ..._base_client import ( + HttpxBinaryResponseContent, + make_request_options, +) if TYPE_CHECKING: from ..._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index d2b4452411..54be1c99a6 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -7,12 +7,21 @@ import httpx -from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes +from ..._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, + FileTypes, +) from ..._utils import extract_files, maybe_transform, deepcopy_minimal from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ...types.audio import Transcription, transcription_create_params -from ..._base_client import make_request_options +from ..._base_client import ( + make_request_options, +) if TYPE_CHECKING: from ..._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index fe7f7f2a40..c4489004ac 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -7,12 +7,21 @@ import httpx -from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes +from ..._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, + FileTypes, +) from ..._utils import extract_files, maybe_transform, deepcopy_minimal from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ...types.audio import Translation, translation_create_params -from ..._base_client import make_request_options +from ..._base_client import ( + make_request_options, +) if TYPE_CHECKING: from ..._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/beta/__init__.py b/src/openai/resources/beta/__init__.py index 55ad243cca..561f8bef60 100644 --- a/src/openai/resources/beta/__init__.py +++ b/src/openai/resources/beta/__init__.py @@ -1,18 +1,8 @@ # File generated from our OpenAPI spec by Stainless. from .beta import Beta, AsyncBeta, BetaWithRawResponse, AsyncBetaWithRawResponse -from .threads import ( - Threads, - AsyncThreads, - ThreadsWithRawResponse, - AsyncThreadsWithRawResponse, -) -from .assistants import ( - Assistants, - AsyncAssistants, - AssistantsWithRawResponse, - AsyncAssistantsWithRawResponse, -) +from .threads import Threads, AsyncThreads, ThreadsWithRawResponse, AsyncThreadsWithRawResponse +from .assistants import Assistants, AsyncAssistants, AssistantsWithRawResponse, AsyncAssistantsWithRawResponse __all__ = [ "Assistants", diff --git a/src/openai/resources/beta/assistants/__init__.py b/src/openai/resources/beta/assistants/__init__.py index 6efb0b21ec..205b2cf0f5 100644 --- a/src/openai/resources/beta/assistants/__init__.py +++ b/src/openai/resources/beta/assistants/__init__.py @@ -1,12 +1,7 @@ # File generated from our OpenAPI spec by Stainless. from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from .assistants import ( - Assistants, - AsyncAssistants, - AssistantsWithRawResponse, - AsyncAssistantsWithRawResponse, -) +from .assistants import Assistants, AsyncAssistants, AssistantsWithRawResponse, AsyncAssistantsWithRawResponse __all__ = [ "Files", diff --git a/src/openai/resources/beta/assistants/assistants.py b/src/openai/resources/beta/assistants/assistants.py index 8854c8b867..13b90ac69c 100644 --- a/src/openai/resources/beta/assistants/assistants.py +++ b/src/openai/resources/beta/assistants/assistants.py @@ -8,7 +8,13 @@ import httpx from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ...._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ...._utils import maybe_transform from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_raw_response_wrapper, async_to_raw_response_wrapper @@ -20,7 +26,10 @@ assistant_create_params, assistant_update_params, ) -from ...._base_client import AsyncPaginator, make_request_options +from ...._base_client import ( + AsyncPaginator, + make_request_options, +) if TYPE_CHECKING: from ...._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/beta/assistants/files.py b/src/openai/resources/beta/assistants/files.py index 5ac5897ca3..5682587487 100644 --- a/src/openai/resources/beta/assistants/files.py +++ b/src/openai/resources/beta/assistants/files.py @@ -7,12 +7,21 @@ import httpx -from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ...._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ...._utils import maybe_transform from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ....pagination import SyncCursorPage, AsyncCursorPage -from ...._base_client import AsyncPaginator, make_request_options +from ...._base_client import ( + AsyncPaginator, + make_request_options, +) from ....types.beta.assistants import ( AssistantFile, FileDeleteResponse, diff --git a/src/openai/resources/beta/beta.py b/src/openai/resources/beta/beta.py index b552561763..5cea6c1460 100644 --- a/src/openai/resources/beta/beta.py +++ b/src/openai/resources/beta/beta.py @@ -4,18 +4,8 @@ from typing import TYPE_CHECKING -from .threads import ( - Threads, - AsyncThreads, - ThreadsWithRawResponse, - AsyncThreadsWithRawResponse, -) -from .assistants import ( - Assistants, - AsyncAssistants, - AssistantsWithRawResponse, - AsyncAssistantsWithRawResponse, -) +from .threads import Threads, AsyncThreads, ThreadsWithRawResponse, AsyncThreadsWithRawResponse +from .assistants import Assistants, AsyncAssistants, AssistantsWithRawResponse, AsyncAssistantsWithRawResponse from ..._resource import SyncAPIResource, AsyncAPIResource if TYPE_CHECKING: diff --git a/src/openai/resources/beta/threads/__init__.py b/src/openai/resources/beta/threads/__init__.py index b9aaada465..fe7c5e5a20 100644 --- a/src/openai/resources/beta/threads/__init__.py +++ b/src/openai/resources/beta/threads/__init__.py @@ -1,18 +1,8 @@ # File generated from our OpenAPI spec by Stainless. from .runs import Runs, AsyncRuns, RunsWithRawResponse, AsyncRunsWithRawResponse -from .threads import ( - Threads, - AsyncThreads, - ThreadsWithRawResponse, - AsyncThreadsWithRawResponse, -) -from .messages import ( - Messages, - AsyncMessages, - MessagesWithRawResponse, - AsyncMessagesWithRawResponse, -) +from .threads import Threads, AsyncThreads, ThreadsWithRawResponse, AsyncThreadsWithRawResponse +from .messages import Messages, AsyncMessages, MessagesWithRawResponse, AsyncMessagesWithRawResponse __all__ = [ "Runs", diff --git a/src/openai/resources/beta/threads/messages/__init__.py b/src/openai/resources/beta/threads/messages/__init__.py index d8d4ce448c..cef618ed14 100644 --- a/src/openai/resources/beta/threads/messages/__init__.py +++ b/src/openai/resources/beta/threads/messages/__init__.py @@ -1,12 +1,7 @@ # File generated from our OpenAPI spec by Stainless. from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from .messages import ( - Messages, - AsyncMessages, - MessagesWithRawResponse, - AsyncMessagesWithRawResponse, -) +from .messages import Messages, AsyncMessages, MessagesWithRawResponse, AsyncMessagesWithRawResponse __all__ = [ "Files", diff --git a/src/openai/resources/beta/threads/messages/files.py b/src/openai/resources/beta/threads/messages/files.py index e028a6fda7..24c9680f3d 100644 --- a/src/openai/resources/beta/threads/messages/files.py +++ b/src/openai/resources/beta/threads/messages/files.py @@ -7,12 +7,21 @@ import httpx -from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ....._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ....._utils import maybe_transform from ....._resource import SyncAPIResource, AsyncAPIResource from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .....pagination import SyncCursorPage, AsyncCursorPage -from ....._base_client import AsyncPaginator, make_request_options +from ....._base_client import ( + AsyncPaginator, + make_request_options, +) from .....types.beta.threads.messages import MessageFile, file_list_params if TYPE_CHECKING: diff --git a/src/openai/resources/beta/threads/messages/messages.py b/src/openai/resources/beta/threads/messages/messages.py index 30ae072512..9a6f5706c3 100644 --- a/src/openai/resources/beta/threads/messages/messages.py +++ b/src/openai/resources/beta/threads/messages/messages.py @@ -8,12 +8,21 @@ import httpx from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ....._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ....._utils import maybe_transform from ....._resource import SyncAPIResource, AsyncAPIResource from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .....pagination import SyncCursorPage, AsyncCursorPage -from ....._base_client import AsyncPaginator, make_request_options +from ....._base_client import ( + AsyncPaginator, + make_request_options, +) from .....types.beta.threads import ( ThreadMessage, message_list_params, diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index aea3b8cefc..6a727b856b 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -8,12 +8,21 @@ import httpx from .steps import Steps, AsyncSteps, StepsWithRawResponse, AsyncStepsWithRawResponse -from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ....._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ....._utils import maybe_transform from ....._resource import SyncAPIResource, AsyncAPIResource from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .....pagination import SyncCursorPage, AsyncCursorPage -from ....._base_client import AsyncPaginator, make_request_options +from ....._base_client import ( + AsyncPaginator, + make_request_options, +) from .....types.beta.threads import ( Run, run_list_params, diff --git a/src/openai/resources/beta/threads/runs/steps.py b/src/openai/resources/beta/threads/runs/steps.py index 4fcc87a0ff..f26034cf82 100644 --- a/src/openai/resources/beta/threads/runs/steps.py +++ b/src/openai/resources/beta/threads/runs/steps.py @@ -7,12 +7,21 @@ import httpx -from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ....._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ....._utils import maybe_transform from ....._resource import SyncAPIResource, AsyncAPIResource from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .....pagination import SyncCursorPage, AsyncCursorPage -from ....._base_client import AsyncPaginator, make_request_options +from ....._base_client import ( + AsyncPaginator, + make_request_options, +) from .....types.beta.threads.runs import RunStep, step_list_params if TYPE_CHECKING: diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 9469fc0513..b37667485d 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -7,13 +7,14 @@ import httpx from .runs import Runs, AsyncRuns, RunsWithRawResponse, AsyncRunsWithRawResponse -from .messages import ( - Messages, - AsyncMessages, - MessagesWithRawResponse, - AsyncMessagesWithRawResponse, +from .messages import Messages, AsyncMessages, MessagesWithRawResponse, AsyncMessagesWithRawResponse +from ...._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, ) -from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ...._utils import maybe_transform from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_raw_response_wrapper, async_to_raw_response_wrapper @@ -24,7 +25,9 @@ thread_update_params, thread_create_and_run_params, ) -from ...._base_client import make_request_options +from ...._base_client import ( + make_request_options, +) from ....types.beta.threads import Run if TYPE_CHECKING: diff --git a/src/openai/resources/chat/__init__.py b/src/openai/resources/chat/__init__.py index 2e56c0cbfa..85b246509e 100644 --- a/src/openai/resources/chat/__init__.py +++ b/src/openai/resources/chat/__init__.py @@ -1,12 +1,7 @@ # File generated from our OpenAPI spec by Stainless. from .chat import Chat, AsyncChat, ChatWithRawResponse, AsyncChatWithRawResponse -from .completions import ( - Completions, - AsyncCompletions, - CompletionsWithRawResponse, - AsyncCompletionsWithRawResponse, -) +from .completions import Completions, AsyncCompletions, CompletionsWithRawResponse, AsyncCompletionsWithRawResponse __all__ = [ "Completions", diff --git a/src/openai/resources/chat/chat.py b/src/openai/resources/chat/chat.py index 3847b20512..d93a501b1f 100644 --- a/src/openai/resources/chat/chat.py +++ b/src/openai/resources/chat/chat.py @@ -5,12 +5,7 @@ from typing import TYPE_CHECKING from ..._resource import SyncAPIResource, AsyncAPIResource -from .completions import ( - Completions, - AsyncCompletions, - CompletionsWithRawResponse, - AsyncCompletionsWithRawResponse, -) +from .completions import Completions, AsyncCompletions, CompletionsWithRawResponse, AsyncCompletionsWithRawResponse if TYPE_CHECKING: from ..._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index 5aac234227..6bde8383dc 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -7,7 +7,13 @@ import httpx -from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ..._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ..._utils import required_args, maybe_transform from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper @@ -20,7 +26,9 @@ ChatCompletionToolChoiceOptionParam, completion_create_params, ) -from ..._base_client import make_request_options +from ..._base_client import ( + make_request_options, +) if TYPE_CHECKING: from ..._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index d22e288054..a13c901529 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -8,12 +8,20 @@ import httpx from ..types import Completion, completion_create_params -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from .._utils import required_args, maybe_transform from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .._streaming import Stream, AsyncStream -from .._base_client import make_request_options +from .._base_client import ( + make_request_options, +) if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/edits.py b/src/openai/resources/edits.py index eafaa82fdf..587da02c8f 100644 --- a/src/openai/resources/edits.py +++ b/src/openai/resources/edits.py @@ -9,11 +9,19 @@ import httpx from ..types import Edit, edit_create_params -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from .._utils import maybe_transform from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper -from .._base_client import make_request_options +from .._base_client import ( + make_request_options, +) if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/embeddings.py b/src/openai/resources/embeddings.py index 978d239774..f22acad401 100644 --- a/src/openai/resources/embeddings.py +++ b/src/openai/resources/embeddings.py @@ -9,13 +9,20 @@ import httpx from ..types import CreateEmbeddingResponse, embedding_create_params -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from .._utils import is_given, maybe_transform -from .._extras import numpy as np -from .._extras import has_numpy +from .._extras import numpy as np, has_numpy from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper -from .._base_client import make_request_options +from .._base_client import ( + make_request_options, +) if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index e4d978d3af..bc7823783b 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -9,8 +9,20 @@ import httpx -from ..types import FileObject, FileDeleted, file_list_params, file_create_params -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes +from ..types import ( + FileObject, + FileDeleted, + file_list_params, + file_create_params, +) +from .._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, + FileTypes, +) from .._utils import extract_files, maybe_transform, deepcopy_minimal from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper diff --git a/src/openai/resources/fine_tunes.py b/src/openai/resources/fine_tunes.py index 91c8201cbb..f50d78717b 100644 --- a/src/openai/resources/fine_tunes.py +++ b/src/openai/resources/fine_tunes.py @@ -14,13 +14,22 @@ fine_tune_create_params, fine_tune_list_events_params, ) -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from .._utils import maybe_transform from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .._streaming import Stream, AsyncStream from ..pagination import SyncPage, AsyncPage -from .._base_client import AsyncPaginator, make_request_options +from .._base_client import ( + AsyncPaginator, + make_request_options, +) if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/fine_tuning/__init__.py b/src/openai/resources/fine_tuning/__init__.py index 9133c25d4a..27445fb707 100644 --- a/src/openai/resources/fine_tuning/__init__.py +++ b/src/openai/resources/fine_tuning/__init__.py @@ -1,12 +1,7 @@ # File generated from our OpenAPI spec by Stainless. from .jobs import Jobs, AsyncJobs, JobsWithRawResponse, AsyncJobsWithRawResponse -from .fine_tuning import ( - FineTuning, - AsyncFineTuning, - FineTuningWithRawResponse, - AsyncFineTuningWithRawResponse, -) +from .fine_tuning import FineTuning, AsyncFineTuning, FineTuningWithRawResponse, AsyncFineTuningWithRawResponse __all__ = [ "Jobs", diff --git a/src/openai/resources/fine_tuning/jobs.py b/src/openai/resources/fine_tuning/jobs.py index 3d9aed8d91..55eee67044 100644 --- a/src/openai/resources/fine_tuning/jobs.py +++ b/src/openai/resources/fine_tuning/jobs.py @@ -7,12 +7,21 @@ import httpx -from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ..._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ..._utils import maybe_transform from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ...pagination import SyncCursorPage, AsyncCursorPage -from ..._base_client import AsyncPaginator, make_request_options +from ..._base_client import ( + AsyncPaginator, + make_request_options, +) from ...types.fine_tuning import ( FineTuningJob, FineTuningJobEvent, diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py index 94b1bc1fc8..0e1313078f 100644 --- a/src/openai/resources/images.py +++ b/src/openai/resources/images.py @@ -13,11 +13,20 @@ image_generate_params, image_create_variation_params, ) -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes +from .._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, + FileTypes, +) from .._utils import extract_files, maybe_transform, deepcopy_minimal from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper -from .._base_client import make_request_options +from .._base_client import ( + make_request_options, +) if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/models.py b/src/openai/resources/models.py index 2d04bdc5cc..a44a7ffbb0 100644 --- a/src/openai/resources/models.py +++ b/src/openai/resources/models.py @@ -7,11 +7,20 @@ import httpx from ..types import Model, ModelDeleted -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ..pagination import SyncPage, AsyncPage -from .._base_client import AsyncPaginator, make_request_options +from .._base_client import ( + AsyncPaginator, + make_request_options, +) if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/moderations.py b/src/openai/resources/moderations.py index 12a7c68a7b..9de7cd640f 100644 --- a/src/openai/resources/moderations.py +++ b/src/openai/resources/moderations.py @@ -8,11 +8,19 @@ import httpx from ..types import ModerationCreateResponse, moderation_create_params -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from .._utils import maybe_transform from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper -from .._base_client import make_request_options +from .._base_client import ( + make_request_options, +) if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index 1b4fca26ee..df2b580587 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -5,8 +5,7 @@ from .edit import Edit as Edit from .image import Image as Image from .model import Model as Model -from .shared import FunctionDefinition as FunctionDefinition -from .shared import FunctionParameters as FunctionParameters +from .shared import FunctionDefinition as FunctionDefinition, FunctionParameters as FunctionParameters from .embedding import Embedding as Embedding from .fine_tune import FineTune as FineTune from .completion import Completion as Completion @@ -28,18 +27,8 @@ from .fine_tune_create_params import FineTuneCreateParams as FineTuneCreateParams from .completion_create_params import CompletionCreateParams as CompletionCreateParams from .moderation_create_params import ModerationCreateParams as ModerationCreateParams -from .create_embedding_response import ( - CreateEmbeddingResponse as CreateEmbeddingResponse, -) -from .moderation_create_response import ( - ModerationCreateResponse as ModerationCreateResponse, -) -from .fine_tune_list_events_params import ( - FineTuneListEventsParams as FineTuneListEventsParams, -) -from .image_create_variation_params import ( - ImageCreateVariationParams as ImageCreateVariationParams, -) -from .fine_tune_events_list_response import ( - FineTuneEventsListResponse as FineTuneEventsListResponse, -) +from .create_embedding_response import CreateEmbeddingResponse as CreateEmbeddingResponse +from .moderation_create_response import ModerationCreateResponse as ModerationCreateResponse +from .fine_tune_list_events_params import FineTuneListEventsParams as FineTuneListEventsParams +from .image_create_variation_params import ImageCreateVariationParams as ImageCreateVariationParams +from .fine_tune_events_list_response import FineTuneEventsListResponse as FineTuneEventsListResponse diff --git a/src/openai/types/audio/__init__.py b/src/openai/types/audio/__init__.py index 83afa060f8..ba5f7fd8e0 100644 --- a/src/openai/types/audio/__init__.py +++ b/src/openai/types/audio/__init__.py @@ -5,9 +5,5 @@ from .translation import Translation as Translation from .transcription import Transcription as Transcription from .speech_create_params import SpeechCreateParams as SpeechCreateParams -from .translation_create_params import ( - TranslationCreateParams as TranslationCreateParams, -) -from .transcription_create_params import ( - TranscriptionCreateParams as TranscriptionCreateParams, -) +from .translation_create_params import TranslationCreateParams as TranslationCreateParams +from .transcription_create_params import TranscriptionCreateParams as TranscriptionCreateParams diff --git a/src/openai/types/beta/__init__.py b/src/openai/types/beta/__init__.py index c03d823b8c..e6742521e9 100644 --- a/src/openai/types/beta/__init__.py +++ b/src/openai/types/beta/__init__.py @@ -11,6 +11,4 @@ from .assistant_list_params import AssistantListParams as AssistantListParams from .assistant_create_params import AssistantCreateParams as AssistantCreateParams from .assistant_update_params import AssistantUpdateParams as AssistantUpdateParams -from .thread_create_and_run_params import ( - ThreadCreateAndRunParams as ThreadCreateAndRunParams, -) +from .thread_create_and_run_params import ThreadCreateAndRunParams as ThreadCreateAndRunParams diff --git a/src/openai/types/beta/threads/__init__.py b/src/openai/types/beta/threads/__init__.py index 0cb557a514..8c77466dec 100644 --- a/src/openai/types/beta/threads/__init__.py +++ b/src/openai/types/beta/threads/__init__.py @@ -11,12 +11,6 @@ from .message_content_text import MessageContentText as MessageContentText from .message_create_params import MessageCreateParams as MessageCreateParams from .message_update_params import MessageUpdateParams as MessageUpdateParams -from .message_content_image_file import ( - MessageContentImageFile as MessageContentImageFile, -) -from .run_submit_tool_outputs_params import ( - RunSubmitToolOutputsParams as RunSubmitToolOutputsParams, -) -from .required_action_function_tool_call import ( - RequiredActionFunctionToolCall as RequiredActionFunctionToolCall, -) +from .message_content_image_file import MessageContentImageFile as MessageContentImageFile +from .run_submit_tool_outputs_params import RunSubmitToolOutputsParams as RunSubmitToolOutputsParams +from .required_action_function_tool_call import RequiredActionFunctionToolCall as RequiredActionFunctionToolCall diff --git a/src/openai/types/beta/threads/runs/__init__.py b/src/openai/types/beta/threads/runs/__init__.py index 72b972a986..16cb852922 100644 --- a/src/openai/types/beta/threads/runs/__init__.py +++ b/src/openai/types/beta/threads/runs/__init__.py @@ -8,6 +8,4 @@ from .function_tool_call import FunctionToolCall as FunctionToolCall from .retrieval_tool_call import RetrievalToolCall as RetrievalToolCall from .tool_calls_step_details import ToolCallsStepDetails as ToolCallsStepDetails -from .message_creation_step_details import ( - MessageCreationStepDetails as MessageCreationStepDetails, -) +from .message_creation_step_details import MessageCreationStepDetails as MessageCreationStepDetails diff --git a/src/openai/types/chat/__init__.py b/src/openai/types/chat/__init__.py index ba21982a2b..39a6335f64 100644 --- a/src/openai/types/chat/__init__.py +++ b/src/openai/types/chat/__init__.py @@ -7,30 +7,14 @@ from .chat_completion_chunk import ChatCompletionChunk as ChatCompletionChunk from .chat_completion_message import ChatCompletionMessage as ChatCompletionMessage from .completion_create_params import CompletionCreateParams as CompletionCreateParams -from .chat_completion_tool_param import ( - ChatCompletionToolParam as ChatCompletionToolParam, -) -from .chat_completion_message_param import ( - ChatCompletionMessageParam as ChatCompletionMessageParam, -) -from .chat_completion_token_logprob import ( - ChatCompletionTokenLogprob as ChatCompletionTokenLogprob, -) -from .chat_completion_message_tool_call import ( - ChatCompletionMessageToolCall as ChatCompletionMessageToolCall, -) -from .chat_completion_content_part_param import ( - ChatCompletionContentPartParam as ChatCompletionContentPartParam, -) -from .chat_completion_tool_message_param import ( - ChatCompletionToolMessageParam as ChatCompletionToolMessageParam, -) -from .chat_completion_user_message_param import ( - ChatCompletionUserMessageParam as ChatCompletionUserMessageParam, -) -from .chat_completion_system_message_param import ( - ChatCompletionSystemMessageParam as ChatCompletionSystemMessageParam, -) +from .chat_completion_tool_param import ChatCompletionToolParam as ChatCompletionToolParam +from .chat_completion_message_param import ChatCompletionMessageParam as ChatCompletionMessageParam +from .chat_completion_token_logprob import ChatCompletionTokenLogprob as ChatCompletionTokenLogprob +from .chat_completion_message_tool_call import ChatCompletionMessageToolCall as ChatCompletionMessageToolCall +from .chat_completion_content_part_param import ChatCompletionContentPartParam as ChatCompletionContentPartParam +from .chat_completion_tool_message_param import ChatCompletionToolMessageParam as ChatCompletionToolMessageParam +from .chat_completion_user_message_param import ChatCompletionUserMessageParam as ChatCompletionUserMessageParam +from .chat_completion_system_message_param import ChatCompletionSystemMessageParam as ChatCompletionSystemMessageParam from .chat_completion_function_message_param import ( ChatCompletionFunctionMessageParam as ChatCompletionFunctionMessageParam, ) diff --git a/src/openai/types/chat/chat_completion_content_part_param.py b/src/openai/types/chat/chat_completion_content_part_param.py index 587578e2ef..8e58239258 100644 --- a/src/openai/types/chat/chat_completion_content_part_param.py +++ b/src/openai/types/chat/chat_completion_content_part_param.py @@ -5,9 +5,7 @@ from typing import Union from .chat_completion_content_part_text_param import ChatCompletionContentPartTextParam -from .chat_completion_content_part_image_param import ( - ChatCompletionContentPartImageParam, -) +from .chat_completion_content_part_image_param import ChatCompletionContentPartImageParam __all__ = ["ChatCompletionContentPartParam"] diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 41b71efa04..49807a372e 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -8,12 +8,8 @@ from ...types import shared_params from .chat_completion_tool_param import ChatCompletionToolParam from .chat_completion_message_param import ChatCompletionMessageParam -from .chat_completion_tool_choice_option_param import ( - ChatCompletionToolChoiceOptionParam, -) -from .chat_completion_function_call_option_param import ( - ChatCompletionFunctionCallOptionParam, -) +from .chat_completion_tool_choice_option_param import ChatCompletionToolChoiceOptionParam +from .chat_completion_function_call_option_param import ChatCompletionFunctionCallOptionParam __all__ = [ "CompletionCreateParamsBase", diff --git a/tests/api_resources/beta/test_assistants.py b/tests/api_resources/beta/test_assistants.py index 82e975b46d..97e74c61e4 100644 --- a/tests/api_resources/beta/test_assistants.py +++ b/tests/api_resources/beta/test_assistants.py @@ -10,7 +10,10 @@ from tests.utils import assert_matches_type from openai._client import OpenAI, AsyncOpenAI from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta import Assistant, AssistantDeleted +from openai.types.beta import ( + Assistant, + AssistantDeleted, +) base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") api_key = "My API Key" diff --git a/tests/api_resources/beta/test_threads.py b/tests/api_resources/beta/test_threads.py index 8fa1fc20ea..860159ffb3 100644 --- a/tests/api_resources/beta/test_threads.py +++ b/tests/api_resources/beta/test_threads.py @@ -9,7 +9,10 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai._client import OpenAI, AsyncOpenAI -from openai.types.beta import Thread, ThreadDeleted +from openai.types.beta import ( + Thread, + ThreadDeleted, +) from openai.types.beta.threads import Run base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index 494cae2656..9d04a95c80 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -10,7 +10,9 @@ from tests.utils import assert_matches_type from openai._client import OpenAI, AsyncOpenAI from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta.threads import Run +from openai.types.beta.threads import ( + Run, +) base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") api_key = "My API Key" diff --git a/tests/api_resources/fine_tuning/test_jobs.py b/tests/api_resources/fine_tuning/test_jobs.py index 5716a23d54..927ca9bbdd 100644 --- a/tests/api_resources/fine_tuning/test_jobs.py +++ b/tests/api_resources/fine_tuning/test_jobs.py @@ -10,7 +10,10 @@ from tests.utils import assert_matches_type from openai._client import OpenAI, AsyncOpenAI from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.fine_tuning import FineTuningJob, FineTuningJobEvent +from openai.types.fine_tuning import ( + FineTuningJob, + FineTuningJobEvent, +) base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") api_key = "My API Key" diff --git a/tests/test_client.py b/tests/test_client.py index ffa779fb38..c49e4d629e 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -20,18 +20,8 @@ from openai._client import OpenAI, AsyncOpenAI from openai._models import BaseModel, FinalRequestOptions from openai._streaming import Stream, AsyncStream -from openai._exceptions import ( - OpenAIError, - APIStatusError, - APITimeoutError, - APIResponseValidationError, -) -from openai._base_client import ( - DEFAULT_TIMEOUT, - HTTPX_DEFAULT_TIMEOUT, - BaseClient, - make_request_options, -) +from openai._exceptions import OpenAIError, APIStatusError, APITimeoutError, APIResponseValidationError +from openai._base_client import DEFAULT_TIMEOUT, HTTPX_DEFAULT_TIMEOUT, BaseClient, make_request_options from .utils import update_env diff --git a/tests/utils.py b/tests/utils.py index 57486c733a..02dd9c0acc 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -8,7 +8,12 @@ from typing_extensions import Literal, get_args, get_origin, assert_type from openai._types import NoneType -from openai._utils import is_dict, is_list, is_list_type, is_union_type +from openai._utils import ( + is_dict, + is_list, + is_list_type, + is_union_type, +) from openai._compat import PYDANTIC_V2, field_outer_type, get_model_fields from openai._models import BaseModel From c4db321ba157282f8db03442ceb3528e030b94ad Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 3 Jan 2024 21:27:18 -0500 Subject: [PATCH 183/816] feat: add `None` default value to nullable response properties (#1043) --- src/openai/_exceptions.py | 4 ++-- src/openai/types/beta/assistant.py | 8 ++++---- src/openai/types/beta/thread.py | 2 +- src/openai/types/beta/threads/run.py | 14 +++++++------- .../types/beta/threads/runs/function_tool_call.py | 2 +- src/openai/types/beta/threads/runs/run_step.py | 12 ++++++------ src/openai/types/beta/threads/thread_message.py | 6 +++--- src/openai/types/chat/chat_completion.py | 4 ++-- src/openai/types/chat/chat_completion_chunk.py | 4 ++-- src/openai/types/chat/chat_completion_message.py | 2 +- .../types/chat/chat_completion_token_logprob.py | 4 ++-- src/openai/types/completion_choice.py | 2 +- src/openai/types/fine_tune.py | 2 +- src/openai/types/fine_tuning/fine_tuning_job.py | 12 ++++++------ 14 files changed, 39 insertions(+), 39 deletions(-) diff --git a/src/openai/_exceptions.py b/src/openai/_exceptions.py index 40b163270d..d7ded1248f 100644 --- a/src/openai/_exceptions.py +++ b/src/openai/_exceptions.py @@ -40,8 +40,8 @@ class APIError(OpenAIError): If there was no response associated with this error then it will be `None`. """ - code: Optional[str] - param: Optional[str] + code: Optional[str] = None + param: Optional[str] = None type: Optional[str] def __init__(self, message: str, request: httpx.Request, *, body: object | None) -> None: diff --git a/src/openai/types/beta/assistant.py b/src/openai/types/beta/assistant.py index a21206765a..89e45d4806 100644 --- a/src/openai/types/beta/assistant.py +++ b/src/openai/types/beta/assistant.py @@ -37,7 +37,7 @@ class Assistant(BaseModel): created_at: int """The Unix timestamp (in seconds) for when the assistant was created.""" - description: Optional[str] + description: Optional[str] = None """The description of the assistant. The maximum length is 512 characters.""" file_ids: List[str] @@ -47,13 +47,13 @@ class Assistant(BaseModel): assistant. Files are ordered by their creation date in ascending order. """ - instructions: Optional[str] + instructions: Optional[str] = None """The system instructions that the assistant uses. The maximum length is 32768 characters. """ - metadata: Optional[builtins.object] + metadata: Optional[builtins.object] = None """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a @@ -71,7 +71,7 @@ class Assistant(BaseModel): descriptions of them. """ - name: Optional[str] + name: Optional[str] = None """The name of the assistant. The maximum length is 256 characters.""" object: Literal["assistant"] diff --git a/src/openai/types/beta/thread.py b/src/openai/types/beta/thread.py index a340bffd60..474527033a 100644 --- a/src/openai/types/beta/thread.py +++ b/src/openai/types/beta/thread.py @@ -16,7 +16,7 @@ class Thread(BaseModel): created_at: int """The Unix timestamp (in seconds) for when the thread was created.""" - metadata: Optional[builtins.object] + metadata: Optional[builtins.object] = None """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a diff --git a/src/openai/types/beta/threads/run.py b/src/openai/types/beta/threads/run.py index ffbba1e504..b6d66bd8dd 100644 --- a/src/openai/types/beta/threads/run.py +++ b/src/openai/types/beta/threads/run.py @@ -72,10 +72,10 @@ class Run(BaseModel): execution of this run. """ - cancelled_at: Optional[int] + cancelled_at: Optional[int] = None """The Unix timestamp (in seconds) for when the run was cancelled.""" - completed_at: Optional[int] + completed_at: Optional[int] = None """The Unix timestamp (in seconds) for when the run was completed.""" created_at: int @@ -84,7 +84,7 @@ class Run(BaseModel): expires_at: int """The Unix timestamp (in seconds) for when the run will expire.""" - failed_at: Optional[int] + failed_at: Optional[int] = None """The Unix timestamp (in seconds) for when the run failed.""" file_ids: List[str] @@ -101,10 +101,10 @@ class Run(BaseModel): this run. """ - last_error: Optional[LastError] + last_error: Optional[LastError] = None """The last error associated with this run. Will be `null` if there are no errors.""" - metadata: Optional[builtins.object] + metadata: Optional[builtins.object] = None """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a @@ -122,13 +122,13 @@ class Run(BaseModel): object: Literal["thread.run"] """The object type, which is always `thread.run`.""" - required_action: Optional[RequiredAction] + required_action: Optional[RequiredAction] = None """Details on the action required to continue the run. Will be `null` if no action is required. """ - started_at: Optional[int] + started_at: Optional[int] = None """The Unix timestamp (in seconds) for when the run was started.""" status: Literal[ diff --git a/src/openai/types/beta/threads/runs/function_tool_call.py b/src/openai/types/beta/threads/runs/function_tool_call.py index f4cf8bbdd0..bbd3cb7052 100644 --- a/src/openai/types/beta/threads/runs/function_tool_call.py +++ b/src/openai/types/beta/threads/runs/function_tool_call.py @@ -15,7 +15,7 @@ class Function(BaseModel): name: str """The name of the function.""" - output: Optional[str] + output: Optional[str] = None """The output of the function. This will be `null` if the outputs have not been diff --git a/src/openai/types/beta/threads/runs/run_step.py b/src/openai/types/beta/threads/runs/run_step.py index 5f8723b71a..1d95e9d6eb 100644 --- a/src/openai/types/beta/threads/runs/run_step.py +++ b/src/openai/types/beta/threads/runs/run_step.py @@ -33,31 +33,31 @@ class RunStep(BaseModel): associated with the run step. """ - cancelled_at: Optional[int] + cancelled_at: Optional[int] = None """The Unix timestamp (in seconds) for when the run step was cancelled.""" - completed_at: Optional[int] + completed_at: Optional[int] = None """The Unix timestamp (in seconds) for when the run step completed.""" created_at: int """The Unix timestamp (in seconds) for when the run step was created.""" - expired_at: Optional[int] + expired_at: Optional[int] = None """The Unix timestamp (in seconds) for when the run step expired. A step is considered expired if the parent run is expired. """ - failed_at: Optional[int] + failed_at: Optional[int] = None """The Unix timestamp (in seconds) for when the run step failed.""" - last_error: Optional[LastError] + last_error: Optional[LastError] = None """The last error associated with this run step. Will be `null` if there are no errors. """ - metadata: Optional[builtins.object] + metadata: Optional[builtins.object] = None """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a diff --git a/src/openai/types/beta/threads/thread_message.py b/src/openai/types/beta/threads/thread_message.py index 0f782ef845..8f1ac07d0a 100644 --- a/src/openai/types/beta/threads/thread_message.py +++ b/src/openai/types/beta/threads/thread_message.py @@ -17,7 +17,7 @@ class ThreadMessage(BaseModel): id: str """The identifier, which can be referenced in API endpoints.""" - assistant_id: Optional[str] + assistant_id: Optional[str] = None """ If applicable, the ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) that @@ -37,7 +37,7 @@ class ThreadMessage(BaseModel): that can access files. A maximum of 10 files can be attached to a message. """ - metadata: Optional[builtins.object] + metadata: Optional[builtins.object] = None """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a @@ -51,7 +51,7 @@ class ThreadMessage(BaseModel): role: Literal["user", "assistant"] """The entity that produced the message. One of `user` or `assistant`.""" - run_id: Optional[str] + run_id: Optional[str] = None """ If applicable, the ID of the [run](https://platform.openai.com/docs/api-reference/runs) associated with the diff --git a/src/openai/types/chat/chat_completion.py b/src/openai/types/chat/chat_completion.py index 055280c347..dc63d84945 100644 --- a/src/openai/types/chat/chat_completion.py +++ b/src/openai/types/chat/chat_completion.py @@ -12,7 +12,7 @@ class ChoiceLogprobs(BaseModel): - content: Optional[List[ChatCompletionTokenLogprob]] + content: Optional[List[ChatCompletionTokenLogprob]] = None """A list of message content tokens with log probability information.""" @@ -30,7 +30,7 @@ class Choice(BaseModel): index: int """The index of the choice in the list of choices.""" - logprobs: Optional[ChoiceLogprobs] + logprobs: Optional[ChoiceLogprobs] = None """Log probability information for the choice.""" message: ChatCompletionMessage diff --git a/src/openai/types/chat/chat_completion_chunk.py b/src/openai/types/chat/chat_completion_chunk.py index ccc7ad79ec..95013e7a4f 100644 --- a/src/openai/types/chat/chat_completion_chunk.py +++ b/src/openai/types/chat/chat_completion_chunk.py @@ -73,7 +73,7 @@ class ChoiceDelta(BaseModel): class ChoiceLogprobs(BaseModel): - content: Optional[List[ChatCompletionTokenLogprob]] + content: Optional[List[ChatCompletionTokenLogprob]] = None """A list of message content tokens with log probability information.""" @@ -81,7 +81,7 @@ class Choice(BaseModel): delta: ChoiceDelta """A chat completion delta generated by streamed model responses.""" - finish_reason: Optional[Literal["stop", "length", "tool_calls", "content_filter", "function_call"]] + finish_reason: Optional[Literal["stop", "length", "tool_calls", "content_filter", "function_call"]] = None """The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop diff --git a/src/openai/types/chat/chat_completion_message.py b/src/openai/types/chat/chat_completion_message.py index 4749798a33..da8b2fcd5c 100644 --- a/src/openai/types/chat/chat_completion_message.py +++ b/src/openai/types/chat/chat_completion_message.py @@ -23,7 +23,7 @@ class FunctionCall(BaseModel): class ChatCompletionMessage(BaseModel): - content: Optional[str] + content: Optional[str] = None """The contents of the message.""" role: Literal["assistant"] diff --git a/src/openai/types/chat/chat_completion_token_logprob.py b/src/openai/types/chat/chat_completion_token_logprob.py index 8896da8b85..728845fb33 100644 --- a/src/openai/types/chat/chat_completion_token_logprob.py +++ b/src/openai/types/chat/chat_completion_token_logprob.py @@ -11,7 +11,7 @@ class TopLogprob(BaseModel): token: str """The token.""" - bytes: Optional[List[int]] + bytes: Optional[List[int]] = None """A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and @@ -27,7 +27,7 @@ class ChatCompletionTokenLogprob(BaseModel): token: str """The token.""" - bytes: Optional[List[int]] + bytes: Optional[List[int]] = None """A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and diff --git a/src/openai/types/completion_choice.py b/src/openai/types/completion_choice.py index 71de0f9247..7b08582bfd 100644 --- a/src/openai/types/completion_choice.py +++ b/src/openai/types/completion_choice.py @@ -30,6 +30,6 @@ class CompletionChoice(BaseModel): index: int - logprobs: Optional[Logprobs] + logprobs: Optional[Logprobs] = None text: str diff --git a/src/openai/types/fine_tune.py b/src/openai/types/fine_tune.py index de1e097ee4..d1a063a065 100644 --- a/src/openai/types/fine_tune.py +++ b/src/openai/types/fine_tune.py @@ -50,7 +50,7 @@ class FineTune(BaseModel): created_at: int """The Unix timestamp (in seconds) for when the fine-tuning job was created.""" - fine_tuned_model: Optional[str] + fine_tuned_model: Optional[str] = None """The name of the fine-tuned model that is being created.""" hyperparams: Hyperparams diff --git a/src/openai/types/fine_tuning/fine_tuning_job.py b/src/openai/types/fine_tuning/fine_tuning_job.py index 3897176a47..5aa4f07eb1 100644 --- a/src/openai/types/fine_tuning/fine_tuning_job.py +++ b/src/openai/types/fine_tuning/fine_tuning_job.py @@ -15,7 +15,7 @@ class Error(BaseModel): message: str """A human-readable error message.""" - param: Optional[str] + param: Optional[str] = None """The parameter that was invalid, usually `training_file` or `validation_file`. This field will be null if the failure was not parameter-specific. @@ -39,19 +39,19 @@ class FineTuningJob(BaseModel): created_at: int """The Unix timestamp (in seconds) for when the fine-tuning job was created.""" - error: Optional[Error] + error: Optional[Error] = None """ For fine-tuning jobs that have `failed`, this will contain more information on the cause of the failure. """ - fine_tuned_model: Optional[str] + fine_tuned_model: Optional[str] = None """The name of the fine-tuned model that is being created. The value will be null if the fine-tuning job is still running. """ - finished_at: Optional[int] + finished_at: Optional[int] = None """The Unix timestamp (in seconds) for when the fine-tuning job was finished. The value will be null if the fine-tuning job is still running. @@ -86,7 +86,7 @@ class FineTuningJob(BaseModel): `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`. """ - trained_tokens: Optional[int] + trained_tokens: Optional[int] = None """The total number of billable tokens processed by this fine-tuning job. The value will be null if the fine-tuning job is still running. @@ -99,7 +99,7 @@ class FineTuningJob(BaseModel): [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). """ - validation_file: Optional[str] + validation_file: Optional[str] = None """The file ID used for validation. You can retrieve the validation results with the From 4aa7cbee29591c1db8b0778c76fe581ce4122dbc Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 4 Jan 2024 16:26:07 -0500 Subject: [PATCH 184/816] chore: use property declarations for resource members (#1047) This will speedup client instantiation in certain cases. --- pyproject.toml | 1 + src/openai/_compat.py | 10 ++++ src/openai/resources/audio/audio.py | 56 ++++++++++--------- src/openai/resources/audio/speech.py | 22 +++----- src/openai/resources/audio/transcriptions.py | 22 +++----- src/openai/resources/audio/translations.py | 22 +++----- .../resources/beta/assistants/assistants.py | 30 +++++----- src/openai/resources/beta/assistants/files.py | 28 +++------- src/openai/resources/beta/beta.py | 46 +++++++-------- .../resources/beta/threads/messages/files.py | 21 +++---- .../beta/threads/messages/messages.py | 37 +++++------- .../resources/beta/threads/runs/runs.py | 30 +++++----- .../resources/beta/threads/runs/steps.py | 21 +++---- src/openai/resources/beta/threads/threads.py | 46 ++++++++------- src/openai/resources/chat/chat.py | 30 +++++----- src/openai/resources/chat/completions.py | 22 +++----- src/openai/resources/completions.py | 22 +++----- src/openai/resources/edits.py | 22 +++----- src/openai/resources/embeddings.py | 22 +++----- src/openai/resources/files.py | 29 +++------- src/openai/resources/fine_tunes.py | 22 +++----- .../resources/fine_tuning/fine_tuning.py | 30 +++++----- src/openai/resources/fine_tuning/jobs.py | 22 +++----- src/openai/resources/images.py | 22 +++----- src/openai/resources/models.py | 22 +++----- src/openai/resources/moderations.py | 22 +++----- 26 files changed, 285 insertions(+), 394 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index a4eba4a0d9..64f90ae1b6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,6 +14,7 @@ dependencies = [ "anyio>=3.5.0, <5", "distro>=1.7.0, <2", "sniffio", + "cached-property; python_version < '3.8'", "tqdm > 4" ] requires-python = ">= 3.7.1" diff --git a/src/openai/_compat.py b/src/openai/_compat.py index d95db8ed1e..3cda39909b 100644 --- a/src/openai/_compat.py +++ b/src/openai/_compat.py @@ -173,3 +173,13 @@ class GenericModel(pydantic.BaseModel): class GenericModel(pydantic.generics.GenericModel, pydantic.BaseModel): ... + + +# cached properties +if TYPE_CHECKING: + cached_property = property +else: + try: + from functools import cached_property as cached_property + except ImportError: + from cached_property import cached_property as cached_property diff --git a/src/openai/resources/audio/audio.py b/src/openai/resources/audio/audio.py index 6b9242f0c2..4e3ca0ed4f 100644 --- a/src/openai/resources/audio/audio.py +++ b/src/openai/resources/audio/audio.py @@ -2,9 +2,8 @@ from __future__ import annotations -from typing import TYPE_CHECKING - from .speech import Speech, AsyncSpeech, SpeechWithRawResponse, AsyncSpeechWithRawResponse +from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from .translations import Translations, AsyncTranslations, TranslationsWithRawResponse, AsyncTranslationsWithRawResponse from .transcriptions import ( @@ -14,38 +13,43 @@ AsyncTranscriptionsWithRawResponse, ) -if TYPE_CHECKING: - from ..._client import OpenAI, AsyncOpenAI - __all__ = ["Audio", "AsyncAudio"] class Audio(SyncAPIResource): - transcriptions: Transcriptions - translations: Translations - speech: Speech - with_raw_response: AudioWithRawResponse + @cached_property + def transcriptions(self) -> Transcriptions: + return Transcriptions(self._client) + + @cached_property + def translations(self) -> Translations: + return Translations(self._client) + + @cached_property + def speech(self) -> Speech: + return Speech(self._client) - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.transcriptions = Transcriptions(client) - self.translations = Translations(client) - self.speech = Speech(client) - self.with_raw_response = AudioWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AudioWithRawResponse: + return AudioWithRawResponse(self) class AsyncAudio(AsyncAPIResource): - transcriptions: AsyncTranscriptions - translations: AsyncTranslations - speech: AsyncSpeech - with_raw_response: AsyncAudioWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.transcriptions = AsyncTranscriptions(client) - self.translations = AsyncTranslations(client) - self.speech = AsyncSpeech(client) - self.with_raw_response = AsyncAudioWithRawResponse(self) + @cached_property + def transcriptions(self) -> AsyncTranscriptions: + return AsyncTranscriptions(self._client) + + @cached_property + def translations(self) -> AsyncTranslations: + return AsyncTranslations(self._client) + + @cached_property + def speech(self) -> AsyncSpeech: + return AsyncSpeech(self._client) + + @cached_property + def with_raw_response(self) -> AsyncAudioWithRawResponse: + return AsyncAudioWithRawResponse(self) class AudioWithRawResponse: diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index 7ae552c12f..49fded960d 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Union +from typing import Union from typing_extensions import Literal import httpx @@ -15,6 +15,7 @@ NotGiven, ) from ..._utils import maybe_transform +from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ...types.audio import speech_create_params @@ -23,18 +24,13 @@ make_request_options, ) -if TYPE_CHECKING: - from ..._client import OpenAI, AsyncOpenAI - __all__ = ["Speech", "AsyncSpeech"] class Speech(SyncAPIResource): - with_raw_response: SpeechWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = SpeechWithRawResponse(self) + @cached_property + def with_raw_response(self) -> SpeechWithRawResponse: + return SpeechWithRawResponse(self) def create( self, @@ -99,11 +95,9 @@ def create( class AsyncSpeech(AsyncAPIResource): - with_raw_response: AsyncSpeechWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncSpeechWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncSpeechWithRawResponse: + return AsyncSpeechWithRawResponse(self) async def create( self, diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index 54be1c99a6..f211678928 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Union, Mapping, cast +from typing import Union, Mapping, cast from typing_extensions import Literal import httpx @@ -16,6 +16,7 @@ FileTypes, ) from ..._utils import extract_files, maybe_transform, deepcopy_minimal +from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ...types.audio import Transcription, transcription_create_params @@ -23,18 +24,13 @@ make_request_options, ) -if TYPE_CHECKING: - from ..._client import OpenAI, AsyncOpenAI - __all__ = ["Transcriptions", "AsyncTranscriptions"] class Transcriptions(SyncAPIResource): - with_raw_response: TranscriptionsWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = TranscriptionsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> TranscriptionsWithRawResponse: + return TranscriptionsWithRawResponse(self) def create( self, @@ -117,11 +113,9 @@ def create( class AsyncTranscriptions(AsyncAPIResource): - with_raw_response: AsyncTranscriptionsWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncTranscriptionsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncTranscriptionsWithRawResponse: + return AsyncTranscriptionsWithRawResponse(self) async def create( self, diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index c4489004ac..402ec8ac1e 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Union, Mapping, cast +from typing import Union, Mapping, cast from typing_extensions import Literal import httpx @@ -16,6 +16,7 @@ FileTypes, ) from ..._utils import extract_files, maybe_transform, deepcopy_minimal +from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ...types.audio import Translation, translation_create_params @@ -23,18 +24,13 @@ make_request_options, ) -if TYPE_CHECKING: - from ..._client import OpenAI, AsyncOpenAI - __all__ = ["Translations", "AsyncTranslations"] class Translations(SyncAPIResource): - with_raw_response: TranslationsWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = TranslationsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> TranslationsWithRawResponse: + return TranslationsWithRawResponse(self) def create( self, @@ -110,11 +106,9 @@ def create( class AsyncTranslations(AsyncAPIResource): - with_raw_response: AsyncTranslationsWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncTranslationsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncTranslationsWithRawResponse: + return AsyncTranslationsWithRawResponse(self) async def create( self, diff --git a/src/openai/resources/beta/assistants/assistants.py b/src/openai/resources/beta/assistants/assistants.py index 13b90ac69c..064ca1197c 100644 --- a/src/openai/resources/beta/assistants/assistants.py +++ b/src/openai/resources/beta/assistants/assistants.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, List, Optional +from typing import List, Optional from typing_extensions import Literal import httpx @@ -16,6 +16,7 @@ NotGiven, ) from ...._utils import maybe_transform +from ...._compat import cached_property from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ....pagination import SyncCursorPage, AsyncCursorPage @@ -31,20 +32,17 @@ make_request_options, ) -if TYPE_CHECKING: - from ...._client import OpenAI, AsyncOpenAI - __all__ = ["Assistants", "AsyncAssistants"] class Assistants(SyncAPIResource): - files: Files - with_raw_response: AssistantsWithRawResponse + @cached_property + def files(self) -> Files: + return Files(self._client) - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.files = Files(client) - self.with_raw_response = AssistantsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AssistantsWithRawResponse: + return AssistantsWithRawResponse(self) def create( self, @@ -331,13 +329,13 @@ def delete( class AsyncAssistants(AsyncAPIResource): - files: AsyncFiles - with_raw_response: AsyncAssistantsWithRawResponse + @cached_property + def files(self) -> AsyncFiles: + return AsyncFiles(self._client) - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.files = AsyncFiles(client) - self.with_raw_response = AsyncAssistantsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncAssistantsWithRawResponse: + return AsyncAssistantsWithRawResponse(self) async def create( self, diff --git a/src/openai/resources/beta/assistants/files.py b/src/openai/resources/beta/assistants/files.py index 5682587487..f8a665b75c 100644 --- a/src/openai/resources/beta/assistants/files.py +++ b/src/openai/resources/beta/assistants/files.py @@ -2,7 +2,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING from typing_extensions import Literal import httpx @@ -15,6 +14,7 @@ NotGiven, ) from ...._utils import maybe_transform +from ...._compat import cached_property from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ....pagination import SyncCursorPage, AsyncCursorPage @@ -22,25 +22,15 @@ AsyncPaginator, make_request_options, ) -from ....types.beta.assistants import ( - AssistantFile, - FileDeleteResponse, - file_list_params, - file_create_params, -) - -if TYPE_CHECKING: - from ...._client import OpenAI, AsyncOpenAI +from ....types.beta.assistants import AssistantFile, FileDeleteResponse, file_list_params, file_create_params __all__ = ["Files", "AsyncFiles"] class Files(SyncAPIResource): - with_raw_response: FilesWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = FilesWithRawResponse(self) + @cached_property + def with_raw_response(self) -> FilesWithRawResponse: + return FilesWithRawResponse(self) def create( self, @@ -215,11 +205,9 @@ def delete( class AsyncFiles(AsyncAPIResource): - with_raw_response: AsyncFilesWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncFilesWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncFilesWithRawResponse: + return AsyncFilesWithRawResponse(self) async def create( self, diff --git a/src/openai/resources/beta/beta.py b/src/openai/resources/beta/beta.py index 5cea6c1460..d87406ac9d 100644 --- a/src/openai/resources/beta/beta.py +++ b/src/openai/resources/beta/beta.py @@ -2,40 +2,42 @@ from __future__ import annotations -from typing import TYPE_CHECKING - from .threads import Threads, AsyncThreads, ThreadsWithRawResponse, AsyncThreadsWithRawResponse +from ..._compat import cached_property from .assistants import Assistants, AsyncAssistants, AssistantsWithRawResponse, AsyncAssistantsWithRawResponse from ..._resource import SyncAPIResource, AsyncAPIResource - -if TYPE_CHECKING: - from ..._client import OpenAI, AsyncOpenAI +from .threads.threads import Threads, AsyncThreads +from .assistants.assistants import Assistants, AsyncAssistants __all__ = ["Beta", "AsyncBeta"] class Beta(SyncAPIResource): - assistants: Assistants - threads: Threads - with_raw_response: BetaWithRawResponse + @cached_property + def assistants(self) -> Assistants: + return Assistants(self._client) + + @cached_property + def threads(self) -> Threads: + return Threads(self._client) - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.assistants = Assistants(client) - self.threads = Threads(client) - self.with_raw_response = BetaWithRawResponse(self) + @cached_property + def with_raw_response(self) -> BetaWithRawResponse: + return BetaWithRawResponse(self) class AsyncBeta(AsyncAPIResource): - assistants: AsyncAssistants - threads: AsyncThreads - with_raw_response: AsyncBetaWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.assistants = AsyncAssistants(client) - self.threads = AsyncThreads(client) - self.with_raw_response = AsyncBetaWithRawResponse(self) + @cached_property + def assistants(self) -> AsyncAssistants: + return AsyncAssistants(self._client) + + @cached_property + def threads(self) -> AsyncThreads: + return AsyncThreads(self._client) + + @cached_property + def with_raw_response(self) -> AsyncBetaWithRawResponse: + return AsyncBetaWithRawResponse(self) class BetaWithRawResponse: diff --git a/src/openai/resources/beta/threads/messages/files.py b/src/openai/resources/beta/threads/messages/files.py index 24c9680f3d..d0c8c7f0ae 100644 --- a/src/openai/resources/beta/threads/messages/files.py +++ b/src/openai/resources/beta/threads/messages/files.py @@ -2,7 +2,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING from typing_extensions import Literal import httpx @@ -15,6 +14,7 @@ NotGiven, ) from ....._utils import maybe_transform +from ....._compat import cached_property from ....._resource import SyncAPIResource, AsyncAPIResource from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .....pagination import SyncCursorPage, AsyncCursorPage @@ -24,18 +24,13 @@ ) from .....types.beta.threads.messages import MessageFile, file_list_params -if TYPE_CHECKING: - from ....._client import OpenAI, AsyncOpenAI - __all__ = ["Files", "AsyncFiles"] class Files(SyncAPIResource): - with_raw_response: FilesWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = FilesWithRawResponse(self) + @cached_property + def with_raw_response(self) -> FilesWithRawResponse: + return FilesWithRawResponse(self) def retrieve( self, @@ -140,11 +135,9 @@ def list( class AsyncFiles(AsyncAPIResource): - with_raw_response: AsyncFilesWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncFilesWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncFilesWithRawResponse: + return AsyncFilesWithRawResponse(self) async def retrieve( self, diff --git a/src/openai/resources/beta/threads/messages/messages.py b/src/openai/resources/beta/threads/messages/messages.py index 9a6f5706c3..7adc8b7829 100644 --- a/src/openai/resources/beta/threads/messages/messages.py +++ b/src/openai/resources/beta/threads/messages/messages.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, List, Optional +from typing import List, Optional from typing_extensions import Literal import httpx @@ -16,6 +16,7 @@ NotGiven, ) from ....._utils import maybe_transform +from ....._compat import cached_property from ....._resource import SyncAPIResource, AsyncAPIResource from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .....pagination import SyncCursorPage, AsyncCursorPage @@ -23,27 +24,19 @@ AsyncPaginator, make_request_options, ) -from .....types.beta.threads import ( - ThreadMessage, - message_list_params, - message_create_params, - message_update_params, -) - -if TYPE_CHECKING: - from ....._client import OpenAI, AsyncOpenAI +from .....types.beta.threads import ThreadMessage, message_list_params, message_create_params, message_update_params __all__ = ["Messages", "AsyncMessages"] class Messages(SyncAPIResource): - files: Files - with_raw_response: MessagesWithRawResponse + @cached_property + def files(self) -> Files: + return Files(self._client) - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.files = Files(client) - self.with_raw_response = MessagesWithRawResponse(self) + @cached_property + def with_raw_response(self) -> MessagesWithRawResponse: + return MessagesWithRawResponse(self) def create( self, @@ -245,13 +238,13 @@ def list( class AsyncMessages(AsyncAPIResource): - files: AsyncFiles - with_raw_response: AsyncMessagesWithRawResponse + @cached_property + def files(self) -> AsyncFiles: + return AsyncFiles(self._client) - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.files = AsyncFiles(client) - self.with_raw_response = AsyncMessagesWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncMessagesWithRawResponse: + return AsyncMessagesWithRawResponse(self) async def create( self, diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 6a727b856b..902d3f3f92 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, List, Optional +from typing import List, Optional from typing_extensions import Literal import httpx @@ -16,6 +16,7 @@ NotGiven, ) from ....._utils import maybe_transform +from ....._compat import cached_property from ....._resource import SyncAPIResource, AsyncAPIResource from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .....pagination import SyncCursorPage, AsyncCursorPage @@ -31,20 +32,17 @@ run_submit_tool_outputs_params, ) -if TYPE_CHECKING: - from ....._client import OpenAI, AsyncOpenAI - __all__ = ["Runs", "AsyncRuns"] class Runs(SyncAPIResource): - steps: Steps - with_raw_response: RunsWithRawResponse + @cached_property + def steps(self) -> Steps: + return Steps(self._client) - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.steps = Steps(client) - self.with_raw_response = RunsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> RunsWithRawResponse: + return RunsWithRawResponse(self) def create( self, @@ -335,13 +333,13 @@ def submit_tool_outputs( class AsyncRuns(AsyncAPIResource): - steps: AsyncSteps - with_raw_response: AsyncRunsWithRawResponse + @cached_property + def steps(self) -> AsyncSteps: + return AsyncSteps(self._client) - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.steps = AsyncSteps(client) - self.with_raw_response = AsyncRunsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncRunsWithRawResponse: + return AsyncRunsWithRawResponse(self) async def create( self, diff --git a/src/openai/resources/beta/threads/runs/steps.py b/src/openai/resources/beta/threads/runs/steps.py index f26034cf82..ff218a4beb 100644 --- a/src/openai/resources/beta/threads/runs/steps.py +++ b/src/openai/resources/beta/threads/runs/steps.py @@ -2,7 +2,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING from typing_extensions import Literal import httpx @@ -15,6 +14,7 @@ NotGiven, ) from ....._utils import maybe_transform +from ....._compat import cached_property from ....._resource import SyncAPIResource, AsyncAPIResource from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .....pagination import SyncCursorPage, AsyncCursorPage @@ -24,18 +24,13 @@ ) from .....types.beta.threads.runs import RunStep, step_list_params -if TYPE_CHECKING: - from ....._client import OpenAI, AsyncOpenAI - __all__ = ["Steps", "AsyncSteps"] class Steps(SyncAPIResource): - with_raw_response: StepsWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = StepsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> StepsWithRawResponse: + return StepsWithRawResponse(self) def retrieve( self, @@ -139,11 +134,9 @@ def list( class AsyncSteps(AsyncAPIResource): - with_raw_response: AsyncStepsWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncStepsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncStepsWithRawResponse: + return AsyncStepsWithRawResponse(self) async def retrieve( self, diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index b37667485d..caae758416 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, List, Optional +from typing import List, Optional import httpx @@ -16,6 +16,8 @@ NotGiven, ) from ...._utils import maybe_transform +from .runs.runs import Runs, AsyncRuns +from ...._compat import cached_property from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ....types.beta import ( @@ -28,24 +30,24 @@ from ...._base_client import ( make_request_options, ) +from .messages.messages import Messages, AsyncMessages from ....types.beta.threads import Run -if TYPE_CHECKING: - from ...._client import OpenAI, AsyncOpenAI - __all__ = ["Threads", "AsyncThreads"] class Threads(SyncAPIResource): - runs: Runs - messages: Messages - with_raw_response: ThreadsWithRawResponse + @cached_property + def runs(self) -> Runs: + return Runs(self._client) + + @cached_property + def messages(self) -> Messages: + return Messages(self._client) - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.runs = Runs(client) - self.messages = Messages(client) - self.with_raw_response = ThreadsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> ThreadsWithRawResponse: + return ThreadsWithRawResponse(self) def create( self, @@ -270,15 +272,17 @@ def create_and_run( class AsyncThreads(AsyncAPIResource): - runs: AsyncRuns - messages: AsyncMessages - with_raw_response: AsyncThreadsWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.runs = AsyncRuns(client) - self.messages = AsyncMessages(client) - self.with_raw_response = AsyncThreadsWithRawResponse(self) + @cached_property + def runs(self) -> AsyncRuns: + return AsyncRuns(self._client) + + @cached_property + def messages(self) -> AsyncMessages: + return AsyncMessages(self._client) + + @cached_property + def with_raw_response(self) -> AsyncThreadsWithRawResponse: + return AsyncThreadsWithRawResponse(self) async def create( self, diff --git a/src/openai/resources/chat/chat.py b/src/openai/resources/chat/chat.py index d93a501b1f..000520de23 100644 --- a/src/openai/resources/chat/chat.py +++ b/src/openai/resources/chat/chat.py @@ -2,35 +2,31 @@ from __future__ import annotations -from typing import TYPE_CHECKING - +from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from .completions import Completions, AsyncCompletions, CompletionsWithRawResponse, AsyncCompletionsWithRawResponse -if TYPE_CHECKING: - from ..._client import OpenAI, AsyncOpenAI - __all__ = ["Chat", "AsyncChat"] class Chat(SyncAPIResource): - completions: Completions - with_raw_response: ChatWithRawResponse + @cached_property + def completions(self) -> Completions: + return Completions(self._client) - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.completions = Completions(client) - self.with_raw_response = ChatWithRawResponse(self) + @cached_property + def with_raw_response(self) -> ChatWithRawResponse: + return ChatWithRawResponse(self) class AsyncChat(AsyncAPIResource): - completions: AsyncCompletions - with_raw_response: AsyncChatWithRawResponse + @cached_property + def completions(self) -> AsyncCompletions: + return AsyncCompletions(self._client) - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.completions = AsyncCompletions(client) - self.with_raw_response = AsyncChatWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncChatWithRawResponse: + return AsyncChatWithRawResponse(self) class ChatWithRawResponse: diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index 6bde8383dc..81dff146c8 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Dict, List, Union, Optional, overload +from typing import Dict, List, Union, Optional, overload from typing_extensions import Literal import httpx @@ -15,6 +15,7 @@ NotGiven, ) from ..._utils import required_args, maybe_transform +from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ..._streaming import Stream, AsyncStream @@ -30,18 +31,13 @@ make_request_options, ) -if TYPE_CHECKING: - from ..._client import OpenAI, AsyncOpenAI - __all__ = ["Completions", "AsyncCompletions"] class Completions(SyncAPIResource): - with_raw_response: CompletionsWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = CompletionsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> CompletionsWithRawResponse: + return CompletionsWithRawResponse(self) @overload def create( @@ -687,11 +683,9 @@ def create( class AsyncCompletions(AsyncAPIResource): - with_raw_response: AsyncCompletionsWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncCompletionsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncCompletionsWithRawResponse: + return AsyncCompletionsWithRawResponse(self) @overload async def create( diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index a13c901529..1339c34472 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Dict, List, Union, Optional, overload +from typing import Dict, List, Union, Optional, overload from typing_extensions import Literal import httpx @@ -16,6 +16,7 @@ NotGiven, ) from .._utils import required_args, maybe_transform +from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .._streaming import Stream, AsyncStream @@ -23,18 +24,13 @@ make_request_options, ) -if TYPE_CHECKING: - from .._client import OpenAI, AsyncOpenAI - __all__ = ["Completions", "AsyncCompletions"] class Completions(SyncAPIResource): - with_raw_response: CompletionsWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = CompletionsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> CompletionsWithRawResponse: + return CompletionsWithRawResponse(self) @overload def create( @@ -601,11 +597,9 @@ def create( class AsyncCompletions(AsyncAPIResource): - with_raw_response: AsyncCompletionsWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncCompletionsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncCompletionsWithRawResponse: + return AsyncCompletionsWithRawResponse(self) @overload async def create( diff --git a/src/openai/resources/edits.py b/src/openai/resources/edits.py index 587da02c8f..355a11ac9d 100644 --- a/src/openai/resources/edits.py +++ b/src/openai/resources/edits.py @@ -3,7 +3,7 @@ from __future__ import annotations import typing_extensions -from typing import TYPE_CHECKING, Union, Optional +from typing import Union, Optional from typing_extensions import Literal import httpx @@ -17,24 +17,20 @@ NotGiven, ) from .._utils import maybe_transform +from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .._base_client import ( make_request_options, ) -if TYPE_CHECKING: - from .._client import OpenAI, AsyncOpenAI - __all__ = ["Edits", "AsyncEdits"] class Edits(SyncAPIResource): - with_raw_response: EditsWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = EditsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> EditsWithRawResponse: + return EditsWithRawResponse(self) @typing_extensions.deprecated( "The Edits API is deprecated; please use Chat Completions instead.\n\nhttps://openai.com/blog/gpt-4-api-general-availability#deprecation-of-the-edits-api\n" @@ -109,11 +105,9 @@ def create( class AsyncEdits(AsyncAPIResource): - with_raw_response: AsyncEditsWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncEditsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncEditsWithRawResponse: + return AsyncEditsWithRawResponse(self) @typing_extensions.deprecated( "The Edits API is deprecated; please use Chat Completions instead.\n\nhttps://openai.com/blog/gpt-4-api-general-availability#deprecation-of-the-edits-api\n" diff --git a/src/openai/resources/embeddings.py b/src/openai/resources/embeddings.py index f22acad401..409f5832fc 100644 --- a/src/openai/resources/embeddings.py +++ b/src/openai/resources/embeddings.py @@ -3,7 +3,7 @@ from __future__ import annotations import base64 -from typing import TYPE_CHECKING, List, Union, cast +from typing import List, Union, cast from typing_extensions import Literal import httpx @@ -17,6 +17,7 @@ NotGiven, ) from .._utils import is_given, maybe_transform +from .._compat import cached_property from .._extras import numpy as np, has_numpy from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper @@ -24,18 +25,13 @@ make_request_options, ) -if TYPE_CHECKING: - from .._client import OpenAI, AsyncOpenAI - __all__ = ["Embeddings", "AsyncEmbeddings"] class Embeddings(SyncAPIResource): - with_raw_response: EmbeddingsWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = EmbeddingsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> EmbeddingsWithRawResponse: + return EmbeddingsWithRawResponse(self) def create( self, @@ -125,11 +121,9 @@ def parser(obj: CreateEmbeddingResponse) -> CreateEmbeddingResponse: class AsyncEmbeddings(AsyncAPIResource): - with_raw_response: AsyncEmbeddingsWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncEmbeddingsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncEmbeddingsWithRawResponse: + return AsyncEmbeddingsWithRawResponse(self) async def create( self, diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index bc7823783b..b8ffaf64d0 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -4,17 +4,12 @@ import time import typing_extensions -from typing import TYPE_CHECKING, Mapping, cast +from typing import Mapping, cast from typing_extensions import Literal import httpx -from ..types import ( - FileObject, - FileDeleted, - file_list_params, - file_create_params, -) +from ..types import FileObject, FileDeleted, file_list_params, file_create_params from .._types import ( NOT_GIVEN, Body, @@ -24,6 +19,7 @@ FileTypes, ) from .._utils import extract_files, maybe_transform, deepcopy_minimal +from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ..pagination import SyncPage, AsyncPage @@ -33,18 +29,13 @@ make_request_options, ) -if TYPE_CHECKING: - from .._client import OpenAI, AsyncOpenAI - __all__ = ["Files", "AsyncFiles"] class Files(SyncAPIResource): - with_raw_response: FilesWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = FilesWithRawResponse(self) + @cached_property + def with_raw_response(self) -> FilesWithRawResponse: + return FilesWithRawResponse(self) def create( self, @@ -304,11 +295,9 @@ def wait_for_processing( class AsyncFiles(AsyncAPIResource): - with_raw_response: AsyncFilesWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncFilesWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncFilesWithRawResponse: + return AsyncFilesWithRawResponse(self) async def create( self, diff --git a/src/openai/resources/fine_tunes.py b/src/openai/resources/fine_tunes.py index f50d78717b..1c4a3057ac 100644 --- a/src/openai/resources/fine_tunes.py +++ b/src/openai/resources/fine_tunes.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, List, Union, Optional, overload +from typing import List, Union, Optional, overload from typing_extensions import Literal import httpx @@ -22,6 +22,7 @@ NotGiven, ) from .._utils import maybe_transform +from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .._streaming import Stream, AsyncStream @@ -31,18 +32,13 @@ make_request_options, ) -if TYPE_CHECKING: - from .._client import OpenAI, AsyncOpenAI - __all__ = ["FineTunes", "AsyncFineTunes"] class FineTunes(SyncAPIResource): - with_raw_response: FineTunesWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = FineTunesWithRawResponse(self) + @cached_property + def with_raw_response(self) -> FineTunesWithRawResponse: + return FineTunesWithRawResponse(self) def create( self, @@ -416,11 +412,9 @@ def list_events( class AsyncFineTunes(AsyncAPIResource): - with_raw_response: AsyncFineTunesWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncFineTunesWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncFineTunesWithRawResponse: + return AsyncFineTunesWithRawResponse(self) async def create( self, diff --git a/src/openai/resources/fine_tuning/fine_tuning.py b/src/openai/resources/fine_tuning/fine_tuning.py index 2e5f36e546..a5a68b08eb 100644 --- a/src/openai/resources/fine_tuning/fine_tuning.py +++ b/src/openai/resources/fine_tuning/fine_tuning.py @@ -2,35 +2,31 @@ from __future__ import annotations -from typing import TYPE_CHECKING - from .jobs import Jobs, AsyncJobs, JobsWithRawResponse, AsyncJobsWithRawResponse +from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource -if TYPE_CHECKING: - from ..._client import OpenAI, AsyncOpenAI - __all__ = ["FineTuning", "AsyncFineTuning"] class FineTuning(SyncAPIResource): - jobs: Jobs - with_raw_response: FineTuningWithRawResponse + @cached_property + def jobs(self) -> Jobs: + return Jobs(self._client) - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.jobs = Jobs(client) - self.with_raw_response = FineTuningWithRawResponse(self) + @cached_property + def with_raw_response(self) -> FineTuningWithRawResponse: + return FineTuningWithRawResponse(self) class AsyncFineTuning(AsyncAPIResource): - jobs: AsyncJobs - with_raw_response: AsyncFineTuningWithRawResponse + @cached_property + def jobs(self) -> AsyncJobs: + return AsyncJobs(self._client) - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.jobs = AsyncJobs(client) - self.with_raw_response = AsyncFineTuningWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncFineTuningWithRawResponse: + return AsyncFineTuningWithRawResponse(self) class FineTuningWithRawResponse: diff --git a/src/openai/resources/fine_tuning/jobs.py b/src/openai/resources/fine_tuning/jobs.py index 55eee67044..98615cdfec 100644 --- a/src/openai/resources/fine_tuning/jobs.py +++ b/src/openai/resources/fine_tuning/jobs.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Union, Optional +from typing import Union, Optional from typing_extensions import Literal import httpx @@ -15,6 +15,7 @@ NotGiven, ) from ..._utils import maybe_transform +from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ...pagination import SyncCursorPage, AsyncCursorPage @@ -30,18 +31,13 @@ job_list_events_params, ) -if TYPE_CHECKING: - from ..._client import OpenAI, AsyncOpenAI - __all__ = ["Jobs", "AsyncJobs"] class Jobs(SyncAPIResource): - with_raw_response: JobsWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = JobsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> JobsWithRawResponse: + return JobsWithRawResponse(self) def create( self, @@ -289,11 +285,9 @@ def list_events( class AsyncJobs(AsyncAPIResource): - with_raw_response: AsyncJobsWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncJobsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncJobsWithRawResponse: + return AsyncJobsWithRawResponse(self) async def create( self, diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py index 0e1313078f..365bd37c06 100644 --- a/src/openai/resources/images.py +++ b/src/openai/resources/images.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Union, Mapping, Optional, cast +from typing import Union, Mapping, Optional, cast from typing_extensions import Literal import httpx @@ -22,24 +22,20 @@ FileTypes, ) from .._utils import extract_files, maybe_transform, deepcopy_minimal +from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .._base_client import ( make_request_options, ) -if TYPE_CHECKING: - from .._client import OpenAI, AsyncOpenAI - __all__ = ["Images", "AsyncImages"] class Images(SyncAPIResource): - with_raw_response: ImagesWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = ImagesWithRawResponse(self) + @cached_property + def with_raw_response(self) -> ImagesWithRawResponse: + return ImagesWithRawResponse(self) def create_variation( self, @@ -280,11 +276,9 @@ def generate( class AsyncImages(AsyncAPIResource): - with_raw_response: AsyncImagesWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncImagesWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncImagesWithRawResponse: + return AsyncImagesWithRawResponse(self) async def create_variation( self, diff --git a/src/openai/resources/models.py b/src/openai/resources/models.py index a44a7ffbb0..2950e733eb 100644 --- a/src/openai/resources/models.py +++ b/src/openai/resources/models.py @@ -2,8 +2,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING - import httpx from ..types import Model, ModelDeleted @@ -14,6 +12,7 @@ Headers, NotGiven, ) +from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ..pagination import SyncPage, AsyncPage @@ -22,18 +21,13 @@ make_request_options, ) -if TYPE_CHECKING: - from .._client import OpenAI, AsyncOpenAI - __all__ = ["Models", "AsyncModels"] class Models(SyncAPIResource): - with_raw_response: ModelsWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = ModelsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> ModelsWithRawResponse: + return ModelsWithRawResponse(self) def retrieve( self, @@ -125,11 +119,9 @@ def delete( class AsyncModels(AsyncAPIResource): - with_raw_response: AsyncModelsWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncModelsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncModelsWithRawResponse: + return AsyncModelsWithRawResponse(self) async def retrieve( self, diff --git a/src/openai/resources/moderations.py b/src/openai/resources/moderations.py index 9de7cd640f..cb27f48467 100644 --- a/src/openai/resources/moderations.py +++ b/src/openai/resources/moderations.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, List, Union +from typing import List, Union from typing_extensions import Literal import httpx @@ -16,24 +16,20 @@ NotGiven, ) from .._utils import maybe_transform +from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .._base_client import ( make_request_options, ) -if TYPE_CHECKING: - from .._client import OpenAI, AsyncOpenAI - __all__ = ["Moderations", "AsyncModerations"] class Moderations(SyncAPIResource): - with_raw_response: ModerationsWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = ModerationsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> ModerationsWithRawResponse: + return ModerationsWithRawResponse(self) def create( self, @@ -87,11 +83,9 @@ def create( class AsyncModerations(AsyncAPIResource): - with_raw_response: AsyncModerationsWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncModerationsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncModerationsWithRawResponse: + return AsyncModerationsWithRawResponse(self) async def create( self, From d0a20e9e6aca5dfd121f5f99bbafaccb47498cc4 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 5 Jan 2024 18:07:54 -0500 Subject: [PATCH 185/816] chore(internal): loosen type var restrictions (#1049) --- src/openai/_base_client.py | 41 +++++++++---------- src/openai/_response.py | 4 +- src/openai/_types.py | 17 +++++--- src/openai/pagination.py | 29 ++++++------- src/openai/resources/audio/speech.py | 8 +--- src/openai/resources/audio/transcriptions.py | 9 +--- src/openai/resources/audio/translations.py | 9 +--- .../resources/beta/assistants/assistants.py | 8 +--- src/openai/resources/beta/assistants/files.py | 8 +--- .../resources/beta/threads/messages/files.py | 8 +--- .../beta/threads/messages/messages.py | 8 +--- .../resources/beta/threads/runs/runs.py | 8 +--- .../resources/beta/threads/runs/steps.py | 8 +--- src/openai/resources/beta/threads/threads.py | 8 +--- src/openai/resources/chat/completions.py | 8 +--- src/openai/resources/completions.py | 8 +--- src/openai/resources/edits.py | 8 +--- src/openai/resources/embeddings.py | 8 +--- src/openai/resources/files.py | 9 +--- src/openai/resources/fine_tunes.py | 8 +--- src/openai/resources/fine_tuning/jobs.py | 8 +--- src/openai/resources/images.py | 9 +--- src/openai/resources/models.py | 8 +--- src/openai/resources/moderations.py | 8 +--- 24 files changed, 67 insertions(+), 188 deletions(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 53a53d8016..97c6bef913 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -48,7 +48,6 @@ Body, Omit, Query, - ModelT, Headers, Timeout, NotGiven, @@ -61,7 +60,6 @@ HttpxSendArgs, AsyncTransport, RequestOptions, - UnknownResponse, ModelBuilderProtocol, BinaryResponseContent, ) @@ -142,7 +140,7 @@ def __init__( self.params = params -class BasePage(GenericModel, Generic[ModelT]): +class BasePage(GenericModel, Generic[_T]): """ Defines the core interface for pagination. @@ -155,7 +153,7 @@ class BasePage(GenericModel, Generic[ModelT]): """ _options: FinalRequestOptions = PrivateAttr() - _model: Type[ModelT] = PrivateAttr() + _model: Type[_T] = PrivateAttr() def has_next_page(self) -> bool: items = self._get_page_items() @@ -166,7 +164,7 @@ def has_next_page(self) -> bool: def next_page_info(self) -> Optional[PageInfo]: ... - def _get_page_items(self) -> Iterable[ModelT]: # type: ignore[empty-body] + def _get_page_items(self) -> Iterable[_T]: # type: ignore[empty-body] ... def _params_from_url(http://github.com/self,%20url:%20URL) -> httpx.QueryParams: @@ -191,13 +189,13 @@ def _info_to_options(self, info: PageInfo) -> FinalRequestOptions: raise ValueError("Unexpected PageInfo state") -class BaseSyncPage(BasePage[ModelT], Generic[ModelT]): +class BaseSyncPage(BasePage[_T], Generic[_T]): _client: SyncAPIClient = pydantic.PrivateAttr() def _set_private_attributes( self, client: SyncAPIClient, - model: Type[ModelT], + model: Type[_T], options: FinalRequestOptions, ) -> None: self._model = model @@ -212,7 +210,7 @@ def _set_private_attributes( # methods should continue to work as expected as there is an alternative method # to cast a model to a dictionary, model.dict(), which is used internally # by pydantic. - def __iter__(self) -> Iterator[ModelT]: # type: ignore + def __iter__(self) -> Iterator[_T]: # type: ignore for page in self.iter_pages(): for item in page._get_page_items(): yield item @@ -237,13 +235,13 @@ def get_next_page(self: SyncPageT) -> SyncPageT: return self._client._request_api_list(self._model, page=self.__class__, options=options) -class AsyncPaginator(Generic[ModelT, AsyncPageT]): +class AsyncPaginator(Generic[_T, AsyncPageT]): def __init__( self, client: AsyncAPIClient, options: FinalRequestOptions, page_cls: Type[AsyncPageT], - model: Type[ModelT], + model: Type[_T], ) -> None: self._model = model self._client = client @@ -266,7 +264,7 @@ def _parser(resp: AsyncPageT) -> AsyncPageT: return await self._client.request(self._page_cls, self._options) - async def __aiter__(self) -> AsyncIterator[ModelT]: + async def __aiter__(self) -> AsyncIterator[_T]: # https://github.com/microsoft/pyright/issues/3464 page = cast( AsyncPageT, @@ -276,12 +274,12 @@ async def __aiter__(self) -> AsyncIterator[ModelT]: yield item -class BaseAsyncPage(BasePage[ModelT], Generic[ModelT]): +class BaseAsyncPage(BasePage[_T], Generic[_T]): _client: AsyncAPIClient = pydantic.PrivateAttr() def _set_private_attributes( self, - model: Type[ModelT], + model: Type[_T], client: AsyncAPIClient, options: FinalRequestOptions, ) -> None: @@ -289,7 +287,7 @@ def _set_private_attributes( self._client = client self._options = options - async def __aiter__(self) -> AsyncIterator[ModelT]: + async def __aiter__(self) -> AsyncIterator[_T]: async for page in self.iter_pages(): for item in page._get_page_items(): yield item @@ -528,7 +526,7 @@ def _process_response_data( if data is None: return cast(ResponseT, None) - if cast_to is UnknownResponse: + if cast_to is object: return cast(ResponseT, data) try: @@ -970,7 +968,7 @@ def _retry_request( def _request_api_list( self, - model: Type[ModelT], + model: Type[object], page: Type[SyncPageT], options: FinalRequestOptions, ) -> SyncPageT: @@ -1132,7 +1130,7 @@ def get_api_list( self, path: str, *, - model: Type[ModelT], + model: Type[object], page: Type[SyncPageT], body: Body | None = None, options: RequestOptions = {}, @@ -1434,10 +1432,10 @@ async def _retry_request( def _request_api_list( self, - model: Type[ModelT], + model: Type[_T], page: Type[AsyncPageT], options: FinalRequestOptions, - ) -> AsyncPaginator[ModelT, AsyncPageT]: + ) -> AsyncPaginator[_T, AsyncPageT]: return AsyncPaginator(client=self, options=options, page_cls=page, model=model) @overload @@ -1584,13 +1582,12 @@ def get_api_list( self, path: str, *, - # TODO: support paginating `str` - model: Type[ModelT], + model: Type[_T], page: Type[AsyncPageT], body: Body | None = None, options: RequestOptions = {}, method: str = "get", - ) -> AsyncPaginator[ModelT, AsyncPageT]: + ) -> AsyncPaginator[_T, AsyncPageT]: opts = FinalRequestOptions.construct(method=method, url=path, json_data=body, **options) return self._request_api_list(model, page, opts) diff --git a/src/openai/_response.py b/src/openai/_response.py index 6b7c86e544..bf72d18fd5 100644 --- a/src/openai/_response.py +++ b/src/openai/_response.py @@ -9,7 +9,7 @@ import httpx -from ._types import NoneType, UnknownResponse, BinaryResponseContent +from ._types import NoneType, BinaryResponseContent from ._utils import is_given, extract_type_var_from_base from ._models import BaseModel, is_basemodel from ._constants import RAW_RESPONSE_HEADER @@ -162,7 +162,7 @@ def _parse(self) -> R: # `ResponseT` TypeVar, however if that TypeVar is ever updated in the future, then # this function would become unsafe but a type checker would not report an error. if ( - cast_to is not UnknownResponse + cast_to is not object and not origin is list and not origin is dict and not origin is Union diff --git a/src/openai/_types.py b/src/openai/_types.py index b52af6882f..e6b83b2a3f 100644 --- a/src/openai/_types.py +++ b/src/openai/_types.py @@ -258,11 +258,6 @@ class RequestOptions(TypedDict, total=False): idempotency_key: str -# Sentinel class used when the response type is an object with an unknown schema -class UnknownResponse: - ... - - # Sentinel class used until PEP 0661 is accepted class NotGiven: """ @@ -339,7 +334,17 @@ def get(self, __key: str) -> str | None: ResponseT = TypeVar( "ResponseT", - bound="Union[str, None, BaseModel, List[Any], Dict[str, Any], Response, UnknownResponse, ModelBuilderProtocol, BinaryResponseContent]", + bound=Union[ + object, + str, + None, + "BaseModel", + List[Any], + Dict[str, Any], + Response, + ModelBuilderProtocol, + BinaryResponseContent, + ], ) StrBytesIntFloat = Union[str, bytes, int, float] diff --git a/src/openai/pagination.py b/src/openai/pagination.py index d47deb17be..f7527753e1 100644 --- a/src/openai/pagination.py +++ b/src/openai/pagination.py @@ -1,27 +1,28 @@ # File generated from our OpenAPI spec by Stainless. -from typing import Any, List, Generic, Optional, cast +from typing import Any, List, Generic, TypeVar, Optional, cast from typing_extensions import Protocol, override, runtime_checkable -from ._types import ModelT from ._base_client import BasePage, PageInfo, BaseSyncPage, BaseAsyncPage __all__ = ["SyncPage", "AsyncPage", "SyncCursorPage", "AsyncCursorPage"] +_T = TypeVar("_T") + @runtime_checkable class CursorPageItem(Protocol): id: Optional[str] -class SyncPage(BaseSyncPage[ModelT], BasePage[ModelT], Generic[ModelT]): +class SyncPage(BaseSyncPage[_T], BasePage[_T], Generic[_T]): """Note: no pagination actually occurs yet, this is for forwards-compatibility.""" - data: List[ModelT] + data: List[_T] object: str @override - def _get_page_items(self) -> List[ModelT]: + def _get_page_items(self) -> List[_T]: data = self.data if not data: return [] @@ -36,14 +37,14 @@ def next_page_info(self) -> None: return None -class AsyncPage(BaseAsyncPage[ModelT], BasePage[ModelT], Generic[ModelT]): +class AsyncPage(BaseAsyncPage[_T], BasePage[_T], Generic[_T]): """Note: no pagination actually occurs yet, this is for forwards-compatibility.""" - data: List[ModelT] + data: List[_T] object: str @override - def _get_page_items(self) -> List[ModelT]: + def _get_page_items(self) -> List[_T]: data = self.data if not data: return [] @@ -58,11 +59,11 @@ def next_page_info(self) -> None: return None -class SyncCursorPage(BaseSyncPage[ModelT], BasePage[ModelT], Generic[ModelT]): - data: List[ModelT] +class SyncCursorPage(BaseSyncPage[_T], BasePage[_T], Generic[_T]): + data: List[_T] @override - def _get_page_items(self) -> List[ModelT]: + def _get_page_items(self) -> List[_T]: data = self.data if not data: return [] @@ -82,11 +83,11 @@ def next_page_info(self) -> Optional[PageInfo]: return PageInfo(params={"after": item.id}) -class AsyncCursorPage(BaseAsyncPage[ModelT], BasePage[ModelT], Generic[ModelT]): - data: List[ModelT] +class AsyncCursorPage(BaseAsyncPage[_T], BasePage[_T], Generic[_T]): + data: List[_T] @override - def _get_page_items(self) -> List[ModelT]: + def _get_page_items(self) -> List[_T]: data = self.data if not data: return [] diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index 49fded960d..b7cd3733a9 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -7,13 +7,7 @@ import httpx -from ..._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ..._utils import maybe_transform from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index f211678928..7d7441a9f6 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -7,14 +7,7 @@ import httpx -from ..._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, - FileTypes, -) +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from ..._utils import extract_files, maybe_transform, deepcopy_minimal from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index 402ec8ac1e..7f5f65b6c8 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -7,14 +7,7 @@ import httpx -from ..._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, - FileTypes, -) +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from ..._utils import extract_files, maybe_transform, deepcopy_minimal from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource diff --git a/src/openai/resources/beta/assistants/assistants.py b/src/openai/resources/beta/assistants/assistants.py index 064ca1197c..0ae054795d 100644 --- a/src/openai/resources/beta/assistants/assistants.py +++ b/src/openai/resources/beta/assistants/assistants.py @@ -8,13 +8,7 @@ import httpx from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from ...._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ...._utils import maybe_transform from ...._compat import cached_property from ...._resource import SyncAPIResource, AsyncAPIResource diff --git a/src/openai/resources/beta/assistants/files.py b/src/openai/resources/beta/assistants/files.py index f8a665b75c..0624e562f8 100644 --- a/src/openai/resources/beta/assistants/files.py +++ b/src/openai/resources/beta/assistants/files.py @@ -6,13 +6,7 @@ import httpx -from ...._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ...._utils import maybe_transform from ...._compat import cached_property from ...._resource import SyncAPIResource, AsyncAPIResource diff --git a/src/openai/resources/beta/threads/messages/files.py b/src/openai/resources/beta/threads/messages/files.py index d0c8c7f0ae..4b95b200eb 100644 --- a/src/openai/resources/beta/threads/messages/files.py +++ b/src/openai/resources/beta/threads/messages/files.py @@ -6,13 +6,7 @@ import httpx -from ....._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import maybe_transform from ....._compat import cached_property from ....._resource import SyncAPIResource, AsyncAPIResource diff --git a/src/openai/resources/beta/threads/messages/messages.py b/src/openai/resources/beta/threads/messages/messages.py index 7adc8b7829..146f665624 100644 --- a/src/openai/resources/beta/threads/messages/messages.py +++ b/src/openai/resources/beta/threads/messages/messages.py @@ -8,13 +8,7 @@ import httpx from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from ....._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import maybe_transform from ....._compat import cached_property from ....._resource import SyncAPIResource, AsyncAPIResource diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 902d3f3f92..87e62eb362 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -8,13 +8,7 @@ import httpx from .steps import Steps, AsyncSteps, StepsWithRawResponse, AsyncStepsWithRawResponse -from ....._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import maybe_transform from ....._compat import cached_property from ....._resource import SyncAPIResource, AsyncAPIResource diff --git a/src/openai/resources/beta/threads/runs/steps.py b/src/openai/resources/beta/threads/runs/steps.py index ff218a4beb..439926a412 100644 --- a/src/openai/resources/beta/threads/runs/steps.py +++ b/src/openai/resources/beta/threads/runs/steps.py @@ -6,13 +6,7 @@ import httpx -from ....._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import maybe_transform from ....._compat import cached_property from ....._resource import SyncAPIResource, AsyncAPIResource diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index caae758416..0ae409bb24 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -8,13 +8,7 @@ from .runs import Runs, AsyncRuns, RunsWithRawResponse, AsyncRunsWithRawResponse from .messages import Messages, AsyncMessages, MessagesWithRawResponse, AsyncMessagesWithRawResponse -from ...._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ...._utils import maybe_transform from .runs.runs import Runs, AsyncRuns from ...._compat import cached_property diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index 81dff146c8..b047c1d2a0 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -7,13 +7,7 @@ import httpx -from ..._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ..._utils import required_args, maybe_transform from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index 1339c34472..d3e7c54b11 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -8,13 +8,7 @@ import httpx from ..types import Completion, completion_create_params -from .._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import required_args, maybe_transform from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource diff --git a/src/openai/resources/edits.py b/src/openai/resources/edits.py index 355a11ac9d..ac15494263 100644 --- a/src/openai/resources/edits.py +++ b/src/openai/resources/edits.py @@ -9,13 +9,7 @@ import httpx from ..types import Edit, edit_create_params -from .._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import maybe_transform from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource diff --git a/src/openai/resources/embeddings.py b/src/openai/resources/embeddings.py index 409f5832fc..e93b29d45b 100644 --- a/src/openai/resources/embeddings.py +++ b/src/openai/resources/embeddings.py @@ -9,13 +9,7 @@ import httpx from ..types import CreateEmbeddingResponse, embedding_create_params -from .._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import is_given, maybe_transform from .._compat import cached_property from .._extras import numpy as np, has_numpy diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index b8ffaf64d0..1acf6f8060 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -10,14 +10,7 @@ import httpx from ..types import FileObject, FileDeleted, file_list_params, file_create_params -from .._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, - FileTypes, -) +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from .._utils import extract_files, maybe_transform, deepcopy_minimal from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource diff --git a/src/openai/resources/fine_tunes.py b/src/openai/resources/fine_tunes.py index 1c4a3057ac..411952387c 100644 --- a/src/openai/resources/fine_tunes.py +++ b/src/openai/resources/fine_tunes.py @@ -14,13 +14,7 @@ fine_tune_create_params, fine_tune_list_events_params, ) -from .._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import maybe_transform from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource diff --git a/src/openai/resources/fine_tuning/jobs.py b/src/openai/resources/fine_tuning/jobs.py index 98615cdfec..a8f24efce5 100644 --- a/src/openai/resources/fine_tuning/jobs.py +++ b/src/openai/resources/fine_tuning/jobs.py @@ -7,13 +7,7 @@ import httpx -from ..._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ..._utils import maybe_transform from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py index 365bd37c06..8e9c288af7 100644 --- a/src/openai/resources/images.py +++ b/src/openai/resources/images.py @@ -13,14 +13,7 @@ image_generate_params, image_create_variation_params, ) -from .._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, - FileTypes, -) +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from .._utils import extract_files, maybe_transform, deepcopy_minimal from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource diff --git a/src/openai/resources/models.py b/src/openai/resources/models.py index 2950e733eb..48888d98b5 100644 --- a/src/openai/resources/models.py +++ b/src/openai/resources/models.py @@ -5,13 +5,7 @@ import httpx from ..types import Model, ModelDeleted -from .._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper diff --git a/src/openai/resources/moderations.py b/src/openai/resources/moderations.py index cb27f48467..120a499186 100644 --- a/src/openai/resources/moderations.py +++ b/src/openai/resources/moderations.py @@ -8,13 +8,7 @@ import httpx from ..types import ModerationCreateResponse, moderation_create_params -from .._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import maybe_transform from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource From 98bf2549c6bfb8a308d347a055d1b81375ca76c8 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 8 Jan 2024 15:28:02 -0500 Subject: [PATCH 186/816] chore: add .keep files for examples and custom code directories (#1057) --- examples/.keep | 4 ++++ src/openai/lib/.keep | 4 ++++ 2 files changed, 8 insertions(+) create mode 100644 examples/.keep create mode 100644 src/openai/lib/.keep diff --git a/examples/.keep b/examples/.keep new file mode 100644 index 0000000000..d8c73e937a --- /dev/null +++ b/examples/.keep @@ -0,0 +1,4 @@ +File generated from our OpenAPI spec by Stainless. + +This directory can be used to store example files demonstrating usage of this SDK. +It is ignored by Stainless code generation and its content (other than this keep file) won't be touched. \ No newline at end of file diff --git a/src/openai/lib/.keep b/src/openai/lib/.keep new file mode 100644 index 0000000000..5e2c99fdbe --- /dev/null +++ b/src/openai/lib/.keep @@ -0,0 +1,4 @@ +File generated from our OpenAPI spec by Stainless. + +This directory can be used to store custom files to expand the SDK. +It is ignored by Stainless code generation and its content (other than this keep file) won't be touched. \ No newline at end of file From fa931da6db06f8e8102d91bfe3a4a64b31bbd02c Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 8 Jan 2024 15:28:46 -0500 Subject: [PATCH 187/816] release: 1.7.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 30 ++++++++++++++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 33 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 59565e8e31..cce9d1c6d3 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.6.1" + ".": "1.7.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 83bf20f775..09c81dae8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,35 @@ # Changelog +## 1.7.0 (2024-01-08) + +Full Changelog: [v1.6.1...v1.7.0](https://github.com/openai/openai-python/compare/v1.6.1...v1.7.0) + +### Features + +* add `None` default value to nullable response properties ([#1043](https://github.com/openai/openai-python/issues/1043)) ([d94b4d3](https://github.com/openai/openai-python/commit/d94b4d3d0adcd1a49a1c25cc9730cef013a3e9c9)) + + +### Bug Fixes + +* **client:** correctly use custom http client auth ([#1028](https://github.com/openai/openai-python/issues/1028)) ([3d7d93e](https://github.com/openai/openai-python/commit/3d7d93e951eb7fe09cd9d94d10a62a020398c7f9)) + + +### Chores + +* add .keep files for examples and custom code directories ([#1057](https://github.com/openai/openai-python/issues/1057)) ([7524097](https://github.com/openai/openai-python/commit/7524097a47af0fdc8b560186ef3b111b59430741)) +* **internal:** bump license ([#1037](https://github.com/openai/openai-python/issues/1037)) ([d828527](https://github.com/openai/openai-python/commit/d828527540ebd97679075f48744818f06311b0cb)) +* **internal:** loosen type var restrictions ([#1049](https://github.com/openai/openai-python/issues/1049)) ([e00876b](https://github.com/openai/openai-python/commit/e00876b20b93038450eb317899d8775c7661b8eb)) +* **internal:** replace isort with ruff ([#1042](https://github.com/openai/openai-python/issues/1042)) ([f1fbc9c](https://github.com/openai/openai-python/commit/f1fbc9c0d62e7d89ab32c8bdfa39cd94b560690b)) +* **internal:** update formatting ([#1041](https://github.com/openai/openai-python/issues/1041)) ([2e9ecee](https://github.com/openai/openai-python/commit/2e9ecee9bdfa8ec33b1b1527d5187483b700fad3)) +* **src:** fix typos ([#988](https://github.com/openai/openai-python/issues/988)) ([6a8b806](https://github.com/openai/openai-python/commit/6a8b80624636f9a0e5ada151b2509710a6f74808)) +* use property declarations for resource members ([#1047](https://github.com/openai/openai-python/issues/1047)) ([131f6bc](https://github.com/openai/openai-python/commit/131f6bc6b0ccf79119096057079e10906b3d4678)) + + +### Documentation + +* fix docstring typos ([#1022](https://github.com/openai/openai-python/issues/1022)) ([ad3fd2c](https://github.com/openai/openai-python/commit/ad3fd2cd19bf91f94473e368554dff39a8f9ad16)) +* improve audio example to show how to stream to a file ([#1017](https://github.com/openai/openai-python/issues/1017)) ([d45ed7f](https://github.com/openai/openai-python/commit/d45ed7f0513b167555ae875f1877fa205c5790d2)) + ## 1.6.1 (2023-12-22) Full Changelog: [v1.6.0...v1.6.1](https://github.com/openai/openai-python/compare/v1.6.0...v1.6.1) diff --git a/pyproject.toml b/pyproject.toml index 64f90ae1b6..85d19f1d0e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.6.1" +version = "1.7.0" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 9ab131d176..aa1cd4305c 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.6.1" # x-release-please-version +__version__ = "1.7.0" # x-release-please-version From bac5e4f8a9bd920a22e7dc9e0fb738d8327487ee Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 10 Jan 2024 12:30:16 -0500 Subject: [PATCH 188/816] chore(client): improve debug logging for failed requests (#1060) --- src/openai/_base_client.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 97c6bef913..c2c2db5f49 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -646,26 +646,33 @@ def _should_retry(self, response: httpx.Response) -> bool: # If the server explicitly says whether or not to retry, obey. if should_retry_header == "true": + log.debug("Retrying as header `x-should-retry` is set to `true`") return True if should_retry_header == "false": + log.debug("Not retrying as header `x-should-retry` is set to `false`") return False # Retry on request timeouts. if response.status_code == 408: + log.debug("Retrying due to status code %i", response.status_code) return True # Retry on lock timeouts. if response.status_code == 409: + log.debug("Retrying due to status code %i", response.status_code) return True # Retry on rate limits. if response.status_code == 429: + log.debug("Retrying due to status code %i", response.status_code) return True # Retry internal errors. if response.status_code >= 500: + log.debug("Retrying due to status code %i", response.status_code) return True + log.debug("Not retrying") return False def _idempotency_key(self) -> str: @@ -883,6 +890,8 @@ def _request( **kwargs, ) except httpx.TimeoutException as err: + log.debug("Encountered httpx.TimeoutException", exc_info=True) + if retries > 0: return self._retry_request( options, @@ -893,8 +902,11 @@ def _request( response_headers=None, ) + log.debug("Raising timeout error") raise APITimeoutError(request=request) from err except Exception as err: + log.debug("Encountered Exception", exc_info=True) + if retries > 0: return self._retry_request( options, @@ -905,6 +917,7 @@ def _request( response_headers=None, ) + log.debug("Raising connection error") raise APIConnectionError(request=request) from err log.debug( @@ -914,6 +927,8 @@ def _request( try: response.raise_for_status() except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code + log.debug("Encountered httpx.HTTPStatusError", exc_info=True) + if retries > 0 and self._should_retry(err.response): err.response.close() return self._retry_request( @@ -930,6 +945,7 @@ def _request( if not err.response.is_closed: err.response.read() + log.debug("Re-raising status error") raise self._make_status_error_from_response(err.response) from None return self._process_response( @@ -951,6 +967,11 @@ def _retry_request( stream_cls: type[_StreamT] | None, ) -> ResponseT | _StreamT: remaining = remaining_retries - 1 + if remaining == 1: + log.debug("1 retry left") + else: + log.debug("%i retries left", remaining) + timeout = self._calculate_retry_timeout(remaining, options, response_headers) log.info("Retrying request to %s in %f seconds", options.url, timeout) @@ -1349,6 +1370,8 @@ async def _request( **kwargs, ) except httpx.TimeoutException as err: + log.debug("Encountered httpx.TimeoutException", exc_info=True) + if retries > 0: return await self._retry_request( options, @@ -1359,8 +1382,11 @@ async def _request( response_headers=None, ) + log.debug("Raising timeout error") raise APITimeoutError(request=request) from err except Exception as err: + log.debug("Encountered Exception", exc_info=True) + if retries > 0: return await self._retry_request( options, @@ -1371,6 +1397,7 @@ async def _request( response_headers=None, ) + log.debug("Raising connection error") raise APIConnectionError(request=request) from err log.debug( @@ -1380,6 +1407,8 @@ async def _request( try: response.raise_for_status() except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code + log.debug("Encountered httpx.HTTPStatusError", exc_info=True) + if retries > 0 and self._should_retry(err.response): await err.response.aclose() return await self._retry_request( @@ -1396,6 +1425,7 @@ async def _request( if not err.response.is_closed: await err.response.aread() + log.debug("Re-raising status error") raise self._make_status_error_from_response(err.response) from None return self._process_response( @@ -1417,6 +1447,11 @@ async def _retry_request( stream_cls: type[_AsyncStreamT] | None, ) -> ResponseT | _AsyncStreamT: remaining = remaining_retries - 1 + if remaining == 1: + log.debug("1 retry left") + else: + log.debug("%i retries left", remaining) + timeout = self._calculate_retry_timeout(remaining, options, response_headers) log.info("Retrying request to %s in %f seconds", options.url, timeout) From 3fb66ddd5e2b6810f9f11619302a8b82d3712f10 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 10 Jan 2024 12:31:03 -0500 Subject: [PATCH 189/816] release: 1.7.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index cce9d1c6d3..5660725203 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.7.0" + ".": "1.7.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 09c81dae8d..19fb9c3e58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.7.1 (2024-01-10) + +Full Changelog: [v1.7.0...v1.7.1](https://github.com/openai/openai-python/compare/v1.7.0...v1.7.1) + +### Chores + +* **client:** improve debug logging for failed requests ([#1060](https://github.com/openai/openai-python/issues/1060)) ([cf9a651](https://github.com/openai/openai-python/commit/cf9a6517b4aa0f24bcbe143c54ea908d43dfda92)) + ## 1.7.0 (2024-01-08) Full Changelog: [v1.6.1...v1.7.0](https://github.com/openai/openai-python/compare/v1.6.1...v1.7.0) diff --git a/pyproject.toml b/pyproject.toml index 85d19f1d0e..9ff951873a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.7.0" +version = "1.7.1" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index aa1cd4305c..b25177f3a5 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.7.0" # x-release-please-version +__version__ = "1.7.1" # x-release-please-version From d253af575402224113020d533d55a640d6bebc6e Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 12 Jan 2024 08:45:01 -0500 Subject: [PATCH 190/816] docs(readme): improve api reference (#1065) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f644cdeefe..989f838384 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ It is generated from our [OpenAPI specification](https://github.com/openai/opena ## Documentation -The API documentation can be found [here](https://platform.openai.com/docs). +The REST API documentation can be found [on platform.openai.com](https://platform.openai.com/docs). The full API of this library can be found in [api.md](https://www.github.com/openai/openai-python/blob/main/api.md). ## Installation From 8dab14211822297ceb05e270911d9bfcede3141e Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 12 Jan 2024 10:02:22 -0500 Subject: [PATCH 191/816] refactor(api): remove deprecated endpoints (#1067) The fine tunes and edits APIs are no longer provided by OpenAI. This is not a breaking change as attempting to call these APIs, even on older versions, will result in an error at runtime. --- .stats.yml | 2 +- README.md | 5 +- api.md | 28 - src/openai/__init__.py | 2 - src/openai/_client.py | 12 - src/openai/_module_client.py | 14 - src/openai/resources/__init__.py | 10 - src/openai/resources/chat/completions.py | 12 +- src/openai/resources/completions.py | 194 +---- src/openai/resources/edits.py | 189 ---- src/openai/resources/fine_tunes.py | 819 ------------------ src/openai/resources/fine_tuning/jobs.py | 6 +- src/openai/types/__init__.py | 7 - .../types/chat/completion_create_params.py | 2 +- src/openai/types/completion_create_params.py | 29 +- src/openai/types/edit.py | 40 - src/openai/types/edit_create_params.py | 44 - src/openai/types/fine_tune.py | 94 -- src/openai/types/fine_tune_create_params.py | 140 --- src/openai/types/fine_tune_event.py | 17 - .../types/fine_tune_events_list_response.py | 15 - .../types/fine_tune_list_events_params.py | 41 - tests/api_resources/test_edits.py | 95 -- tests/api_resources/test_fine_tunes.py | 274 ------ 24 files changed, 59 insertions(+), 2032 deletions(-) delete mode 100644 src/openai/resources/edits.py delete mode 100644 src/openai/resources/fine_tunes.py delete mode 100644 src/openai/types/edit.py delete mode 100644 src/openai/types/edit_create_params.py delete mode 100644 src/openai/types/fine_tune.py delete mode 100644 src/openai/types/fine_tune_create_params.py delete mode 100644 src/openai/types/fine_tune_event.py delete mode 100644 src/openai/types/fine_tune_events_list_response.py delete mode 100644 src/openai/types/fine_tune_list_events_params.py delete mode 100644 tests/api_resources/test_edits.py delete mode 100644 tests/api_resources/test_fine_tunes.py diff --git a/.stats.yml b/.stats.yml index 03b0268ffa..c550abf3c6 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1 +1 @@ -configured_endpoints: 57 +configured_endpoints: 51 diff --git a/README.md b/README.md index 989f838384..e86ac6553e 100644 --- a/README.md +++ b/README.md @@ -296,8 +296,9 @@ from openai import OpenAI client = OpenAI() try: - client.fine_tunes.create( - training_file="file-XGinujblHPwGLSztz8cPS8XY", + client.fine_tuning.jobs.create( + model="gpt-3.5-turbo", + training_file="file-abc123", ) except openai.APIConnectionError as e: print("The server could not be reached") diff --git a/api.md b/api.md index 9d9993105b..86b972d14e 100644 --- a/api.md +++ b/api.md @@ -50,18 +50,6 @@ Methods: - client.chat.completions.create(\*\*params) -> ChatCompletion -# Edits - -Types: - -```python -from openai.types import Edit -``` - -Methods: - -- client.edits.create(\*\*params) -> Edit - # Embeddings Types: @@ -182,22 +170,6 @@ Methods: - client.fine_tuning.jobs.cancel(fine_tuning_job_id) -> FineTuningJob - client.fine_tuning.jobs.list_events(fine_tuning_job_id, \*\*params) -> SyncCursorPage[FineTuningJobEvent] -# FineTunes - -Types: - -```python -from openai.types import FineTune, FineTuneEvent, FineTuneEventsListResponse -``` - -Methods: - -- client.fine_tunes.create(\*\*params) -> FineTune -- client.fine_tunes.retrieve(fine_tune_id) -> FineTune -- client.fine_tunes.list() -> SyncPage[FineTune] -- client.fine_tunes.cancel(fine_tune_id) -> FineTune -- client.fine_tunes.list_events(fine_tune_id, \*\*params) -> FineTuneEventsListResponse - # Beta ## Assistants diff --git a/src/openai/__init__.py b/src/openai/__init__.py index ee96f06919..64c93e9449 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -316,12 +316,10 @@ def _reset_client() -> None: # type: ignore[reportUnusedFunction] beta as beta, chat as chat, audio as audio, - edits as edits, files as files, images as images, models as models, embeddings as embeddings, - fine_tunes as fine_tunes, completions as completions, fine_tuning as fine_tuning, moderations as moderations, diff --git a/src/openai/_client.py b/src/openai/_client.py index 9eb6888909..09f54e1b12 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -49,7 +49,6 @@ class OpenAI(SyncAPIClient): completions: resources.Completions chat: resources.Chat - edits: resources.Edits embeddings: resources.Embeddings files: resources.Files images: resources.Images @@ -57,7 +56,6 @@ class OpenAI(SyncAPIClient): moderations: resources.Moderations models: resources.Models fine_tuning: resources.FineTuning - fine_tunes: resources.FineTunes beta: resources.Beta with_raw_response: OpenAIWithRawResponse @@ -125,7 +123,6 @@ def __init__( self.completions = resources.Completions(self) self.chat = resources.Chat(self) - self.edits = resources.Edits(self) self.embeddings = resources.Embeddings(self) self.files = resources.Files(self) self.images = resources.Images(self) @@ -133,7 +130,6 @@ def __init__( self.moderations = resources.Moderations(self) self.models = resources.Models(self) self.fine_tuning = resources.FineTuning(self) - self.fine_tunes = resources.FineTunes(self) self.beta = resources.Beta(self) self.with_raw_response = OpenAIWithRawResponse(self) @@ -249,7 +245,6 @@ def _make_status_error( class AsyncOpenAI(AsyncAPIClient): completions: resources.AsyncCompletions chat: resources.AsyncChat - edits: resources.AsyncEdits embeddings: resources.AsyncEmbeddings files: resources.AsyncFiles images: resources.AsyncImages @@ -257,7 +252,6 @@ class AsyncOpenAI(AsyncAPIClient): moderations: resources.AsyncModerations models: resources.AsyncModels fine_tuning: resources.AsyncFineTuning - fine_tunes: resources.AsyncFineTunes beta: resources.AsyncBeta with_raw_response: AsyncOpenAIWithRawResponse @@ -325,7 +319,6 @@ def __init__( self.completions = resources.AsyncCompletions(self) self.chat = resources.AsyncChat(self) - self.edits = resources.AsyncEdits(self) self.embeddings = resources.AsyncEmbeddings(self) self.files = resources.AsyncFiles(self) self.images = resources.AsyncImages(self) @@ -333,7 +326,6 @@ def __init__( self.moderations = resources.AsyncModerations(self) self.models = resources.AsyncModels(self) self.fine_tuning = resources.AsyncFineTuning(self) - self.fine_tunes = resources.AsyncFineTunes(self) self.beta = resources.AsyncBeta(self) self.with_raw_response = AsyncOpenAIWithRawResponse(self) @@ -450,7 +442,6 @@ class OpenAIWithRawResponse: def __init__(self, client: OpenAI) -> None: self.completions = resources.CompletionsWithRawResponse(client.completions) self.chat = resources.ChatWithRawResponse(client.chat) - self.edits = resources.EditsWithRawResponse(client.edits) self.embeddings = resources.EmbeddingsWithRawResponse(client.embeddings) self.files = resources.FilesWithRawResponse(client.files) self.images = resources.ImagesWithRawResponse(client.images) @@ -458,7 +449,6 @@ def __init__(self, client: OpenAI) -> None: self.moderations = resources.ModerationsWithRawResponse(client.moderations) self.models = resources.ModelsWithRawResponse(client.models) self.fine_tuning = resources.FineTuningWithRawResponse(client.fine_tuning) - self.fine_tunes = resources.FineTunesWithRawResponse(client.fine_tunes) self.beta = resources.BetaWithRawResponse(client.beta) @@ -466,7 +456,6 @@ class AsyncOpenAIWithRawResponse: def __init__(self, client: AsyncOpenAI) -> None: self.completions = resources.AsyncCompletionsWithRawResponse(client.completions) self.chat = resources.AsyncChatWithRawResponse(client.chat) - self.edits = resources.AsyncEditsWithRawResponse(client.edits) self.embeddings = resources.AsyncEmbeddingsWithRawResponse(client.embeddings) self.files = resources.AsyncFilesWithRawResponse(client.files) self.images = resources.AsyncImagesWithRawResponse(client.images) @@ -474,7 +463,6 @@ def __init__(self, client: AsyncOpenAI) -> None: self.moderations = resources.AsyncModerationsWithRawResponse(client.moderations) self.models = resources.AsyncModelsWithRawResponse(client.models) self.fine_tuning = resources.AsyncFineTuningWithRawResponse(client.fine_tuning) - self.fine_tunes = resources.AsyncFineTunesWithRawResponse(client.fine_tunes) self.beta = resources.AsyncBetaWithRawResponse(client.beta) diff --git a/src/openai/_module_client.py b/src/openai/_module_client.py index fe8e0a2139..d66e137ecd 100644 --- a/src/openai/_module_client.py +++ b/src/openai/_module_client.py @@ -18,12 +18,6 @@ def __load__(self) -> resources.Beta: return _load_client().beta -class EditsProxy(LazyProxy[resources.Edits]): - @override - def __load__(self) -> resources.Edits: - return _load_client().edits - - class FilesProxy(LazyProxy[resources.Files]): @override def __load__(self) -> resources.Files: @@ -54,12 +48,6 @@ def __load__(self) -> resources.Embeddings: return _load_client().embeddings -class FineTunesProxy(LazyProxy[resources.FineTunes]): - @override - def __load__(self) -> resources.FineTunes: - return _load_client().fine_tunes - - class CompletionsProxy(LazyProxy[resources.Completions]): @override def __load__(self) -> resources.Completions: @@ -80,13 +68,11 @@ def __load__(self) -> resources.FineTuning: chat: resources.Chat = ChatProxy().__as_proxied__() beta: resources.Beta = BetaProxy().__as_proxied__() -edits: resources.Edits = EditsProxy().__as_proxied__() files: resources.Files = FilesProxy().__as_proxied__() audio: resources.Audio = AudioProxy().__as_proxied__() images: resources.Images = ImagesProxy().__as_proxied__() models: resources.Models = ModelsProxy().__as_proxied__() embeddings: resources.Embeddings = EmbeddingsProxy().__as_proxied__() -fine_tunes: resources.FineTunes = FineTunesProxy().__as_proxied__() completions: resources.Completions = CompletionsProxy().__as_proxied__() moderations: resources.Moderations = ModerationsProxy().__as_proxied__() fine_tuning: resources.FineTuning = FineTuningProxy().__as_proxied__() diff --git a/src/openai/resources/__init__.py b/src/openai/resources/__init__.py index 2cdbeb6ae1..8219be12e6 100644 --- a/src/openai/resources/__init__.py +++ b/src/openai/resources/__init__.py @@ -3,12 +3,10 @@ from .beta import Beta, AsyncBeta, BetaWithRawResponse, AsyncBetaWithRawResponse from .chat import Chat, AsyncChat, ChatWithRawResponse, AsyncChatWithRawResponse from .audio import Audio, AsyncAudio, AudioWithRawResponse, AsyncAudioWithRawResponse -from .edits import Edits, AsyncEdits, EditsWithRawResponse, AsyncEditsWithRawResponse from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse from .images import Images, AsyncImages, ImagesWithRawResponse, AsyncImagesWithRawResponse from .models import Models, AsyncModels, ModelsWithRawResponse, AsyncModelsWithRawResponse from .embeddings import Embeddings, AsyncEmbeddings, EmbeddingsWithRawResponse, AsyncEmbeddingsWithRawResponse -from .fine_tunes import FineTunes, AsyncFineTunes, FineTunesWithRawResponse, AsyncFineTunesWithRawResponse from .completions import Completions, AsyncCompletions, CompletionsWithRawResponse, AsyncCompletionsWithRawResponse from .fine_tuning import FineTuning, AsyncFineTuning, FineTuningWithRawResponse, AsyncFineTuningWithRawResponse from .moderations import Moderations, AsyncModerations, ModerationsWithRawResponse, AsyncModerationsWithRawResponse @@ -22,10 +20,6 @@ "AsyncChat", "ChatWithRawResponse", "AsyncChatWithRawResponse", - "Edits", - "AsyncEdits", - "EditsWithRawResponse", - "AsyncEditsWithRawResponse", "Embeddings", "AsyncEmbeddings", "EmbeddingsWithRawResponse", @@ -54,10 +48,6 @@ "AsyncFineTuning", "FineTuningWithRawResponse", "AsyncFineTuningWithRawResponse", - "FineTunes", - "AsyncFineTunes", - "FineTunesWithRawResponse", - "AsyncFineTunesWithRawResponse", "Beta", "AsyncBeta", "BetaWithRawResponse", diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index b047c1d2a0..fa096784d2 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -185,7 +185,7 @@ def create( will not call a function and instead generates a message. `auto` means the model can pick between generating a message or calling a function. Specifying a particular function via - `{"type: "function", "function": {"name": "my_function"}}` forces the model to + `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that function. `none` is the default when no functions are present. `auto` is the default if @@ -371,7 +371,7 @@ def create( will not call a function and instead generates a message. `auto` means the model can pick between generating a message or calling a function. Specifying a particular function via - `{"type: "function", "function": {"name": "my_function"}}` forces the model to + `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that function. `none` is the default when no functions are present. `auto` is the default if @@ -557,7 +557,7 @@ def create( will not call a function and instead generates a message. `auto` means the model can pick between generating a message or calling a function. Specifying a particular function via - `{"type: "function", "function": {"name": "my_function"}}` forces the model to + `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that function. `none` is the default when no functions are present. `auto` is the default if @@ -833,7 +833,7 @@ async def create( will not call a function and instead generates a message. `auto` means the model can pick between generating a message or calling a function. Specifying a particular function via - `{"type: "function", "function": {"name": "my_function"}}` forces the model to + `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that function. `none` is the default when no functions are present. `auto` is the default if @@ -1019,7 +1019,7 @@ async def create( will not call a function and instead generates a message. `auto` means the model can pick between generating a message or calling a function. Specifying a particular function via - `{"type: "function", "function": {"name": "my_function"}}` forces the model to + `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that function. `none` is the default when no functions are present. `auto` is the default if @@ -1205,7 +1205,7 @@ async def create( will not call a function and instead generates a message. `auto` means the model can pick between generating a message or calling a function. Specifying a particular function via - `{"type: "function", "function": {"name": "my_function"}}` forces the model to + `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that function. `none` is the default when no functions are present. `auto` is the default if diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index d3e7c54b11..87dd090052 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -30,21 +30,7 @@ def with_raw_response(self) -> CompletionsWithRawResponse: def create( self, *, - model: Union[ - str, - Literal[ - "babbage-002", - "davinci-002", - "gpt-3.5-turbo-instruct", - "text-davinci-003", - "text-davinci-002", - "text-davinci-001", - "code-davinci-002", - "text-curie-001", - "text-babbage-001", - "text-ada-001", - ], - ], + model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]], prompt: Union[str, List[str], List[int], List[List[int]], None], best_of: Optional[int] | NotGiven = NOT_GIVEN, echo: Optional[bool] | NotGiven = NOT_GIVEN, @@ -107,12 +93,11 @@ def create( Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this - [tokenizer tool](/tokenizer?view=bpe) (which works for both GPT-2 and GPT-3) to - convert text to token IDs. Mathematically, the bias is added to the logits - generated by the model prior to sampling. The exact effect will vary per model, - but values between -1 and 1 should decrease or increase likelihood of selection; - values like -100 or 100 should result in a ban or exclusive selection of the - relevant token. + [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs. + Mathematically, the bias is added to the logits generated by the model prior to + sampling. The exact effect will vary per model, but values between -1 and 1 + should decrease or increase likelihood of selection; values like -100 or 100 + should result in a ban or exclusive selection of the relevant token. As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token from being generated. @@ -193,21 +178,7 @@ def create( def create( self, *, - model: Union[ - str, - Literal[ - "babbage-002", - "davinci-002", - "gpt-3.5-turbo-instruct", - "text-davinci-003", - "text-davinci-002", - "text-davinci-001", - "code-davinci-002", - "text-curie-001", - "text-babbage-001", - "text-ada-001", - ], - ], + model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]], prompt: Union[str, List[str], List[int], List[List[int]], None], stream: Literal[True], best_of: Optional[int] | NotGiven = NOT_GIVEN, @@ -277,12 +248,11 @@ def create( Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this - [tokenizer tool](/tokenizer?view=bpe) (which works for both GPT-2 and GPT-3) to - convert text to token IDs. Mathematically, the bias is added to the logits - generated by the model prior to sampling. The exact effect will vary per model, - but values between -1 and 1 should decrease or increase likelihood of selection; - values like -100 or 100 should result in a ban or exclusive selection of the - relevant token. + [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs. + Mathematically, the bias is added to the logits generated by the model prior to + sampling. The exact effect will vary per model, but values between -1 and 1 + should decrease or increase likelihood of selection; values like -100 or 100 + should result in a ban or exclusive selection of the relevant token. As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token from being generated. @@ -356,21 +326,7 @@ def create( def create( self, *, - model: Union[ - str, - Literal[ - "babbage-002", - "davinci-002", - "gpt-3.5-turbo-instruct", - "text-davinci-003", - "text-davinci-002", - "text-davinci-001", - "code-davinci-002", - "text-curie-001", - "text-babbage-001", - "text-ada-001", - ], - ], + model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]], prompt: Union[str, List[str], List[int], List[List[int]], None], stream: bool, best_of: Optional[int] | NotGiven = NOT_GIVEN, @@ -440,12 +396,11 @@ def create( Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this - [tokenizer tool](/tokenizer?view=bpe) (which works for both GPT-2 and GPT-3) to - convert text to token IDs. Mathematically, the bias is added to the logits - generated by the model prior to sampling. The exact effect will vary per model, - but values between -1 and 1 should decrease or increase likelihood of selection; - values like -100 or 100 should result in a ban or exclusive selection of the - relevant token. + [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs. + Mathematically, the bias is added to the logits generated by the model prior to + sampling. The exact effect will vary per model, but values between -1 and 1 + should decrease or increase likelihood of selection; values like -100 or 100 + should result in a ban or exclusive selection of the relevant token. As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token from being generated. @@ -519,21 +474,7 @@ def create( def create( self, *, - model: Union[ - str, - Literal[ - "babbage-002", - "davinci-002", - "gpt-3.5-turbo-instruct", - "text-davinci-003", - "text-davinci-002", - "text-davinci-001", - "code-davinci-002", - "text-curie-001", - "text-babbage-001", - "text-ada-001", - ], - ], + model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]], prompt: Union[str, List[str], List[int], List[List[int]], None], best_of: Optional[int] | NotGiven = NOT_GIVEN, echo: Optional[bool] | NotGiven = NOT_GIVEN, @@ -599,21 +540,7 @@ def with_raw_response(self) -> AsyncCompletionsWithRawResponse: async def create( self, *, - model: Union[ - str, - Literal[ - "babbage-002", - "davinci-002", - "gpt-3.5-turbo-instruct", - "text-davinci-003", - "text-davinci-002", - "text-davinci-001", - "code-davinci-002", - "text-curie-001", - "text-babbage-001", - "text-ada-001", - ], - ], + model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]], prompt: Union[str, List[str], List[int], List[List[int]], None], best_of: Optional[int] | NotGiven = NOT_GIVEN, echo: Optional[bool] | NotGiven = NOT_GIVEN, @@ -676,12 +603,11 @@ async def create( Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this - [tokenizer tool](/tokenizer?view=bpe) (which works for both GPT-2 and GPT-3) to - convert text to token IDs. Mathematically, the bias is added to the logits - generated by the model prior to sampling. The exact effect will vary per model, - but values between -1 and 1 should decrease or increase likelihood of selection; - values like -100 or 100 should result in a ban or exclusive selection of the - relevant token. + [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs. + Mathematically, the bias is added to the logits generated by the model prior to + sampling. The exact effect will vary per model, but values between -1 and 1 + should decrease or increase likelihood of selection; values like -100 or 100 + should result in a ban or exclusive selection of the relevant token. As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token from being generated. @@ -762,21 +688,7 @@ async def create( async def create( self, *, - model: Union[ - str, - Literal[ - "babbage-002", - "davinci-002", - "gpt-3.5-turbo-instruct", - "text-davinci-003", - "text-davinci-002", - "text-davinci-001", - "code-davinci-002", - "text-curie-001", - "text-babbage-001", - "text-ada-001", - ], - ], + model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]], prompt: Union[str, List[str], List[int], List[List[int]], None], stream: Literal[True], best_of: Optional[int] | NotGiven = NOT_GIVEN, @@ -846,12 +758,11 @@ async def create( Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this - [tokenizer tool](/tokenizer?view=bpe) (which works for both GPT-2 and GPT-3) to - convert text to token IDs. Mathematically, the bias is added to the logits - generated by the model prior to sampling. The exact effect will vary per model, - but values between -1 and 1 should decrease or increase likelihood of selection; - values like -100 or 100 should result in a ban or exclusive selection of the - relevant token. + [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs. + Mathematically, the bias is added to the logits generated by the model prior to + sampling. The exact effect will vary per model, but values between -1 and 1 + should decrease or increase likelihood of selection; values like -100 or 100 + should result in a ban or exclusive selection of the relevant token. As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token from being generated. @@ -925,21 +836,7 @@ async def create( async def create( self, *, - model: Union[ - str, - Literal[ - "babbage-002", - "davinci-002", - "gpt-3.5-turbo-instruct", - "text-davinci-003", - "text-davinci-002", - "text-davinci-001", - "code-davinci-002", - "text-curie-001", - "text-babbage-001", - "text-ada-001", - ], - ], + model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]], prompt: Union[str, List[str], List[int], List[List[int]], None], stream: bool, best_of: Optional[int] | NotGiven = NOT_GIVEN, @@ -1009,12 +906,11 @@ async def create( Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this - [tokenizer tool](/tokenizer?view=bpe) (which works for both GPT-2 and GPT-3) to - convert text to token IDs. Mathematically, the bias is added to the logits - generated by the model prior to sampling. The exact effect will vary per model, - but values between -1 and 1 should decrease or increase likelihood of selection; - values like -100 or 100 should result in a ban or exclusive selection of the - relevant token. + [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs. + Mathematically, the bias is added to the logits generated by the model prior to + sampling. The exact effect will vary per model, but values between -1 and 1 + should decrease or increase likelihood of selection; values like -100 or 100 + should result in a ban or exclusive selection of the relevant token. As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token from being generated. @@ -1088,21 +984,7 @@ async def create( async def create( self, *, - model: Union[ - str, - Literal[ - "babbage-002", - "davinci-002", - "gpt-3.5-turbo-instruct", - "text-davinci-003", - "text-davinci-002", - "text-davinci-001", - "code-davinci-002", - "text-curie-001", - "text-babbage-001", - "text-ada-001", - ], - ], + model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]], prompt: Union[str, List[str], List[int], List[List[int]], None], best_of: Optional[int] | NotGiven = NOT_GIVEN, echo: Optional[bool] | NotGiven = NOT_GIVEN, diff --git a/src/openai/resources/edits.py b/src/openai/resources/edits.py deleted file mode 100644 index ac15494263..0000000000 --- a/src/openai/resources/edits.py +++ /dev/null @@ -1,189 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. - -from __future__ import annotations - -import typing_extensions -from typing import Union, Optional -from typing_extensions import Literal - -import httpx - -from ..types import Edit, edit_create_params -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from .._utils import maybe_transform -from .._compat import cached_property -from .._resource import SyncAPIResource, AsyncAPIResource -from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper -from .._base_client import ( - make_request_options, -) - -__all__ = ["Edits", "AsyncEdits"] - - -class Edits(SyncAPIResource): - @cached_property - def with_raw_response(self) -> EditsWithRawResponse: - return EditsWithRawResponse(self) - - @typing_extensions.deprecated( - "The Edits API is deprecated; please use Chat Completions instead.\n\nhttps://openai.com/blog/gpt-4-api-general-availability#deprecation-of-the-edits-api\n" - ) - def create( - self, - *, - instruction: str, - model: Union[str, Literal["text-davinci-edit-001", "code-davinci-edit-001"]], - input: Optional[str] | NotGiven = NOT_GIVEN, - n: Optional[int] | NotGiven = NOT_GIVEN, - temperature: Optional[float] | NotGiven = NOT_GIVEN, - top_p: Optional[float] | NotGiven = NOT_GIVEN, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> Edit: - """ - Creates a new edit for the provided input, instruction, and parameters. - - Args: - instruction: The instruction that tells the model how to edit the prompt. - - model: ID of the model to use. You can use the `text-davinci-edit-001` or - `code-davinci-edit-001` model with this endpoint. - - input: The input text to use as a starting point for the edit. - - n: How many edits to generate for the input and instruction. - - temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will - make the output more random, while lower values like 0.2 will make it more - focused and deterministic. - - We generally recommend altering this or `top_p` but not both. - - top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. So 0.1 - means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or `temperature` but not both. - - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - return self._post( - "/edits", - body=maybe_transform( - { - "instruction": instruction, - "model": model, - "input": input, - "n": n, - "temperature": temperature, - "top_p": top_p, - }, - edit_create_params.EditCreateParams, - ), - options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout - ), - cast_to=Edit, - ) - - -class AsyncEdits(AsyncAPIResource): - @cached_property - def with_raw_response(self) -> AsyncEditsWithRawResponse: - return AsyncEditsWithRawResponse(self) - - @typing_extensions.deprecated( - "The Edits API is deprecated; please use Chat Completions instead.\n\nhttps://openai.com/blog/gpt-4-api-general-availability#deprecation-of-the-edits-api\n" - ) - async def create( - self, - *, - instruction: str, - model: Union[str, Literal["text-davinci-edit-001", "code-davinci-edit-001"]], - input: Optional[str] | NotGiven = NOT_GIVEN, - n: Optional[int] | NotGiven = NOT_GIVEN, - temperature: Optional[float] | NotGiven = NOT_GIVEN, - top_p: Optional[float] | NotGiven = NOT_GIVEN, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> Edit: - """ - Creates a new edit for the provided input, instruction, and parameters. - - Args: - instruction: The instruction that tells the model how to edit the prompt. - - model: ID of the model to use. You can use the `text-davinci-edit-001` or - `code-davinci-edit-001` model with this endpoint. - - input: The input text to use as a starting point for the edit. - - n: How many edits to generate for the input and instruction. - - temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will - make the output more random, while lower values like 0.2 will make it more - focused and deterministic. - - We generally recommend altering this or `top_p` but not both. - - top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. So 0.1 - means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or `temperature` but not both. - - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - return await self._post( - "/edits", - body=maybe_transform( - { - "instruction": instruction, - "model": model, - "input": input, - "n": n, - "temperature": temperature, - "top_p": top_p, - }, - edit_create_params.EditCreateParams, - ), - options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout - ), - cast_to=Edit, - ) - - -class EditsWithRawResponse: - def __init__(self, edits: Edits) -> None: - self.create = to_raw_response_wrapper( # pyright: ignore[reportDeprecated] - edits.create # pyright: ignore[reportDeprecated], - ) - - -class AsyncEditsWithRawResponse: - def __init__(self, edits: AsyncEdits) -> None: - self.create = async_to_raw_response_wrapper( # pyright: ignore[reportDeprecated] - edits.create # pyright: ignore[reportDeprecated], - ) diff --git a/src/openai/resources/fine_tunes.py b/src/openai/resources/fine_tunes.py deleted file mode 100644 index 411952387c..0000000000 --- a/src/openai/resources/fine_tunes.py +++ /dev/null @@ -1,819 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. - -from __future__ import annotations - -from typing import List, Union, Optional, overload -from typing_extensions import Literal - -import httpx - -from ..types import ( - FineTune, - FineTuneEvent, - FineTuneEventsListResponse, - fine_tune_create_params, - fine_tune_list_events_params, -) -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from .._utils import maybe_transform -from .._compat import cached_property -from .._resource import SyncAPIResource, AsyncAPIResource -from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper -from .._streaming import Stream, AsyncStream -from ..pagination import SyncPage, AsyncPage -from .._base_client import ( - AsyncPaginator, - make_request_options, -) - -__all__ = ["FineTunes", "AsyncFineTunes"] - - -class FineTunes(SyncAPIResource): - @cached_property - def with_raw_response(self) -> FineTunesWithRawResponse: - return FineTunesWithRawResponse(self) - - def create( - self, - *, - training_file: str, - batch_size: Optional[int] | NotGiven = NOT_GIVEN, - classification_betas: Optional[List[float]] | NotGiven = NOT_GIVEN, - classification_n_classes: Optional[int] | NotGiven = NOT_GIVEN, - classification_positive_class: Optional[str] | NotGiven = NOT_GIVEN, - compute_classification_metrics: Optional[bool] | NotGiven = NOT_GIVEN, - hyperparameters: fine_tune_create_params.Hyperparameters | NotGiven = NOT_GIVEN, - learning_rate_multiplier: Optional[float] | NotGiven = NOT_GIVEN, - model: Union[str, Literal["ada", "babbage", "curie", "davinci"], None] | NotGiven = NOT_GIVEN, - prompt_loss_weight: Optional[float] | NotGiven = NOT_GIVEN, - suffix: Optional[str] | NotGiven = NOT_GIVEN, - validation_file: Optional[str] | NotGiven = NOT_GIVEN, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> FineTune: - """ - Creates a job that fine-tunes a specified model from a given dataset. - - Response includes details of the enqueued job including job status and the name - of the fine-tuned models once complete. - - [Learn more about fine-tuning](https://platform.openai.com/docs/guides/legacy-fine-tuning) - - Args: - training_file: The ID of an uploaded file that contains training data. - - See [upload file](https://platform.openai.com/docs/api-reference/files/upload) - for how to upload a file. - - Your dataset must be formatted as a JSONL file, where each training example is a - JSON object with the keys "prompt" and "completion". Additionally, you must - upload your file with the purpose `fine-tune`. - - See the - [fine-tuning guide](https://platform.openai.com/docs/guides/legacy-fine-tuning/creating-training-data) - for more details. - - batch_size: The batch size to use for training. The batch size is the number of training - examples used to train a single forward and backward pass. - - By default, the batch size will be dynamically configured to be ~0.2% of the - number of examples in the training set, capped at 256 - in general, we've found - that larger batch sizes tend to work better for larger datasets. - - classification_betas: If this is provided, we calculate F-beta scores at the specified beta values. - The F-beta score is a generalization of F-1 score. This is only used for binary - classification. - - With a beta of 1 (i.e. the F-1 score), precision and recall are given the same - weight. A larger beta score puts more weight on recall and less on precision. A - smaller beta score puts more weight on precision and less on recall. - - classification_n_classes: The number of classes in a classification task. - - This parameter is required for multiclass classification. - - classification_positive_class: The positive class in binary classification. - - This parameter is needed to generate precision, recall, and F1 metrics when - doing binary classification. - - compute_classification_metrics: If set, we calculate classification-specific metrics such as accuracy and F-1 - score using the validation set at the end of every epoch. These metrics can be - viewed in the - [results file](https://platform.openai.com/docs/guides/legacy-fine-tuning/analyzing-your-fine-tuned-model). - - In order to compute classification metrics, you must provide a - `validation_file`. Additionally, you must specify `classification_n_classes` for - multiclass classification or `classification_positive_class` for binary - classification. - - hyperparameters: The hyperparameters used for the fine-tuning job. - - learning_rate_multiplier: The learning rate multiplier to use for training. The fine-tuning learning rate - is the original learning rate used for pretraining multiplied by this value. - - By default, the learning rate multiplier is the 0.05, 0.1, or 0.2 depending on - final `batch_size` (larger learning rates tend to perform better with larger - batch sizes). We recommend experimenting with values in the range 0.02 to 0.2 to - see what produces the best results. - - model: The name of the base model to fine-tune. You can select one of "ada", "babbage", - "curie", "davinci", or a fine-tuned model created after 2022-04-21 and before - 2023-08-22. To learn more about these models, see the - [Models](https://platform.openai.com/docs/models) documentation. - - prompt_loss_weight: The weight to use for loss on the prompt tokens. This controls how much the - model tries to learn to generate the prompt (as compared to the completion which - always has a weight of 1.0), and can add a stabilizing effect to training when - completions are short. - - If prompts are extremely long (relative to completions), it may make sense to - reduce this weight so as to avoid over-prioritizing learning the prompt. - - suffix: A string of up to 40 characters that will be added to your fine-tuned model - name. - - For example, a `suffix` of "custom-model-name" would produce a model name like - `ada:ft-your-org:custom-model-name-2022-02-15-04-21-04`. - - validation_file: The ID of an uploaded file that contains validation data. - - If you provide this file, the data is used to generate validation metrics - periodically during fine-tuning. These metrics can be viewed in the - [fine-tuning results file](https://platform.openai.com/docs/guides/legacy-fine-tuning/analyzing-your-fine-tuned-model). - Your train and validation data should be mutually exclusive. - - Your dataset must be formatted as a JSONL file, where each validation example is - a JSON object with the keys "prompt" and "completion". Additionally, you must - upload your file with the purpose `fine-tune`. - - See the - [fine-tuning guide](https://platform.openai.com/docs/guides/legacy-fine-tuning/creating-training-data) - for more details. - - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - return self._post( - "/fine-tunes", - body=maybe_transform( - { - "training_file": training_file, - "batch_size": batch_size, - "classification_betas": classification_betas, - "classification_n_classes": classification_n_classes, - "classification_positive_class": classification_positive_class, - "compute_classification_metrics": compute_classification_metrics, - "hyperparameters": hyperparameters, - "learning_rate_multiplier": learning_rate_multiplier, - "model": model, - "prompt_loss_weight": prompt_loss_weight, - "suffix": suffix, - "validation_file": validation_file, - }, - fine_tune_create_params.FineTuneCreateParams, - ), - options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout - ), - cast_to=FineTune, - ) - - def retrieve( - self, - fine_tune_id: str, - *, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> FineTune: - """ - Gets info about the fine-tune job. - - [Learn more about fine-tuning](https://platform.openai.com/docs/guides/legacy-fine-tuning) - - Args: - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - return self._get( - f"/fine-tunes/{fine_tune_id}", - options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout - ), - cast_to=FineTune, - ) - - def list( - self, - *, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> SyncPage[FineTune]: - """List your organization's fine-tuning jobs""" - return self._get_api_list( - "/fine-tunes", - page=SyncPage[FineTune], - options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout - ), - model=FineTune, - ) - - def cancel( - self, - fine_tune_id: str, - *, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> FineTune: - """ - Immediately cancel a fine-tune job. - - Args: - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - return self._post( - f"/fine-tunes/{fine_tune_id}/cancel", - options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout - ), - cast_to=FineTune, - ) - - @overload - def list_events( - self, - fine_tune_id: str, - *, - stream: Literal[False] | NotGiven = NOT_GIVEN, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = 86400, - ) -> FineTuneEventsListResponse: - """ - Get fine-grained status updates for a fine-tune job. - - Args: - stream: Whether to stream events for the fine-tune job. If set to true, events will be - sent as data-only - [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) - as they become available. The stream will terminate with a `data: [DONE]` - message when the job is finished (succeeded, cancelled, or failed). - - If set to false, only events generated so far will be returned. - - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - ... - - @overload - def list_events( - self, - fine_tune_id: str, - *, - stream: Literal[True], - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = 86400, - ) -> Stream[FineTuneEvent]: - """ - Get fine-grained status updates for a fine-tune job. - - Args: - stream: Whether to stream events for the fine-tune job. If set to true, events will be - sent as data-only - [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) - as they become available. The stream will terminate with a `data: [DONE]` - message when the job is finished (succeeded, cancelled, or failed). - - If set to false, only events generated so far will be returned. - - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - ... - - @overload - def list_events( - self, - fine_tune_id: str, - *, - stream: bool, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = 86400, - ) -> FineTuneEventsListResponse | Stream[FineTuneEvent]: - """ - Get fine-grained status updates for a fine-tune job. - - Args: - stream: Whether to stream events for the fine-tune job. If set to true, events will be - sent as data-only - [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) - as they become available. The stream will terminate with a `data: [DONE]` - message when the job is finished (succeeded, cancelled, or failed). - - If set to false, only events generated so far will be returned. - - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - ... - - def list_events( - self, - fine_tune_id: str, - *, - stream: Literal[False] | Literal[True] | NotGiven = NOT_GIVEN, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = 86400, - ) -> FineTuneEventsListResponse | Stream[FineTuneEvent]: - return self._get( - f"/fine-tunes/{fine_tune_id}/events", - options=make_request_options( - extra_headers=extra_headers, - extra_query=extra_query, - extra_body=extra_body, - timeout=timeout, - query=maybe_transform({"stream": stream}, fine_tune_list_events_params.FineTuneListEventsParams), - ), - cast_to=FineTuneEventsListResponse, - stream=stream or False, - stream_cls=Stream[FineTuneEvent], - ) - - -class AsyncFineTunes(AsyncAPIResource): - @cached_property - def with_raw_response(self) -> AsyncFineTunesWithRawResponse: - return AsyncFineTunesWithRawResponse(self) - - async def create( - self, - *, - training_file: str, - batch_size: Optional[int] | NotGiven = NOT_GIVEN, - classification_betas: Optional[List[float]] | NotGiven = NOT_GIVEN, - classification_n_classes: Optional[int] | NotGiven = NOT_GIVEN, - classification_positive_class: Optional[str] | NotGiven = NOT_GIVEN, - compute_classification_metrics: Optional[bool] | NotGiven = NOT_GIVEN, - hyperparameters: fine_tune_create_params.Hyperparameters | NotGiven = NOT_GIVEN, - learning_rate_multiplier: Optional[float] | NotGiven = NOT_GIVEN, - model: Union[str, Literal["ada", "babbage", "curie", "davinci"], None] | NotGiven = NOT_GIVEN, - prompt_loss_weight: Optional[float] | NotGiven = NOT_GIVEN, - suffix: Optional[str] | NotGiven = NOT_GIVEN, - validation_file: Optional[str] | NotGiven = NOT_GIVEN, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> FineTune: - """ - Creates a job that fine-tunes a specified model from a given dataset. - - Response includes details of the enqueued job including job status and the name - of the fine-tuned models once complete. - - [Learn more about fine-tuning](https://platform.openai.com/docs/guides/legacy-fine-tuning) - - Args: - training_file: The ID of an uploaded file that contains training data. - - See [upload file](https://platform.openai.com/docs/api-reference/files/upload) - for how to upload a file. - - Your dataset must be formatted as a JSONL file, where each training example is a - JSON object with the keys "prompt" and "completion". Additionally, you must - upload your file with the purpose `fine-tune`. - - See the - [fine-tuning guide](https://platform.openai.com/docs/guides/legacy-fine-tuning/creating-training-data) - for more details. - - batch_size: The batch size to use for training. The batch size is the number of training - examples used to train a single forward and backward pass. - - By default, the batch size will be dynamically configured to be ~0.2% of the - number of examples in the training set, capped at 256 - in general, we've found - that larger batch sizes tend to work better for larger datasets. - - classification_betas: If this is provided, we calculate F-beta scores at the specified beta values. - The F-beta score is a generalization of F-1 score. This is only used for binary - classification. - - With a beta of 1 (i.e. the F-1 score), precision and recall are given the same - weight. A larger beta score puts more weight on recall and less on precision. A - smaller beta score puts more weight on precision and less on recall. - - classification_n_classes: The number of classes in a classification task. - - This parameter is required for multiclass classification. - - classification_positive_class: The positive class in binary classification. - - This parameter is needed to generate precision, recall, and F1 metrics when - doing binary classification. - - compute_classification_metrics: If set, we calculate classification-specific metrics such as accuracy and F-1 - score using the validation set at the end of every epoch. These metrics can be - viewed in the - [results file](https://platform.openai.com/docs/guides/legacy-fine-tuning/analyzing-your-fine-tuned-model). - - In order to compute classification metrics, you must provide a - `validation_file`. Additionally, you must specify `classification_n_classes` for - multiclass classification or `classification_positive_class` for binary - classification. - - hyperparameters: The hyperparameters used for the fine-tuning job. - - learning_rate_multiplier: The learning rate multiplier to use for training. The fine-tuning learning rate - is the original learning rate used for pretraining multiplied by this value. - - By default, the learning rate multiplier is the 0.05, 0.1, or 0.2 depending on - final `batch_size` (larger learning rates tend to perform better with larger - batch sizes). We recommend experimenting with values in the range 0.02 to 0.2 to - see what produces the best results. - - model: The name of the base model to fine-tune. You can select one of "ada", "babbage", - "curie", "davinci", or a fine-tuned model created after 2022-04-21 and before - 2023-08-22. To learn more about these models, see the - [Models](https://platform.openai.com/docs/models) documentation. - - prompt_loss_weight: The weight to use for loss on the prompt tokens. This controls how much the - model tries to learn to generate the prompt (as compared to the completion which - always has a weight of 1.0), and can add a stabilizing effect to training when - completions are short. - - If prompts are extremely long (relative to completions), it may make sense to - reduce this weight so as to avoid over-prioritizing learning the prompt. - - suffix: A string of up to 40 characters that will be added to your fine-tuned model - name. - - For example, a `suffix` of "custom-model-name" would produce a model name like - `ada:ft-your-org:custom-model-name-2022-02-15-04-21-04`. - - validation_file: The ID of an uploaded file that contains validation data. - - If you provide this file, the data is used to generate validation metrics - periodically during fine-tuning. These metrics can be viewed in the - [fine-tuning results file](https://platform.openai.com/docs/guides/legacy-fine-tuning/analyzing-your-fine-tuned-model). - Your train and validation data should be mutually exclusive. - - Your dataset must be formatted as a JSONL file, where each validation example is - a JSON object with the keys "prompt" and "completion". Additionally, you must - upload your file with the purpose `fine-tune`. - - See the - [fine-tuning guide](https://platform.openai.com/docs/guides/legacy-fine-tuning/creating-training-data) - for more details. - - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - return await self._post( - "/fine-tunes", - body=maybe_transform( - { - "training_file": training_file, - "batch_size": batch_size, - "classification_betas": classification_betas, - "classification_n_classes": classification_n_classes, - "classification_positive_class": classification_positive_class, - "compute_classification_metrics": compute_classification_metrics, - "hyperparameters": hyperparameters, - "learning_rate_multiplier": learning_rate_multiplier, - "model": model, - "prompt_loss_weight": prompt_loss_weight, - "suffix": suffix, - "validation_file": validation_file, - }, - fine_tune_create_params.FineTuneCreateParams, - ), - options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout - ), - cast_to=FineTune, - ) - - async def retrieve( - self, - fine_tune_id: str, - *, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> FineTune: - """ - Gets info about the fine-tune job. - - [Learn more about fine-tuning](https://platform.openai.com/docs/guides/legacy-fine-tuning) - - Args: - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - return await self._get( - f"/fine-tunes/{fine_tune_id}", - options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout - ), - cast_to=FineTune, - ) - - def list( - self, - *, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> AsyncPaginator[FineTune, AsyncPage[FineTune]]: - """List your organization's fine-tuning jobs""" - return self._get_api_list( - "/fine-tunes", - page=AsyncPage[FineTune], - options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout - ), - model=FineTune, - ) - - async def cancel( - self, - fine_tune_id: str, - *, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> FineTune: - """ - Immediately cancel a fine-tune job. - - Args: - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - return await self._post( - f"/fine-tunes/{fine_tune_id}/cancel", - options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout - ), - cast_to=FineTune, - ) - - @overload - async def list_events( - self, - fine_tune_id: str, - *, - stream: Literal[False] | NotGiven = NOT_GIVEN, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = 86400, - ) -> FineTuneEventsListResponse: - """ - Get fine-grained status updates for a fine-tune job. - - Args: - stream: Whether to stream events for the fine-tune job. If set to true, events will be - sent as data-only - [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) - as they become available. The stream will terminate with a `data: [DONE]` - message when the job is finished (succeeded, cancelled, or failed). - - If set to false, only events generated so far will be returned. - - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - ... - - @overload - async def list_events( - self, - fine_tune_id: str, - *, - stream: Literal[True], - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = 86400, - ) -> AsyncStream[FineTuneEvent]: - """ - Get fine-grained status updates for a fine-tune job. - - Args: - stream: Whether to stream events for the fine-tune job. If set to true, events will be - sent as data-only - [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) - as they become available. The stream will terminate with a `data: [DONE]` - message when the job is finished (succeeded, cancelled, or failed). - - If set to false, only events generated so far will be returned. - - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - ... - - @overload - async def list_events( - self, - fine_tune_id: str, - *, - stream: bool, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = 86400, - ) -> FineTuneEventsListResponse | AsyncStream[FineTuneEvent]: - """ - Get fine-grained status updates for a fine-tune job. - - Args: - stream: Whether to stream events for the fine-tune job. If set to true, events will be - sent as data-only - [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) - as they become available. The stream will terminate with a `data: [DONE]` - message when the job is finished (succeeded, cancelled, or failed). - - If set to false, only events generated so far will be returned. - - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - ... - - async def list_events( - self, - fine_tune_id: str, - *, - stream: Literal[False] | Literal[True] | NotGiven = NOT_GIVEN, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = 86400, - ) -> FineTuneEventsListResponse | AsyncStream[FineTuneEvent]: - return await self._get( - f"/fine-tunes/{fine_tune_id}/events", - options=make_request_options( - extra_headers=extra_headers, - extra_query=extra_query, - extra_body=extra_body, - timeout=timeout, - query=maybe_transform({"stream": stream}, fine_tune_list_events_params.FineTuneListEventsParams), - ), - cast_to=FineTuneEventsListResponse, - stream=stream or False, - stream_cls=AsyncStream[FineTuneEvent], - ) - - -class FineTunesWithRawResponse: - def __init__(self, fine_tunes: FineTunes) -> None: - self.create = to_raw_response_wrapper( - fine_tunes.create, - ) - self.retrieve = to_raw_response_wrapper( - fine_tunes.retrieve, - ) - self.list = to_raw_response_wrapper( - fine_tunes.list, - ) - self.cancel = to_raw_response_wrapper( - fine_tunes.cancel, - ) - self.list_events = to_raw_response_wrapper( - fine_tunes.list_events, - ) - - -class AsyncFineTunesWithRawResponse: - def __init__(self, fine_tunes: AsyncFineTunes) -> None: - self.create = async_to_raw_response_wrapper( - fine_tunes.create, - ) - self.retrieve = async_to_raw_response_wrapper( - fine_tunes.retrieve, - ) - self.list = async_to_raw_response_wrapper( - fine_tunes.list, - ) - self.cancel = async_to_raw_response_wrapper( - fine_tunes.cancel, - ) - self.list_events = async_to_raw_response_wrapper( - fine_tunes.list_events, - ) diff --git a/src/openai/resources/fine_tuning/jobs.py b/src/openai/resources/fine_tuning/jobs.py index a8f24efce5..7537b48daa 100644 --- a/src/openai/resources/fine_tuning/jobs.py +++ b/src/openai/resources/fine_tuning/jobs.py @@ -49,7 +49,8 @@ def create( timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> FineTuningJob: """ - Creates a job that fine-tunes a specified model from a given dataset. + Creates a fine-tuning job which begins the process of creating a new model from + a given dataset. Response includes details of the enqueued job including job status and the name of the fine-tuned models once complete. @@ -299,7 +300,8 @@ async def create( timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> FineTuningJob: """ - Creates a job that fine-tunes a specified model from a given dataset. + Creates a fine-tuning job which begins the process of creating a new model from + a given dataset. Response includes details of the enqueued job including job status and the name of the fine-tuned models once complete. diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index df2b580587..d6108e1eed 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -2,33 +2,26 @@ from __future__ import annotations -from .edit import Edit as Edit from .image import Image as Image from .model import Model as Model from .shared import FunctionDefinition as FunctionDefinition, FunctionParameters as FunctionParameters from .embedding import Embedding as Embedding -from .fine_tune import FineTune as FineTune from .completion import Completion as Completion from .moderation import Moderation as Moderation from .file_object import FileObject as FileObject from .file_content import FileContent as FileContent from .file_deleted import FileDeleted as FileDeleted from .model_deleted import ModelDeleted as ModelDeleted -from .fine_tune_event import FineTuneEvent as FineTuneEvent from .images_response import ImagesResponse as ImagesResponse from .completion_usage import CompletionUsage as CompletionUsage from .file_list_params import FileListParams as FileListParams from .completion_choice import CompletionChoice as CompletionChoice from .image_edit_params import ImageEditParams as ImageEditParams -from .edit_create_params import EditCreateParams as EditCreateParams from .file_create_params import FileCreateParams as FileCreateParams from .image_generate_params import ImageGenerateParams as ImageGenerateParams from .embedding_create_params import EmbeddingCreateParams as EmbeddingCreateParams -from .fine_tune_create_params import FineTuneCreateParams as FineTuneCreateParams from .completion_create_params import CompletionCreateParams as CompletionCreateParams from .moderation_create_params import ModerationCreateParams as ModerationCreateParams from .create_embedding_response import CreateEmbeddingResponse as CreateEmbeddingResponse from .moderation_create_response import ModerationCreateResponse as ModerationCreateResponse -from .fine_tune_list_events_params import FineTuneListEventsParams as FineTuneListEventsParams from .image_create_variation_params import ImageCreateVariationParams as ImageCreateVariationParams -from .fine_tune_events_list_response import FineTuneEventsListResponse as FineTuneEventsListResponse diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 49807a372e..6b38a89263 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -174,7 +174,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): will not call a function and instead generates a message. `auto` means the model can pick between generating a message or calling a function. Specifying a particular function via - `{"type: "function", "function": {"name": "my_function"}}` forces the model to + `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that function. `none` is the default when no functions are present. `auto` is the default if diff --git a/src/openai/types/completion_create_params.py b/src/openai/types/completion_create_params.py index ab6609a06b..e14c2860df 100644 --- a/src/openai/types/completion_create_params.py +++ b/src/openai/types/completion_create_params.py @@ -9,23 +9,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): - model: Required[ - Union[ - str, - Literal[ - "babbage-002", - "davinci-002", - "gpt-3.5-turbo-instruct", - "text-davinci-003", - "text-davinci-002", - "text-davinci-001", - "code-davinci-002", - "text-curie-001", - "text-babbage-001", - "text-ada-001", - ], - ] - ] + model: Required[Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]]] """ID of the model to use. You can use the @@ -75,12 +59,11 @@ class CompletionCreateParamsBase(TypedDict, total=False): Accepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this - [tokenizer tool](/tokenizer?view=bpe) (which works for both GPT-2 and GPT-3) to - convert text to token IDs. Mathematically, the bias is added to the logits - generated by the model prior to sampling. The exact effect will vary per model, - but values between -1 and 1 should decrease or increase likelihood of selection; - values like -100 or 100 should result in a ban or exclusive selection of the - relevant token. + [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs. + Mathematically, the bias is added to the logits generated by the model prior to + sampling. The exact effect will vary per model, but values between -1 and 1 + should decrease or increase likelihood of selection; values like -100 or 100 + should result in a ban or exclusive selection of the relevant token. As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token from being generated. diff --git a/src/openai/types/edit.py b/src/openai/types/edit.py deleted file mode 100644 index 48bca2987b..0000000000 --- a/src/openai/types/edit.py +++ /dev/null @@ -1,40 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. - -from typing import List -from typing_extensions import Literal - -from .._models import BaseModel -from .completion_usage import CompletionUsage - -__all__ = ["Edit", "Choice"] - - -class Choice(BaseModel): - finish_reason: Literal["stop", "length"] - """The reason the model stopped generating tokens. - - This will be `stop` if the model hit a natural stop point or a provided stop - sequence, `length` if the maximum number of tokens specified in the request was - reached, or `content_filter` if content was omitted due to a flag from our - content filters. - """ - - index: int - """The index of the choice in the list of choices.""" - - text: str - """The edited result.""" - - -class Edit(BaseModel): - choices: List[Choice] - """A list of edit choices. Can be more than one if `n` is greater than 1.""" - - created: int - """The Unix timestamp (in seconds) of when the edit was created.""" - - object: Literal["edit"] - """The object type, which is always `edit`.""" - - usage: CompletionUsage - """Usage statistics for the completion request.""" diff --git a/src/openai/types/edit_create_params.py b/src/openai/types/edit_create_params.py deleted file mode 100644 index a23b79c369..0000000000 --- a/src/openai/types/edit_create_params.py +++ /dev/null @@ -1,44 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. - -from __future__ import annotations - -from typing import Union, Optional -from typing_extensions import Literal, Required, TypedDict - -__all__ = ["EditCreateParams"] - - -class EditCreateParams(TypedDict, total=False): - instruction: Required[str] - """The instruction that tells the model how to edit the prompt.""" - - model: Required[Union[str, Literal["text-davinci-edit-001", "code-davinci-edit-001"]]] - """ID of the model to use. - - You can use the `text-davinci-edit-001` or `code-davinci-edit-001` model with - this endpoint. - """ - - input: Optional[str] - """The input text to use as a starting point for the edit.""" - - n: Optional[int] - """How many edits to generate for the input and instruction.""" - - temperature: Optional[float] - """What sampling temperature to use, between 0 and 2. - - Higher values like 0.8 will make the output more random, while lower values like - 0.2 will make it more focused and deterministic. - - We generally recommend altering this or `top_p` but not both. - """ - - top_p: Optional[float] - """ - An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. So 0.1 - means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or `temperature` but not both. - """ diff --git a/src/openai/types/fine_tune.py b/src/openai/types/fine_tune.py deleted file mode 100644 index d1a063a065..0000000000 --- a/src/openai/types/fine_tune.py +++ /dev/null @@ -1,94 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. - -from typing import List, Optional -from typing_extensions import Literal - -from .._models import BaseModel -from .file_object import FileObject -from .fine_tune_event import FineTuneEvent - -__all__ = ["FineTune", "Hyperparams"] - - -class Hyperparams(BaseModel): - batch_size: int - """The batch size to use for training. - - The batch size is the number of training examples used to train a single forward - and backward pass. - """ - - learning_rate_multiplier: float - """The learning rate multiplier to use for training.""" - - n_epochs: int - """The number of epochs to train the model for. - - An epoch refers to one full cycle through the training dataset. - """ - - prompt_loss_weight: float - """The weight to use for loss on the prompt tokens.""" - - classification_n_classes: Optional[int] = None - """The number of classes to use for computing classification metrics.""" - - classification_positive_class: Optional[str] = None - """The positive class to use for computing classification metrics.""" - - compute_classification_metrics: Optional[bool] = None - """ - The classification metrics to compute using the validation dataset at the end of - every epoch. - """ - - -class FineTune(BaseModel): - id: str - """The object identifier, which can be referenced in the API endpoints.""" - - created_at: int - """The Unix timestamp (in seconds) for when the fine-tuning job was created.""" - - fine_tuned_model: Optional[str] = None - """The name of the fine-tuned model that is being created.""" - - hyperparams: Hyperparams - """The hyperparameters used for the fine-tuning job. - - See the - [fine-tuning guide](https://platform.openai.com/docs/guides/legacy-fine-tuning/hyperparameters) - for more details. - """ - - model: str - """The base model that is being fine-tuned.""" - - object: Literal["fine-tune"] - """The object type, which is always "fine-tune".""" - - organization_id: str - """The organization that owns the fine-tuning job.""" - - result_files: List[FileObject] - """The compiled results files for the fine-tuning job.""" - - status: str - """ - The current status of the fine-tuning job, which can be either `created`, - `running`, `succeeded`, `failed`, or `cancelled`. - """ - - training_files: List[FileObject] - """The list of files used for training.""" - - updated_at: int - """The Unix timestamp (in seconds) for when the fine-tuning job was last updated.""" - - validation_files: List[FileObject] - """The list of files used for validation.""" - - events: Optional[List[FineTuneEvent]] = None - """ - The list of events that have been observed in the lifecycle of the FineTune job. - """ diff --git a/src/openai/types/fine_tune_create_params.py b/src/openai/types/fine_tune_create_params.py deleted file mode 100644 index 1be9c9ea04..0000000000 --- a/src/openai/types/fine_tune_create_params.py +++ /dev/null @@ -1,140 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. - -from __future__ import annotations - -from typing import List, Union, Optional -from typing_extensions import Literal, Required, TypedDict - -__all__ = ["FineTuneCreateParams", "Hyperparameters"] - - -class FineTuneCreateParams(TypedDict, total=False): - training_file: Required[str] - """The ID of an uploaded file that contains training data. - - See [upload file](https://platform.openai.com/docs/api-reference/files/upload) - for how to upload a file. - - Your dataset must be formatted as a JSONL file, where each training example is a - JSON object with the keys "prompt" and "completion". Additionally, you must - upload your file with the purpose `fine-tune`. - - See the - [fine-tuning guide](https://platform.openai.com/docs/guides/legacy-fine-tuning/creating-training-data) - for more details. - """ - - batch_size: Optional[int] - """The batch size to use for training. - - The batch size is the number of training examples used to train a single forward - and backward pass. - - By default, the batch size will be dynamically configured to be ~0.2% of the - number of examples in the training set, capped at 256 - in general, we've found - that larger batch sizes tend to work better for larger datasets. - """ - - classification_betas: Optional[List[float]] - """If this is provided, we calculate F-beta scores at the specified beta values. - - The F-beta score is a generalization of F-1 score. This is only used for binary - classification. - - With a beta of 1 (i.e. the F-1 score), precision and recall are given the same - weight. A larger beta score puts more weight on recall and less on precision. A - smaller beta score puts more weight on precision and less on recall. - """ - - classification_n_classes: Optional[int] - """The number of classes in a classification task. - - This parameter is required for multiclass classification. - """ - - classification_positive_class: Optional[str] - """The positive class in binary classification. - - This parameter is needed to generate precision, recall, and F1 metrics when - doing binary classification. - """ - - compute_classification_metrics: Optional[bool] - """ - If set, we calculate classification-specific metrics such as accuracy and F-1 - score using the validation set at the end of every epoch. These metrics can be - viewed in the - [results file](https://platform.openai.com/docs/guides/legacy-fine-tuning/analyzing-your-fine-tuned-model). - - In order to compute classification metrics, you must provide a - `validation_file`. Additionally, you must specify `classification_n_classes` for - multiclass classification or `classification_positive_class` for binary - classification. - """ - - hyperparameters: Hyperparameters - """The hyperparameters used for the fine-tuning job.""" - - learning_rate_multiplier: Optional[float] - """ - The learning rate multiplier to use for training. The fine-tuning learning rate - is the original learning rate used for pretraining multiplied by this value. - - By default, the learning rate multiplier is the 0.05, 0.1, or 0.2 depending on - final `batch_size` (larger learning rates tend to perform better with larger - batch sizes). We recommend experimenting with values in the range 0.02 to 0.2 to - see what produces the best results. - """ - - model: Union[str, Literal["ada", "babbage", "curie", "davinci"], None] - """The name of the base model to fine-tune. - - You can select one of "ada", "babbage", "curie", "davinci", or a fine-tuned - model created after 2022-04-21 and before 2023-08-22. To learn more about these - models, see the [Models](https://platform.openai.com/docs/models) documentation. - """ - - prompt_loss_weight: Optional[float] - """The weight to use for loss on the prompt tokens. - - This controls how much the model tries to learn to generate the prompt (as - compared to the completion which always has a weight of 1.0), and can add a - stabilizing effect to training when completions are short. - - If prompts are extremely long (relative to completions), it may make sense to - reduce this weight so as to avoid over-prioritizing learning the prompt. - """ - - suffix: Optional[str] - """ - A string of up to 40 characters that will be added to your fine-tuned model - name. - - For example, a `suffix` of "custom-model-name" would produce a model name like - `ada:ft-your-org:custom-model-name-2022-02-15-04-21-04`. - """ - - validation_file: Optional[str] - """The ID of an uploaded file that contains validation data. - - If you provide this file, the data is used to generate validation metrics - periodically during fine-tuning. These metrics can be viewed in the - [fine-tuning results file](https://platform.openai.com/docs/guides/legacy-fine-tuning/analyzing-your-fine-tuned-model). - Your train and validation data should be mutually exclusive. - - Your dataset must be formatted as a JSONL file, where each validation example is - a JSON object with the keys "prompt" and "completion". Additionally, you must - upload your file with the purpose `fine-tune`. - - See the - [fine-tuning guide](https://platform.openai.com/docs/guides/legacy-fine-tuning/creating-training-data) - for more details. - """ - - -class Hyperparameters(TypedDict, total=False): - n_epochs: Union[Literal["auto"], int] - """The number of epochs to train the model for. - - An epoch refers to one full cycle through the training dataset. - """ diff --git a/src/openai/types/fine_tune_event.py b/src/openai/types/fine_tune_event.py deleted file mode 100644 index 299f0de24b..0000000000 --- a/src/openai/types/fine_tune_event.py +++ /dev/null @@ -1,17 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. - -from typing_extensions import Literal - -from .._models import BaseModel - -__all__ = ["FineTuneEvent"] - - -class FineTuneEvent(BaseModel): - created_at: int - - level: str - - message: str - - object: Literal["fine-tune-event"] diff --git a/src/openai/types/fine_tune_events_list_response.py b/src/openai/types/fine_tune_events_list_response.py deleted file mode 100644 index c69746104d..0000000000 --- a/src/openai/types/fine_tune_events_list_response.py +++ /dev/null @@ -1,15 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. - -from typing import List -from typing_extensions import Literal - -from .._models import BaseModel -from .fine_tune_event import FineTuneEvent - -__all__ = ["FineTuneEventsListResponse"] - - -class FineTuneEventsListResponse(BaseModel): - data: List[FineTuneEvent] - - object: Literal["list"] diff --git a/src/openai/types/fine_tune_list_events_params.py b/src/openai/types/fine_tune_list_events_params.py deleted file mode 100644 index 1f23b108e6..0000000000 --- a/src/openai/types/fine_tune_list_events_params.py +++ /dev/null @@ -1,41 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. - -from __future__ import annotations - -from typing import Union -from typing_extensions import Literal, Required, TypedDict - -__all__ = ["FineTuneListEventsParamsBase", "FineTuneListEventsParamsNonStreaming", "FineTuneListEventsParamsStreaming"] - - -class FineTuneListEventsParamsBase(TypedDict, total=False): - pass - - -class FineTuneListEventsParamsNonStreaming(FineTuneListEventsParamsBase): - stream: Literal[False] - """Whether to stream events for the fine-tune job. - - If set to true, events will be sent as data-only - [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) - as they become available. The stream will terminate with a `data: [DONE]` - message when the job is finished (succeeded, cancelled, or failed). - - If set to false, only events generated so far will be returned. - """ - - -class FineTuneListEventsParamsStreaming(FineTuneListEventsParamsBase): - stream: Required[Literal[True]] - """Whether to stream events for the fine-tune job. - - If set to true, events will be sent as data-only - [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) - as they become available. The stream will terminate with a `data: [DONE]` - message when the job is finished (succeeded, cancelled, or failed). - - If set to false, only events generated so far will be returned. - """ - - -FineTuneListEventsParams = Union[FineTuneListEventsParamsNonStreaming, FineTuneListEventsParamsStreaming] diff --git a/tests/api_resources/test_edits.py b/tests/api_resources/test_edits.py deleted file mode 100644 index 76069d6b83..0000000000 --- a/tests/api_resources/test_edits.py +++ /dev/null @@ -1,95 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. - -from __future__ import annotations - -import os - -import pytest - -from openai import OpenAI, AsyncOpenAI -from tests.utils import assert_matches_type -from openai.types import Edit -from openai._client import OpenAI, AsyncOpenAI - -# pyright: reportDeprecated=false - -base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") -api_key = "My API Key" - - -class TestEdits: - strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) - - @parametrize - def test_method_create(self, client: OpenAI) -> None: - with pytest.warns(DeprecationWarning): - edit = client.edits.create( - instruction="Fix the spelling mistakes.", - model="text-davinci-edit-001", - ) - assert_matches_type(Edit, edit, path=["response"]) - - @parametrize - def test_method_create_with_all_params(self, client: OpenAI) -> None: - with pytest.warns(DeprecationWarning): - edit = client.edits.create( - instruction="Fix the spelling mistakes.", - model="text-davinci-edit-001", - input="What day of the wek is it?", - n=1, - temperature=1, - top_p=1, - ) - assert_matches_type(Edit, edit, path=["response"]) - - @parametrize - def test_raw_response_create(self, client: OpenAI) -> None: - with pytest.warns(DeprecationWarning): - response = client.edits.with_raw_response.create( - instruction="Fix the spelling mistakes.", - model="text-davinci-edit-001", - ) - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - edit = response.parse() - assert_matches_type(Edit, edit, path=["response"]) - - -class TestAsyncEdits: - strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) - - @parametrize - async def test_method_create(self, client: AsyncOpenAI) -> None: - with pytest.warns(DeprecationWarning): - edit = await client.edits.create( - instruction="Fix the spelling mistakes.", - model="text-davinci-edit-001", - ) - assert_matches_type(Edit, edit, path=["response"]) - - @parametrize - async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: - with pytest.warns(DeprecationWarning): - edit = await client.edits.create( - instruction="Fix the spelling mistakes.", - model="text-davinci-edit-001", - input="What day of the wek is it?", - n=1, - temperature=1, - top_p=1, - ) - assert_matches_type(Edit, edit, path=["response"]) - - @parametrize - async def test_raw_response_create(self, client: AsyncOpenAI) -> None: - with pytest.warns(DeprecationWarning): - response = await client.edits.with_raw_response.create( - instruction="Fix the spelling mistakes.", - model="text-davinci-edit-001", - ) - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - edit = response.parse() - assert_matches_type(Edit, edit, path=["response"]) diff --git a/tests/api_resources/test_fine_tunes.py b/tests/api_resources/test_fine_tunes.py deleted file mode 100644 index edaf784848..0000000000 --- a/tests/api_resources/test_fine_tunes.py +++ /dev/null @@ -1,274 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. - -from __future__ import annotations - -import os - -import pytest - -from openai import OpenAI, AsyncOpenAI -from tests.utils import assert_matches_type -from openai.types import FineTune, FineTuneEventsListResponse -from openai._client import OpenAI, AsyncOpenAI -from openai.pagination import SyncPage, AsyncPage - -base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") -api_key = "My API Key" - - -class TestFineTunes: - strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) - - @parametrize - def test_method_create(self, client: OpenAI) -> None: - fine_tune = client.fine_tunes.create( - training_file="file-abc123", - ) - assert_matches_type(FineTune, fine_tune, path=["response"]) - - @parametrize - def test_method_create_with_all_params(self, client: OpenAI) -> None: - fine_tune = client.fine_tunes.create( - training_file="file-abc123", - batch_size=0, - classification_betas=[0.6, 1, 1.5, 2], - classification_n_classes=0, - classification_positive_class="string", - compute_classification_metrics=True, - hyperparameters={"n_epochs": "auto"}, - learning_rate_multiplier=0, - model="curie", - prompt_loss_weight=0, - suffix="x", - validation_file="file-abc123", - ) - assert_matches_type(FineTune, fine_tune, path=["response"]) - - @parametrize - def test_raw_response_create(self, client: OpenAI) -> None: - response = client.fine_tunes.with_raw_response.create( - training_file="file-abc123", - ) - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - fine_tune = response.parse() - assert_matches_type(FineTune, fine_tune, path=["response"]) - - @parametrize - def test_method_retrieve(self, client: OpenAI) -> None: - fine_tune = client.fine_tunes.retrieve( - "ft-AF1WoRqd3aJAHsqc9NY7iL8F", - ) - assert_matches_type(FineTune, fine_tune, path=["response"]) - - @parametrize - def test_raw_response_retrieve(self, client: OpenAI) -> None: - response = client.fine_tunes.with_raw_response.retrieve( - "ft-AF1WoRqd3aJAHsqc9NY7iL8F", - ) - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - fine_tune = response.parse() - assert_matches_type(FineTune, fine_tune, path=["response"]) - - @parametrize - def test_method_list(self, client: OpenAI) -> None: - fine_tune = client.fine_tunes.list() - assert_matches_type(SyncPage[FineTune], fine_tune, path=["response"]) - - @parametrize - def test_raw_response_list(self, client: OpenAI) -> None: - response = client.fine_tunes.with_raw_response.list() - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - fine_tune = response.parse() - assert_matches_type(SyncPage[FineTune], fine_tune, path=["response"]) - - @parametrize - def test_method_cancel(self, client: OpenAI) -> None: - fine_tune = client.fine_tunes.cancel( - "ft-AF1WoRqd3aJAHsqc9NY7iL8F", - ) - assert_matches_type(FineTune, fine_tune, path=["response"]) - - @parametrize - def test_raw_response_cancel(self, client: OpenAI) -> None: - response = client.fine_tunes.with_raw_response.cancel( - "ft-AF1WoRqd3aJAHsqc9NY7iL8F", - ) - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - fine_tune = response.parse() - assert_matches_type(FineTune, fine_tune, path=["response"]) - - @pytest.mark.skip(reason="Prism chokes on this") - @parametrize - def test_method_list_events_overload_1(self, client: OpenAI) -> None: - fine_tune = client.fine_tunes.list_events( - "ft-AF1WoRqd3aJAHsqc9NY7iL8F", - ) - assert_matches_type(FineTuneEventsListResponse, fine_tune, path=["response"]) - - @pytest.mark.skip(reason="Prism chokes on this") - @parametrize - def test_method_list_events_with_all_params_overload_1(self, client: OpenAI) -> None: - fine_tune = client.fine_tunes.list_events( - "ft-AF1WoRqd3aJAHsqc9NY7iL8F", - stream=False, - ) - assert_matches_type(FineTuneEventsListResponse, fine_tune, path=["response"]) - - @pytest.mark.skip(reason="Prism chokes on this") - @parametrize - def test_raw_response_list_events_overload_1(self, client: OpenAI) -> None: - response = client.fine_tunes.with_raw_response.list_events( - "ft-AF1WoRqd3aJAHsqc9NY7iL8F", - ) - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - fine_tune = response.parse() - assert_matches_type(FineTuneEventsListResponse, fine_tune, path=["response"]) - - @pytest.mark.skip(reason="Prism chokes on this") - @parametrize - def test_method_list_events_overload_2(self, client: OpenAI) -> None: - client.fine_tunes.list_events( - "ft-AF1WoRqd3aJAHsqc9NY7iL8F", - stream=True, - ) - - @pytest.mark.skip(reason="Prism chokes on this") - @parametrize - def test_raw_response_list_events_overload_2(self, client: OpenAI) -> None: - response = client.fine_tunes.with_raw_response.list_events( - "ft-AF1WoRqd3aJAHsqc9NY7iL8F", - stream=True, - ) - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - response.parse() - - -class TestAsyncFineTunes: - strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) - - @parametrize - async def test_method_create(self, client: AsyncOpenAI) -> None: - fine_tune = await client.fine_tunes.create( - training_file="file-abc123", - ) - assert_matches_type(FineTune, fine_tune, path=["response"]) - - @parametrize - async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: - fine_tune = await client.fine_tunes.create( - training_file="file-abc123", - batch_size=0, - classification_betas=[0.6, 1, 1.5, 2], - classification_n_classes=0, - classification_positive_class="string", - compute_classification_metrics=True, - hyperparameters={"n_epochs": "auto"}, - learning_rate_multiplier=0, - model="curie", - prompt_loss_weight=0, - suffix="x", - validation_file="file-abc123", - ) - assert_matches_type(FineTune, fine_tune, path=["response"]) - - @parametrize - async def test_raw_response_create(self, client: AsyncOpenAI) -> None: - response = await client.fine_tunes.with_raw_response.create( - training_file="file-abc123", - ) - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - fine_tune = response.parse() - assert_matches_type(FineTune, fine_tune, path=["response"]) - - @parametrize - async def test_method_retrieve(self, client: AsyncOpenAI) -> None: - fine_tune = await client.fine_tunes.retrieve( - "ft-AF1WoRqd3aJAHsqc9NY7iL8F", - ) - assert_matches_type(FineTune, fine_tune, path=["response"]) - - @parametrize - async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: - response = await client.fine_tunes.with_raw_response.retrieve( - "ft-AF1WoRqd3aJAHsqc9NY7iL8F", - ) - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - fine_tune = response.parse() - assert_matches_type(FineTune, fine_tune, path=["response"]) - - @parametrize - async def test_method_list(self, client: AsyncOpenAI) -> None: - fine_tune = await client.fine_tunes.list() - assert_matches_type(AsyncPage[FineTune], fine_tune, path=["response"]) - - @parametrize - async def test_raw_response_list(self, client: AsyncOpenAI) -> None: - response = await client.fine_tunes.with_raw_response.list() - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - fine_tune = response.parse() - assert_matches_type(AsyncPage[FineTune], fine_tune, path=["response"]) - - @parametrize - async def test_method_cancel(self, client: AsyncOpenAI) -> None: - fine_tune = await client.fine_tunes.cancel( - "ft-AF1WoRqd3aJAHsqc9NY7iL8F", - ) - assert_matches_type(FineTune, fine_tune, path=["response"]) - - @parametrize - async def test_raw_response_cancel(self, client: AsyncOpenAI) -> None: - response = await client.fine_tunes.with_raw_response.cancel( - "ft-AF1WoRqd3aJAHsqc9NY7iL8F", - ) - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - fine_tune = response.parse() - assert_matches_type(FineTune, fine_tune, path=["response"]) - - @pytest.mark.skip(reason="Prism chokes on this") - @parametrize - async def test_method_list_events_overload_1(self, client: AsyncOpenAI) -> None: - fine_tune = await client.fine_tunes.list_events( - "ft-AF1WoRqd3aJAHsqc9NY7iL8F", - ) - assert_matches_type(FineTuneEventsListResponse, fine_tune, path=["response"]) - - @pytest.mark.skip(reason="Prism chokes on this") - @parametrize - async def test_method_list_events_with_all_params_overload_1(self, client: AsyncOpenAI) -> None: - fine_tune = await client.fine_tunes.list_events( - "ft-AF1WoRqd3aJAHsqc9NY7iL8F", - stream=False, - ) - assert_matches_type(FineTuneEventsListResponse, fine_tune, path=["response"]) - - @pytest.mark.skip(reason="Prism chokes on this") - @parametrize - async def test_raw_response_list_events_overload_1(self, client: AsyncOpenAI) -> None: - response = await client.fine_tunes.with_raw_response.list_events( - "ft-AF1WoRqd3aJAHsqc9NY7iL8F", - ) - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - fine_tune = response.parse() - assert_matches_type(FineTuneEventsListResponse, fine_tune, path=["response"]) - - @pytest.mark.skip(reason="Prism chokes on this") - @parametrize - async def test_method_list_events_overload_2(self, client: AsyncOpenAI) -> None: - await client.fine_tunes.list_events( - "ft-AF1WoRqd3aJAHsqc9NY7iL8F", - stream=True, - ) - - @pytest.mark.skip(reason="Prism chokes on this") - @parametrize - async def test_raw_response_list_events_overload_2(self, client: AsyncOpenAI) -> None: - response = await client.fine_tunes.with_raw_response.list_events( - "ft-AF1WoRqd3aJAHsqc9NY7iL8F", - stream=True, - ) - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - response.parse() From ac33853ba10d13ac149b1fa3ca6dba7d613065c9 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 12 Jan 2024 10:03:04 -0500 Subject: [PATCH 192/816] release: 1.7.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 5660725203..b08a26cbda 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.7.1" + ".": "1.7.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 19fb9c3e58..ab502f8137 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.7.2 (2024-01-12) + +Full Changelog: [v1.7.1...v1.7.2](https://github.com/openai/openai-python/compare/v1.7.1...v1.7.2) + +### Documentation + +* **readme:** improve api reference ([#1065](https://github.com/openai/openai-python/issues/1065)) ([745b9e0](https://github.com/openai/openai-python/commit/745b9e08ae0abb8bf4cd87ed40fa450d9ad81ede)) + + +### Refactors + +* **api:** remove deprecated endpoints ([#1067](https://github.com/openai/openai-python/issues/1067)) ([199ddcd](https://github.com/openai/openai-python/commit/199ddcdca00c136e4e0c3ff16521eff22acf2a1a)) + ## 1.7.1 (2024-01-10) Full Changelog: [v1.7.0...v1.7.1](https://github.com/openai/openai-python/compare/v1.7.0...v1.7.1) diff --git a/pyproject.toml b/pyproject.toml index 9ff951873a..354d763812 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.7.1" +version = "1.7.2" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index b25177f3a5..0b4aa63ffe 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.7.1" # x-release-please-version +__version__ = "1.7.2" # x-release-please-version From 86379b4471d67a9d2e85f0b0c098787fb99aa4e0 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 15 Jan 2024 09:11:27 -0500 Subject: [PATCH 193/816] feat(client): add support for streaming raw responses (#1072) As an alternative to `with_raw_response` we now provide `with_streaming_response` as well. When using these methods you will have to use a context manager to ensure that the response is always cleaned up. --- README.md | 37 +- examples/audio.py | 16 +- src/openai/__init__.py | 1 + src/openai/_base_client.py | 279 +++++---- src/openai/_client.py | 32 + src/openai/_constants.py | 2 +- src/openai/_legacy_response.py | 385 ++++++++++++ src/openai/_response.py | 570 ++++++++++++++++-- src/openai/_types.py | 166 +---- src/openai/resources/__init__.py | 110 +++- src/openai/resources/audio/__init__.py | 37 +- src/openai/resources/audio/audio.py | 42 +- src/openai/resources/audio/speech.py | 45 +- src/openai/resources/audio/transcriptions.py | 29 +- src/openai/resources/audio/translations.py | 29 +- src/openai/resources/beta/__init__.py | 33 +- .../resources/beta/assistants/__init__.py | 22 +- .../resources/beta/assistants/assistants.py | 82 ++- src/openai/resources/beta/assistants/files.py | 59 +- src/openai/resources/beta/beta.py | 38 +- src/openai/resources/beta/threads/__init__.py | 33 +- .../beta/threads/messages/__init__.py | 22 +- .../resources/beta/threads/messages/files.py | 39 +- .../beta/threads/messages/messages.py | 72 ++- .../resources/beta/threads/runs/__init__.py | 22 +- .../resources/beta/threads/runs/runs.py | 92 ++- .../resources/beta/threads/runs/steps.py | 39 +- src/openai/resources/beta/threads/threads.py | 93 ++- src/openai/resources/chat/__init__.py | 22 +- src/openai/resources/chat/chat.py | 27 +- src/openai/resources/chat/completions.py | 29 +- src/openai/resources/completions.py | 29 +- src/openai/resources/embeddings.py | 29 +- src/openai/resources/files.py | 109 +++- src/openai/resources/fine_tuning/__init__.py | 22 +- .../resources/fine_tuning/fine_tuning.py | 27 +- src/openai/resources/fine_tuning/jobs.py | 69 ++- src/openai/resources/images.py | 49 +- src/openai/resources/models.py | 49 +- src/openai/resources/moderations.py | 29 +- tests/api_resources/audio/test_speech.py | 66 +- .../audio/test_transcriptions.py | 33 + .../api_resources/audio/test_translations.py | 33 + .../beta/assistants/test_files.py | 127 ++++ tests/api_resources/beta/test_assistants.py | 147 +++++ tests/api_resources/beta/test_threads.py | 147 +++++ .../beta/threads/messages/test_files.py | 67 ++ .../beta/threads/runs/test_steps.py | 67 ++ .../beta/threads/test_messages.py | 129 ++++ tests/api_resources/beta/threads/test_runs.py | 193 ++++++ tests/api_resources/chat/test_completions.py | 103 +++- tests/api_resources/fine_tuning/test_jobs.py | 149 +++++ tests/api_resources/test_completions.py | 83 ++- tests/api_resources/test_embeddings.py | 33 + tests/api_resources/test_files.py | 201 +++++- tests/api_resources/test_images.py | 93 +++ tests/api_resources/test_models.py | 87 +++ tests/api_resources/test_moderations.py | 31 + tests/test_client.py | 76 ++- tests/test_response.py | 50 ++ tests/utils.py | 5 + 61 files changed, 4273 insertions(+), 563 deletions(-) create mode 100644 src/openai/_legacy_response.py create mode 100644 tests/test_response.py diff --git a/README.md b/README.md index e86ac6553e..22e7ac795f 100644 --- a/README.md +++ b/README.md @@ -414,7 +414,7 @@ if response.my_field is None: ### Accessing raw response data (e.g. headers) -The "raw" Response object can be accessed by prefixing `.with_raw_response.` to any HTTP method call. +The "raw" Response object can be accessed by prefixing `.with_raw_response.` to any HTTP method call, e.g., ```py from openai import OpenAI @@ -433,7 +433,40 @@ completion = response.parse() # get the object that `chat.completions.create()` print(completion) ``` -These methods return an [`APIResponse`](https://github.com/openai/openai-python/tree/main/src/openai/_response.py) object. +These methods return an [`LegacyAPIResponse`](https://github.com/openai/openai-python/tree/main/src/openai/_legacy_response.py) object. This is a legacy class as we're changing it slightly in the next major version. + +For the sync client this will mostly be the same with the exception +of `content` & `text` will be methods instead of properties. In the +async client, all methods will be async. + +A migration script will be provided & the migration in general should +be smooth. + +#### `.with_streaming_response` + +The above interface eagerly reads the full response body when you make the request, which may not always be what you want. + +To stream the response body, use `.with_streaming_response` instead, which requires a context manager and only reads the response body once you call `.read()`, `.text()`, `.json()`, `.iter_bytes()`, `.iter_text()`, `.iter_lines()` or `.parse()`. In the async client, these are async methods. + +As such, `.with_streaming_response` methods return a different [`APIResponse`](https://github.com/openai/openai-python/tree/main/src/openai/_response.py) object, and the async client returns an [`AsyncAPIResponse`](https://github.com/openai/openai-python/tree/main/src/openai/_response.py) object. + +```python +with client.chat.completions.with_streaming_response.create( + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-3.5-turbo", +) as response: + print(response.headers.get("X-My-Header")) + + for line in response.iter_lines(): + print(line) +``` + +The context manager is required so that the response will reliably be closed. ### Configuring the HTTP client diff --git a/examples/audio.py b/examples/audio.py index a5f535dcd6..73491090f5 100755 --- a/examples/audio.py +++ b/examples/audio.py @@ -12,14 +12,18 @@ def main() -> None: # Create text-to-speech audio file - response = openai.audio.speech.create( - model="tts-1", voice="alloy", input="the quick brown fox jumped over the lazy dogs" - ) - - response.stream_to_file(speech_file_path) + with openai.audio.speech.with_streaming_response.create( + model="tts-1", + voice="alloy", + input="the quick brown fox jumped over the lazy dogs", + ) as response: + response.stream_to_file(speech_file_path) # Create transcription from audio file - transcription = openai.audio.transcriptions.create(model="whisper-1", file=speech_file_path) + transcription = openai.audio.transcriptions.create( + model="whisper-1", + file=speech_file_path, + ) print(transcription.text) # Create translation from audio file diff --git a/src/openai/__init__.py b/src/openai/__init__.py index 64c93e9449..0de58b3327 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -10,6 +10,7 @@ from ._utils import file_from_path from ._client import Client, OpenAI, Stream, Timeout, Transport, AsyncClient, AsyncOpenAI, AsyncStream, RequestOptions from ._version import __title__, __version__ +from ._response import APIResponse as APIResponse, AsyncAPIResponse as AsyncAPIResponse from ._exceptions import ( APIError, OpenAIError, diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index c2c2db5f49..1dfbd7dfb3 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -1,6 +1,5 @@ from __future__ import annotations -import os import json import time import uuid @@ -31,7 +30,7 @@ overload, ) from functools import lru_cache -from typing_extensions import Literal, override +from typing_extensions import Literal, override, get_origin import anyio import httpx @@ -61,18 +60,22 @@ AsyncTransport, RequestOptions, ModelBuilderProtocol, - BinaryResponseContent, ) from ._utils import is_dict, is_given, is_mapping from ._compat import model_copy, model_dump from ._models import GenericModel, FinalRequestOptions, validate_type, construct_type -from ._response import APIResponse +from ._response import ( + APIResponse, + BaseAPIResponse, + AsyncAPIResponse, + extract_response_type, +) from ._constants import ( DEFAULT_LIMITS, DEFAULT_TIMEOUT, DEFAULT_MAX_RETRIES, RAW_RESPONSE_HEADER, - STREAMED_RAW_RESPONSE_HEADER, + OVERRIDE_CAST_TO_HEADER, ) from ._streaming import Stream, AsyncStream from ._exceptions import ( @@ -81,6 +84,7 @@ APIConnectionError, APIResponseValidationError, ) +from ._legacy_response import LegacyAPIResponse log: logging.Logger = logging.getLogger(__name__) @@ -493,28 +497,25 @@ def _serialize_multipartform(self, data: Mapping[object, object]) -> dict[str, o serialized[key] = value return serialized - def _process_response( - self, - *, - cast_to: Type[ResponseT], - options: FinalRequestOptions, - response: httpx.Response, - stream: bool, - stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None, - ) -> ResponseT: - api_response = APIResponse( - raw=response, - client=self, - cast_to=cast_to, - stream=stream, - stream_cls=stream_cls, - options=options, - ) + def _maybe_override_cast_to(self, cast_to: type[ResponseT], options: FinalRequestOptions) -> type[ResponseT]: + if not is_given(options.headers): + return cast_to - if response.request.headers.get(RAW_RESPONSE_HEADER) == "true": - return cast(ResponseT, api_response) + # make a copy of the headers so we don't mutate user-input + headers = dict(options.headers) - return api_response.parse() + # we internally support defining a temporary header to override the + # default `cast_to` type for use with `.with_raw_response` and `.with_streaming_response` + # see _response.py for implementation details + override_cast_to = headers.pop(OVERRIDE_CAST_TO_HEADER, NOT_GIVEN) + if is_given(override_cast_to): + options.headers = headers + return cast(Type[ResponseT], override_cast_to) + + return cast_to + + def _should_stream_response_body(self, request: httpx.Request) -> bool: + return request.headers.get(RAW_RESPONSE_HEADER) == "stream" # type: ignore[no-any-return] def _process_response_data( self, @@ -540,12 +541,6 @@ def _process_response_data( except pydantic.ValidationError as err: raise APIResponseValidationError(response=response, body=data) from err - def _should_stream_response_body(self, *, request: httpx.Request) -> bool: - if request.headers.get(STREAMED_RAW_RESPONSE_HEADER) == "true": - return True - - return False - @property def qs(self) -> Querystring: return Querystring() @@ -610,6 +605,8 @@ def _calculate_retry_timeout( if response_headers is not None: retry_header = response_headers.get("retry-after") try: + # note: the spec indicates that this should only ever be an integer + # but if someone sends a float there's no reason for us to not respect it retry_after = float(retry_header) except Exception: retry_date_tuple = email.utils.parsedate_tz(retry_header) @@ -873,6 +870,7 @@ def _request( stream: bool, stream_cls: type[_StreamT] | None, ) -> ResponseT | _StreamT: + cast_to = self._maybe_override_cast_to(cast_to, options) self._prepare_options(options) retries = self._remaining_retries(remaining_retries, options) @@ -987,6 +985,63 @@ def _retry_request( stream_cls=stream_cls, ) + def _process_response( + self, + *, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + response: httpx.Response, + stream: bool, + stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None, + ) -> ResponseT: + if response.request.headers.get(RAW_RESPONSE_HEADER) == "true": + return cast( + ResponseT, + LegacyAPIResponse( + raw=response, + client=self, + cast_to=cast_to, + stream=stream, + stream_cls=stream_cls, + options=options, + ), + ) + + origin = get_origin(cast_to) or cast_to + + if inspect.isclass(origin) and issubclass(origin, BaseAPIResponse): + if not issubclass(origin, APIResponse): + raise TypeError(f"API Response types must subclass {APIResponse}; Received {origin}") + + response_cls = cast("type[BaseAPIResponse[Any]]", cast_to) + return cast( + ResponseT, + response_cls( + raw=response, + client=self, + cast_to=extract_response_type(response_cls), + stream=stream, + stream_cls=stream_cls, + options=options, + ), + ) + + if cast_to == httpx.Response: + return cast(ResponseT, response) + + api_response = APIResponse( + raw=response, + client=self, + cast_to=cast("type[ResponseT]", cast_to), # pyright: ignore[reportUnnecessaryCast] + stream=stream, + stream_cls=stream_cls, + options=options, + ) + if bool(response.request.headers.get(RAW_RESPONSE_HEADER)): + return cast(ResponseT, api_response) + + return api_response.parse() + def _request_api_list( self, model: Type[object], @@ -1353,6 +1408,7 @@ async def _request( stream_cls: type[_AsyncStreamT] | None, remaining_retries: int | None, ) -> ResponseT | _AsyncStreamT: + cast_to = self._maybe_override_cast_to(cast_to, options) await self._prepare_options(options) retries = self._remaining_retries(remaining_retries, options) @@ -1428,7 +1484,7 @@ async def _request( log.debug("Re-raising status error") raise self._make_status_error_from_response(err.response) from None - return self._process_response( + return await self._process_response( cast_to=cast_to, options=options, response=response, @@ -1465,6 +1521,63 @@ async def _retry_request( stream_cls=stream_cls, ) + async def _process_response( + self, + *, + cast_to: Type[ResponseT], + options: FinalRequestOptions, + response: httpx.Response, + stream: bool, + stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None, + ) -> ResponseT: + if response.request.headers.get(RAW_RESPONSE_HEADER) == "true": + return cast( + ResponseT, + LegacyAPIResponse( + raw=response, + client=self, + cast_to=cast_to, + stream=stream, + stream_cls=stream_cls, + options=options, + ), + ) + + origin = get_origin(cast_to) or cast_to + + if inspect.isclass(origin) and issubclass(origin, BaseAPIResponse): + if not issubclass(origin, AsyncAPIResponse): + raise TypeError(f"API Response types must subclass {AsyncAPIResponse}; Received {origin}") + + response_cls = cast("type[BaseAPIResponse[Any]]", cast_to) + return cast( + "ResponseT", + response_cls( + raw=response, + client=self, + cast_to=extract_response_type(response_cls), + stream=stream, + stream_cls=stream_cls, + options=options, + ), + ) + + if cast_to == httpx.Response: + return cast(ResponseT, response) + + api_response = AsyncAPIResponse( + raw=response, + client=self, + cast_to=cast("type[ResponseT]", cast_to), # pyright: ignore[reportUnnecessaryCast] + stream=stream, + stream_cls=stream_cls, + options=options, + ) + if bool(response.request.headers.get(RAW_RESPONSE_HEADER)): + return cast(ResponseT, api_response) + + return await api_response.parse() + def _request_api_list( self, model: Type[_T], @@ -1783,105 +1896,3 @@ def _merge_mappings( """ merged = {**obj1, **obj2} return {key: value for key, value in merged.items() if not isinstance(value, Omit)} - - -class HttpxBinaryResponseContent(BinaryResponseContent): - response: httpx.Response - - def __init__(self, response: httpx.Response) -> None: - self.response = response - - @property - @override - def content(self) -> bytes: - return self.response.content - - @property - @override - def text(self) -> str: - return self.response.text - - @property - @override - def encoding(self) -> Optional[str]: - return self.response.encoding - - @property - @override - def charset_encoding(self) -> Optional[str]: - return self.response.charset_encoding - - @override - def json(self, **kwargs: Any) -> Any: - return self.response.json(**kwargs) - - @override - def read(self) -> bytes: - return self.response.read() - - @override - def iter_bytes(self, chunk_size: Optional[int] = None) -> Iterator[bytes]: - return self.response.iter_bytes(chunk_size) - - @override - def iter_text(self, chunk_size: Optional[int] = None) -> Iterator[str]: - return self.response.iter_text(chunk_size) - - @override - def iter_lines(self) -> Iterator[str]: - return self.response.iter_lines() - - @override - def iter_raw(self, chunk_size: Optional[int] = None) -> Iterator[bytes]: - return self.response.iter_raw(chunk_size) - - @override - def stream_to_file( - self, - file: str | os.PathLike[str], - *, - chunk_size: int | None = None, - ) -> None: - with open(file, mode="wb") as f: - for data in self.response.iter_bytes(chunk_size): - f.write(data) - - @override - def close(self) -> None: - return self.response.close() - - @override - async def aread(self) -> bytes: - return await self.response.aread() - - @override - async def aiter_bytes(self, chunk_size: Optional[int] = None) -> AsyncIterator[bytes]: - return self.response.aiter_bytes(chunk_size) - - @override - async def aiter_text(self, chunk_size: Optional[int] = None) -> AsyncIterator[str]: - return self.response.aiter_text(chunk_size) - - @override - async def aiter_lines(self) -> AsyncIterator[str]: - return self.response.aiter_lines() - - @override - async def aiter_raw(self, chunk_size: Optional[int] = None) -> AsyncIterator[bytes]: - return self.response.aiter_raw(chunk_size) - - @override - async def astream_to_file( - self, - file: str | os.PathLike[str], - *, - chunk_size: int | None = None, - ) -> None: - path = anyio.Path(file) - async with await path.open(mode="wb") as f: - async for data in self.response.aiter_bytes(chunk_size): - await f.write(data) - - @override - async def aclose(self) -> None: - return await self.response.aclose() diff --git a/src/openai/_client.py b/src/openai/_client.py index 09f54e1b12..5043d60e2a 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -58,6 +58,7 @@ class OpenAI(SyncAPIClient): fine_tuning: resources.FineTuning beta: resources.Beta with_raw_response: OpenAIWithRawResponse + with_streaming_response: OpenAIWithStreamedResponse # client options api_key: str @@ -132,6 +133,7 @@ def __init__( self.fine_tuning = resources.FineTuning(self) self.beta = resources.Beta(self) self.with_raw_response = OpenAIWithRawResponse(self) + self.with_streaming_response = OpenAIWithStreamedResponse(self) @property @override @@ -254,6 +256,7 @@ class AsyncOpenAI(AsyncAPIClient): fine_tuning: resources.AsyncFineTuning beta: resources.AsyncBeta with_raw_response: AsyncOpenAIWithRawResponse + with_streaming_response: AsyncOpenAIWithStreamedResponse # client options api_key: str @@ -328,6 +331,7 @@ def __init__( self.fine_tuning = resources.AsyncFineTuning(self) self.beta = resources.AsyncBeta(self) self.with_raw_response = AsyncOpenAIWithRawResponse(self) + self.with_streaming_response = AsyncOpenAIWithStreamedResponse(self) @property @override @@ -466,6 +470,34 @@ def __init__(self, client: AsyncOpenAI) -> None: self.beta = resources.AsyncBetaWithRawResponse(client.beta) +class OpenAIWithStreamedResponse: + def __init__(self, client: OpenAI) -> None: + self.completions = resources.CompletionsWithStreamingResponse(client.completions) + self.chat = resources.ChatWithStreamingResponse(client.chat) + self.embeddings = resources.EmbeddingsWithStreamingResponse(client.embeddings) + self.files = resources.FilesWithStreamingResponse(client.files) + self.images = resources.ImagesWithStreamingResponse(client.images) + self.audio = resources.AudioWithStreamingResponse(client.audio) + self.moderations = resources.ModerationsWithStreamingResponse(client.moderations) + self.models = resources.ModelsWithStreamingResponse(client.models) + self.fine_tuning = resources.FineTuningWithStreamingResponse(client.fine_tuning) + self.beta = resources.BetaWithStreamingResponse(client.beta) + + +class AsyncOpenAIWithStreamedResponse: + def __init__(self, client: AsyncOpenAI) -> None: + self.completions = resources.AsyncCompletionsWithStreamingResponse(client.completions) + self.chat = resources.AsyncChatWithStreamingResponse(client.chat) + self.embeddings = resources.AsyncEmbeddingsWithStreamingResponse(client.embeddings) + self.files = resources.AsyncFilesWithStreamingResponse(client.files) + self.images = resources.AsyncImagesWithStreamingResponse(client.images) + self.audio = resources.AsyncAudioWithStreamingResponse(client.audio) + self.moderations = resources.AsyncModerationsWithStreamingResponse(client.moderations) + self.models = resources.AsyncModelsWithStreamingResponse(client.models) + self.fine_tuning = resources.AsyncFineTuningWithStreamingResponse(client.fine_tuning) + self.beta = resources.AsyncBetaWithStreamingResponse(client.beta) + + Client = OpenAI AsyncClient = AsyncOpenAI diff --git a/src/openai/_constants.py b/src/openai/_constants.py index 7c13feaa25..af9a04b80c 100644 --- a/src/openai/_constants.py +++ b/src/openai/_constants.py @@ -3,7 +3,7 @@ import httpx RAW_RESPONSE_HEADER = "X-Stainless-Raw-Response" -STREAMED_RAW_RESPONSE_HEADER = "X-Stainless-Streamed-Raw-Response" +OVERRIDE_CAST_TO_HEADER = "____stainless_override_cast_to" # default timeout is 10 minutes DEFAULT_TIMEOUT = httpx.Timeout(timeout=600.0, connect=5.0) diff --git a/src/openai/_legacy_response.py b/src/openai/_legacy_response.py new file mode 100644 index 0000000000..5a398efebf --- /dev/null +++ b/src/openai/_legacy_response.py @@ -0,0 +1,385 @@ +from __future__ import annotations + +import os +import inspect +import logging +import datetime +import functools +from typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, Iterator, AsyncIterator, cast +from typing_extensions import Awaitable, ParamSpec, get_args, override, deprecated, get_origin + +import anyio +import httpx + +from ._types import NoneType +from ._utils import is_given +from ._models import BaseModel, is_basemodel +from ._constants import RAW_RESPONSE_HEADER +from ._exceptions import APIResponseValidationError + +if TYPE_CHECKING: + from ._models import FinalRequestOptions + from ._base_client import Stream, BaseClient, AsyncStream + + +P = ParamSpec("P") +R = TypeVar("R") + +log: logging.Logger = logging.getLogger(__name__) + + +class LegacyAPIResponse(Generic[R]): + """This is a legacy class as it will be replaced by `APIResponse` + and `AsyncAPIResponse` in the `_response.py` file in the next major + release. + + For the sync client this will mostly be the same with the exception + of `content` & `text` will be methods instead of properties. In the + async client, all methods will be async. + + A migration script will be provided & the migration in general should + be smooth. + """ + + _cast_to: type[R] + _client: BaseClient[Any, Any] + _parsed: R | None + _stream: bool + _stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None + _options: FinalRequestOptions + + http_response: httpx.Response + + def __init__( + self, + *, + raw: httpx.Response, + cast_to: type[R], + client: BaseClient[Any, Any], + stream: bool, + stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None, + options: FinalRequestOptions, + ) -> None: + self._cast_to = cast_to + self._client = client + self._parsed = None + self._stream = stream + self._stream_cls = stream_cls + self._options = options + self.http_response = raw + + def parse(self) -> R: + """Returns the rich python representation of this response's data. + + For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`. + + NOTE: For the async client: this will become a coroutine in the next major version. + """ + if self._parsed is not None: + return self._parsed + + parsed = self._parse() + if is_given(self._options.post_parser): + parsed = self._options.post_parser(parsed) + + self._parsed = parsed + return parsed + + @property + def headers(self) -> httpx.Headers: + return self.http_response.headers + + @property + def http_request(self) -> httpx.Request: + return self.http_response.request + + @property + def status_code(self) -> int: + return self.http_response.status_code + + @property + def url(http://github.com/self) -> httpx.URL: + return self.http_response.url + + @property + def method(self) -> str: + return self.http_request.method + + @property + def content(self) -> bytes: + """Return the binary response content. + + NOTE: this will be removed in favour of `.read()` in the + next major version. + """ + return self.http_response.content + + @property + def text(self) -> str: + """Return the decoded response content. + + NOTE: this will be turned into a method in the next major version. + """ + return self.http_response.text + + @property + def http_version(self) -> str: + return self.http_response.http_version + + @property + def is_closed(self) -> bool: + return self.http_response.is_closed + + @property + def elapsed(self) -> datetime.timedelta: + """The time taken for the complete request/response cycle to complete.""" + return self.http_response.elapsed + + def _parse(self) -> R: + if self._stream: + if self._stream_cls: + return cast( + R, + self._stream_cls( + cast_to=_extract_stream_chunk_type(self._stream_cls), + response=self.http_response, + client=cast(Any, self._client), + ), + ) + + stream_cls = cast("type[Stream[Any]] | type[AsyncStream[Any]] | None", self._client._default_stream_cls) + if stream_cls is None: + raise MissingStreamClassError() + + return cast( + R, + stream_cls( + cast_to=self._cast_to, + response=self.http_response, + client=cast(Any, self._client), + ), + ) + + cast_to = self._cast_to + if cast_to is NoneType: + return cast(R, None) + + response = self.http_response + if cast_to == str: + return cast(R, response.text) + + origin = get_origin(cast_to) or cast_to + + if inspect.isclass(origin) and issubclass(origin, HttpxBinaryResponseContent): + return cast(R, cast_to(response)) # type: ignore + + if origin == LegacyAPIResponse: + raise RuntimeError("Unexpected state - cast_to is `APIResponse`") + + if inspect.isclass(origin) and issubclass(origin, httpx.Response): + # Because of the invariance of our ResponseT TypeVar, users can subclass httpx.Response + # and pass that class to our request functions. We cannot change the variance to be either + # covariant or contravariant as that makes our usage of ResponseT illegal. We could construct + # the response class ourselves but that is something that should be supported directly in httpx + # as it would be easy to incorrectly construct the Response object due to the multitude of arguments. + if cast_to != httpx.Response: + raise ValueError(f"Subclasses of httpx.Response cannot be passed to `cast_to`") + return cast(R, response) + + # The check here is necessary as we are subverting the the type system + # with casts as the relationship between TypeVars and Types are very strict + # which means we must return *exactly* what was input or transform it in a + # way that retains the TypeVar state. As we cannot do that in this function + # then we have to resort to using `cast`. At the time of writing, we know this + # to be safe as we have handled all the types that could be bound to the + # `ResponseT` TypeVar, however if that TypeVar is ever updated in the future, then + # this function would become unsafe but a type checker would not report an error. + if ( + cast_to is not object + and not origin is list + and not origin is dict + and not origin is Union + and not issubclass(origin, BaseModel) + ): + raise RuntimeError( + f"Invalid state, expected {cast_to} to be a subclass type of {BaseModel}, {dict}, {list} or {Union}." + ) + + # split is required to handle cases where additional information is included + # in the response, e.g. application/json; charset=utf-8 + content_type, *_ = response.headers.get("content-type").split(";") + if content_type != "application/json": + if is_basemodel(cast_to): + try: + data = response.json() + except Exception as exc: + log.debug("Could not read JSON from response data due to %s - %s", type(exc), exc) + else: + return self._client._process_response_data( + data=data, + cast_to=cast_to, # type: ignore + response=response, + ) + + if self._client._strict_response_validation: + raise APIResponseValidationError( + response=response, + message=f"Expected Content-Type response header to be `application/json` but received `{content_type}` instead.", + body=response.text, + ) + + # If the API responds with content that isn't JSON then we just return + # the (decoded) text without performing any parsing so that you can still + # handle the response however you need to. + return response.text # type: ignore + + data = response.json() + + return self._client._process_response_data( + data=data, + cast_to=cast_to, # type: ignore + response=response, + ) + + @override + def __repr__(self) -> str: + return f"" + + +class MissingStreamClassError(TypeError): + def __init__(self) -> None: + super().__init__( + "The `stream` argument was set to `True` but the `stream_cls` argument was not given. See `openai._streaming` for reference", + ) + + +def _extract_stream_chunk_type(stream_cls: type) -> type: + args = get_args(stream_cls) + if not args: + raise TypeError( + f"Expected stream_cls to have been given a generic type argument, e.g. Stream[Foo] but received {stream_cls}", + ) + return cast(type, args[0]) + + +def to_raw_response_wrapper(func: Callable[P, R]) -> Callable[P, LegacyAPIResponse[R]]: + """Higher order function that takes one of our bound API methods and wraps it + to support returning the raw `APIResponse` object directly. + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> LegacyAPIResponse[R]: + extra_headers = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "true" + + kwargs["extra_headers"] = extra_headers + + return cast(LegacyAPIResponse[R], func(*args, **kwargs)) + + return wrapped + + +def async_to_raw_response_wrapper(func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[LegacyAPIResponse[R]]]: + """Higher order function that takes one of our bound API methods and wraps it + to support returning the raw `APIResponse` object directly. + """ + + @functools.wraps(func) + async def wrapped(*args: P.args, **kwargs: P.kwargs) -> LegacyAPIResponse[R]: + extra_headers = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "true" + + kwargs["extra_headers"] = extra_headers + + return cast(LegacyAPIResponse[R], await func(*args, **kwargs)) + + return wrapped + + +class HttpxBinaryResponseContent: + response: httpx.Response + + def __init__(self, response: httpx.Response) -> None: + self.response = response + + @property + def content(self) -> bytes: + return self.response.content + + @property + def text(self) -> str: + return self.response.text + + @property + def encoding(self) -> str | None: + return self.response.encoding + + @property + def charset_encoding(self) -> str | None: + return self.response.charset_encoding + + def json(self, **kwargs: Any) -> Any: + return self.response.json(**kwargs) + + def read(self) -> bytes: + return self.response.read() + + def iter_bytes(self, chunk_size: int | None = None) -> Iterator[bytes]: + return self.response.iter_bytes(chunk_size) + + def iter_text(self, chunk_size: int | None = None) -> Iterator[str]: + return self.response.iter_text(chunk_size) + + def iter_lines(self) -> Iterator[str]: + return self.response.iter_lines() + + def iter_raw(self, chunk_size: int | None = None) -> Iterator[bytes]: + return self.response.iter_raw(chunk_size) + + @deprecated( + "Due to a bug, this method doesn't actually stream the response content, `.with_streaming_response.method()` should be used instead" + ) + def stream_to_file( + self, + file: str | os.PathLike[str], + *, + chunk_size: int | None = None, + ) -> None: + with open(file, mode="wb") as f: + for data in self.response.iter_bytes(chunk_size): + f.write(data) + + def close(self) -> None: + return self.response.close() + + async def aread(self) -> bytes: + return await self.response.aread() + + async def aiter_bytes(self, chunk_size: int | None = None) -> AsyncIterator[bytes]: + return self.response.aiter_bytes(chunk_size) + + async def aiter_text(self, chunk_size: int | None = None) -> AsyncIterator[str]: + return self.response.aiter_text(chunk_size) + + async def aiter_lines(self) -> AsyncIterator[str]: + return self.response.aiter_lines() + + async def aiter_raw(self, chunk_size: int | None = None) -> AsyncIterator[bytes]: + return self.response.aiter_raw(chunk_size) + + @deprecated( + "Due to a bug, this method doesn't actually stream the response content, `.with_streaming_response.method()` should be used instead" + ) + async def astream_to_file( + self, + file: str | os.PathLike[str], + *, + chunk_size: int | None = None, + ) -> None: + path = anyio.Path(file) + async with await path.open(mode="wb") as f: + async for data in self.response.aiter_bytes(chunk_size): + await f.write(data) + + async def aclose(self) -> None: + return await self.response.aclose() diff --git a/src/openai/_response.py b/src/openai/_response.py index bf72d18fd5..15a323afa4 100644 --- a/src/openai/_response.py +++ b/src/openai/_response.py @@ -1,19 +1,32 @@ from __future__ import annotations +import os import inspect import logging import datetime import functools -from typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, cast +from types import TracebackType +from typing import ( + TYPE_CHECKING, + Any, + Union, + Generic, + TypeVar, + Callable, + Iterator, + AsyncIterator, + cast, +) from typing_extensions import Awaitable, ParamSpec, override, get_origin +import anyio import httpx -from ._types import NoneType, BinaryResponseContent +from ._types import NoneType from ._utils import is_given, extract_type_var_from_base from ._models import BaseModel, is_basemodel -from ._constants import RAW_RESPONSE_HEADER -from ._exceptions import APIResponseValidationError +from ._constants import RAW_RESPONSE_HEADER, OVERRIDE_CAST_TO_HEADER +from ._exceptions import OpenAIError, APIResponseValidationError if TYPE_CHECKING: from ._models import FinalRequestOptions @@ -22,15 +35,17 @@ P = ParamSpec("P") R = TypeVar("R") +_APIResponseT = TypeVar("_APIResponseT", bound="APIResponse[Any]") +_AsyncAPIResponseT = TypeVar("_AsyncAPIResponseT", bound="AsyncAPIResponse[Any]") log: logging.Logger = logging.getLogger(__name__) -class APIResponse(Generic[R]): +class BaseAPIResponse(Generic[R]): _cast_to: type[R] _client: BaseClient[Any, Any] _parsed: R | None - _stream: bool + _is_sse_stream: bool _stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None _options: FinalRequestOptions @@ -49,28 +64,18 @@ def __init__( self._cast_to = cast_to self._client = client self._parsed = None - self._stream = stream + self._is_sse_stream = stream self._stream_cls = stream_cls self._options = options self.http_response = raw - def parse(self) -> R: - if self._parsed is not None: - return self._parsed - - parsed = self._parse() - if is_given(self._options.post_parser): - parsed = self._options.post_parser(parsed) - - self._parsed = parsed - return parsed - @property def headers(self) -> httpx.Headers: return self.http_response.headers @property def http_request(self) -> httpx.Request: + """Returns the httpx Request instance associated with the current response.""" return self.http_response.request @property @@ -79,20 +84,13 @@ def status_code(self) -> int: @property def url(http://github.com/self) -> httpx.URL: + """Returns the URL for which the request was made.""" return self.http_response.url @property def method(self) -> str: return self.http_request.method - @property - def content(self) -> bytes: - return self.http_response.content - - @property - def text(self) -> str: - return self.http_response.text - @property def http_version(self) -> str: return self.http_response.http_version @@ -102,13 +100,29 @@ def elapsed(self) -> datetime.timedelta: """The time taken for the complete request/response cycle to complete.""" return self.http_response.elapsed + @property + def is_closed(self) -> bool: + """Whether or not the response body has been closed. + + If this is False then there is response data that has not been read yet. + You must either fully consume the response body or call `.close()` + before discarding the response to prevent resource leaks. + """ + return self.http_response.is_closed + + @override + def __repr__(self) -> str: + return ( + f"<{self.__class__.__name__} [{self.status_code} {self.http_response.reason_phrase}] type={self._cast_to}>" + ) + def _parse(self) -> R: - if self._stream: + if self._is_sse_stream: if self._stream_cls: return cast( R, self._stream_cls( - cast_to=_extract_stream_chunk_type(self._stream_cls), + cast_to=extract_stream_chunk_type(self._stream_cls), response=self.http_response, client=cast(Any, self._client), ), @@ -135,9 +149,13 @@ def _parse(self) -> R: if cast_to == str: return cast(R, response.text) + if cast_to == bytes: + return cast(R, response.content) + origin = get_origin(cast_to) or cast_to - if inspect.isclass(origin) and issubclass(origin, BinaryResponseContent): + # handle the legacy binary response case + if inspect.isclass(cast_to) and cast_to.__name__ == "HttpxBinaryResponseContent": return cast(R, cast_to(response)) # type: ignore if origin == APIResponse: @@ -208,9 +226,227 @@ def _parse(self) -> R: response=response, ) - @override - def __repr__(self) -> str: - return f"" + +class APIResponse(BaseAPIResponse[R]): + def parse(self) -> R: + """Returns the rich python representation of this response's data. + + For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`. + """ + if self._parsed is not None: + return self._parsed + + if not self._is_sse_stream: + self.read() + + parsed = self._parse() + if is_given(self._options.post_parser): + parsed = self._options.post_parser(parsed) + + self._parsed = parsed + return parsed + + def read(self) -> bytes: + """Read and return the binary response content.""" + try: + return self.http_response.read() + except httpx.StreamConsumed as exc: + # The default error raised by httpx isn't very + # helpful in our case so we re-raise it with + # a different error message. + raise StreamAlreadyConsumed() from exc + + def text(self) -> str: + """Read and decode the response content into a string.""" + self.read() + return self.http_response.text + + def json(self) -> object: + """Read and decode the JSON response content.""" + self.read() + return self.http_response.json() + + def close(self) -> None: + """Close the response and release the connection. + + Automatically called if the response body is read to completion. + """ + self.http_response.close() + + def iter_bytes(self, chunk_size: int | None = None) -> Iterator[bytes]: + """ + A byte-iterator over the decoded response content. + + This automatically handles gzip, deflate and brotli encoded responses. + """ + for chunk in self.http_response.iter_bytes(chunk_size): + yield chunk + + def iter_text(self, chunk_size: int | None = None) -> Iterator[str]: + """A str-iterator over the decoded response content + that handles both gzip, deflate, etc but also detects the content's + string encoding. + """ + for chunk in self.http_response.iter_text(chunk_size): + yield chunk + + def iter_lines(self) -> Iterator[str]: + """Like `iter_text()` but will only yield chunks for each line""" + for chunk in self.http_response.iter_lines(): + yield chunk + + +class AsyncAPIResponse(BaseAPIResponse[R]): + async def parse(self) -> R: + """Returns the rich python representation of this response's data. + + For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`. + """ + if self._parsed is not None: + return self._parsed + + if not self._is_sse_stream: + await self.read() + + parsed = self._parse() + if is_given(self._options.post_parser): + parsed = self._options.post_parser(parsed) + + self._parsed = parsed + return parsed + + async def read(self) -> bytes: + """Read and return the binary response content.""" + try: + return await self.http_response.aread() + except httpx.StreamConsumed as exc: + # the default error raised by httpx isn't very + # helpful in our case so we re-raise it with + # a different error message + raise StreamAlreadyConsumed() from exc + + async def text(self) -> str: + """Read and decode the response content into a string.""" + await self.read() + return self.http_response.text + + async def json(self) -> object: + """Read and decode the JSON response content.""" + await self.read() + return self.http_response.json() + + async def close(self) -> None: + """Close the response and release the connection. + + Automatically called if the response body is read to completion. + """ + await self.http_response.aclose() + + async def iter_bytes(self, chunk_size: int | None = None) -> AsyncIterator[bytes]: + """ + A byte-iterator over the decoded response content. + + This automatically handles gzip, deflate and brotli encoded responses. + """ + async for chunk in self.http_response.aiter_bytes(chunk_size): + yield chunk + + async def iter_text(self, chunk_size: int | None = None) -> AsyncIterator[str]: + """A str-iterator over the decoded response content + that handles both gzip, deflate, etc but also detects the content's + string encoding. + """ + async for chunk in self.http_response.aiter_text(chunk_size): + yield chunk + + async def iter_lines(self) -> AsyncIterator[str]: + """Like `iter_text()` but will only yield chunks for each line""" + async for chunk in self.http_response.aiter_lines(): + yield chunk + + +class BinaryAPIResponse(APIResponse[bytes]): + """Subclass of APIResponse providing helpers for dealing with binary data. + + Note: If you want to stream the response data instead of eagerly reading it + all at once then you should use `.with_streaming_response` when making + the API request, e.g. `.with_streaming_response.get_binary_response()` + """ + + def write_to_file( + self, + file: str | os.PathLike[str], + ) -> None: + """Write the output to the given file. + + Accepts a filename or any path-like object, e.g. pathlib.Path + + Note: if you want to stream the data to the file instead of writing + all at once then you should use `.with_streaming_response` when making + the API request, e.g. `.with_streaming_response.get_binary_response()` + """ + with open(file, mode="wb") as f: + for data in self.iter_bytes(): + f.write(data) + + +class AsyncBinaryAPIResponse(AsyncAPIResponse[bytes]): + """Subclass of APIResponse providing helpers for dealing with binary data. + + Note: If you want to stream the response data instead of eagerly reading it + all at once then you should use `.with_streaming_response` when making + the API request, e.g. `.with_streaming_response.get_binary_response()` + """ + + async def write_to_file( + self, + file: str | os.PathLike[str], + ) -> None: + """Write the output to the given file. + + Accepts a filename or any path-like object, e.g. pathlib.Path + + Note: if you want to stream the data to the file instead of writing + all at once then you should use `.with_streaming_response` when making + the API request, e.g. `.with_streaming_response.get_binary_response()` + """ + path = anyio.Path(file) + async with await path.open(mode="wb") as f: + async for data in self.iter_bytes(): + await f.write(data) + + +class StreamedBinaryAPIResponse(APIResponse[bytes]): + def stream_to_file( + self, + file: str | os.PathLike[str], + *, + chunk_size: int | None = None, + ) -> None: + """Streams the output to the given file. + + Accepts a filename or any path-like object, e.g. pathlib.Path + """ + with open(file, mode="wb") as f: + for data in self.iter_bytes(chunk_size): + f.write(data) + + +class AsyncStreamedBinaryAPIResponse(AsyncAPIResponse[bytes]): + async def stream_to_file( + self, + file: str | os.PathLike[str], + *, + chunk_size: int | None = None, + ) -> None: + """Streams the output to the given file. + + Accepts a filename or any path-like object, e.g. pathlib.Path + """ + path = anyio.Path(file) + async with await path.open(mode="wb") as f: + async for data in self.iter_bytes(chunk_size): + await f.write(data) class MissingStreamClassError(TypeError): @@ -220,14 +456,176 @@ def __init__(self) -> None: ) -def _extract_stream_chunk_type(stream_cls: type) -> type: - from ._base_client import Stream, AsyncStream +class StreamAlreadyConsumed(OpenAIError): + """ + Attempted to read or stream content, but the content has already + been streamed. - return extract_type_var_from_base( - stream_cls, - index=0, - generic_bases=cast("tuple[type, ...]", (Stream, AsyncStream)), - ) + This can happen if you use a method like `.iter_lines()` and then attempt + to read th entire response body afterwards, e.g. + + ```py + response = await client.post(...) + async for line in response.iter_lines(): + ... # do something with `line` + + content = await response.read() + # ^ error + ``` + + If you want this behaviour you'll need to either manually accumulate the response + content or call `await response.read()` before iterating over the stream. + """ + + def __init__(self) -> None: + message = ( + "Attempted to read or stream some content, but the content has " + "already been streamed. " + "This could be due to attempting to stream the response " + "content more than once." + "\n\n" + "You can fix this by manually accumulating the response content while streaming " + "or by calling `.read()` before starting to stream." + ) + super().__init__(message) + + +class ResponseContextManager(Generic[_APIResponseT]): + """Context manager for ensuring that a request is not made + until it is entered and that the response will always be closed + when the context manager exits + """ + + def __init__(self, request_func: Callable[[], _APIResponseT]) -> None: + self._request_func = request_func + self.__response: _APIResponseT | None = None + + def __enter__(self) -> _APIResponseT: + self.__response = self._request_func() + return self.__response + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self.__response is not None: + self.__response.close() + + +class AsyncResponseContextManager(Generic[_AsyncAPIResponseT]): + """Context manager for ensuring that a request is not made + until it is entered and that the response will always be closed + when the context manager exits + """ + + def __init__(self, api_request: Awaitable[_AsyncAPIResponseT]) -> None: + self._api_request = api_request + self.__response: _AsyncAPIResponseT | None = None + + async def __aenter__(self) -> _AsyncAPIResponseT: + self.__response = await self._api_request + return self.__response + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self.__response is not None: + await self.__response.close() + + +def to_streamed_response_wrapper(func: Callable[P, R]) -> Callable[P, ResponseContextManager[APIResponse[R]]]: + """Higher order function that takes one of our bound API methods and wraps it + to support streaming and returning the raw `APIResponse` object directly. + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> ResponseContextManager[APIResponse[R]]: + extra_headers = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "stream" + + kwargs["extra_headers"] = extra_headers + + make_request = functools.partial(func, *args, **kwargs) + + return ResponseContextManager(cast(Callable[[], APIResponse[R]], make_request)) + + return wrapped + + +def async_to_streamed_response_wrapper( + func: Callable[P, Awaitable[R]], +) -> Callable[P, AsyncResponseContextManager[AsyncAPIResponse[R]]]: + """Higher order function that takes one of our bound API methods and wraps it + to support streaming and returning the raw `APIResponse` object directly. + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncResponseContextManager[AsyncAPIResponse[R]]: + extra_headers = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "stream" + + kwargs["extra_headers"] = extra_headers + + make_request = func(*args, **kwargs) + + return AsyncResponseContextManager(cast(Awaitable[AsyncAPIResponse[R]], make_request)) + + return wrapped + + +def to_custom_streamed_response_wrapper( + func: Callable[P, object], + response_cls: type[_APIResponseT], +) -> Callable[P, ResponseContextManager[_APIResponseT]]: + """Higher order function that takes one of our bound API methods and an `APIResponse` class + and wraps the method to support streaming and returning the given response class directly. + + Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])` + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> ResponseContextManager[_APIResponseT]: + extra_headers = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "stream" + extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls + + kwargs["extra_headers"] = extra_headers + + make_request = functools.partial(func, *args, **kwargs) + + return ResponseContextManager(cast(Callable[[], _APIResponseT], make_request)) + + return wrapped + + +def async_to_custom_streamed_response_wrapper( + func: Callable[P, Awaitable[object]], + response_cls: type[_AsyncAPIResponseT], +) -> Callable[P, AsyncResponseContextManager[_AsyncAPIResponseT]]: + """Higher order function that takes one of our bound API methods and an `APIResponse` class + and wraps the method to support streaming and returning the given response class directly. + + Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])` + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncResponseContextManager[_AsyncAPIResponseT]: + extra_headers = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "stream" + extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls + + kwargs["extra_headers"] = extra_headers + + make_request = func(*args, **kwargs) + + return AsyncResponseContextManager(cast(Awaitable[_AsyncAPIResponseT], make_request)) + + return wrapped def to_raw_response_wrapper(func: Callable[P, R]) -> Callable[P, APIResponse[R]]: @@ -238,7 +636,7 @@ def to_raw_response_wrapper(func: Callable[P, R]) -> Callable[P, APIResponse[R]] @functools.wraps(func) def wrapped(*args: P.args, **kwargs: P.kwargs) -> APIResponse[R]: extra_headers = {**(cast(Any, kwargs.get("extra_headers")) or {})} - extra_headers[RAW_RESPONSE_HEADER] = "true" + extra_headers[RAW_RESPONSE_HEADER] = "raw" kwargs["extra_headers"] = extra_headers @@ -247,18 +645,102 @@ def wrapped(*args: P.args, **kwargs: P.kwargs) -> APIResponse[R]: return wrapped -def async_to_raw_response_wrapper(func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[APIResponse[R]]]: +def async_to_raw_response_wrapper(func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[AsyncAPIResponse[R]]]: """Higher order function that takes one of our bound API methods and wraps it to support returning the raw `APIResponse` object directly. """ @functools.wraps(func) - async def wrapped(*args: P.args, **kwargs: P.kwargs) -> APIResponse[R]: + async def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncAPIResponse[R]: extra_headers = {**(cast(Any, kwargs.get("extra_headers")) or {})} - extra_headers[RAW_RESPONSE_HEADER] = "true" + extra_headers[RAW_RESPONSE_HEADER] = "raw" kwargs["extra_headers"] = extra_headers - return cast(APIResponse[R], await func(*args, **kwargs)) + return cast(AsyncAPIResponse[R], await func(*args, **kwargs)) return wrapped + + +def to_custom_raw_response_wrapper( + func: Callable[P, object], + response_cls: type[_APIResponseT], +) -> Callable[P, _APIResponseT]: + """Higher order function that takes one of our bound API methods and an `APIResponse` class + and wraps the method to support returning the given response class directly. + + Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])` + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> _APIResponseT: + extra_headers = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "raw" + extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls + + kwargs["extra_headers"] = extra_headers + + return cast(_APIResponseT, func(*args, **kwargs)) + + return wrapped + + +def async_to_custom_raw_response_wrapper( + func: Callable[P, Awaitable[object]], + response_cls: type[_AsyncAPIResponseT], +) -> Callable[P, Awaitable[_AsyncAPIResponseT]]: + """Higher order function that takes one of our bound API methods and an `APIResponse` class + and wraps the method to support returning the given response class directly. + + Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])` + """ + + @functools.wraps(func) + def wrapped(*args: P.args, **kwargs: P.kwargs) -> Awaitable[_AsyncAPIResponseT]: + extra_headers = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers[RAW_RESPONSE_HEADER] = "raw" + extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls + + kwargs["extra_headers"] = extra_headers + + return cast(Awaitable[_AsyncAPIResponseT], func(*args, **kwargs)) + + return wrapped + + +def extract_stream_chunk_type(stream_cls: type) -> type: + """Given a type like `Stream[T]`, returns the generic type variable `T`. + + This also handles the case where a concrete subclass is given, e.g. + ```py + class MyStream(Stream[bytes]): + ... + + extract_stream_chunk_type(MyStream) -> bytes + ``` + """ + from ._base_client import Stream, AsyncStream + + return extract_type_var_from_base( + stream_cls, + index=0, + generic_bases=cast("tuple[type, ...]", (Stream, AsyncStream)), + ) + + +def extract_response_type(typ: type[BaseAPIResponse[Any]]) -> type: + """Given a type like `APIResponse[T]`, returns the generic type variable `T`. + + This also handles the case where a concrete subclass is given, e.g. + ```py + class MyResponse(APIResponse[bytes]): + ... + + extract_response_type(MyResponse) -> bytes + ``` + """ + return extract_type_var_from_base( + typ, + generic_bases=cast("tuple[type, ...]", (BaseAPIResponse, APIResponse, AsyncAPIResponse)), + index=0, + ) diff --git a/src/openai/_types.py b/src/openai/_types.py index e6b83b2a3f..b5bf8f8af0 100644 --- a/src/openai/_types.py +++ b/src/openai/_types.py @@ -1,7 +1,6 @@ from __future__ import annotations from os import PathLike -from abc import ABC, abstractmethod from typing import ( IO, TYPE_CHECKING, @@ -14,10 +13,8 @@ Mapping, TypeVar, Callable, - Iterator, Optional, Sequence, - AsyncIterator, ) from typing_extensions import Literal, Protocol, TypeAlias, TypedDict, override, runtime_checkable @@ -27,6 +24,8 @@ if TYPE_CHECKING: from ._models import BaseModel + from ._response import APIResponse, AsyncAPIResponse + from ._legacy_response import HttpxBinaryResponseContent Transport = BaseTransport AsyncTransport = AsyncBaseTransport @@ -37,162 +36,6 @@ _T = TypeVar("_T") -class BinaryResponseContent(ABC): - @abstractmethod - def __init__( - self, - response: Any, - ) -> None: - ... - - @property - @abstractmethod - def content(self) -> bytes: - pass - - @property - @abstractmethod - def text(self) -> str: - pass - - @property - @abstractmethod - def encoding(self) -> Optional[str]: - """ - Return an encoding to use for decoding the byte content into text. - The priority for determining this is given by... - - * `.encoding = <>` has been set explicitly. - * The encoding as specified by the charset parameter in the Content-Type header. - * The encoding as determined by `default_encoding`, which may either be - a string like "utf-8" indicating the encoding to use, or may be a callable - which enables charset autodetection. - """ - pass - - @property - @abstractmethod - def charset_encoding(self) -> Optional[str]: - """ - Return the encoding, as specified by the Content-Type header. - """ - pass - - @abstractmethod - def json(self, **kwargs: Any) -> Any: - pass - - @abstractmethod - def read(self) -> bytes: - """ - Read and return the response content. - """ - pass - - @abstractmethod - def iter_bytes(self, chunk_size: Optional[int] = None) -> Iterator[bytes]: - """ - A byte-iterator over the decoded response content. - This allows us to handle gzip, deflate, and brotli encoded responses. - """ - pass - - @abstractmethod - def iter_text(self, chunk_size: Optional[int] = None) -> Iterator[str]: - """ - A str-iterator over the decoded response content - that handles both gzip, deflate, etc but also detects the content's - string encoding. - """ - pass - - @abstractmethod - def iter_lines(self) -> Iterator[str]: - pass - - @abstractmethod - def iter_raw(self, chunk_size: Optional[int] = None) -> Iterator[bytes]: - """ - A byte-iterator over the raw response content. - """ - pass - - @abstractmethod - def stream_to_file( - self, - file: str | PathLike[str], - *, - chunk_size: int | None = None, - ) -> None: - """ - Stream the output to the given file. - """ - pass - - @abstractmethod - def close(self) -> None: - """ - Close the response and release the connection. - Automatically called if the response body is read to completion. - """ - pass - - @abstractmethod - async def aread(self) -> bytes: - """ - Read and return the response content. - """ - pass - - @abstractmethod - async def aiter_bytes(self, chunk_size: Optional[int] = None) -> AsyncIterator[bytes]: - """ - A byte-iterator over the decoded response content. - This allows us to handle gzip, deflate, and brotli encoded responses. - """ - pass - - @abstractmethod - async def aiter_text(self, chunk_size: Optional[int] = None) -> AsyncIterator[str]: - """ - A str-iterator over the decoded response content - that handles both gzip, deflate, etc but also detects the content's - string encoding. - """ - pass - - @abstractmethod - async def aiter_lines(self) -> AsyncIterator[str]: - pass - - @abstractmethod - async def aiter_raw(self, chunk_size: Optional[int] = None) -> AsyncIterator[bytes]: - """ - A byte-iterator over the raw response content. - """ - pass - - @abstractmethod - async def astream_to_file( - self, - file: str | PathLike[str], - *, - chunk_size: int | None = None, - ) -> None: - """ - Stream the output to the given file. - """ - pass - - @abstractmethod - async def aclose(self) -> None: - """ - Close the response and release the connection. - Automatically called if the response body is read to completion. - """ - pass - - # Approximates httpx internal ProxiesTypes and RequestFiles types # while adding support for `PathLike` instances ProxiesDict = Dict["str | URL", Union[None, str, URL, Proxy]] @@ -343,7 +186,9 @@ def get(self, __key: str) -> str | None: Dict[str, Any], Response, ModelBuilderProtocol, - BinaryResponseContent, + "APIResponse[Any]", + "AsyncAPIResponse[Any]", + "HttpxBinaryResponseContent", ], ) @@ -359,6 +204,7 @@ def get(self, __key: str) -> str | None: @runtime_checkable class InheritsGeneric(Protocol): """Represents a type that has inherited from `Generic` + The `__orig_bases__` property can be used to determine the resolved type variable for a given base class. """ diff --git a/src/openai/resources/__init__.py b/src/openai/resources/__init__.py index 8219be12e6..1fb4aa62ec 100644 --- a/src/openai/resources/__init__.py +++ b/src/openai/resources/__init__.py @@ -1,55 +1,145 @@ # File generated from our OpenAPI spec by Stainless. -from .beta import Beta, AsyncBeta, BetaWithRawResponse, AsyncBetaWithRawResponse -from .chat import Chat, AsyncChat, ChatWithRawResponse, AsyncChatWithRawResponse -from .audio import Audio, AsyncAudio, AudioWithRawResponse, AsyncAudioWithRawResponse -from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from .images import Images, AsyncImages, ImagesWithRawResponse, AsyncImagesWithRawResponse -from .models import Models, AsyncModels, ModelsWithRawResponse, AsyncModelsWithRawResponse -from .embeddings import Embeddings, AsyncEmbeddings, EmbeddingsWithRawResponse, AsyncEmbeddingsWithRawResponse -from .completions import Completions, AsyncCompletions, CompletionsWithRawResponse, AsyncCompletionsWithRawResponse -from .fine_tuning import FineTuning, AsyncFineTuning, FineTuningWithRawResponse, AsyncFineTuningWithRawResponse -from .moderations import Moderations, AsyncModerations, ModerationsWithRawResponse, AsyncModerationsWithRawResponse +from .beta import ( + Beta, + AsyncBeta, + BetaWithRawResponse, + AsyncBetaWithRawResponse, + BetaWithStreamingResponse, + AsyncBetaWithStreamingResponse, +) +from .chat import ( + Chat, + AsyncChat, + ChatWithRawResponse, + AsyncChatWithRawResponse, + ChatWithStreamingResponse, + AsyncChatWithStreamingResponse, +) +from .audio import ( + Audio, + AsyncAudio, + AudioWithRawResponse, + AsyncAudioWithRawResponse, + AudioWithStreamingResponse, + AsyncAudioWithStreamingResponse, +) +from .files import ( + Files, + AsyncFiles, + FilesWithRawResponse, + AsyncFilesWithRawResponse, + FilesWithStreamingResponse, + AsyncFilesWithStreamingResponse, +) +from .images import ( + Images, + AsyncImages, + ImagesWithRawResponse, + AsyncImagesWithRawResponse, + ImagesWithStreamingResponse, + AsyncImagesWithStreamingResponse, +) +from .models import ( + Models, + AsyncModels, + ModelsWithRawResponse, + AsyncModelsWithRawResponse, + ModelsWithStreamingResponse, + AsyncModelsWithStreamingResponse, +) +from .embeddings import ( + Embeddings, + AsyncEmbeddings, + EmbeddingsWithRawResponse, + AsyncEmbeddingsWithRawResponse, + EmbeddingsWithStreamingResponse, + AsyncEmbeddingsWithStreamingResponse, +) +from .completions import ( + Completions, + AsyncCompletions, + CompletionsWithRawResponse, + AsyncCompletionsWithRawResponse, + CompletionsWithStreamingResponse, + AsyncCompletionsWithStreamingResponse, +) +from .fine_tuning import ( + FineTuning, + AsyncFineTuning, + FineTuningWithRawResponse, + AsyncFineTuningWithRawResponse, + FineTuningWithStreamingResponse, + AsyncFineTuningWithStreamingResponse, +) +from .moderations import ( + Moderations, + AsyncModerations, + ModerationsWithRawResponse, + AsyncModerationsWithRawResponse, + ModerationsWithStreamingResponse, + AsyncModerationsWithStreamingResponse, +) __all__ = [ "Completions", "AsyncCompletions", "CompletionsWithRawResponse", "AsyncCompletionsWithRawResponse", + "CompletionsWithStreamingResponse", + "AsyncCompletionsWithStreamingResponse", "Chat", "AsyncChat", "ChatWithRawResponse", "AsyncChatWithRawResponse", + "ChatWithStreamingResponse", + "AsyncChatWithStreamingResponse", "Embeddings", "AsyncEmbeddings", "EmbeddingsWithRawResponse", "AsyncEmbeddingsWithRawResponse", + "EmbeddingsWithStreamingResponse", + "AsyncEmbeddingsWithStreamingResponse", "Files", "AsyncFiles", "FilesWithRawResponse", "AsyncFilesWithRawResponse", + "FilesWithStreamingResponse", + "AsyncFilesWithStreamingResponse", "Images", "AsyncImages", "ImagesWithRawResponse", "AsyncImagesWithRawResponse", + "ImagesWithStreamingResponse", + "AsyncImagesWithStreamingResponse", "Audio", "AsyncAudio", "AudioWithRawResponse", "AsyncAudioWithRawResponse", + "AudioWithStreamingResponse", + "AsyncAudioWithStreamingResponse", "Moderations", "AsyncModerations", "ModerationsWithRawResponse", "AsyncModerationsWithRawResponse", + "ModerationsWithStreamingResponse", + "AsyncModerationsWithStreamingResponse", "Models", "AsyncModels", "ModelsWithRawResponse", "AsyncModelsWithRawResponse", + "ModelsWithStreamingResponse", + "AsyncModelsWithStreamingResponse", "FineTuning", "AsyncFineTuning", "FineTuningWithRawResponse", "AsyncFineTuningWithRawResponse", + "FineTuningWithStreamingResponse", + "AsyncFineTuningWithStreamingResponse", "Beta", "AsyncBeta", "BetaWithRawResponse", "AsyncBetaWithRawResponse", + "BetaWithStreamingResponse", + "AsyncBetaWithStreamingResponse", ] diff --git a/src/openai/resources/audio/__init__.py b/src/openai/resources/audio/__init__.py index b6ff4322d4..63d06494b8 100644 --- a/src/openai/resources/audio/__init__.py +++ b/src/openai/resources/audio/__init__.py @@ -1,13 +1,36 @@ # File generated from our OpenAPI spec by Stainless. -from .audio import Audio, AsyncAudio, AudioWithRawResponse, AsyncAudioWithRawResponse -from .speech import Speech, AsyncSpeech, SpeechWithRawResponse, AsyncSpeechWithRawResponse -from .translations import Translations, AsyncTranslations, TranslationsWithRawResponse, AsyncTranslationsWithRawResponse +from .audio import ( + Audio, + AsyncAudio, + AudioWithRawResponse, + AsyncAudioWithRawResponse, + AudioWithStreamingResponse, + AsyncAudioWithStreamingResponse, +) +from .speech import ( + Speech, + AsyncSpeech, + SpeechWithRawResponse, + AsyncSpeechWithRawResponse, + SpeechWithStreamingResponse, + AsyncSpeechWithStreamingResponse, +) +from .translations import ( + Translations, + AsyncTranslations, + TranslationsWithRawResponse, + AsyncTranslationsWithRawResponse, + TranslationsWithStreamingResponse, + AsyncTranslationsWithStreamingResponse, +) from .transcriptions import ( Transcriptions, AsyncTranscriptions, TranscriptionsWithRawResponse, AsyncTranscriptionsWithRawResponse, + TranscriptionsWithStreamingResponse, + AsyncTranscriptionsWithStreamingResponse, ) __all__ = [ @@ -15,16 +38,24 @@ "AsyncTranscriptions", "TranscriptionsWithRawResponse", "AsyncTranscriptionsWithRawResponse", + "TranscriptionsWithStreamingResponse", + "AsyncTranscriptionsWithStreamingResponse", "Translations", "AsyncTranslations", "TranslationsWithRawResponse", "AsyncTranslationsWithRawResponse", + "TranslationsWithStreamingResponse", + "AsyncTranslationsWithStreamingResponse", "Speech", "AsyncSpeech", "SpeechWithRawResponse", "AsyncSpeechWithRawResponse", + "SpeechWithStreamingResponse", + "AsyncSpeechWithStreamingResponse", "Audio", "AsyncAudio", "AudioWithRawResponse", "AsyncAudioWithRawResponse", + "AudioWithStreamingResponse", + "AsyncAudioWithStreamingResponse", ] diff --git a/src/openai/resources/audio/audio.py b/src/openai/resources/audio/audio.py index 4e3ca0ed4f..b14e64cff6 100644 --- a/src/openai/resources/audio/audio.py +++ b/src/openai/resources/audio/audio.py @@ -2,15 +2,31 @@ from __future__ import annotations -from .speech import Speech, AsyncSpeech, SpeechWithRawResponse, AsyncSpeechWithRawResponse +from .speech import ( + Speech, + AsyncSpeech, + SpeechWithRawResponse, + AsyncSpeechWithRawResponse, + SpeechWithStreamingResponse, + AsyncSpeechWithStreamingResponse, +) from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource -from .translations import Translations, AsyncTranslations, TranslationsWithRawResponse, AsyncTranslationsWithRawResponse +from .translations import ( + Translations, + AsyncTranslations, + TranslationsWithRawResponse, + AsyncTranslationsWithRawResponse, + TranslationsWithStreamingResponse, + AsyncTranslationsWithStreamingResponse, +) from .transcriptions import ( Transcriptions, AsyncTranscriptions, TranscriptionsWithRawResponse, AsyncTranscriptionsWithRawResponse, + TranscriptionsWithStreamingResponse, + AsyncTranscriptionsWithStreamingResponse, ) __all__ = ["Audio", "AsyncAudio"] @@ -33,6 +49,10 @@ def speech(self) -> Speech: def with_raw_response(self) -> AudioWithRawResponse: return AudioWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> AudioWithStreamingResponse: + return AudioWithStreamingResponse(self) + class AsyncAudio(AsyncAPIResource): @cached_property @@ -51,6 +71,10 @@ def speech(self) -> AsyncSpeech: def with_raw_response(self) -> AsyncAudioWithRawResponse: return AsyncAudioWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> AsyncAudioWithStreamingResponse: + return AsyncAudioWithStreamingResponse(self) + class AudioWithRawResponse: def __init__(self, audio: Audio) -> None: @@ -64,3 +88,17 @@ def __init__(self, audio: AsyncAudio) -> None: self.transcriptions = AsyncTranscriptionsWithRawResponse(audio.transcriptions) self.translations = AsyncTranslationsWithRawResponse(audio.translations) self.speech = AsyncSpeechWithRawResponse(audio.speech) + + +class AudioWithStreamingResponse: + def __init__(self, audio: Audio) -> None: + self.transcriptions = TranscriptionsWithStreamingResponse(audio.transcriptions) + self.translations = TranslationsWithStreamingResponse(audio.translations) + self.speech = SpeechWithStreamingResponse(audio.speech) + + +class AsyncAudioWithStreamingResponse: + def __init__(self, audio: AsyncAudio) -> None: + self.transcriptions = AsyncTranscriptionsWithStreamingResponse(audio.transcriptions) + self.translations = AsyncTranslationsWithStreamingResponse(audio.translations) + self.speech = AsyncSpeechWithStreamingResponse(audio.speech) diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index b7cd3733a9..9c051624d5 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -7,14 +7,19 @@ import httpx +from ... import _legacy_response from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ..._utils import maybe_transform from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource -from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from ..._response import ( + StreamedBinaryAPIResponse, + AsyncStreamedBinaryAPIResponse, + to_custom_streamed_response_wrapper, + async_to_custom_streamed_response_wrapper, +) from ...types.audio import speech_create_params from ..._base_client import ( - HttpxBinaryResponseContent, make_request_options, ) @@ -26,6 +31,10 @@ class Speech(SyncAPIResource): def with_raw_response(self) -> SpeechWithRawResponse: return SpeechWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> SpeechWithStreamingResponse: + return SpeechWithStreamingResponse(self) + def create( self, *, @@ -40,7 +49,7 @@ def create( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> HttpxBinaryResponseContent: + ) -> _legacy_response.HttpxBinaryResponseContent: """ Generates audio from the input text. @@ -84,7 +93,7 @@ def create( options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), - cast_to=HttpxBinaryResponseContent, + cast_to=_legacy_response.HttpxBinaryResponseContent, ) @@ -93,6 +102,10 @@ class AsyncSpeech(AsyncAPIResource): def with_raw_response(self) -> AsyncSpeechWithRawResponse: return AsyncSpeechWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> AsyncSpeechWithStreamingResponse: + return AsyncSpeechWithStreamingResponse(self) + async def create( self, *, @@ -107,7 +120,7 @@ async def create( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> HttpxBinaryResponseContent: + ) -> _legacy_response.HttpxBinaryResponseContent: """ Generates audio from the input text. @@ -151,19 +164,35 @@ async def create( options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), - cast_to=HttpxBinaryResponseContent, + cast_to=_legacy_response.HttpxBinaryResponseContent, ) class SpeechWithRawResponse: def __init__(self, speech: Speech) -> None: - self.create = to_raw_response_wrapper( + self.create = _legacy_response.to_raw_response_wrapper( speech.create, ) class AsyncSpeechWithRawResponse: def __init__(self, speech: AsyncSpeech) -> None: - self.create = async_to_raw_response_wrapper( + self.create = _legacy_response.async_to_raw_response_wrapper( + speech.create, + ) + + +class SpeechWithStreamingResponse: + def __init__(self, speech: Speech) -> None: + self.create = to_custom_streamed_response_wrapper( + speech.create, + StreamedBinaryAPIResponse, + ) + + +class AsyncSpeechWithStreamingResponse: + def __init__(self, speech: AsyncSpeech) -> None: + self.create = async_to_custom_streamed_response_wrapper( speech.create, + AsyncStreamedBinaryAPIResponse, ) diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index 7d7441a9f6..053ac30095 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -7,11 +7,12 @@ import httpx +from ... import _legacy_response from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from ..._utils import extract_files, maybe_transform, deepcopy_minimal from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource -from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ...types.audio import Transcription, transcription_create_params from ..._base_client import ( make_request_options, @@ -25,6 +26,10 @@ class Transcriptions(SyncAPIResource): def with_raw_response(self) -> TranscriptionsWithRawResponse: return TranscriptionsWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> TranscriptionsWithStreamingResponse: + return TranscriptionsWithStreamingResponse(self) + def create( self, *, @@ -110,6 +115,10 @@ class AsyncTranscriptions(AsyncAPIResource): def with_raw_response(self) -> AsyncTranscriptionsWithRawResponse: return AsyncTranscriptionsWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> AsyncTranscriptionsWithStreamingResponse: + return AsyncTranscriptionsWithStreamingResponse(self) + async def create( self, *, @@ -192,13 +201,27 @@ async def create( class TranscriptionsWithRawResponse: def __init__(self, transcriptions: Transcriptions) -> None: - self.create = to_raw_response_wrapper( + self.create = _legacy_response.to_raw_response_wrapper( transcriptions.create, ) class AsyncTranscriptionsWithRawResponse: def __init__(self, transcriptions: AsyncTranscriptions) -> None: - self.create = async_to_raw_response_wrapper( + self.create = _legacy_response.async_to_raw_response_wrapper( + transcriptions.create, + ) + + +class TranscriptionsWithStreamingResponse: + def __init__(self, transcriptions: Transcriptions) -> None: + self.create = to_streamed_response_wrapper( + transcriptions.create, + ) + + +class AsyncTranscriptionsWithStreamingResponse: + def __init__(self, transcriptions: AsyncTranscriptions) -> None: + self.create = async_to_streamed_response_wrapper( transcriptions.create, ) diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index 7f5f65b6c8..db41b194b6 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -7,11 +7,12 @@ import httpx +from ... import _legacy_response from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from ..._utils import extract_files, maybe_transform, deepcopy_minimal from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource -from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ...types.audio import Translation, translation_create_params from ..._base_client import ( make_request_options, @@ -25,6 +26,10 @@ class Translations(SyncAPIResource): def with_raw_response(self) -> TranslationsWithRawResponse: return TranslationsWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> TranslationsWithStreamingResponse: + return TranslationsWithStreamingResponse(self) + def create( self, *, @@ -103,6 +108,10 @@ class AsyncTranslations(AsyncAPIResource): def with_raw_response(self) -> AsyncTranslationsWithRawResponse: return AsyncTranslationsWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> AsyncTranslationsWithStreamingResponse: + return AsyncTranslationsWithStreamingResponse(self) + async def create( self, *, @@ -178,13 +187,27 @@ async def create( class TranslationsWithRawResponse: def __init__(self, translations: Translations) -> None: - self.create = to_raw_response_wrapper( + self.create = _legacy_response.to_raw_response_wrapper( translations.create, ) class AsyncTranslationsWithRawResponse: def __init__(self, translations: AsyncTranslations) -> None: - self.create = async_to_raw_response_wrapper( + self.create = _legacy_response.async_to_raw_response_wrapper( + translations.create, + ) + + +class TranslationsWithStreamingResponse: + def __init__(self, translations: Translations) -> None: + self.create = to_streamed_response_wrapper( + translations.create, + ) + + +class AsyncTranslationsWithStreamingResponse: + def __init__(self, translations: AsyncTranslations) -> None: + self.create = async_to_streamed_response_wrapper( translations.create, ) diff --git a/src/openai/resources/beta/__init__.py b/src/openai/resources/beta/__init__.py index 561f8bef60..973c6ba54e 100644 --- a/src/openai/resources/beta/__init__.py +++ b/src/openai/resources/beta/__init__.py @@ -1,20 +1,47 @@ # File generated from our OpenAPI spec by Stainless. -from .beta import Beta, AsyncBeta, BetaWithRawResponse, AsyncBetaWithRawResponse -from .threads import Threads, AsyncThreads, ThreadsWithRawResponse, AsyncThreadsWithRawResponse -from .assistants import Assistants, AsyncAssistants, AssistantsWithRawResponse, AsyncAssistantsWithRawResponse +from .beta import ( + Beta, + AsyncBeta, + BetaWithRawResponse, + AsyncBetaWithRawResponse, + BetaWithStreamingResponse, + AsyncBetaWithStreamingResponse, +) +from .threads import ( + Threads, + AsyncThreads, + ThreadsWithRawResponse, + AsyncThreadsWithRawResponse, + ThreadsWithStreamingResponse, + AsyncThreadsWithStreamingResponse, +) +from .assistants import ( + Assistants, + AsyncAssistants, + AssistantsWithRawResponse, + AsyncAssistantsWithRawResponse, + AssistantsWithStreamingResponse, + AsyncAssistantsWithStreamingResponse, +) __all__ = [ "Assistants", "AsyncAssistants", "AssistantsWithRawResponse", "AsyncAssistantsWithRawResponse", + "AssistantsWithStreamingResponse", + "AsyncAssistantsWithStreamingResponse", "Threads", "AsyncThreads", "ThreadsWithRawResponse", "AsyncThreadsWithRawResponse", + "ThreadsWithStreamingResponse", + "AsyncThreadsWithStreamingResponse", "Beta", "AsyncBeta", "BetaWithRawResponse", "AsyncBetaWithRawResponse", + "BetaWithStreamingResponse", + "AsyncBetaWithStreamingResponse", ] diff --git a/src/openai/resources/beta/assistants/__init__.py b/src/openai/resources/beta/assistants/__init__.py index 205b2cf0f5..ad04a71572 100644 --- a/src/openai/resources/beta/assistants/__init__.py +++ b/src/openai/resources/beta/assistants/__init__.py @@ -1,15 +1,33 @@ # File generated from our OpenAPI spec by Stainless. -from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from .assistants import Assistants, AsyncAssistants, AssistantsWithRawResponse, AsyncAssistantsWithRawResponse +from .files import ( + Files, + AsyncFiles, + FilesWithRawResponse, + AsyncFilesWithRawResponse, + FilesWithStreamingResponse, + AsyncFilesWithStreamingResponse, +) +from .assistants import ( + Assistants, + AsyncAssistants, + AssistantsWithRawResponse, + AsyncAssistantsWithRawResponse, + AssistantsWithStreamingResponse, + AsyncAssistantsWithStreamingResponse, +) __all__ = [ "Files", "AsyncFiles", "FilesWithRawResponse", "AsyncFilesWithRawResponse", + "FilesWithStreamingResponse", + "AsyncFilesWithStreamingResponse", "Assistants", "AsyncAssistants", "AssistantsWithRawResponse", "AsyncAssistantsWithRawResponse", + "AssistantsWithStreamingResponse", + "AsyncAssistantsWithStreamingResponse", ] diff --git a/src/openai/resources/beta/assistants/assistants.py b/src/openai/resources/beta/assistants/assistants.py index 0ae054795d..176bf05516 100644 --- a/src/openai/resources/beta/assistants/assistants.py +++ b/src/openai/resources/beta/assistants/assistants.py @@ -7,12 +7,20 @@ import httpx -from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse +from .... import _legacy_response +from .files import ( + Files, + AsyncFiles, + FilesWithRawResponse, + AsyncFilesWithRawResponse, + FilesWithStreamingResponse, + AsyncFilesWithStreamingResponse, +) from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ...._utils import maybe_transform from ...._compat import cached_property from ...._resource import SyncAPIResource, AsyncAPIResource -from ...._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ....pagination import SyncCursorPage, AsyncCursorPage from ....types.beta import ( Assistant, @@ -38,6 +46,10 @@ def files(self) -> Files: def with_raw_response(self) -> AssistantsWithRawResponse: return AssistantsWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> AssistantsWithStreamingResponse: + return AssistantsWithStreamingResponse(self) + def create( self, *, @@ -331,6 +343,10 @@ def files(self) -> AsyncFiles: def with_raw_response(self) -> AsyncAssistantsWithRawResponse: return AsyncAssistantsWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> AsyncAssistantsWithStreamingResponse: + return AsyncAssistantsWithStreamingResponse(self) + async def create( self, *, @@ -619,19 +635,19 @@ class AssistantsWithRawResponse: def __init__(self, assistants: Assistants) -> None: self.files = FilesWithRawResponse(assistants.files) - self.create = to_raw_response_wrapper( + self.create = _legacy_response.to_raw_response_wrapper( assistants.create, ) - self.retrieve = to_raw_response_wrapper( + self.retrieve = _legacy_response.to_raw_response_wrapper( assistants.retrieve, ) - self.update = to_raw_response_wrapper( + self.update = _legacy_response.to_raw_response_wrapper( assistants.update, ) - self.list = to_raw_response_wrapper( + self.list = _legacy_response.to_raw_response_wrapper( assistants.list, ) - self.delete = to_raw_response_wrapper( + self.delete = _legacy_response.to_raw_response_wrapper( assistants.delete, ) @@ -640,18 +656,60 @@ class AsyncAssistantsWithRawResponse: def __init__(self, assistants: AsyncAssistants) -> None: self.files = AsyncFilesWithRawResponse(assistants.files) - self.create = async_to_raw_response_wrapper( + self.create = _legacy_response.async_to_raw_response_wrapper( + assistants.create, + ) + self.retrieve = _legacy_response.async_to_raw_response_wrapper( + assistants.retrieve, + ) + self.update = _legacy_response.async_to_raw_response_wrapper( + assistants.update, + ) + self.list = _legacy_response.async_to_raw_response_wrapper( + assistants.list, + ) + self.delete = _legacy_response.async_to_raw_response_wrapper( + assistants.delete, + ) + + +class AssistantsWithStreamingResponse: + def __init__(self, assistants: Assistants) -> None: + self.files = FilesWithStreamingResponse(assistants.files) + + self.create = to_streamed_response_wrapper( + assistants.create, + ) + self.retrieve = to_streamed_response_wrapper( + assistants.retrieve, + ) + self.update = to_streamed_response_wrapper( + assistants.update, + ) + self.list = to_streamed_response_wrapper( + assistants.list, + ) + self.delete = to_streamed_response_wrapper( + assistants.delete, + ) + + +class AsyncAssistantsWithStreamingResponse: + def __init__(self, assistants: AsyncAssistants) -> None: + self.files = AsyncFilesWithStreamingResponse(assistants.files) + + self.create = async_to_streamed_response_wrapper( assistants.create, ) - self.retrieve = async_to_raw_response_wrapper( + self.retrieve = async_to_streamed_response_wrapper( assistants.retrieve, ) - self.update = async_to_raw_response_wrapper( + self.update = async_to_streamed_response_wrapper( assistants.update, ) - self.list = async_to_raw_response_wrapper( + self.list = async_to_streamed_response_wrapper( assistants.list, ) - self.delete = async_to_raw_response_wrapper( + self.delete = async_to_streamed_response_wrapper( assistants.delete, ) diff --git a/src/openai/resources/beta/assistants/files.py b/src/openai/resources/beta/assistants/files.py index 0624e562f8..9e45ce46d3 100644 --- a/src/openai/resources/beta/assistants/files.py +++ b/src/openai/resources/beta/assistants/files.py @@ -6,11 +6,12 @@ import httpx +from .... import _legacy_response from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ...._utils import maybe_transform from ...._compat import cached_property from ...._resource import SyncAPIResource, AsyncAPIResource -from ...._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ....pagination import SyncCursorPage, AsyncCursorPage from ...._base_client import ( AsyncPaginator, @@ -26,6 +27,10 @@ class Files(SyncAPIResource): def with_raw_response(self) -> FilesWithRawResponse: return FilesWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> FilesWithStreamingResponse: + return FilesWithStreamingResponse(self) + def create( self, assistant_id: str, @@ -203,6 +208,10 @@ class AsyncFiles(AsyncAPIResource): def with_raw_response(self) -> AsyncFilesWithRawResponse: return AsyncFilesWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> AsyncFilesWithStreamingResponse: + return AsyncFilesWithStreamingResponse(self) + async def create( self, assistant_id: str, @@ -377,31 +386,63 @@ async def delete( class FilesWithRawResponse: def __init__(self, files: Files) -> None: - self.create = to_raw_response_wrapper( + self.create = _legacy_response.to_raw_response_wrapper( files.create, ) - self.retrieve = to_raw_response_wrapper( + self.retrieve = _legacy_response.to_raw_response_wrapper( files.retrieve, ) - self.list = to_raw_response_wrapper( + self.list = _legacy_response.to_raw_response_wrapper( files.list, ) - self.delete = to_raw_response_wrapper( + self.delete = _legacy_response.to_raw_response_wrapper( files.delete, ) class AsyncFilesWithRawResponse: def __init__(self, files: AsyncFiles) -> None: - self.create = async_to_raw_response_wrapper( + self.create = _legacy_response.async_to_raw_response_wrapper( + files.create, + ) + self.retrieve = _legacy_response.async_to_raw_response_wrapper( + files.retrieve, + ) + self.list = _legacy_response.async_to_raw_response_wrapper( + files.list, + ) + self.delete = _legacy_response.async_to_raw_response_wrapper( + files.delete, + ) + + +class FilesWithStreamingResponse: + def __init__(self, files: Files) -> None: + self.create = to_streamed_response_wrapper( + files.create, + ) + self.retrieve = to_streamed_response_wrapper( + files.retrieve, + ) + self.list = to_streamed_response_wrapper( + files.list, + ) + self.delete = to_streamed_response_wrapper( + files.delete, + ) + + +class AsyncFilesWithStreamingResponse: + def __init__(self, files: AsyncFiles) -> None: + self.create = async_to_streamed_response_wrapper( files.create, ) - self.retrieve = async_to_raw_response_wrapper( + self.retrieve = async_to_streamed_response_wrapper( files.retrieve, ) - self.list = async_to_raw_response_wrapper( + self.list = async_to_streamed_response_wrapper( files.list, ) - self.delete = async_to_raw_response_wrapper( + self.delete = async_to_streamed_response_wrapper( files.delete, ) diff --git a/src/openai/resources/beta/beta.py b/src/openai/resources/beta/beta.py index d87406ac9d..b11a706d5d 100644 --- a/src/openai/resources/beta/beta.py +++ b/src/openai/resources/beta/beta.py @@ -2,9 +2,23 @@ from __future__ import annotations -from .threads import Threads, AsyncThreads, ThreadsWithRawResponse, AsyncThreadsWithRawResponse +from .threads import ( + Threads, + AsyncThreads, + ThreadsWithRawResponse, + AsyncThreadsWithRawResponse, + ThreadsWithStreamingResponse, + AsyncThreadsWithStreamingResponse, +) from ..._compat import cached_property -from .assistants import Assistants, AsyncAssistants, AssistantsWithRawResponse, AsyncAssistantsWithRawResponse +from .assistants import ( + Assistants, + AsyncAssistants, + AssistantsWithRawResponse, + AsyncAssistantsWithRawResponse, + AssistantsWithStreamingResponse, + AsyncAssistantsWithStreamingResponse, +) from ..._resource import SyncAPIResource, AsyncAPIResource from .threads.threads import Threads, AsyncThreads from .assistants.assistants import Assistants, AsyncAssistants @@ -25,6 +39,10 @@ def threads(self) -> Threads: def with_raw_response(self) -> BetaWithRawResponse: return BetaWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> BetaWithStreamingResponse: + return BetaWithStreamingResponse(self) + class AsyncBeta(AsyncAPIResource): @cached_property @@ -39,6 +57,10 @@ def threads(self) -> AsyncThreads: def with_raw_response(self) -> AsyncBetaWithRawResponse: return AsyncBetaWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> AsyncBetaWithStreamingResponse: + return AsyncBetaWithStreamingResponse(self) + class BetaWithRawResponse: def __init__(self, beta: Beta) -> None: @@ -50,3 +72,15 @@ class AsyncBetaWithRawResponse: def __init__(self, beta: AsyncBeta) -> None: self.assistants = AsyncAssistantsWithRawResponse(beta.assistants) self.threads = AsyncThreadsWithRawResponse(beta.threads) + + +class BetaWithStreamingResponse: + def __init__(self, beta: Beta) -> None: + self.assistants = AssistantsWithStreamingResponse(beta.assistants) + self.threads = ThreadsWithStreamingResponse(beta.threads) + + +class AsyncBetaWithStreamingResponse: + def __init__(self, beta: AsyncBeta) -> None: + self.assistants = AsyncAssistantsWithStreamingResponse(beta.assistants) + self.threads = AsyncThreadsWithStreamingResponse(beta.threads) diff --git a/src/openai/resources/beta/threads/__init__.py b/src/openai/resources/beta/threads/__init__.py index fe7c5e5a20..886574b327 100644 --- a/src/openai/resources/beta/threads/__init__.py +++ b/src/openai/resources/beta/threads/__init__.py @@ -1,20 +1,47 @@ # File generated from our OpenAPI spec by Stainless. -from .runs import Runs, AsyncRuns, RunsWithRawResponse, AsyncRunsWithRawResponse -from .threads import Threads, AsyncThreads, ThreadsWithRawResponse, AsyncThreadsWithRawResponse -from .messages import Messages, AsyncMessages, MessagesWithRawResponse, AsyncMessagesWithRawResponse +from .runs import ( + Runs, + AsyncRuns, + RunsWithRawResponse, + AsyncRunsWithRawResponse, + RunsWithStreamingResponse, + AsyncRunsWithStreamingResponse, +) +from .threads import ( + Threads, + AsyncThreads, + ThreadsWithRawResponse, + AsyncThreadsWithRawResponse, + ThreadsWithStreamingResponse, + AsyncThreadsWithStreamingResponse, +) +from .messages import ( + Messages, + AsyncMessages, + MessagesWithRawResponse, + AsyncMessagesWithRawResponse, + MessagesWithStreamingResponse, + AsyncMessagesWithStreamingResponse, +) __all__ = [ "Runs", "AsyncRuns", "RunsWithRawResponse", "AsyncRunsWithRawResponse", + "RunsWithStreamingResponse", + "AsyncRunsWithStreamingResponse", "Messages", "AsyncMessages", "MessagesWithRawResponse", "AsyncMessagesWithRawResponse", + "MessagesWithStreamingResponse", + "AsyncMessagesWithStreamingResponse", "Threads", "AsyncThreads", "ThreadsWithRawResponse", "AsyncThreadsWithRawResponse", + "ThreadsWithStreamingResponse", + "AsyncThreadsWithStreamingResponse", ] diff --git a/src/openai/resources/beta/threads/messages/__init__.py b/src/openai/resources/beta/threads/messages/__init__.py index cef618ed14..0acb0ab201 100644 --- a/src/openai/resources/beta/threads/messages/__init__.py +++ b/src/openai/resources/beta/threads/messages/__init__.py @@ -1,15 +1,33 @@ # File generated from our OpenAPI spec by Stainless. -from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from .messages import Messages, AsyncMessages, MessagesWithRawResponse, AsyncMessagesWithRawResponse +from .files import ( + Files, + AsyncFiles, + FilesWithRawResponse, + AsyncFilesWithRawResponse, + FilesWithStreamingResponse, + AsyncFilesWithStreamingResponse, +) +from .messages import ( + Messages, + AsyncMessages, + MessagesWithRawResponse, + AsyncMessagesWithRawResponse, + MessagesWithStreamingResponse, + AsyncMessagesWithStreamingResponse, +) __all__ = [ "Files", "AsyncFiles", "FilesWithRawResponse", "AsyncFilesWithRawResponse", + "FilesWithStreamingResponse", + "AsyncFilesWithStreamingResponse", "Messages", "AsyncMessages", "MessagesWithRawResponse", "AsyncMessagesWithRawResponse", + "MessagesWithStreamingResponse", + "AsyncMessagesWithStreamingResponse", ] diff --git a/src/openai/resources/beta/threads/messages/files.py b/src/openai/resources/beta/threads/messages/files.py index 4b95b200eb..d0a963f1ae 100644 --- a/src/openai/resources/beta/threads/messages/files.py +++ b/src/openai/resources/beta/threads/messages/files.py @@ -6,11 +6,12 @@ import httpx +from ..... import _legacy_response from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import maybe_transform from ....._compat import cached_property from ....._resource import SyncAPIResource, AsyncAPIResource -from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from ....._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from .....pagination import SyncCursorPage, AsyncCursorPage from ....._base_client import ( AsyncPaginator, @@ -26,6 +27,10 @@ class Files(SyncAPIResource): def with_raw_response(self) -> FilesWithRawResponse: return FilesWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> FilesWithStreamingResponse: + return FilesWithStreamingResponse(self) + def retrieve( self, file_id: str, @@ -133,6 +138,10 @@ class AsyncFiles(AsyncAPIResource): def with_raw_response(self) -> AsyncFilesWithRawResponse: return AsyncFilesWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> AsyncFilesWithStreamingResponse: + return AsyncFilesWithStreamingResponse(self) + async def retrieve( self, file_id: str, @@ -237,19 +246,39 @@ def list( class FilesWithRawResponse: def __init__(self, files: Files) -> None: - self.retrieve = to_raw_response_wrapper( + self.retrieve = _legacy_response.to_raw_response_wrapper( files.retrieve, ) - self.list = to_raw_response_wrapper( + self.list = _legacy_response.to_raw_response_wrapper( files.list, ) class AsyncFilesWithRawResponse: def __init__(self, files: AsyncFiles) -> None: - self.retrieve = async_to_raw_response_wrapper( + self.retrieve = _legacy_response.async_to_raw_response_wrapper( + files.retrieve, + ) + self.list = _legacy_response.async_to_raw_response_wrapper( + files.list, + ) + + +class FilesWithStreamingResponse: + def __init__(self, files: Files) -> None: + self.retrieve = to_streamed_response_wrapper( + files.retrieve, + ) + self.list = to_streamed_response_wrapper( + files.list, + ) + + +class AsyncFilesWithStreamingResponse: + def __init__(self, files: AsyncFiles) -> None: + self.retrieve = async_to_streamed_response_wrapper( files.retrieve, ) - self.list = async_to_raw_response_wrapper( + self.list = async_to_streamed_response_wrapper( files.list, ) diff --git a/src/openai/resources/beta/threads/messages/messages.py b/src/openai/resources/beta/threads/messages/messages.py index 146f665624..1a15dd36ca 100644 --- a/src/openai/resources/beta/threads/messages/messages.py +++ b/src/openai/resources/beta/threads/messages/messages.py @@ -7,12 +7,20 @@ import httpx -from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse +from ..... import _legacy_response +from .files import ( + Files, + AsyncFiles, + FilesWithRawResponse, + AsyncFilesWithRawResponse, + FilesWithStreamingResponse, + AsyncFilesWithStreamingResponse, +) from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import maybe_transform from ....._compat import cached_property from ....._resource import SyncAPIResource, AsyncAPIResource -from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from ....._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from .....pagination import SyncCursorPage, AsyncCursorPage from ....._base_client import ( AsyncPaginator, @@ -32,6 +40,10 @@ def files(self) -> Files: def with_raw_response(self) -> MessagesWithRawResponse: return MessagesWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> MessagesWithStreamingResponse: + return MessagesWithStreamingResponse(self) + def create( self, thread_id: str, @@ -240,6 +252,10 @@ def files(self) -> AsyncFiles: def with_raw_response(self) -> AsyncMessagesWithRawResponse: return AsyncMessagesWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> AsyncMessagesWithStreamingResponse: + return AsyncMessagesWithStreamingResponse(self) + async def create( self, thread_id: str, @@ -443,16 +459,16 @@ class MessagesWithRawResponse: def __init__(self, messages: Messages) -> None: self.files = FilesWithRawResponse(messages.files) - self.create = to_raw_response_wrapper( + self.create = _legacy_response.to_raw_response_wrapper( messages.create, ) - self.retrieve = to_raw_response_wrapper( + self.retrieve = _legacy_response.to_raw_response_wrapper( messages.retrieve, ) - self.update = to_raw_response_wrapper( + self.update = _legacy_response.to_raw_response_wrapper( messages.update, ) - self.list = to_raw_response_wrapper( + self.list = _legacy_response.to_raw_response_wrapper( messages.list, ) @@ -461,15 +477,51 @@ class AsyncMessagesWithRawResponse: def __init__(self, messages: AsyncMessages) -> None: self.files = AsyncFilesWithRawResponse(messages.files) - self.create = async_to_raw_response_wrapper( + self.create = _legacy_response.async_to_raw_response_wrapper( + messages.create, + ) + self.retrieve = _legacy_response.async_to_raw_response_wrapper( + messages.retrieve, + ) + self.update = _legacy_response.async_to_raw_response_wrapper( + messages.update, + ) + self.list = _legacy_response.async_to_raw_response_wrapper( + messages.list, + ) + + +class MessagesWithStreamingResponse: + def __init__(self, messages: Messages) -> None: + self.files = FilesWithStreamingResponse(messages.files) + + self.create = to_streamed_response_wrapper( + messages.create, + ) + self.retrieve = to_streamed_response_wrapper( + messages.retrieve, + ) + self.update = to_streamed_response_wrapper( + messages.update, + ) + self.list = to_streamed_response_wrapper( + messages.list, + ) + + +class AsyncMessagesWithStreamingResponse: + def __init__(self, messages: AsyncMessages) -> None: + self.files = AsyncFilesWithStreamingResponse(messages.files) + + self.create = async_to_streamed_response_wrapper( messages.create, ) - self.retrieve = async_to_raw_response_wrapper( + self.retrieve = async_to_streamed_response_wrapper( messages.retrieve, ) - self.update = async_to_raw_response_wrapper( + self.update = async_to_streamed_response_wrapper( messages.update, ) - self.list = async_to_raw_response_wrapper( + self.list = async_to_streamed_response_wrapper( messages.list, ) diff --git a/src/openai/resources/beta/threads/runs/__init__.py b/src/openai/resources/beta/threads/runs/__init__.py index 6b61813974..659c96acfb 100644 --- a/src/openai/resources/beta/threads/runs/__init__.py +++ b/src/openai/resources/beta/threads/runs/__init__.py @@ -1,15 +1,33 @@ # File generated from our OpenAPI spec by Stainless. -from .runs import Runs, AsyncRuns, RunsWithRawResponse, AsyncRunsWithRawResponse -from .steps import Steps, AsyncSteps, StepsWithRawResponse, AsyncStepsWithRawResponse +from .runs import ( + Runs, + AsyncRuns, + RunsWithRawResponse, + AsyncRunsWithRawResponse, + RunsWithStreamingResponse, + AsyncRunsWithStreamingResponse, +) +from .steps import ( + Steps, + AsyncSteps, + StepsWithRawResponse, + AsyncStepsWithRawResponse, + StepsWithStreamingResponse, + AsyncStepsWithStreamingResponse, +) __all__ = [ "Steps", "AsyncSteps", "StepsWithRawResponse", "AsyncStepsWithRawResponse", + "StepsWithStreamingResponse", + "AsyncStepsWithStreamingResponse", "Runs", "AsyncRuns", "RunsWithRawResponse", "AsyncRunsWithRawResponse", + "RunsWithStreamingResponse", + "AsyncRunsWithStreamingResponse", ] diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 87e62eb362..eb6c974eaa 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -7,12 +7,20 @@ import httpx -from .steps import Steps, AsyncSteps, StepsWithRawResponse, AsyncStepsWithRawResponse +from ..... import _legacy_response +from .steps import ( + Steps, + AsyncSteps, + StepsWithRawResponse, + AsyncStepsWithRawResponse, + StepsWithStreamingResponse, + AsyncStepsWithStreamingResponse, +) from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import maybe_transform from ....._compat import cached_property from ....._resource import SyncAPIResource, AsyncAPIResource -from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from ....._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from .....pagination import SyncCursorPage, AsyncCursorPage from ....._base_client import ( AsyncPaginator, @@ -38,6 +46,10 @@ def steps(self) -> Steps: def with_raw_response(self) -> RunsWithRawResponse: return RunsWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> RunsWithStreamingResponse: + return RunsWithStreamingResponse(self) + def create( self, thread_id: str, @@ -335,6 +347,10 @@ def steps(self) -> AsyncSteps: def with_raw_response(self) -> AsyncRunsWithRawResponse: return AsyncRunsWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> AsyncRunsWithStreamingResponse: + return AsyncRunsWithStreamingResponse(self) + async def create( self, thread_id: str, @@ -627,22 +643,22 @@ class RunsWithRawResponse: def __init__(self, runs: Runs) -> None: self.steps = StepsWithRawResponse(runs.steps) - self.create = to_raw_response_wrapper( + self.create = _legacy_response.to_raw_response_wrapper( runs.create, ) - self.retrieve = to_raw_response_wrapper( + self.retrieve = _legacy_response.to_raw_response_wrapper( runs.retrieve, ) - self.update = to_raw_response_wrapper( + self.update = _legacy_response.to_raw_response_wrapper( runs.update, ) - self.list = to_raw_response_wrapper( + self.list = _legacy_response.to_raw_response_wrapper( runs.list, ) - self.cancel = to_raw_response_wrapper( + self.cancel = _legacy_response.to_raw_response_wrapper( runs.cancel, ) - self.submit_tool_outputs = to_raw_response_wrapper( + self.submit_tool_outputs = _legacy_response.to_raw_response_wrapper( runs.submit_tool_outputs, ) @@ -651,21 +667,69 @@ class AsyncRunsWithRawResponse: def __init__(self, runs: AsyncRuns) -> None: self.steps = AsyncStepsWithRawResponse(runs.steps) - self.create = async_to_raw_response_wrapper( + self.create = _legacy_response.async_to_raw_response_wrapper( + runs.create, + ) + self.retrieve = _legacy_response.async_to_raw_response_wrapper( + runs.retrieve, + ) + self.update = _legacy_response.async_to_raw_response_wrapper( + runs.update, + ) + self.list = _legacy_response.async_to_raw_response_wrapper( + runs.list, + ) + self.cancel = _legacy_response.async_to_raw_response_wrapper( + runs.cancel, + ) + self.submit_tool_outputs = _legacy_response.async_to_raw_response_wrapper( + runs.submit_tool_outputs, + ) + + +class RunsWithStreamingResponse: + def __init__(self, runs: Runs) -> None: + self.steps = StepsWithStreamingResponse(runs.steps) + + self.create = to_streamed_response_wrapper( + runs.create, + ) + self.retrieve = to_streamed_response_wrapper( + runs.retrieve, + ) + self.update = to_streamed_response_wrapper( + runs.update, + ) + self.list = to_streamed_response_wrapper( + runs.list, + ) + self.cancel = to_streamed_response_wrapper( + runs.cancel, + ) + self.submit_tool_outputs = to_streamed_response_wrapper( + runs.submit_tool_outputs, + ) + + +class AsyncRunsWithStreamingResponse: + def __init__(self, runs: AsyncRuns) -> None: + self.steps = AsyncStepsWithStreamingResponse(runs.steps) + + self.create = async_to_streamed_response_wrapper( runs.create, ) - self.retrieve = async_to_raw_response_wrapper( + self.retrieve = async_to_streamed_response_wrapper( runs.retrieve, ) - self.update = async_to_raw_response_wrapper( + self.update = async_to_streamed_response_wrapper( runs.update, ) - self.list = async_to_raw_response_wrapper( + self.list = async_to_streamed_response_wrapper( runs.list, ) - self.cancel = async_to_raw_response_wrapper( + self.cancel = async_to_streamed_response_wrapper( runs.cancel, ) - self.submit_tool_outputs = async_to_raw_response_wrapper( + self.submit_tool_outputs = async_to_streamed_response_wrapper( runs.submit_tool_outputs, ) diff --git a/src/openai/resources/beta/threads/runs/steps.py b/src/openai/resources/beta/threads/runs/steps.py index 439926a412..566ad9e4dc 100644 --- a/src/openai/resources/beta/threads/runs/steps.py +++ b/src/openai/resources/beta/threads/runs/steps.py @@ -6,11 +6,12 @@ import httpx +from ..... import _legacy_response from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import maybe_transform from ....._compat import cached_property from ....._resource import SyncAPIResource, AsyncAPIResource -from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from ....._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from .....pagination import SyncCursorPage, AsyncCursorPage from ....._base_client import ( AsyncPaginator, @@ -26,6 +27,10 @@ class Steps(SyncAPIResource): def with_raw_response(self) -> StepsWithRawResponse: return StepsWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> StepsWithStreamingResponse: + return StepsWithStreamingResponse(self) + def retrieve( self, step_id: str, @@ -132,6 +137,10 @@ class AsyncSteps(AsyncAPIResource): def with_raw_response(self) -> AsyncStepsWithRawResponse: return AsyncStepsWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> AsyncStepsWithStreamingResponse: + return AsyncStepsWithStreamingResponse(self) + async def retrieve( self, step_id: str, @@ -235,19 +244,39 @@ def list( class StepsWithRawResponse: def __init__(self, steps: Steps) -> None: - self.retrieve = to_raw_response_wrapper( + self.retrieve = _legacy_response.to_raw_response_wrapper( steps.retrieve, ) - self.list = to_raw_response_wrapper( + self.list = _legacy_response.to_raw_response_wrapper( steps.list, ) class AsyncStepsWithRawResponse: def __init__(self, steps: AsyncSteps) -> None: - self.retrieve = async_to_raw_response_wrapper( + self.retrieve = _legacy_response.async_to_raw_response_wrapper( + steps.retrieve, + ) + self.list = _legacy_response.async_to_raw_response_wrapper( + steps.list, + ) + + +class StepsWithStreamingResponse: + def __init__(self, steps: Steps) -> None: + self.retrieve = to_streamed_response_wrapper( + steps.retrieve, + ) + self.list = to_streamed_response_wrapper( + steps.list, + ) + + +class AsyncStepsWithStreamingResponse: + def __init__(self, steps: AsyncSteps) -> None: + self.retrieve = async_to_streamed_response_wrapper( steps.retrieve, ) - self.list = async_to_raw_response_wrapper( + self.list = async_to_streamed_response_wrapper( steps.list, ) diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 0ae409bb24..14bfbe9bba 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -6,14 +6,29 @@ import httpx -from .runs import Runs, AsyncRuns, RunsWithRawResponse, AsyncRunsWithRawResponse -from .messages import Messages, AsyncMessages, MessagesWithRawResponse, AsyncMessagesWithRawResponse +from .... import _legacy_response +from .runs import ( + Runs, + AsyncRuns, + RunsWithRawResponse, + AsyncRunsWithRawResponse, + RunsWithStreamingResponse, + AsyncRunsWithStreamingResponse, +) +from .messages import ( + Messages, + AsyncMessages, + MessagesWithRawResponse, + AsyncMessagesWithRawResponse, + MessagesWithStreamingResponse, + AsyncMessagesWithStreamingResponse, +) from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ...._utils import maybe_transform from .runs.runs import Runs, AsyncRuns from ...._compat import cached_property from ...._resource import SyncAPIResource, AsyncAPIResource -from ...._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ....types.beta import ( Thread, ThreadDeleted, @@ -43,6 +58,10 @@ def messages(self) -> Messages: def with_raw_response(self) -> ThreadsWithRawResponse: return ThreadsWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> ThreadsWithStreamingResponse: + return ThreadsWithStreamingResponse(self) + def create( self, *, @@ -278,6 +297,10 @@ def messages(self) -> AsyncMessages: def with_raw_response(self) -> AsyncThreadsWithRawResponse: return AsyncThreadsWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> AsyncThreadsWithStreamingResponse: + return AsyncThreadsWithStreamingResponse(self) + async def create( self, *, @@ -505,19 +528,19 @@ def __init__(self, threads: Threads) -> None: self.runs = RunsWithRawResponse(threads.runs) self.messages = MessagesWithRawResponse(threads.messages) - self.create = to_raw_response_wrapper( + self.create = _legacy_response.to_raw_response_wrapper( threads.create, ) - self.retrieve = to_raw_response_wrapper( + self.retrieve = _legacy_response.to_raw_response_wrapper( threads.retrieve, ) - self.update = to_raw_response_wrapper( + self.update = _legacy_response.to_raw_response_wrapper( threads.update, ) - self.delete = to_raw_response_wrapper( + self.delete = _legacy_response.to_raw_response_wrapper( threads.delete, ) - self.create_and_run = to_raw_response_wrapper( + self.create_and_run = _legacy_response.to_raw_response_wrapper( threads.create_and_run, ) @@ -527,18 +550,62 @@ def __init__(self, threads: AsyncThreads) -> None: self.runs = AsyncRunsWithRawResponse(threads.runs) self.messages = AsyncMessagesWithRawResponse(threads.messages) - self.create = async_to_raw_response_wrapper( + self.create = _legacy_response.async_to_raw_response_wrapper( + threads.create, + ) + self.retrieve = _legacy_response.async_to_raw_response_wrapper( + threads.retrieve, + ) + self.update = _legacy_response.async_to_raw_response_wrapper( + threads.update, + ) + self.delete = _legacy_response.async_to_raw_response_wrapper( + threads.delete, + ) + self.create_and_run = _legacy_response.async_to_raw_response_wrapper( + threads.create_and_run, + ) + + +class ThreadsWithStreamingResponse: + def __init__(self, threads: Threads) -> None: + self.runs = RunsWithStreamingResponse(threads.runs) + self.messages = MessagesWithStreamingResponse(threads.messages) + + self.create = to_streamed_response_wrapper( + threads.create, + ) + self.retrieve = to_streamed_response_wrapper( + threads.retrieve, + ) + self.update = to_streamed_response_wrapper( + threads.update, + ) + self.delete = to_streamed_response_wrapper( + threads.delete, + ) + self.create_and_run = to_streamed_response_wrapper( + threads.create_and_run, + ) + + +class AsyncThreadsWithStreamingResponse: + def __init__(self, threads: AsyncThreads) -> None: + self.runs = AsyncRunsWithStreamingResponse(threads.runs) + self.messages = AsyncMessagesWithStreamingResponse(threads.messages) + + self.create = async_to_streamed_response_wrapper( threads.create, ) - self.retrieve = async_to_raw_response_wrapper( + self.retrieve = async_to_streamed_response_wrapper( threads.retrieve, ) - self.update = async_to_raw_response_wrapper( + self.update = async_to_streamed_response_wrapper( threads.update, ) - self.delete = async_to_raw_response_wrapper( + self.delete = async_to_streamed_response_wrapper( threads.delete, ) - self.create_and_run = async_to_raw_response_wrapper( + self.create_and_run = async_to_streamed_response_wrapper( threads.create_and_run, ) diff --git a/src/openai/resources/chat/__init__.py b/src/openai/resources/chat/__init__.py index 85b246509e..a9668053c0 100644 --- a/src/openai/resources/chat/__init__.py +++ b/src/openai/resources/chat/__init__.py @@ -1,15 +1,33 @@ # File generated from our OpenAPI spec by Stainless. -from .chat import Chat, AsyncChat, ChatWithRawResponse, AsyncChatWithRawResponse -from .completions import Completions, AsyncCompletions, CompletionsWithRawResponse, AsyncCompletionsWithRawResponse +from .chat import ( + Chat, + AsyncChat, + ChatWithRawResponse, + AsyncChatWithRawResponse, + ChatWithStreamingResponse, + AsyncChatWithStreamingResponse, +) +from .completions import ( + Completions, + AsyncCompletions, + CompletionsWithRawResponse, + AsyncCompletionsWithRawResponse, + CompletionsWithStreamingResponse, + AsyncCompletionsWithStreamingResponse, +) __all__ = [ "Completions", "AsyncCompletions", "CompletionsWithRawResponse", "AsyncCompletionsWithRawResponse", + "CompletionsWithStreamingResponse", + "AsyncCompletionsWithStreamingResponse", "Chat", "AsyncChat", "ChatWithRawResponse", "AsyncChatWithRawResponse", + "ChatWithStreamingResponse", + "AsyncChatWithStreamingResponse", ] diff --git a/src/openai/resources/chat/chat.py b/src/openai/resources/chat/chat.py index 000520de23..467a5e401b 100644 --- a/src/openai/resources/chat/chat.py +++ b/src/openai/resources/chat/chat.py @@ -4,7 +4,14 @@ from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource -from .completions import Completions, AsyncCompletions, CompletionsWithRawResponse, AsyncCompletionsWithRawResponse +from .completions import ( + Completions, + AsyncCompletions, + CompletionsWithRawResponse, + AsyncCompletionsWithRawResponse, + CompletionsWithStreamingResponse, + AsyncCompletionsWithStreamingResponse, +) __all__ = ["Chat", "AsyncChat"] @@ -18,6 +25,10 @@ def completions(self) -> Completions: def with_raw_response(self) -> ChatWithRawResponse: return ChatWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> ChatWithStreamingResponse: + return ChatWithStreamingResponse(self) + class AsyncChat(AsyncAPIResource): @cached_property @@ -28,6 +39,10 @@ def completions(self) -> AsyncCompletions: def with_raw_response(self) -> AsyncChatWithRawResponse: return AsyncChatWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> AsyncChatWithStreamingResponse: + return AsyncChatWithStreamingResponse(self) + class ChatWithRawResponse: def __init__(self, chat: Chat) -> None: @@ -37,3 +52,13 @@ def __init__(self, chat: Chat) -> None: class AsyncChatWithRawResponse: def __init__(self, chat: AsyncChat) -> None: self.completions = AsyncCompletionsWithRawResponse(chat.completions) + + +class ChatWithStreamingResponse: + def __init__(self, chat: Chat) -> None: + self.completions = CompletionsWithStreamingResponse(chat.completions) + + +class AsyncChatWithStreamingResponse: + def __init__(self, chat: AsyncChat) -> None: + self.completions = AsyncCompletionsWithStreamingResponse(chat.completions) diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index fa096784d2..53645a9eb9 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -7,11 +7,12 @@ import httpx +from ... import _legacy_response from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ..._utils import required_args, maybe_transform from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource -from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ..._streaming import Stream, AsyncStream from ...types.chat import ( ChatCompletion, @@ -33,6 +34,10 @@ class Completions(SyncAPIResource): def with_raw_response(self) -> CompletionsWithRawResponse: return CompletionsWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> CompletionsWithStreamingResponse: + return CompletionsWithStreamingResponse(self) + @overload def create( self, @@ -681,6 +686,10 @@ class AsyncCompletions(AsyncAPIResource): def with_raw_response(self) -> AsyncCompletionsWithRawResponse: return AsyncCompletionsWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> AsyncCompletionsWithStreamingResponse: + return AsyncCompletionsWithStreamingResponse(self) + @overload async def create( self, @@ -1326,13 +1335,27 @@ async def create( class CompletionsWithRawResponse: def __init__(self, completions: Completions) -> None: - self.create = to_raw_response_wrapper( + self.create = _legacy_response.to_raw_response_wrapper( completions.create, ) class AsyncCompletionsWithRawResponse: def __init__(self, completions: AsyncCompletions) -> None: - self.create = async_to_raw_response_wrapper( + self.create = _legacy_response.async_to_raw_response_wrapper( + completions.create, + ) + + +class CompletionsWithStreamingResponse: + def __init__(self, completions: Completions) -> None: + self.create = to_streamed_response_wrapper( + completions.create, + ) + + +class AsyncCompletionsWithStreamingResponse: + def __init__(self, completions: AsyncCompletions) -> None: + self.create = async_to_streamed_response_wrapper( completions.create, ) diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index 87dd090052..43a9947524 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -7,12 +7,13 @@ import httpx +from .. import _legacy_response from ..types import Completion, completion_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import required_args, maybe_transform from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource -from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from .._streaming import Stream, AsyncStream from .._base_client import ( make_request_options, @@ -26,6 +27,10 @@ class Completions(SyncAPIResource): def with_raw_response(self) -> CompletionsWithRawResponse: return CompletionsWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> CompletionsWithStreamingResponse: + return CompletionsWithStreamingResponse(self) + @overload def create( self, @@ -536,6 +541,10 @@ class AsyncCompletions(AsyncAPIResource): def with_raw_response(self) -> AsyncCompletionsWithRawResponse: return AsyncCompletionsWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> AsyncCompletionsWithStreamingResponse: + return AsyncCompletionsWithStreamingResponse(self) + @overload async def create( self, @@ -1043,13 +1052,27 @@ async def create( class CompletionsWithRawResponse: def __init__(self, completions: Completions) -> None: - self.create = to_raw_response_wrapper( + self.create = _legacy_response.to_raw_response_wrapper( completions.create, ) class AsyncCompletionsWithRawResponse: def __init__(self, completions: AsyncCompletions) -> None: - self.create = async_to_raw_response_wrapper( + self.create = _legacy_response.async_to_raw_response_wrapper( + completions.create, + ) + + +class CompletionsWithStreamingResponse: + def __init__(self, completions: Completions) -> None: + self.create = to_streamed_response_wrapper( + completions.create, + ) + + +class AsyncCompletionsWithStreamingResponse: + def __init__(self, completions: AsyncCompletions) -> None: + self.create = async_to_streamed_response_wrapper( completions.create, ) diff --git a/src/openai/resources/embeddings.py b/src/openai/resources/embeddings.py index e93b29d45b..49ce0f2fc8 100644 --- a/src/openai/resources/embeddings.py +++ b/src/openai/resources/embeddings.py @@ -8,13 +8,14 @@ import httpx +from .. import _legacy_response from ..types import CreateEmbeddingResponse, embedding_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import is_given, maybe_transform from .._compat import cached_property from .._extras import numpy as np, has_numpy from .._resource import SyncAPIResource, AsyncAPIResource -from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from .._base_client import ( make_request_options, ) @@ -27,6 +28,10 @@ class Embeddings(SyncAPIResource): def with_raw_response(self) -> EmbeddingsWithRawResponse: return EmbeddingsWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> EmbeddingsWithStreamingResponse: + return EmbeddingsWithStreamingResponse(self) + def create( self, *, @@ -119,6 +124,10 @@ class AsyncEmbeddings(AsyncAPIResource): def with_raw_response(self) -> AsyncEmbeddingsWithRawResponse: return AsyncEmbeddingsWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> AsyncEmbeddingsWithStreamingResponse: + return AsyncEmbeddingsWithStreamingResponse(self) + async def create( self, *, @@ -208,13 +217,27 @@ def parser(obj: CreateEmbeddingResponse) -> CreateEmbeddingResponse: class EmbeddingsWithRawResponse: def __init__(self, embeddings: Embeddings) -> None: - self.create = to_raw_response_wrapper( + self.create = _legacy_response.to_raw_response_wrapper( embeddings.create, ) class AsyncEmbeddingsWithRawResponse: def __init__(self, embeddings: AsyncEmbeddings) -> None: - self.create = async_to_raw_response_wrapper( + self.create = _legacy_response.async_to_raw_response_wrapper( + embeddings.create, + ) + + +class EmbeddingsWithStreamingResponse: + def __init__(self, embeddings: Embeddings) -> None: + self.create = to_streamed_response_wrapper( + embeddings.create, + ) + + +class AsyncEmbeddingsWithStreamingResponse: + def __init__(self, embeddings: AsyncEmbeddings) -> None: + self.create = async_to_streamed_response_wrapper( embeddings.create, ) diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index 1acf6f8060..f435e70a2f 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -9,16 +9,23 @@ import httpx +from .. import _legacy_response from ..types import FileObject, FileDeleted, file_list_params, file_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from .._utils import extract_files, maybe_transform, deepcopy_minimal from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource -from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from .._response import ( + StreamedBinaryAPIResponse, + AsyncStreamedBinaryAPIResponse, + to_streamed_response_wrapper, + async_to_streamed_response_wrapper, + to_custom_streamed_response_wrapper, + async_to_custom_streamed_response_wrapper, +) from ..pagination import SyncPage, AsyncPage from .._base_client import ( AsyncPaginator, - HttpxBinaryResponseContent, make_request_options, ) @@ -30,6 +37,10 @@ class Files(SyncAPIResource): def with_raw_response(self) -> FilesWithRawResponse: return FilesWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> FilesWithStreamingResponse: + return FilesWithStreamingResponse(self) + def create( self, *, @@ -209,7 +220,7 @@ def content( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> HttpxBinaryResponseContent: + ) -> _legacy_response.HttpxBinaryResponseContent: """ Returns the contents of the specified file. @@ -227,7 +238,7 @@ def content( options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), - cast_to=HttpxBinaryResponseContent, + cast_to=_legacy_response.HttpxBinaryResponseContent, ) @typing_extensions.deprecated("The `.content()` method should be used instead") @@ -292,6 +303,10 @@ class AsyncFiles(AsyncAPIResource): def with_raw_response(self) -> AsyncFilesWithRawResponse: return AsyncFilesWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> AsyncFilesWithStreamingResponse: + return AsyncFilesWithStreamingResponse(self) + async def create( self, *, @@ -471,7 +486,7 @@ async def content( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> HttpxBinaryResponseContent: + ) -> _legacy_response.HttpxBinaryResponseContent: """ Returns the contents of the specified file. @@ -489,7 +504,7 @@ async def content( options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), - cast_to=HttpxBinaryResponseContent, + cast_to=_legacy_response.HttpxBinaryResponseContent, ) @typing_extensions.deprecated("The `.content()` method should be used instead") @@ -551,43 +566,97 @@ async def wait_for_processing( class FilesWithRawResponse: def __init__(self, files: Files) -> None: - self.create = to_raw_response_wrapper( + self.create = _legacy_response.to_raw_response_wrapper( files.create, ) - self.retrieve = to_raw_response_wrapper( + self.retrieve = _legacy_response.to_raw_response_wrapper( files.retrieve, ) - self.list = to_raw_response_wrapper( + self.list = _legacy_response.to_raw_response_wrapper( files.list, ) - self.delete = to_raw_response_wrapper( + self.delete = _legacy_response.to_raw_response_wrapper( files.delete, ) - self.content = to_raw_response_wrapper( + self.content = _legacy_response.to_raw_response_wrapper( files.content, ) - self.retrieve_content = to_raw_response_wrapper( # pyright: ignore[reportDeprecated] - files.retrieve_content # pyright: ignore[reportDeprecated], + self.retrieve_content = ( # pyright: ignore[reportDeprecated] + _legacy_response.to_raw_response_wrapper( + files.retrieve_content # pyright: ignore[reportDeprecated], + ) ) class AsyncFilesWithRawResponse: def __init__(self, files: AsyncFiles) -> None: - self.create = async_to_raw_response_wrapper( + self.create = _legacy_response.async_to_raw_response_wrapper( + files.create, + ) + self.retrieve = _legacy_response.async_to_raw_response_wrapper( + files.retrieve, + ) + self.list = _legacy_response.async_to_raw_response_wrapper( + files.list, + ) + self.delete = _legacy_response.async_to_raw_response_wrapper( + files.delete, + ) + self.content = _legacy_response.async_to_raw_response_wrapper( + files.content, + ) + self.retrieve_content = ( # pyright: ignore[reportDeprecated] + _legacy_response.async_to_raw_response_wrapper( + files.retrieve_content # pyright: ignore[reportDeprecated], + ) + ) + + +class FilesWithStreamingResponse: + def __init__(self, files: Files) -> None: + self.create = to_streamed_response_wrapper( + files.create, + ) + self.retrieve = to_streamed_response_wrapper( + files.retrieve, + ) + self.list = to_streamed_response_wrapper( + files.list, + ) + self.delete = to_streamed_response_wrapper( + files.delete, + ) + self.content = to_custom_streamed_response_wrapper( + files.content, + StreamedBinaryAPIResponse, + ) + self.retrieve_content = ( # pyright: ignore[reportDeprecated] + to_streamed_response_wrapper( + files.retrieve_content # pyright: ignore[reportDeprecated], + ) + ) + + +class AsyncFilesWithStreamingResponse: + def __init__(self, files: AsyncFiles) -> None: + self.create = async_to_streamed_response_wrapper( files.create, ) - self.retrieve = async_to_raw_response_wrapper( + self.retrieve = async_to_streamed_response_wrapper( files.retrieve, ) - self.list = async_to_raw_response_wrapper( + self.list = async_to_streamed_response_wrapper( files.list, ) - self.delete = async_to_raw_response_wrapper( + self.delete = async_to_streamed_response_wrapper( files.delete, ) - self.content = async_to_raw_response_wrapper( + self.content = async_to_custom_streamed_response_wrapper( files.content, + AsyncStreamedBinaryAPIResponse, ) - self.retrieve_content = async_to_raw_response_wrapper( # pyright: ignore[reportDeprecated] - files.retrieve_content # pyright: ignore[reportDeprecated], + self.retrieve_content = ( # pyright: ignore[reportDeprecated] + async_to_streamed_response_wrapper( + files.retrieve_content # pyright: ignore[reportDeprecated], + ) ) diff --git a/src/openai/resources/fine_tuning/__init__.py b/src/openai/resources/fine_tuning/__init__.py index 27445fb707..ab0c28ef4b 100644 --- a/src/openai/resources/fine_tuning/__init__.py +++ b/src/openai/resources/fine_tuning/__init__.py @@ -1,15 +1,33 @@ # File generated from our OpenAPI spec by Stainless. -from .jobs import Jobs, AsyncJobs, JobsWithRawResponse, AsyncJobsWithRawResponse -from .fine_tuning import FineTuning, AsyncFineTuning, FineTuningWithRawResponse, AsyncFineTuningWithRawResponse +from .jobs import ( + Jobs, + AsyncJobs, + JobsWithRawResponse, + AsyncJobsWithRawResponse, + JobsWithStreamingResponse, + AsyncJobsWithStreamingResponse, +) +from .fine_tuning import ( + FineTuning, + AsyncFineTuning, + FineTuningWithRawResponse, + AsyncFineTuningWithRawResponse, + FineTuningWithStreamingResponse, + AsyncFineTuningWithStreamingResponse, +) __all__ = [ "Jobs", "AsyncJobs", "JobsWithRawResponse", "AsyncJobsWithRawResponse", + "JobsWithStreamingResponse", + "AsyncJobsWithStreamingResponse", "FineTuning", "AsyncFineTuning", "FineTuningWithRawResponse", "AsyncFineTuningWithRawResponse", + "FineTuningWithStreamingResponse", + "AsyncFineTuningWithStreamingResponse", ] diff --git a/src/openai/resources/fine_tuning/fine_tuning.py b/src/openai/resources/fine_tuning/fine_tuning.py index a5a68b08eb..197d46fb83 100644 --- a/src/openai/resources/fine_tuning/fine_tuning.py +++ b/src/openai/resources/fine_tuning/fine_tuning.py @@ -2,7 +2,14 @@ from __future__ import annotations -from .jobs import Jobs, AsyncJobs, JobsWithRawResponse, AsyncJobsWithRawResponse +from .jobs import ( + Jobs, + AsyncJobs, + JobsWithRawResponse, + AsyncJobsWithRawResponse, + JobsWithStreamingResponse, + AsyncJobsWithStreamingResponse, +) from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource @@ -18,6 +25,10 @@ def jobs(self) -> Jobs: def with_raw_response(self) -> FineTuningWithRawResponse: return FineTuningWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> FineTuningWithStreamingResponse: + return FineTuningWithStreamingResponse(self) + class AsyncFineTuning(AsyncAPIResource): @cached_property @@ -28,6 +39,10 @@ def jobs(self) -> AsyncJobs: def with_raw_response(self) -> AsyncFineTuningWithRawResponse: return AsyncFineTuningWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> AsyncFineTuningWithStreamingResponse: + return AsyncFineTuningWithStreamingResponse(self) + class FineTuningWithRawResponse: def __init__(self, fine_tuning: FineTuning) -> None: @@ -37,3 +52,13 @@ def __init__(self, fine_tuning: FineTuning) -> None: class AsyncFineTuningWithRawResponse: def __init__(self, fine_tuning: AsyncFineTuning) -> None: self.jobs = AsyncJobsWithRawResponse(fine_tuning.jobs) + + +class FineTuningWithStreamingResponse: + def __init__(self, fine_tuning: FineTuning) -> None: + self.jobs = JobsWithStreamingResponse(fine_tuning.jobs) + + +class AsyncFineTuningWithStreamingResponse: + def __init__(self, fine_tuning: AsyncFineTuning) -> None: + self.jobs = AsyncJobsWithStreamingResponse(fine_tuning.jobs) diff --git a/src/openai/resources/fine_tuning/jobs.py b/src/openai/resources/fine_tuning/jobs.py index 7537b48daa..f337b136a6 100644 --- a/src/openai/resources/fine_tuning/jobs.py +++ b/src/openai/resources/fine_tuning/jobs.py @@ -7,11 +7,12 @@ import httpx +from ... import _legacy_response from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ..._utils import maybe_transform from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource -from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ...pagination import SyncCursorPage, AsyncCursorPage from ..._base_client import ( AsyncPaginator, @@ -33,6 +34,10 @@ class Jobs(SyncAPIResource): def with_raw_response(self) -> JobsWithRawResponse: return JobsWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> JobsWithStreamingResponse: + return JobsWithStreamingResponse(self) + def create( self, *, @@ -284,6 +289,10 @@ class AsyncJobs(AsyncAPIResource): def with_raw_response(self) -> AsyncJobsWithRawResponse: return AsyncJobsWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> AsyncJobsWithStreamingResponse: + return AsyncJobsWithStreamingResponse(self) + async def create( self, *, @@ -532,37 +541,75 @@ def list_events( class JobsWithRawResponse: def __init__(self, jobs: Jobs) -> None: - self.create = to_raw_response_wrapper( + self.create = _legacy_response.to_raw_response_wrapper( jobs.create, ) - self.retrieve = to_raw_response_wrapper( + self.retrieve = _legacy_response.to_raw_response_wrapper( jobs.retrieve, ) - self.list = to_raw_response_wrapper( + self.list = _legacy_response.to_raw_response_wrapper( jobs.list, ) - self.cancel = to_raw_response_wrapper( + self.cancel = _legacy_response.to_raw_response_wrapper( jobs.cancel, ) - self.list_events = to_raw_response_wrapper( + self.list_events = _legacy_response.to_raw_response_wrapper( jobs.list_events, ) class AsyncJobsWithRawResponse: def __init__(self, jobs: AsyncJobs) -> None: - self.create = async_to_raw_response_wrapper( + self.create = _legacy_response.async_to_raw_response_wrapper( + jobs.create, + ) + self.retrieve = _legacy_response.async_to_raw_response_wrapper( + jobs.retrieve, + ) + self.list = _legacy_response.async_to_raw_response_wrapper( + jobs.list, + ) + self.cancel = _legacy_response.async_to_raw_response_wrapper( + jobs.cancel, + ) + self.list_events = _legacy_response.async_to_raw_response_wrapper( + jobs.list_events, + ) + + +class JobsWithStreamingResponse: + def __init__(self, jobs: Jobs) -> None: + self.create = to_streamed_response_wrapper( + jobs.create, + ) + self.retrieve = to_streamed_response_wrapper( + jobs.retrieve, + ) + self.list = to_streamed_response_wrapper( + jobs.list, + ) + self.cancel = to_streamed_response_wrapper( + jobs.cancel, + ) + self.list_events = to_streamed_response_wrapper( + jobs.list_events, + ) + + +class AsyncJobsWithStreamingResponse: + def __init__(self, jobs: AsyncJobs) -> None: + self.create = async_to_streamed_response_wrapper( jobs.create, ) - self.retrieve = async_to_raw_response_wrapper( + self.retrieve = async_to_streamed_response_wrapper( jobs.retrieve, ) - self.list = async_to_raw_response_wrapper( + self.list = async_to_streamed_response_wrapper( jobs.list, ) - self.cancel = async_to_raw_response_wrapper( + self.cancel = async_to_streamed_response_wrapper( jobs.cancel, ) - self.list_events = async_to_raw_response_wrapper( + self.list_events = async_to_streamed_response_wrapper( jobs.list_events, ) diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py index 8e9c288af7..6f1de221e2 100644 --- a/src/openai/resources/images.py +++ b/src/openai/resources/images.py @@ -7,6 +7,7 @@ import httpx +from .. import _legacy_response from ..types import ( ImagesResponse, image_edit_params, @@ -17,7 +18,7 @@ from .._utils import extract_files, maybe_transform, deepcopy_minimal from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource -from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from .._base_client import ( make_request_options, ) @@ -30,6 +31,10 @@ class Images(SyncAPIResource): def with_raw_response(self) -> ImagesWithRawResponse: return ImagesWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> ImagesWithStreamingResponse: + return ImagesWithStreamingResponse(self) + def create_variation( self, *, @@ -273,6 +278,10 @@ class AsyncImages(AsyncAPIResource): def with_raw_response(self) -> AsyncImagesWithRawResponse: return AsyncImagesWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> AsyncImagesWithStreamingResponse: + return AsyncImagesWithStreamingResponse(self) + async def create_variation( self, *, @@ -513,25 +522,51 @@ async def generate( class ImagesWithRawResponse: def __init__(self, images: Images) -> None: - self.create_variation = to_raw_response_wrapper( + self.create_variation = _legacy_response.to_raw_response_wrapper( images.create_variation, ) - self.edit = to_raw_response_wrapper( + self.edit = _legacy_response.to_raw_response_wrapper( images.edit, ) - self.generate = to_raw_response_wrapper( + self.generate = _legacy_response.to_raw_response_wrapper( images.generate, ) class AsyncImagesWithRawResponse: def __init__(self, images: AsyncImages) -> None: - self.create_variation = async_to_raw_response_wrapper( + self.create_variation = _legacy_response.async_to_raw_response_wrapper( + images.create_variation, + ) + self.edit = _legacy_response.async_to_raw_response_wrapper( + images.edit, + ) + self.generate = _legacy_response.async_to_raw_response_wrapper( + images.generate, + ) + + +class ImagesWithStreamingResponse: + def __init__(self, images: Images) -> None: + self.create_variation = to_streamed_response_wrapper( + images.create_variation, + ) + self.edit = to_streamed_response_wrapper( + images.edit, + ) + self.generate = to_streamed_response_wrapper( + images.generate, + ) + + +class AsyncImagesWithStreamingResponse: + def __init__(self, images: AsyncImages) -> None: + self.create_variation = async_to_streamed_response_wrapper( images.create_variation, ) - self.edit = async_to_raw_response_wrapper( + self.edit = async_to_streamed_response_wrapper( images.edit, ) - self.generate = async_to_raw_response_wrapper( + self.generate = async_to_streamed_response_wrapper( images.generate, ) diff --git a/src/openai/resources/models.py b/src/openai/resources/models.py index 48888d98b5..b431ef84fc 100644 --- a/src/openai/resources/models.py +++ b/src/openai/resources/models.py @@ -4,11 +4,12 @@ import httpx +from .. import _legacy_response from ..types import Model, ModelDeleted from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource -from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ..pagination import SyncPage, AsyncPage from .._base_client import ( AsyncPaginator, @@ -23,6 +24,10 @@ class Models(SyncAPIResource): def with_raw_response(self) -> ModelsWithRawResponse: return ModelsWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> ModelsWithStreamingResponse: + return ModelsWithStreamingResponse(self) + def retrieve( self, model: str, @@ -117,6 +122,10 @@ class AsyncModels(AsyncAPIResource): def with_raw_response(self) -> AsyncModelsWithRawResponse: return AsyncModelsWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> AsyncModelsWithStreamingResponse: + return AsyncModelsWithStreamingResponse(self) + async def retrieve( self, model: str, @@ -208,25 +217,51 @@ async def delete( class ModelsWithRawResponse: def __init__(self, models: Models) -> None: - self.retrieve = to_raw_response_wrapper( + self.retrieve = _legacy_response.to_raw_response_wrapper( models.retrieve, ) - self.list = to_raw_response_wrapper( + self.list = _legacy_response.to_raw_response_wrapper( models.list, ) - self.delete = to_raw_response_wrapper( + self.delete = _legacy_response.to_raw_response_wrapper( models.delete, ) class AsyncModelsWithRawResponse: def __init__(self, models: AsyncModels) -> None: - self.retrieve = async_to_raw_response_wrapper( + self.retrieve = _legacy_response.async_to_raw_response_wrapper( + models.retrieve, + ) + self.list = _legacy_response.async_to_raw_response_wrapper( + models.list, + ) + self.delete = _legacy_response.async_to_raw_response_wrapper( + models.delete, + ) + + +class ModelsWithStreamingResponse: + def __init__(self, models: Models) -> None: + self.retrieve = to_streamed_response_wrapper( + models.retrieve, + ) + self.list = to_streamed_response_wrapper( + models.list, + ) + self.delete = to_streamed_response_wrapper( + models.delete, + ) + + +class AsyncModelsWithStreamingResponse: + def __init__(self, models: AsyncModels) -> None: + self.retrieve = async_to_streamed_response_wrapper( models.retrieve, ) - self.list = async_to_raw_response_wrapper( + self.list = async_to_streamed_response_wrapper( models.list, ) - self.delete = async_to_raw_response_wrapper( + self.delete = async_to_streamed_response_wrapper( models.delete, ) diff --git a/src/openai/resources/moderations.py b/src/openai/resources/moderations.py index 120a499186..e7681f6263 100644 --- a/src/openai/resources/moderations.py +++ b/src/openai/resources/moderations.py @@ -7,12 +7,13 @@ import httpx +from .. import _legacy_response from ..types import ModerationCreateResponse, moderation_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import maybe_transform from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource -from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper +from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from .._base_client import ( make_request_options, ) @@ -25,6 +26,10 @@ class Moderations(SyncAPIResource): def with_raw_response(self) -> ModerationsWithRawResponse: return ModerationsWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> ModerationsWithStreamingResponse: + return ModerationsWithStreamingResponse(self) + def create( self, *, @@ -81,6 +86,10 @@ class AsyncModerations(AsyncAPIResource): def with_raw_response(self) -> AsyncModerationsWithRawResponse: return AsyncModerationsWithRawResponse(self) + @cached_property + def with_streaming_response(self) -> AsyncModerationsWithStreamingResponse: + return AsyncModerationsWithStreamingResponse(self) + async def create( self, *, @@ -134,13 +143,27 @@ async def create( class ModerationsWithRawResponse: def __init__(self, moderations: Moderations) -> None: - self.create = to_raw_response_wrapper( + self.create = _legacy_response.to_raw_response_wrapper( moderations.create, ) class AsyncModerationsWithRawResponse: def __init__(self, moderations: AsyncModerations) -> None: - self.create = async_to_raw_response_wrapper( + self.create = _legacy_response.async_to_raw_response_wrapper( + moderations.create, + ) + + +class ModerationsWithStreamingResponse: + def __init__(self, moderations: Moderations) -> None: + self.create = to_streamed_response_wrapper( + moderations.create, + ) + + +class AsyncModerationsWithStreamingResponse: + def __init__(self, moderations: AsyncModerations) -> None: + self.create = async_to_streamed_response_wrapper( moderations.create, ) diff --git a/tests/api_resources/audio/test_speech.py b/tests/api_resources/audio/test_speech.py index 23f5303153..a689c0d220 100644 --- a/tests/api_resources/audio/test_speech.py +++ b/tests/api_resources/audio/test_speech.py @@ -3,15 +3,19 @@ from __future__ import annotations import os +from typing import Any, cast import httpx import pytest from respx import MockRouter +import openai._legacy_response as _legacy_response from openai import OpenAI, AsyncOpenAI -from openai._types import BinaryResponseContent +from tests.utils import assert_matches_type from openai._client import OpenAI, AsyncOpenAI +# pyright: reportDeprecated=false + base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") api_key = "My API Key" @@ -21,7 +25,6 @@ class TestSpeech: loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) - @pytest.mark.skip(reason="Mocked tests are currently broken") @parametrize @pytest.mark.respx(base_url=base_url) def test_method_create(self, client: OpenAI, respx_mock: MockRouter) -> None: @@ -31,10 +34,9 @@ def test_method_create(self, client: OpenAI, respx_mock: MockRouter) -> None: model="string", voice="alloy", ) - assert isinstance(speech, BinaryResponseContent) + assert isinstance(speech, _legacy_response.HttpxBinaryResponseContent) assert speech.json() == {"foo": "bar"} - @pytest.mark.skip(reason="Mocked tests are currently broken") @parametrize @pytest.mark.respx(base_url=base_url) def test_method_create_with_all_params(self, client: OpenAI, respx_mock: MockRouter) -> None: @@ -46,23 +48,41 @@ def test_method_create_with_all_params(self, client: OpenAI, respx_mock: MockRou response_format="mp3", speed=0.25, ) - assert isinstance(speech, BinaryResponseContent) + assert isinstance(speech, _legacy_response.HttpxBinaryResponseContent) assert speech.json() == {"foo": "bar"} - @pytest.mark.skip(reason="Mocked tests are currently broken") @parametrize @pytest.mark.respx(base_url=base_url) def test_raw_response_create(self, client: OpenAI, respx_mock: MockRouter) -> None: respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + response = client.audio.speech.with_raw_response.create( input="string", model="string", voice="alloy", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" speech = response.parse() - assert isinstance(speech, BinaryResponseContent) - assert speech.json() == {"foo": "bar"} + assert_matches_type(_legacy_response.HttpxBinaryResponseContent, speech, path=["response"]) + + @parametrize + @pytest.mark.respx(base_url=base_url) + def test_streaming_response_create(self, client: OpenAI, respx_mock: MockRouter) -> None: + respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + with client.audio.speech.with_streaming_response.create( + input="string", + model="string", + voice="alloy", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + speech = response.parse() + assert_matches_type(bytes, speech, path=["response"]) + + assert cast(Any, response.is_closed) is True class TestAsyncSpeech: @@ -70,7 +90,6 @@ class TestAsyncSpeech: loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) - @pytest.mark.skip(reason="Mocked tests are currently broken") @parametrize @pytest.mark.respx(base_url=base_url) async def test_method_create(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: @@ -80,10 +99,9 @@ async def test_method_create(self, client: AsyncOpenAI, respx_mock: MockRouter) model="string", voice="alloy", ) - assert isinstance(speech, BinaryResponseContent) + assert isinstance(speech, _legacy_response.HttpxBinaryResponseContent) assert speech.json() == {"foo": "bar"} - @pytest.mark.skip(reason="Mocked tests are currently broken") @parametrize @pytest.mark.respx(base_url=base_url) async def test_method_create_with_all_params(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: @@ -95,20 +113,38 @@ async def test_method_create_with_all_params(self, client: AsyncOpenAI, respx_mo response_format="mp3", speed=0.25, ) - assert isinstance(speech, BinaryResponseContent) + assert isinstance(speech, _legacy_response.HttpxBinaryResponseContent) assert speech.json() == {"foo": "bar"} - @pytest.mark.skip(reason="Mocked tests are currently broken") @parametrize @pytest.mark.respx(base_url=base_url) async def test_raw_response_create(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + response = await client.audio.speech.with_raw_response.create( input="string", model="string", voice="alloy", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" speech = response.parse() - assert isinstance(speech, BinaryResponseContent) - assert speech.json() == {"foo": "bar"} + assert_matches_type(_legacy_response.HttpxBinaryResponseContent, speech, path=["response"]) + + @parametrize + @pytest.mark.respx(base_url=base_url) + async def test_streaming_response_create(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: + respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + async with client.audio.speech.with_streaming_response.create( + input="string", + model="string", + voice="alloy", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + speech = await response.parse() + assert_matches_type(bytes, speech, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/audio/test_transcriptions.py b/tests/api_resources/audio/test_transcriptions.py index aefdf1790f..992adbabd9 100644 --- a/tests/api_resources/audio/test_transcriptions.py +++ b/tests/api_resources/audio/test_transcriptions.py @@ -3,6 +3,7 @@ from __future__ import annotations import os +from typing import Any, cast import pytest @@ -46,10 +47,26 @@ def test_raw_response_create(self, client: OpenAI) -> None: file=b"raw file contents", model="whisper-1", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" transcription = response.parse() assert_matches_type(Transcription, transcription, path=["response"]) + @parametrize + def test_streaming_response_create(self, client: OpenAI) -> None: + with client.audio.transcriptions.with_streaming_response.create( + file=b"raw file contents", + model="whisper-1", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + transcription = response.parse() + assert_matches_type(Transcription, transcription, path=["response"]) + + assert cast(Any, response.is_closed) is True + class TestAsyncTranscriptions: strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -82,6 +99,22 @@ async def test_raw_response_create(self, client: AsyncOpenAI) -> None: file=b"raw file contents", model="whisper-1", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" transcription = response.parse() assert_matches_type(Transcription, transcription, path=["response"]) + + @parametrize + async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: + async with client.audio.transcriptions.with_streaming_response.create( + file=b"raw file contents", + model="whisper-1", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + transcription = await response.parse() + assert_matches_type(Transcription, transcription, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/audio/test_translations.py b/tests/api_resources/audio/test_translations.py index 0657e80eb8..913c443a79 100644 --- a/tests/api_resources/audio/test_translations.py +++ b/tests/api_resources/audio/test_translations.py @@ -3,6 +3,7 @@ from __future__ import annotations import os +from typing import Any, cast import pytest @@ -45,10 +46,26 @@ def test_raw_response_create(self, client: OpenAI) -> None: file=b"raw file contents", model="whisper-1", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" translation = response.parse() assert_matches_type(Translation, translation, path=["response"]) + @parametrize + def test_streaming_response_create(self, client: OpenAI) -> None: + with client.audio.translations.with_streaming_response.create( + file=b"raw file contents", + model="whisper-1", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + translation = response.parse() + assert_matches_type(Translation, translation, path=["response"]) + + assert cast(Any, response.is_closed) is True + class TestAsyncTranslations: strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -80,6 +97,22 @@ async def test_raw_response_create(self, client: AsyncOpenAI) -> None: file=b"raw file contents", model="whisper-1", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" translation = response.parse() assert_matches_type(Translation, translation, path=["response"]) + + @parametrize + async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: + async with client.audio.translations.with_streaming_response.create( + file=b"raw file contents", + model="whisper-1", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + translation = await response.parse() + assert_matches_type(Translation, translation, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/beta/assistants/test_files.py b/tests/api_resources/beta/assistants/test_files.py index 27c12e4475..443408bd44 100644 --- a/tests/api_resources/beta/assistants/test_files.py +++ b/tests/api_resources/beta/assistants/test_files.py @@ -3,6 +3,7 @@ from __future__ import annotations import os +from typing import Any, cast import pytest @@ -35,10 +36,26 @@ def test_raw_response_create(self, client: OpenAI) -> None: "file-abc123", file_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() assert_matches_type(AssistantFile, file, path=["response"]) + @parametrize + def test_streaming_response_create(self, client: OpenAI) -> None: + with client.beta.assistants.files.with_streaming_response.create( + "file-abc123", + file_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = response.parse() + assert_matches_type(AssistantFile, file, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_retrieve(self, client: OpenAI) -> None: file = client.beta.assistants.files.retrieve( @@ -53,10 +70,26 @@ def test_raw_response_retrieve(self, client: OpenAI) -> None: "string", assistant_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() assert_matches_type(AssistantFile, file, path=["response"]) + @parametrize + def test_streaming_response_retrieve(self, client: OpenAI) -> None: + with client.beta.assistants.files.with_streaming_response.retrieve( + "string", + assistant_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = response.parse() + assert_matches_type(AssistantFile, file, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_list(self, client: OpenAI) -> None: file = client.beta.assistants.files.list( @@ -80,10 +113,25 @@ def test_raw_response_list(self, client: OpenAI) -> None: response = client.beta.assistants.files.with_raw_response.list( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() assert_matches_type(SyncCursorPage[AssistantFile], file, path=["response"]) + @parametrize + def test_streaming_response_list(self, client: OpenAI) -> None: + with client.beta.assistants.files.with_streaming_response.list( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = response.parse() + assert_matches_type(SyncCursorPage[AssistantFile], file, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_delete(self, client: OpenAI) -> None: file = client.beta.assistants.files.delete( @@ -98,10 +146,26 @@ def test_raw_response_delete(self, client: OpenAI) -> None: "string", assistant_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() assert_matches_type(FileDeleteResponse, file, path=["response"]) + @parametrize + def test_streaming_response_delete(self, client: OpenAI) -> None: + with client.beta.assistants.files.with_streaming_response.delete( + "string", + assistant_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = response.parse() + assert_matches_type(FileDeleteResponse, file, path=["response"]) + + assert cast(Any, response.is_closed) is True + class TestAsyncFiles: strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -122,10 +186,26 @@ async def test_raw_response_create(self, client: AsyncOpenAI) -> None: "file-abc123", file_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() assert_matches_type(AssistantFile, file, path=["response"]) + @parametrize + async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: + async with client.beta.assistants.files.with_streaming_response.create( + "file-abc123", + file_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = await response.parse() + assert_matches_type(AssistantFile, file, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_retrieve(self, client: AsyncOpenAI) -> None: file = await client.beta.assistants.files.retrieve( @@ -140,10 +220,26 @@ async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: "string", assistant_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() assert_matches_type(AssistantFile, file, path=["response"]) + @parametrize + async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: + async with client.beta.assistants.files.with_streaming_response.retrieve( + "string", + assistant_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = await response.parse() + assert_matches_type(AssistantFile, file, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_list(self, client: AsyncOpenAI) -> None: file = await client.beta.assistants.files.list( @@ -167,10 +263,25 @@ async def test_raw_response_list(self, client: AsyncOpenAI) -> None: response = await client.beta.assistants.files.with_raw_response.list( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() assert_matches_type(AsyncCursorPage[AssistantFile], file, path=["response"]) + @parametrize + async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: + async with client.beta.assistants.files.with_streaming_response.list( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = await response.parse() + assert_matches_type(AsyncCursorPage[AssistantFile], file, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_delete(self, client: AsyncOpenAI) -> None: file = await client.beta.assistants.files.delete( @@ -185,6 +296,22 @@ async def test_raw_response_delete(self, client: AsyncOpenAI) -> None: "string", assistant_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() assert_matches_type(FileDeleteResponse, file, path=["response"]) + + @parametrize + async def test_streaming_response_delete(self, client: AsyncOpenAI) -> None: + async with client.beta.assistants.files.with_streaming_response.delete( + "string", + assistant_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = await response.parse() + assert_matches_type(FileDeleteResponse, file, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/beta/test_assistants.py b/tests/api_resources/beta/test_assistants.py index 97e74c61e4..fbafac03c9 100644 --- a/tests/api_resources/beta/test_assistants.py +++ b/tests/api_resources/beta/test_assistants.py @@ -3,6 +3,7 @@ from __future__ import annotations import os +from typing import Any, cast import pytest @@ -49,10 +50,25 @@ def test_raw_response_create(self, client: OpenAI) -> None: response = client.beta.assistants.with_raw_response.create( model="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" assistant = response.parse() assert_matches_type(Assistant, assistant, path=["response"]) + @parametrize + def test_streaming_response_create(self, client: OpenAI) -> None: + with client.beta.assistants.with_streaming_response.create( + model="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + assistant = response.parse() + assert_matches_type(Assistant, assistant, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_retrieve(self, client: OpenAI) -> None: assistant = client.beta.assistants.retrieve( @@ -65,10 +81,25 @@ def test_raw_response_retrieve(self, client: OpenAI) -> None: response = client.beta.assistants.with_raw_response.retrieve( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" assistant = response.parse() assert_matches_type(Assistant, assistant, path=["response"]) + @parametrize + def test_streaming_response_retrieve(self, client: OpenAI) -> None: + with client.beta.assistants.with_streaming_response.retrieve( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + assistant = response.parse() + assert_matches_type(Assistant, assistant, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_update(self, client: OpenAI) -> None: assistant = client.beta.assistants.update( @@ -95,10 +126,25 @@ def test_raw_response_update(self, client: OpenAI) -> None: response = client.beta.assistants.with_raw_response.update( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" assistant = response.parse() assert_matches_type(Assistant, assistant, path=["response"]) + @parametrize + def test_streaming_response_update(self, client: OpenAI) -> None: + with client.beta.assistants.with_streaming_response.update( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + assistant = response.parse() + assert_matches_type(Assistant, assistant, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_list(self, client: OpenAI) -> None: assistant = client.beta.assistants.list() @@ -117,10 +163,23 @@ def test_method_list_with_all_params(self, client: OpenAI) -> None: @parametrize def test_raw_response_list(self, client: OpenAI) -> None: response = client.beta.assistants.with_raw_response.list() + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" assistant = response.parse() assert_matches_type(SyncCursorPage[Assistant], assistant, path=["response"]) + @parametrize + def test_streaming_response_list(self, client: OpenAI) -> None: + with client.beta.assistants.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + assistant = response.parse() + assert_matches_type(SyncCursorPage[Assistant], assistant, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_delete(self, client: OpenAI) -> None: assistant = client.beta.assistants.delete( @@ -133,10 +192,25 @@ def test_raw_response_delete(self, client: OpenAI) -> None: response = client.beta.assistants.with_raw_response.delete( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" assistant = response.parse() assert_matches_type(AssistantDeleted, assistant, path=["response"]) + @parametrize + def test_streaming_response_delete(self, client: OpenAI) -> None: + with client.beta.assistants.with_streaming_response.delete( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + assistant = response.parse() + assert_matches_type(AssistantDeleted, assistant, path=["response"]) + + assert cast(Any, response.is_closed) is True + class TestAsyncAssistants: strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -168,10 +242,25 @@ async def test_raw_response_create(self, client: AsyncOpenAI) -> None: response = await client.beta.assistants.with_raw_response.create( model="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" assistant = response.parse() assert_matches_type(Assistant, assistant, path=["response"]) + @parametrize + async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: + async with client.beta.assistants.with_streaming_response.create( + model="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + assistant = await response.parse() + assert_matches_type(Assistant, assistant, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_retrieve(self, client: AsyncOpenAI) -> None: assistant = await client.beta.assistants.retrieve( @@ -184,10 +273,25 @@ async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: response = await client.beta.assistants.with_raw_response.retrieve( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" assistant = response.parse() assert_matches_type(Assistant, assistant, path=["response"]) + @parametrize + async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: + async with client.beta.assistants.with_streaming_response.retrieve( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + assistant = await response.parse() + assert_matches_type(Assistant, assistant, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_update(self, client: AsyncOpenAI) -> None: assistant = await client.beta.assistants.update( @@ -214,10 +318,25 @@ async def test_raw_response_update(self, client: AsyncOpenAI) -> None: response = await client.beta.assistants.with_raw_response.update( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" assistant = response.parse() assert_matches_type(Assistant, assistant, path=["response"]) + @parametrize + async def test_streaming_response_update(self, client: AsyncOpenAI) -> None: + async with client.beta.assistants.with_streaming_response.update( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + assistant = await response.parse() + assert_matches_type(Assistant, assistant, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_list(self, client: AsyncOpenAI) -> None: assistant = await client.beta.assistants.list() @@ -236,10 +355,23 @@ async def test_method_list_with_all_params(self, client: AsyncOpenAI) -> None: @parametrize async def test_raw_response_list(self, client: AsyncOpenAI) -> None: response = await client.beta.assistants.with_raw_response.list() + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" assistant = response.parse() assert_matches_type(AsyncCursorPage[Assistant], assistant, path=["response"]) + @parametrize + async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: + async with client.beta.assistants.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + assistant = await response.parse() + assert_matches_type(AsyncCursorPage[Assistant], assistant, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_delete(self, client: AsyncOpenAI) -> None: assistant = await client.beta.assistants.delete( @@ -252,6 +384,21 @@ async def test_raw_response_delete(self, client: AsyncOpenAI) -> None: response = await client.beta.assistants.with_raw_response.delete( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" assistant = response.parse() assert_matches_type(AssistantDeleted, assistant, path=["response"]) + + @parametrize + async def test_streaming_response_delete(self, client: AsyncOpenAI) -> None: + async with client.beta.assistants.with_streaming_response.delete( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + assistant = await response.parse() + assert_matches_type(AssistantDeleted, assistant, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/beta/test_threads.py b/tests/api_resources/beta/test_threads.py index 860159ffb3..488ce38c1b 100644 --- a/tests/api_resources/beta/test_threads.py +++ b/tests/api_resources/beta/test_threads.py @@ -3,6 +3,7 @@ from __future__ import annotations import os +from typing import Any, cast import pytest @@ -59,10 +60,23 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: @parametrize def test_raw_response_create(self, client: OpenAI) -> None: response = client.beta.threads.with_raw_response.create() + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" thread = response.parse() assert_matches_type(Thread, thread, path=["response"]) + @parametrize + def test_streaming_response_create(self, client: OpenAI) -> None: + with client.beta.threads.with_streaming_response.create() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + thread = response.parse() + assert_matches_type(Thread, thread, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_retrieve(self, client: OpenAI) -> None: thread = client.beta.threads.retrieve( @@ -75,10 +89,25 @@ def test_raw_response_retrieve(self, client: OpenAI) -> None: response = client.beta.threads.with_raw_response.retrieve( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" thread = response.parse() assert_matches_type(Thread, thread, path=["response"]) + @parametrize + def test_streaming_response_retrieve(self, client: OpenAI) -> None: + with client.beta.threads.with_streaming_response.retrieve( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + thread = response.parse() + assert_matches_type(Thread, thread, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_update(self, client: OpenAI) -> None: thread = client.beta.threads.update( @@ -99,10 +128,25 @@ def test_raw_response_update(self, client: OpenAI) -> None: response = client.beta.threads.with_raw_response.update( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" thread = response.parse() assert_matches_type(Thread, thread, path=["response"]) + @parametrize + def test_streaming_response_update(self, client: OpenAI) -> None: + with client.beta.threads.with_streaming_response.update( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + thread = response.parse() + assert_matches_type(Thread, thread, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_delete(self, client: OpenAI) -> None: thread = client.beta.threads.delete( @@ -115,10 +159,25 @@ def test_raw_response_delete(self, client: OpenAI) -> None: response = client.beta.threads.with_raw_response.delete( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" thread = response.parse() assert_matches_type(ThreadDeleted, thread, path=["response"]) + @parametrize + def test_streaming_response_delete(self, client: OpenAI) -> None: + with client.beta.threads.with_streaming_response.delete( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + thread = response.parse() + assert_matches_type(ThreadDeleted, thread, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_create_and_run(self, client: OpenAI) -> None: thread = client.beta.threads.create_and_run( @@ -165,10 +224,25 @@ def test_raw_response_create_and_run(self, client: OpenAI) -> None: response = client.beta.threads.with_raw_response.create_and_run( assistant_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" thread = response.parse() assert_matches_type(Run, thread, path=["response"]) + @parametrize + def test_streaming_response_create_and_run(self, client: OpenAI) -> None: + with client.beta.threads.with_streaming_response.create_and_run( + assistant_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + thread = response.parse() + assert_matches_type(Run, thread, path=["response"]) + + assert cast(Any, response.is_closed) is True + class TestAsyncThreads: strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -210,10 +284,23 @@ async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: @parametrize async def test_raw_response_create(self, client: AsyncOpenAI) -> None: response = await client.beta.threads.with_raw_response.create() + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" thread = response.parse() assert_matches_type(Thread, thread, path=["response"]) + @parametrize + async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: + async with client.beta.threads.with_streaming_response.create() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + thread = await response.parse() + assert_matches_type(Thread, thread, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_retrieve(self, client: AsyncOpenAI) -> None: thread = await client.beta.threads.retrieve( @@ -226,10 +313,25 @@ async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: response = await client.beta.threads.with_raw_response.retrieve( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" thread = response.parse() assert_matches_type(Thread, thread, path=["response"]) + @parametrize + async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: + async with client.beta.threads.with_streaming_response.retrieve( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + thread = await response.parse() + assert_matches_type(Thread, thread, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_update(self, client: AsyncOpenAI) -> None: thread = await client.beta.threads.update( @@ -250,10 +352,25 @@ async def test_raw_response_update(self, client: AsyncOpenAI) -> None: response = await client.beta.threads.with_raw_response.update( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" thread = response.parse() assert_matches_type(Thread, thread, path=["response"]) + @parametrize + async def test_streaming_response_update(self, client: AsyncOpenAI) -> None: + async with client.beta.threads.with_streaming_response.update( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + thread = await response.parse() + assert_matches_type(Thread, thread, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_delete(self, client: AsyncOpenAI) -> None: thread = await client.beta.threads.delete( @@ -266,10 +383,25 @@ async def test_raw_response_delete(self, client: AsyncOpenAI) -> None: response = await client.beta.threads.with_raw_response.delete( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" thread = response.parse() assert_matches_type(ThreadDeleted, thread, path=["response"]) + @parametrize + async def test_streaming_response_delete(self, client: AsyncOpenAI) -> None: + async with client.beta.threads.with_streaming_response.delete( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + thread = await response.parse() + assert_matches_type(ThreadDeleted, thread, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_create_and_run(self, client: AsyncOpenAI) -> None: thread = await client.beta.threads.create_and_run( @@ -316,6 +448,21 @@ async def test_raw_response_create_and_run(self, client: AsyncOpenAI) -> None: response = await client.beta.threads.with_raw_response.create_and_run( assistant_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" thread = response.parse() assert_matches_type(Run, thread, path=["response"]) + + @parametrize + async def test_streaming_response_create_and_run(self, client: AsyncOpenAI) -> None: + async with client.beta.threads.with_streaming_response.create_and_run( + assistant_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + thread = await response.parse() + assert_matches_type(Run, thread, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/beta/threads/messages/test_files.py b/tests/api_resources/beta/threads/messages/test_files.py index b97e4debd5..5de352c0d2 100644 --- a/tests/api_resources/beta/threads/messages/test_files.py +++ b/tests/api_resources/beta/threads/messages/test_files.py @@ -3,6 +3,7 @@ from __future__ import annotations import os +from typing import Any, cast import pytest @@ -37,10 +38,27 @@ def test_raw_response_retrieve(self, client: OpenAI) -> None: thread_id="thread_abc123", message_id="msg_abc123", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() assert_matches_type(MessageFile, file, path=["response"]) + @parametrize + def test_streaming_response_retrieve(self, client: OpenAI) -> None: + with client.beta.threads.messages.files.with_streaming_response.retrieve( + "file-abc123", + thread_id="thread_abc123", + message_id="msg_abc123", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = response.parse() + assert_matches_type(MessageFile, file, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_list(self, client: OpenAI) -> None: file = client.beta.threads.messages.files.list( @@ -67,10 +85,26 @@ def test_raw_response_list(self, client: OpenAI) -> None: "string", thread_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() assert_matches_type(SyncCursorPage[MessageFile], file, path=["response"]) + @parametrize + def test_streaming_response_list(self, client: OpenAI) -> None: + with client.beta.threads.messages.files.with_streaming_response.list( + "string", + thread_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = response.parse() + assert_matches_type(SyncCursorPage[MessageFile], file, path=["response"]) + + assert cast(Any, response.is_closed) is True + class TestAsyncFiles: strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -93,10 +127,27 @@ async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: thread_id="thread_abc123", message_id="msg_abc123", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() assert_matches_type(MessageFile, file, path=["response"]) + @parametrize + async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: + async with client.beta.threads.messages.files.with_streaming_response.retrieve( + "file-abc123", + thread_id="thread_abc123", + message_id="msg_abc123", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = await response.parse() + assert_matches_type(MessageFile, file, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_list(self, client: AsyncOpenAI) -> None: file = await client.beta.threads.messages.files.list( @@ -123,6 +174,22 @@ async def test_raw_response_list(self, client: AsyncOpenAI) -> None: "string", thread_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() assert_matches_type(AsyncCursorPage[MessageFile], file, path=["response"]) + + @parametrize + async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: + async with client.beta.threads.messages.files.with_streaming_response.list( + "string", + thread_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = await response.parse() + assert_matches_type(AsyncCursorPage[MessageFile], file, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/beta/threads/runs/test_steps.py b/tests/api_resources/beta/threads/runs/test_steps.py index 3f4f8c1022..f13970fc14 100644 --- a/tests/api_resources/beta/threads/runs/test_steps.py +++ b/tests/api_resources/beta/threads/runs/test_steps.py @@ -3,6 +3,7 @@ from __future__ import annotations import os +from typing import Any, cast import pytest @@ -37,10 +38,27 @@ def test_raw_response_retrieve(self, client: OpenAI) -> None: thread_id="string", run_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" step = response.parse() assert_matches_type(RunStep, step, path=["response"]) + @parametrize + def test_streaming_response_retrieve(self, client: OpenAI) -> None: + with client.beta.threads.runs.steps.with_streaming_response.retrieve( + "string", + thread_id="string", + run_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + step = response.parse() + assert_matches_type(RunStep, step, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_list(self, client: OpenAI) -> None: step = client.beta.threads.runs.steps.list( @@ -67,10 +85,26 @@ def test_raw_response_list(self, client: OpenAI) -> None: "string", thread_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" step = response.parse() assert_matches_type(SyncCursorPage[RunStep], step, path=["response"]) + @parametrize + def test_streaming_response_list(self, client: OpenAI) -> None: + with client.beta.threads.runs.steps.with_streaming_response.list( + "string", + thread_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + step = response.parse() + assert_matches_type(SyncCursorPage[RunStep], step, path=["response"]) + + assert cast(Any, response.is_closed) is True + class TestAsyncSteps: strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -93,10 +127,27 @@ async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: thread_id="string", run_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" step = response.parse() assert_matches_type(RunStep, step, path=["response"]) + @parametrize + async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: + async with client.beta.threads.runs.steps.with_streaming_response.retrieve( + "string", + thread_id="string", + run_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + step = await response.parse() + assert_matches_type(RunStep, step, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_list(self, client: AsyncOpenAI) -> None: step = await client.beta.threads.runs.steps.list( @@ -123,6 +174,22 @@ async def test_raw_response_list(self, client: AsyncOpenAI) -> None: "string", thread_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" step = response.parse() assert_matches_type(AsyncCursorPage[RunStep], step, path=["response"]) + + @parametrize + async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: + async with client.beta.threads.runs.steps.with_streaming_response.list( + "string", + thread_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + step = await response.parse() + assert_matches_type(AsyncCursorPage[RunStep], step, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/beta/threads/test_messages.py b/tests/api_resources/beta/threads/test_messages.py index f3fe7dc2bb..87b6eca03a 100644 --- a/tests/api_resources/beta/threads/test_messages.py +++ b/tests/api_resources/beta/threads/test_messages.py @@ -3,6 +3,7 @@ from __future__ import annotations import os +from typing import Any, cast import pytest @@ -48,10 +49,27 @@ def test_raw_response_create(self, client: OpenAI) -> None: content="x", role="user", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" message = response.parse() assert_matches_type(ThreadMessage, message, path=["response"]) + @parametrize + def test_streaming_response_create(self, client: OpenAI) -> None: + with client.beta.threads.messages.with_streaming_response.create( + "string", + content="x", + role="user", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + message = response.parse() + assert_matches_type(ThreadMessage, message, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_retrieve(self, client: OpenAI) -> None: message = client.beta.threads.messages.retrieve( @@ -66,10 +84,26 @@ def test_raw_response_retrieve(self, client: OpenAI) -> None: "string", thread_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" message = response.parse() assert_matches_type(ThreadMessage, message, path=["response"]) + @parametrize + def test_streaming_response_retrieve(self, client: OpenAI) -> None: + with client.beta.threads.messages.with_streaming_response.retrieve( + "string", + thread_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + message = response.parse() + assert_matches_type(ThreadMessage, message, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_update(self, client: OpenAI) -> None: message = client.beta.threads.messages.update( @@ -93,10 +127,26 @@ def test_raw_response_update(self, client: OpenAI) -> None: "string", thread_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" message = response.parse() assert_matches_type(ThreadMessage, message, path=["response"]) + @parametrize + def test_streaming_response_update(self, client: OpenAI) -> None: + with client.beta.threads.messages.with_streaming_response.update( + "string", + thread_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + message = response.parse() + assert_matches_type(ThreadMessage, message, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_list(self, client: OpenAI) -> None: message = client.beta.threads.messages.list( @@ -120,10 +170,25 @@ def test_raw_response_list(self, client: OpenAI) -> None: response = client.beta.threads.messages.with_raw_response.list( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" message = response.parse() assert_matches_type(SyncCursorPage[ThreadMessage], message, path=["response"]) + @parametrize + def test_streaming_response_list(self, client: OpenAI) -> None: + with client.beta.threads.messages.with_streaming_response.list( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + message = response.parse() + assert_matches_type(SyncCursorPage[ThreadMessage], message, path=["response"]) + + assert cast(Any, response.is_closed) is True + class TestAsyncMessages: strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -157,10 +222,27 @@ async def test_raw_response_create(self, client: AsyncOpenAI) -> None: content="x", role="user", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" message = response.parse() assert_matches_type(ThreadMessage, message, path=["response"]) + @parametrize + async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: + async with client.beta.threads.messages.with_streaming_response.create( + "string", + content="x", + role="user", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + message = await response.parse() + assert_matches_type(ThreadMessage, message, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_retrieve(self, client: AsyncOpenAI) -> None: message = await client.beta.threads.messages.retrieve( @@ -175,10 +257,26 @@ async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: "string", thread_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" message = response.parse() assert_matches_type(ThreadMessage, message, path=["response"]) + @parametrize + async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: + async with client.beta.threads.messages.with_streaming_response.retrieve( + "string", + thread_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + message = await response.parse() + assert_matches_type(ThreadMessage, message, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_update(self, client: AsyncOpenAI) -> None: message = await client.beta.threads.messages.update( @@ -202,10 +300,26 @@ async def test_raw_response_update(self, client: AsyncOpenAI) -> None: "string", thread_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" message = response.parse() assert_matches_type(ThreadMessage, message, path=["response"]) + @parametrize + async def test_streaming_response_update(self, client: AsyncOpenAI) -> None: + async with client.beta.threads.messages.with_streaming_response.update( + "string", + thread_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + message = await response.parse() + assert_matches_type(ThreadMessage, message, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_list(self, client: AsyncOpenAI) -> None: message = await client.beta.threads.messages.list( @@ -229,6 +343,21 @@ async def test_raw_response_list(self, client: AsyncOpenAI) -> None: response = await client.beta.threads.messages.with_raw_response.list( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" message = response.parse() assert_matches_type(AsyncCursorPage[ThreadMessage], message, path=["response"]) + + @parametrize + async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: + async with client.beta.threads.messages.with_streaming_response.list( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + message = await response.parse() + assert_matches_type(AsyncCursorPage[ThreadMessage], message, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index 9d04a95c80..e0070c3395 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -3,6 +3,7 @@ from __future__ import annotations import os +from typing import Any, cast import pytest @@ -50,10 +51,26 @@ def test_raw_response_create(self, client: OpenAI) -> None: "string", assistant_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" run = response.parse() assert_matches_type(Run, run, path=["response"]) + @parametrize + def test_streaming_response_create(self, client: OpenAI) -> None: + with client.beta.threads.runs.with_streaming_response.create( + "string", + assistant_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + run = response.parse() + assert_matches_type(Run, run, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_retrieve(self, client: OpenAI) -> None: run = client.beta.threads.runs.retrieve( @@ -68,10 +85,26 @@ def test_raw_response_retrieve(self, client: OpenAI) -> None: "string", thread_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" run = response.parse() assert_matches_type(Run, run, path=["response"]) + @parametrize + def test_streaming_response_retrieve(self, client: OpenAI) -> None: + with client.beta.threads.runs.with_streaming_response.retrieve( + "string", + thread_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + run = response.parse() + assert_matches_type(Run, run, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_update(self, client: OpenAI) -> None: run = client.beta.threads.runs.update( @@ -95,10 +128,26 @@ def test_raw_response_update(self, client: OpenAI) -> None: "string", thread_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" run = response.parse() assert_matches_type(Run, run, path=["response"]) + @parametrize + def test_streaming_response_update(self, client: OpenAI) -> None: + with client.beta.threads.runs.with_streaming_response.update( + "string", + thread_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + run = response.parse() + assert_matches_type(Run, run, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_list(self, client: OpenAI) -> None: run = client.beta.threads.runs.list( @@ -122,10 +171,25 @@ def test_raw_response_list(self, client: OpenAI) -> None: response = client.beta.threads.runs.with_raw_response.list( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" run = response.parse() assert_matches_type(SyncCursorPage[Run], run, path=["response"]) + @parametrize + def test_streaming_response_list(self, client: OpenAI) -> None: + with client.beta.threads.runs.with_streaming_response.list( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + run = response.parse() + assert_matches_type(SyncCursorPage[Run], run, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_cancel(self, client: OpenAI) -> None: run = client.beta.threads.runs.cancel( @@ -140,10 +204,26 @@ def test_raw_response_cancel(self, client: OpenAI) -> None: "string", thread_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" run = response.parse() assert_matches_type(Run, run, path=["response"]) + @parametrize + def test_streaming_response_cancel(self, client: OpenAI) -> None: + with client.beta.threads.runs.with_streaming_response.cancel( + "string", + thread_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + run = response.parse() + assert_matches_type(Run, run, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_submit_tool_outputs(self, client: OpenAI) -> None: run = client.beta.threads.runs.submit_tool_outputs( @@ -160,10 +240,27 @@ def test_raw_response_submit_tool_outputs(self, client: OpenAI) -> None: thread_id="string", tool_outputs=[{}, {}, {}], ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" run = response.parse() assert_matches_type(Run, run, path=["response"]) + @parametrize + def test_streaming_response_submit_tool_outputs(self, client: OpenAI) -> None: + with client.beta.threads.runs.with_streaming_response.submit_tool_outputs( + "string", + thread_id="string", + tool_outputs=[{}, {}, {}], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + run = response.parse() + assert_matches_type(Run, run, path=["response"]) + + assert cast(Any, response.is_closed) is True + class TestAsyncRuns: strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -197,10 +294,26 @@ async def test_raw_response_create(self, client: AsyncOpenAI) -> None: "string", assistant_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" run = response.parse() assert_matches_type(Run, run, path=["response"]) + @parametrize + async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: + async with client.beta.threads.runs.with_streaming_response.create( + "string", + assistant_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + run = await response.parse() + assert_matches_type(Run, run, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_retrieve(self, client: AsyncOpenAI) -> None: run = await client.beta.threads.runs.retrieve( @@ -215,10 +328,26 @@ async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: "string", thread_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" run = response.parse() assert_matches_type(Run, run, path=["response"]) + @parametrize + async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: + async with client.beta.threads.runs.with_streaming_response.retrieve( + "string", + thread_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + run = await response.parse() + assert_matches_type(Run, run, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_update(self, client: AsyncOpenAI) -> None: run = await client.beta.threads.runs.update( @@ -242,10 +371,26 @@ async def test_raw_response_update(self, client: AsyncOpenAI) -> None: "string", thread_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" run = response.parse() assert_matches_type(Run, run, path=["response"]) + @parametrize + async def test_streaming_response_update(self, client: AsyncOpenAI) -> None: + async with client.beta.threads.runs.with_streaming_response.update( + "string", + thread_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + run = await response.parse() + assert_matches_type(Run, run, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_list(self, client: AsyncOpenAI) -> None: run = await client.beta.threads.runs.list( @@ -269,10 +414,25 @@ async def test_raw_response_list(self, client: AsyncOpenAI) -> None: response = await client.beta.threads.runs.with_raw_response.list( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" run = response.parse() assert_matches_type(AsyncCursorPage[Run], run, path=["response"]) + @parametrize + async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: + async with client.beta.threads.runs.with_streaming_response.list( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + run = await response.parse() + assert_matches_type(AsyncCursorPage[Run], run, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_cancel(self, client: AsyncOpenAI) -> None: run = await client.beta.threads.runs.cancel( @@ -287,10 +447,26 @@ async def test_raw_response_cancel(self, client: AsyncOpenAI) -> None: "string", thread_id="string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" run = response.parse() assert_matches_type(Run, run, path=["response"]) + @parametrize + async def test_streaming_response_cancel(self, client: AsyncOpenAI) -> None: + async with client.beta.threads.runs.with_streaming_response.cancel( + "string", + thread_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + run = await response.parse() + assert_matches_type(Run, run, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_submit_tool_outputs(self, client: AsyncOpenAI) -> None: run = await client.beta.threads.runs.submit_tool_outputs( @@ -307,6 +483,23 @@ async def test_raw_response_submit_tool_outputs(self, client: AsyncOpenAI) -> No thread_id="string", tool_outputs=[{}, {}, {}], ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" run = response.parse() assert_matches_type(Run, run, path=["response"]) + + @parametrize + async def test_streaming_response_submit_tool_outputs(self, client: AsyncOpenAI) -> None: + async with client.beta.threads.runs.with_streaming_response.submit_tool_outputs( + "string", + thread_id="string", + tool_outputs=[{}, {}, {}], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + run = await response.parse() + assert_matches_type(Run, run, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index 985d5f1c04..860ec80f48 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -3,6 +3,7 @@ from __future__ import annotations import os +from typing import Any, cast import pytest @@ -107,13 +108,34 @@ def test_raw_response_create_overload_1(self, client: OpenAI) -> None: ], model="gpt-3.5-turbo", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" completion = response.parse() assert_matches_type(ChatCompletion, completion, path=["response"]) + @parametrize + def test_streaming_response_create_overload_1(self, client: OpenAI) -> None: + with client.chat.completions.with_streaming_response.create( + messages=[ + { + "content": "string", + "role": "system", + } + ], + model="gpt-3.5-turbo", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + completion = response.parse() + assert_matches_type(ChatCompletion, completion, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_create_overload_2(self, client: OpenAI) -> None: - client.chat.completions.create( + completion_stream = client.chat.completions.create( messages=[ { "content": "string", @@ -123,10 +145,11 @@ def test_method_create_overload_2(self, client: OpenAI) -> None: model="gpt-3.5-turbo", stream=True, ) + completion_stream.response.close() @parametrize def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: - client.chat.completions.create( + completion_stream = client.chat.completions.create( messages=[ { "content": "string", @@ -185,6 +208,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: top_p=1, user="user-1234", ) + completion_stream.response.close() @parametrize def test_raw_response_create_overload_2(self, client: OpenAI) -> None: @@ -198,8 +222,30 @@ def test_raw_response_create_overload_2(self, client: OpenAI) -> None: model="gpt-3.5-turbo", stream=True, ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" - response.parse() + stream = response.parse() + stream.close() + + @parametrize + def test_streaming_response_create_overload_2(self, client: OpenAI) -> None: + with client.chat.completions.with_streaming_response.create( + messages=[ + { + "content": "string", + "role": "system", + } + ], + model="gpt-3.5-turbo", + stream=True, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + stream = response.parse() + stream.close() + + assert cast(Any, response.is_closed) is True class TestAsyncCompletions: @@ -294,13 +340,34 @@ async def test_raw_response_create_overload_1(self, client: AsyncOpenAI) -> None ], model="gpt-3.5-turbo", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" completion = response.parse() assert_matches_type(ChatCompletion, completion, path=["response"]) + @parametrize + async def test_streaming_response_create_overload_1(self, client: AsyncOpenAI) -> None: + async with client.chat.completions.with_streaming_response.create( + messages=[ + { + "content": "string", + "role": "system", + } + ], + model="gpt-3.5-turbo", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + completion = await response.parse() + assert_matches_type(ChatCompletion, completion, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_create_overload_2(self, client: AsyncOpenAI) -> None: - await client.chat.completions.create( + completion_stream = await client.chat.completions.create( messages=[ { "content": "string", @@ -310,10 +377,11 @@ async def test_method_create_overload_2(self, client: AsyncOpenAI) -> None: model="gpt-3.5-turbo", stream=True, ) + await completion_stream.response.aclose() @parametrize async def test_method_create_with_all_params_overload_2(self, client: AsyncOpenAI) -> None: - await client.chat.completions.create( + completion_stream = await client.chat.completions.create( messages=[ { "content": "string", @@ -372,6 +440,7 @@ async def test_method_create_with_all_params_overload_2(self, client: AsyncOpenA top_p=1, user="user-1234", ) + await completion_stream.response.aclose() @parametrize async def test_raw_response_create_overload_2(self, client: AsyncOpenAI) -> None: @@ -385,5 +454,27 @@ async def test_raw_response_create_overload_2(self, client: AsyncOpenAI) -> None model="gpt-3.5-turbo", stream=True, ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" - response.parse() + stream = response.parse() + await stream.close() + + @parametrize + async def test_streaming_response_create_overload_2(self, client: AsyncOpenAI) -> None: + async with client.chat.completions.with_streaming_response.create( + messages=[ + { + "content": "string", + "role": "system", + } + ], + model="gpt-3.5-turbo", + stream=True, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + stream = await response.parse() + await stream.close() + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/fine_tuning/test_jobs.py b/tests/api_resources/fine_tuning/test_jobs.py index 927ca9bbdd..3db0cdc0a5 100644 --- a/tests/api_resources/fine_tuning/test_jobs.py +++ b/tests/api_resources/fine_tuning/test_jobs.py @@ -3,6 +3,7 @@ from __future__ import annotations import os +from typing import Any, cast import pytest @@ -53,10 +54,26 @@ def test_raw_response_create(self, client: OpenAI) -> None: model="gpt-3.5-turbo", training_file="file-abc123", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" job = response.parse() assert_matches_type(FineTuningJob, job, path=["response"]) + @parametrize + def test_streaming_response_create(self, client: OpenAI) -> None: + with client.fine_tuning.jobs.with_streaming_response.create( + model="gpt-3.5-turbo", + training_file="file-abc123", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + job = response.parse() + assert_matches_type(FineTuningJob, job, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_retrieve(self, client: OpenAI) -> None: job = client.fine_tuning.jobs.retrieve( @@ -69,10 +86,25 @@ def test_raw_response_retrieve(self, client: OpenAI) -> None: response = client.fine_tuning.jobs.with_raw_response.retrieve( "ft-AF1WoRqd3aJAHsqc9NY7iL8F", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" job = response.parse() assert_matches_type(FineTuningJob, job, path=["response"]) + @parametrize + def test_streaming_response_retrieve(self, client: OpenAI) -> None: + with client.fine_tuning.jobs.with_streaming_response.retrieve( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + job = response.parse() + assert_matches_type(FineTuningJob, job, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_list(self, client: OpenAI) -> None: job = client.fine_tuning.jobs.list() @@ -89,10 +121,23 @@ def test_method_list_with_all_params(self, client: OpenAI) -> None: @parametrize def test_raw_response_list(self, client: OpenAI) -> None: response = client.fine_tuning.jobs.with_raw_response.list() + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" job = response.parse() assert_matches_type(SyncCursorPage[FineTuningJob], job, path=["response"]) + @parametrize + def test_streaming_response_list(self, client: OpenAI) -> None: + with client.fine_tuning.jobs.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + job = response.parse() + assert_matches_type(SyncCursorPage[FineTuningJob], job, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_cancel(self, client: OpenAI) -> None: job = client.fine_tuning.jobs.cancel( @@ -105,10 +150,25 @@ def test_raw_response_cancel(self, client: OpenAI) -> None: response = client.fine_tuning.jobs.with_raw_response.cancel( "ft-AF1WoRqd3aJAHsqc9NY7iL8F", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" job = response.parse() assert_matches_type(FineTuningJob, job, path=["response"]) + @parametrize + def test_streaming_response_cancel(self, client: OpenAI) -> None: + with client.fine_tuning.jobs.with_streaming_response.cancel( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + job = response.parse() + assert_matches_type(FineTuningJob, job, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_list_events(self, client: OpenAI) -> None: job = client.fine_tuning.jobs.list_events( @@ -130,10 +190,25 @@ def test_raw_response_list_events(self, client: OpenAI) -> None: response = client.fine_tuning.jobs.with_raw_response.list_events( "ft-AF1WoRqd3aJAHsqc9NY7iL8F", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" job = response.parse() assert_matches_type(SyncCursorPage[FineTuningJobEvent], job, path=["response"]) + @parametrize + def test_streaming_response_list_events(self, client: OpenAI) -> None: + with client.fine_tuning.jobs.with_streaming_response.list_events( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + job = response.parse() + assert_matches_type(SyncCursorPage[FineTuningJobEvent], job, path=["response"]) + + assert cast(Any, response.is_closed) is True + class TestAsyncJobs: strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -169,10 +244,26 @@ async def test_raw_response_create(self, client: AsyncOpenAI) -> None: model="gpt-3.5-turbo", training_file="file-abc123", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" job = response.parse() assert_matches_type(FineTuningJob, job, path=["response"]) + @parametrize + async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: + async with client.fine_tuning.jobs.with_streaming_response.create( + model="gpt-3.5-turbo", + training_file="file-abc123", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + job = await response.parse() + assert_matches_type(FineTuningJob, job, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_retrieve(self, client: AsyncOpenAI) -> None: job = await client.fine_tuning.jobs.retrieve( @@ -185,10 +276,25 @@ async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: response = await client.fine_tuning.jobs.with_raw_response.retrieve( "ft-AF1WoRqd3aJAHsqc9NY7iL8F", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" job = response.parse() assert_matches_type(FineTuningJob, job, path=["response"]) + @parametrize + async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: + async with client.fine_tuning.jobs.with_streaming_response.retrieve( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + job = await response.parse() + assert_matches_type(FineTuningJob, job, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_list(self, client: AsyncOpenAI) -> None: job = await client.fine_tuning.jobs.list() @@ -205,10 +311,23 @@ async def test_method_list_with_all_params(self, client: AsyncOpenAI) -> None: @parametrize async def test_raw_response_list(self, client: AsyncOpenAI) -> None: response = await client.fine_tuning.jobs.with_raw_response.list() + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" job = response.parse() assert_matches_type(AsyncCursorPage[FineTuningJob], job, path=["response"]) + @parametrize + async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: + async with client.fine_tuning.jobs.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + job = await response.parse() + assert_matches_type(AsyncCursorPage[FineTuningJob], job, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_cancel(self, client: AsyncOpenAI) -> None: job = await client.fine_tuning.jobs.cancel( @@ -221,10 +340,25 @@ async def test_raw_response_cancel(self, client: AsyncOpenAI) -> None: response = await client.fine_tuning.jobs.with_raw_response.cancel( "ft-AF1WoRqd3aJAHsqc9NY7iL8F", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" job = response.parse() assert_matches_type(FineTuningJob, job, path=["response"]) + @parametrize + async def test_streaming_response_cancel(self, client: AsyncOpenAI) -> None: + async with client.fine_tuning.jobs.with_streaming_response.cancel( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + job = await response.parse() + assert_matches_type(FineTuningJob, job, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_list_events(self, client: AsyncOpenAI) -> None: job = await client.fine_tuning.jobs.list_events( @@ -246,6 +380,21 @@ async def test_raw_response_list_events(self, client: AsyncOpenAI) -> None: response = await client.fine_tuning.jobs.with_raw_response.list_events( "ft-AF1WoRqd3aJAHsqc9NY7iL8F", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" job = response.parse() assert_matches_type(AsyncCursorPage[FineTuningJobEvent], job, path=["response"]) + + @parametrize + async def test_streaming_response_list_events(self, client: AsyncOpenAI) -> None: + async with client.fine_tuning.jobs.with_streaming_response.list_events( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + job = await response.parse() + assert_matches_type(AsyncCursorPage[FineTuningJobEvent], job, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/test_completions.py b/tests/api_resources/test_completions.py index b12fd6401e..a5e8dc809a 100644 --- a/tests/api_resources/test_completions.py +++ b/tests/api_resources/test_completions.py @@ -3,6 +3,7 @@ from __future__ import annotations import os +from typing import Any, cast import pytest @@ -57,21 +58,38 @@ def test_raw_response_create_overload_1(self, client: OpenAI) -> None: model="string", prompt="This is a test.", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" completion = response.parse() assert_matches_type(Completion, completion, path=["response"]) + @parametrize + def test_streaming_response_create_overload_1(self, client: OpenAI) -> None: + with client.completions.with_streaming_response.create( + model="string", + prompt="This is a test.", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + completion = response.parse() + assert_matches_type(Completion, completion, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_create_overload_2(self, client: OpenAI) -> None: - client.completions.create( + completion_stream = client.completions.create( model="string", prompt="This is a test.", stream=True, ) + completion_stream.response.close() @parametrize def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: - client.completions.create( + completion_stream = client.completions.create( model="string", prompt="This is a test.", stream=True, @@ -90,6 +108,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: top_p=1, user="user-1234", ) + completion_stream.response.close() @parametrize def test_raw_response_create_overload_2(self, client: OpenAI) -> None: @@ -98,8 +117,25 @@ def test_raw_response_create_overload_2(self, client: OpenAI) -> None: prompt="This is a test.", stream=True, ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" - response.parse() + stream = response.parse() + stream.close() + + @parametrize + def test_streaming_response_create_overload_2(self, client: OpenAI) -> None: + with client.completions.with_streaming_response.create( + model="string", + prompt="This is a test.", + stream=True, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + stream = response.parse() + stream.close() + + assert cast(Any, response.is_closed) is True class TestAsyncCompletions: @@ -144,21 +180,38 @@ async def test_raw_response_create_overload_1(self, client: AsyncOpenAI) -> None model="string", prompt="This is a test.", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" completion = response.parse() assert_matches_type(Completion, completion, path=["response"]) + @parametrize + async def test_streaming_response_create_overload_1(self, client: AsyncOpenAI) -> None: + async with client.completions.with_streaming_response.create( + model="string", + prompt="This is a test.", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + completion = await response.parse() + assert_matches_type(Completion, completion, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_create_overload_2(self, client: AsyncOpenAI) -> None: - await client.completions.create( + completion_stream = await client.completions.create( model="string", prompt="This is a test.", stream=True, ) + await completion_stream.response.aclose() @parametrize async def test_method_create_with_all_params_overload_2(self, client: AsyncOpenAI) -> None: - await client.completions.create( + completion_stream = await client.completions.create( model="string", prompt="This is a test.", stream=True, @@ -177,6 +230,7 @@ async def test_method_create_with_all_params_overload_2(self, client: AsyncOpenA top_p=1, user="user-1234", ) + await completion_stream.response.aclose() @parametrize async def test_raw_response_create_overload_2(self, client: AsyncOpenAI) -> None: @@ -185,5 +239,22 @@ async def test_raw_response_create_overload_2(self, client: AsyncOpenAI) -> None prompt="This is a test.", stream=True, ) + assert response.http_request.headers.get("X-Stainless-Lang") == "python" - response.parse() + stream = response.parse() + await stream.close() + + @parametrize + async def test_streaming_response_create_overload_2(self, client: AsyncOpenAI) -> None: + async with client.completions.with_streaming_response.create( + model="string", + prompt="This is a test.", + stream=True, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + stream = await response.parse() + await stream.close() + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/test_embeddings.py b/tests/api_resources/test_embeddings.py index faf07ffb7c..77875fc46f 100644 --- a/tests/api_resources/test_embeddings.py +++ b/tests/api_resources/test_embeddings.py @@ -3,6 +3,7 @@ from __future__ import annotations import os +from typing import Any, cast import pytest @@ -44,10 +45,26 @@ def test_raw_response_create(self, client: OpenAI) -> None: input="The quick brown fox jumped over the lazy dog", model="text-embedding-ada-002", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" embedding = response.parse() assert_matches_type(CreateEmbeddingResponse, embedding, path=["response"]) + @parametrize + def test_streaming_response_create(self, client: OpenAI) -> None: + with client.embeddings.with_streaming_response.create( + input="The quick brown fox jumped over the lazy dog", + model="text-embedding-ada-002", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + embedding = response.parse() + assert_matches_type(CreateEmbeddingResponse, embedding, path=["response"]) + + assert cast(Any, response.is_closed) is True + class TestAsyncEmbeddings: strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -78,6 +95,22 @@ async def test_raw_response_create(self, client: AsyncOpenAI) -> None: input="The quick brown fox jumped over the lazy dog", model="text-embedding-ada-002", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" embedding = response.parse() assert_matches_type(CreateEmbeddingResponse, embedding, path=["response"]) + + @parametrize + async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: + async with client.embeddings.with_streaming_response.create( + input="The quick brown fox jumped over the lazy dog", + model="text-embedding-ada-002", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + embedding = await response.parse() + assert_matches_type(CreateEmbeddingResponse, embedding, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/test_files.py b/tests/api_resources/test_files.py index 13ffca9773..e36a7839f2 100644 --- a/tests/api_resources/test_files.py +++ b/tests/api_resources/test_files.py @@ -3,15 +3,16 @@ from __future__ import annotations import os +from typing import Any, cast import httpx import pytest from respx import MockRouter +import openai._legacy_response as _legacy_response from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.types import FileObject, FileDeleted -from openai._types import BinaryResponseContent from openai._client import OpenAI, AsyncOpenAI from openai.pagination import SyncPage, AsyncPage @@ -40,10 +41,26 @@ def test_raw_response_create(self, client: OpenAI) -> None: file=b"raw file contents", purpose="fine-tune", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() assert_matches_type(FileObject, file, path=["response"]) + @parametrize + def test_streaming_response_create(self, client: OpenAI) -> None: + with client.files.with_streaming_response.create( + file=b"raw file contents", + purpose="fine-tune", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = response.parse() + assert_matches_type(FileObject, file, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_retrieve(self, client: OpenAI) -> None: file = client.files.retrieve( @@ -56,10 +73,25 @@ def test_raw_response_retrieve(self, client: OpenAI) -> None: response = client.files.with_raw_response.retrieve( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() assert_matches_type(FileObject, file, path=["response"]) + @parametrize + def test_streaming_response_retrieve(self, client: OpenAI) -> None: + with client.files.with_streaming_response.retrieve( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = response.parse() + assert_matches_type(FileObject, file, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_list(self, client: OpenAI) -> None: file = client.files.list() @@ -75,10 +107,23 @@ def test_method_list_with_all_params(self, client: OpenAI) -> None: @parametrize def test_raw_response_list(self, client: OpenAI) -> None: response = client.files.with_raw_response.list() + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() assert_matches_type(SyncPage[FileObject], file, path=["response"]) + @parametrize + def test_streaming_response_list(self, client: OpenAI) -> None: + with client.files.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = response.parse() + assert_matches_type(SyncPage[FileObject], file, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_delete(self, client: OpenAI) -> None: file = client.files.delete( @@ -91,10 +136,25 @@ def test_raw_response_delete(self, client: OpenAI) -> None: response = client.files.with_raw_response.delete( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() assert_matches_type(FileDeleted, file, path=["response"]) + @parametrize + def test_streaming_response_delete(self, client: OpenAI) -> None: + with client.files.with_streaming_response.delete( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = response.parse() + assert_matches_type(FileDeleted, file, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize @pytest.mark.respx(base_url=base_url) def test_method_content(self, client: OpenAI, respx_mock: MockRouter) -> None: @@ -102,20 +162,37 @@ def test_method_content(self, client: OpenAI, respx_mock: MockRouter) -> None: file = client.files.content( "string", ) - assert isinstance(file, BinaryResponseContent) + assert isinstance(file, _legacy_response.HttpxBinaryResponseContent) assert file.json() == {"foo": "bar"} @parametrize @pytest.mark.respx(base_url=base_url) def test_raw_response_content(self, client: OpenAI, respx_mock: MockRouter) -> None: respx_mock.get("/files/string/content").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + response = client.files.with_raw_response.content( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() - assert isinstance(file, BinaryResponseContent) - assert file.json() == {"foo": "bar"} + assert_matches_type(_legacy_response.HttpxBinaryResponseContent, file, path=["response"]) + + @parametrize + @pytest.mark.respx(base_url=base_url) + def test_streaming_response_content(self, client: OpenAI, respx_mock: MockRouter) -> None: + respx_mock.get("/files/string/content").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + with client.files.with_streaming_response.content( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = response.parse() + assert_matches_type(bytes, file, path=["response"]) + + assert cast(Any, response.is_closed) is True @parametrize def test_method_retrieve_content(self, client: OpenAI) -> None: @@ -123,6 +200,7 @@ def test_method_retrieve_content(self, client: OpenAI) -> None: file = client.files.retrieve_content( "string", ) + assert_matches_type(str, file, path=["response"]) @parametrize @@ -131,10 +209,26 @@ def test_raw_response_retrieve_content(self, client: OpenAI) -> None: response = client.files.with_raw_response.retrieve_content( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() assert_matches_type(str, file, path=["response"]) + @parametrize + def test_streaming_response_retrieve_content(self, client: OpenAI) -> None: + with pytest.warns(DeprecationWarning): + with client.files.with_streaming_response.retrieve_content( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = response.parse() + assert_matches_type(str, file, path=["response"]) + + assert cast(Any, response.is_closed) is True + class TestAsyncFiles: strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -155,10 +249,26 @@ async def test_raw_response_create(self, client: AsyncOpenAI) -> None: file=b"raw file contents", purpose="fine-tune", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() assert_matches_type(FileObject, file, path=["response"]) + @parametrize + async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: + async with client.files.with_streaming_response.create( + file=b"raw file contents", + purpose="fine-tune", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = await response.parse() + assert_matches_type(FileObject, file, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_retrieve(self, client: AsyncOpenAI) -> None: file = await client.files.retrieve( @@ -171,10 +281,25 @@ async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: response = await client.files.with_raw_response.retrieve( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() assert_matches_type(FileObject, file, path=["response"]) + @parametrize + async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: + async with client.files.with_streaming_response.retrieve( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = await response.parse() + assert_matches_type(FileObject, file, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_list(self, client: AsyncOpenAI) -> None: file = await client.files.list() @@ -190,10 +315,23 @@ async def test_method_list_with_all_params(self, client: AsyncOpenAI) -> None: @parametrize async def test_raw_response_list(self, client: AsyncOpenAI) -> None: response = await client.files.with_raw_response.list() + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() assert_matches_type(AsyncPage[FileObject], file, path=["response"]) + @parametrize + async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: + async with client.files.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = await response.parse() + assert_matches_type(AsyncPage[FileObject], file, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_delete(self, client: AsyncOpenAI) -> None: file = await client.files.delete( @@ -206,10 +344,25 @@ async def test_raw_response_delete(self, client: AsyncOpenAI) -> None: response = await client.files.with_raw_response.delete( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() assert_matches_type(FileDeleted, file, path=["response"]) + @parametrize + async def test_streaming_response_delete(self, client: AsyncOpenAI) -> None: + async with client.files.with_streaming_response.delete( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = await response.parse() + assert_matches_type(FileDeleted, file, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize @pytest.mark.respx(base_url=base_url) async def test_method_content(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: @@ -217,20 +370,37 @@ async def test_method_content(self, client: AsyncOpenAI, respx_mock: MockRouter) file = await client.files.content( "string", ) - assert isinstance(file, BinaryResponseContent) + assert isinstance(file, _legacy_response.HttpxBinaryResponseContent) assert file.json() == {"foo": "bar"} @parametrize @pytest.mark.respx(base_url=base_url) async def test_raw_response_content(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: respx_mock.get("/files/string/content").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + response = await client.files.with_raw_response.content( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() - assert isinstance(file, BinaryResponseContent) - assert file.json() == {"foo": "bar"} + assert_matches_type(_legacy_response.HttpxBinaryResponseContent, file, path=["response"]) + + @parametrize + @pytest.mark.respx(base_url=base_url) + async def test_streaming_response_content(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: + respx_mock.get("/files/string/content").mock(return_value=httpx.Response(200, json={"foo": "bar"})) + async with client.files.with_streaming_response.content( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = await response.parse() + assert_matches_type(bytes, file, path=["response"]) + + assert cast(Any, response.is_closed) is True @parametrize async def test_method_retrieve_content(self, client: AsyncOpenAI) -> None: @@ -238,6 +408,7 @@ async def test_method_retrieve_content(self, client: AsyncOpenAI) -> None: file = await client.files.retrieve_content( "string", ) + assert_matches_type(str, file, path=["response"]) @parametrize @@ -246,6 +417,22 @@ async def test_raw_response_retrieve_content(self, client: AsyncOpenAI) -> None: response = await client.files.with_raw_response.retrieve_content( "string", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() assert_matches_type(str, file, path=["response"]) + + @parametrize + async def test_streaming_response_retrieve_content(self, client: AsyncOpenAI) -> None: + with pytest.warns(DeprecationWarning): + async with client.files.with_streaming_response.retrieve_content( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = await response.parse() + assert_matches_type(str, file, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/test_images.py b/tests/api_resources/test_images.py index c7f5e5bcd2..553bd018ee 100644 --- a/tests/api_resources/test_images.py +++ b/tests/api_resources/test_images.py @@ -3,6 +3,7 @@ from __future__ import annotations import os +from typing import Any, cast import pytest @@ -44,10 +45,25 @@ def test_raw_response_create_variation(self, client: OpenAI) -> None: response = client.images.with_raw_response.create_variation( image=b"raw file contents", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" image = response.parse() assert_matches_type(ImagesResponse, image, path=["response"]) + @parametrize + def test_streaming_response_create_variation(self, client: OpenAI) -> None: + with client.images.with_streaming_response.create_variation( + image=b"raw file contents", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + image = response.parse() + assert_matches_type(ImagesResponse, image, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_edit(self, client: OpenAI) -> None: image = client.images.edit( @@ -76,10 +92,26 @@ def test_raw_response_edit(self, client: OpenAI) -> None: image=b"raw file contents", prompt="A cute baby sea otter wearing a beret", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" image = response.parse() assert_matches_type(ImagesResponse, image, path=["response"]) + @parametrize + def test_streaming_response_edit(self, client: OpenAI) -> None: + with client.images.with_streaming_response.edit( + image=b"raw file contents", + prompt="A cute baby sea otter wearing a beret", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + image = response.parse() + assert_matches_type(ImagesResponse, image, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_generate(self, client: OpenAI) -> None: image = client.images.generate( @@ -106,10 +138,25 @@ def test_raw_response_generate(self, client: OpenAI) -> None: response = client.images.with_raw_response.generate( prompt="A cute baby sea otter", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" image = response.parse() assert_matches_type(ImagesResponse, image, path=["response"]) + @parametrize + def test_streaming_response_generate(self, client: OpenAI) -> None: + with client.images.with_streaming_response.generate( + prompt="A cute baby sea otter", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + image = response.parse() + assert_matches_type(ImagesResponse, image, path=["response"]) + + assert cast(Any, response.is_closed) is True + class TestAsyncImages: strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -140,10 +187,25 @@ async def test_raw_response_create_variation(self, client: AsyncOpenAI) -> None: response = await client.images.with_raw_response.create_variation( image=b"raw file contents", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" image = response.parse() assert_matches_type(ImagesResponse, image, path=["response"]) + @parametrize + async def test_streaming_response_create_variation(self, client: AsyncOpenAI) -> None: + async with client.images.with_streaming_response.create_variation( + image=b"raw file contents", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + image = await response.parse() + assert_matches_type(ImagesResponse, image, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_edit(self, client: AsyncOpenAI) -> None: image = await client.images.edit( @@ -172,10 +234,26 @@ async def test_raw_response_edit(self, client: AsyncOpenAI) -> None: image=b"raw file contents", prompt="A cute baby sea otter wearing a beret", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" image = response.parse() assert_matches_type(ImagesResponse, image, path=["response"]) + @parametrize + async def test_streaming_response_edit(self, client: AsyncOpenAI) -> None: + async with client.images.with_streaming_response.edit( + image=b"raw file contents", + prompt="A cute baby sea otter wearing a beret", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + image = await response.parse() + assert_matches_type(ImagesResponse, image, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_generate(self, client: AsyncOpenAI) -> None: image = await client.images.generate( @@ -202,6 +280,21 @@ async def test_raw_response_generate(self, client: AsyncOpenAI) -> None: response = await client.images.with_raw_response.generate( prompt="A cute baby sea otter", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" image = response.parse() assert_matches_type(ImagesResponse, image, path=["response"]) + + @parametrize + async def test_streaming_response_generate(self, client: AsyncOpenAI) -> None: + async with client.images.with_streaming_response.generate( + prompt="A cute baby sea otter", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + image = await response.parse() + assert_matches_type(ImagesResponse, image, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/test_models.py b/tests/api_resources/test_models.py index 3998809610..5afda86a7a 100644 --- a/tests/api_resources/test_models.py +++ b/tests/api_resources/test_models.py @@ -3,6 +3,7 @@ from __future__ import annotations import os +from typing import Any, cast import pytest @@ -33,10 +34,25 @@ def test_raw_response_retrieve(self, client: OpenAI) -> None: response = client.models.with_raw_response.retrieve( "gpt-3.5-turbo", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" model = response.parse() assert_matches_type(Model, model, path=["response"]) + @parametrize + def test_streaming_response_retrieve(self, client: OpenAI) -> None: + with client.models.with_streaming_response.retrieve( + "gpt-3.5-turbo", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + model = response.parse() + assert_matches_type(Model, model, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_list(self, client: OpenAI) -> None: model = client.models.list() @@ -45,10 +61,23 @@ def test_method_list(self, client: OpenAI) -> None: @parametrize def test_raw_response_list(self, client: OpenAI) -> None: response = client.models.with_raw_response.list() + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" model = response.parse() assert_matches_type(SyncPage[Model], model, path=["response"]) + @parametrize + def test_streaming_response_list(self, client: OpenAI) -> None: + with client.models.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + model = response.parse() + assert_matches_type(SyncPage[Model], model, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_delete(self, client: OpenAI) -> None: model = client.models.delete( @@ -61,10 +90,25 @@ def test_raw_response_delete(self, client: OpenAI) -> None: response = client.models.with_raw_response.delete( "ft:gpt-3.5-turbo:acemeco:suffix:abc123", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" model = response.parse() assert_matches_type(ModelDeleted, model, path=["response"]) + @parametrize + def test_streaming_response_delete(self, client: OpenAI) -> None: + with client.models.with_streaming_response.delete( + "ft:gpt-3.5-turbo:acemeco:suffix:abc123", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + model = response.parse() + assert_matches_type(ModelDeleted, model, path=["response"]) + + assert cast(Any, response.is_closed) is True + class TestAsyncModels: strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -83,10 +127,25 @@ async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: response = await client.models.with_raw_response.retrieve( "gpt-3.5-turbo", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" model = response.parse() assert_matches_type(Model, model, path=["response"]) + @parametrize + async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: + async with client.models.with_streaming_response.retrieve( + "gpt-3.5-turbo", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + model = await response.parse() + assert_matches_type(Model, model, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_list(self, client: AsyncOpenAI) -> None: model = await client.models.list() @@ -95,10 +154,23 @@ async def test_method_list(self, client: AsyncOpenAI) -> None: @parametrize async def test_raw_response_list(self, client: AsyncOpenAI) -> None: response = await client.models.with_raw_response.list() + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" model = response.parse() assert_matches_type(AsyncPage[Model], model, path=["response"]) + @parametrize + async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: + async with client.models.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + model = await response.parse() + assert_matches_type(AsyncPage[Model], model, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_delete(self, client: AsyncOpenAI) -> None: model = await client.models.delete( @@ -111,6 +183,21 @@ async def test_raw_response_delete(self, client: AsyncOpenAI) -> None: response = await client.models.with_raw_response.delete( "ft:gpt-3.5-turbo:acemeco:suffix:abc123", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" model = response.parse() assert_matches_type(ModelDeleted, model, path=["response"]) + + @parametrize + async def test_streaming_response_delete(self, client: AsyncOpenAI) -> None: + async with client.models.with_streaming_response.delete( + "ft:gpt-3.5-turbo:acemeco:suffix:abc123", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + model = await response.parse() + assert_matches_type(ModelDeleted, model, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/test_moderations.py b/tests/api_resources/test_moderations.py index 502030d614..88d35f003d 100644 --- a/tests/api_resources/test_moderations.py +++ b/tests/api_resources/test_moderations.py @@ -3,6 +3,7 @@ from __future__ import annotations import os +from typing import Any, cast import pytest @@ -40,10 +41,25 @@ def test_raw_response_create(self, client: OpenAI) -> None: response = client.moderations.with_raw_response.create( input="I want to kill them.", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" moderation = response.parse() assert_matches_type(ModerationCreateResponse, moderation, path=["response"]) + @parametrize + def test_streaming_response_create(self, client: OpenAI) -> None: + with client.moderations.with_streaming_response.create( + input="I want to kill them.", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + moderation = response.parse() + assert_matches_type(ModerationCreateResponse, moderation, path=["response"]) + + assert cast(Any, response.is_closed) is True + class TestAsyncModerations: strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -70,6 +86,21 @@ async def test_raw_response_create(self, client: AsyncOpenAI) -> None: response = await client.moderations.with_raw_response.create( input="I want to kill them.", ) + + assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" moderation = response.parse() assert_matches_type(ModerationCreateResponse, moderation, path=["response"]) + + @parametrize + async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: + async with client.moderations.with_streaming_response.create( + input="I want to kill them.", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + moderation = await response.parse() + assert_matches_type(ModerationCreateResponse, moderation, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/test_client.py b/tests/test_client.py index c49e4d629e..7aa473fe9b 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -19,6 +19,8 @@ from openai import OpenAI, AsyncOpenAI, APIResponseValidationError from openai._client import OpenAI, AsyncOpenAI from openai._models import BaseModel, FinalRequestOptions +from openai._response import APIResponse, AsyncAPIResponse +from openai._constants import RAW_RESPONSE_HEADER from openai._streaming import Stream, AsyncStream from openai._exceptions import OpenAIError, APIStatusError, APITimeoutError, APIResponseValidationError from openai._base_client import DEFAULT_TIMEOUT, HTTPX_DEFAULT_TIMEOUT, BaseClient, make_request_options @@ -220,6 +222,7 @@ def add_leak(leaks: list[tracemalloc.StatisticDiff], diff: tracemalloc.Statistic # to_raw_response_wrapper leaks through the @functools.wraps() decorator. # # removing the decorator fixes the leak for reasons we don't understand. + "openai/_legacy_response.py", "openai/_response.py", # pydantic.BaseModel.model_dump || pydantic.BaseModel.dict leak memory for some reason. "openai/_compat.py", @@ -612,8 +615,9 @@ class Model(BaseModel): respx_mock.post("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"})) - response = self.client.post("/foo", cast_to=Model, stream=True) - assert isinstance(response, Stream) + stream = self.client.post("/foo", cast_to=Model, stream=True, stream_cls=Stream[Model]) + assert isinstance(stream, Stream) + stream.response.close() @pytest.mark.respx(base_url=base_url) def test_received_text_for_expected_json(self, respx_mock: MockRouter) -> None: @@ -661,6 +665,33 @@ def test_parse_retry_after_header(self, remaining_retries: int, retry_after: str calculated = client._calculate_retry_timeout(remaining_retries, options, headers) assert calculated == pytest.approx(timeout, 0.5 * 0.875) # pyright: ignore[reportUnknownMemberType] + @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) + @pytest.mark.respx(base_url=base_url) + def test_streaming_response(self) -> None: + response = self.client.post( + "/chat/completions", + body=dict( + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-3.5-turbo", + ), + cast_to=APIResponse[bytes], + options={"headers": {RAW_RESPONSE_HEADER: "stream"}}, + ) + + assert not cast(Any, response.is_closed) + assert _get_open_connections(self.client) == 1 + + for _ in response.iter_bytes(): + ... + + assert cast(Any, response.is_closed) + assert _get_open_connections(self.client) == 0 + @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) @pytest.mark.respx(base_url=base_url) def test_retrying_timeout_errors_doesnt_leak(self, respx_mock: MockRouter) -> None: @@ -679,7 +710,7 @@ def test_retrying_timeout_errors_doesnt_leak(self, respx_mock: MockRouter) -> No model="gpt-3.5-turbo", ), cast_to=httpx.Response, - options={"headers": {"X-Stainless-Streamed-Raw-Response": "true"}}, + options={"headers": {RAW_RESPONSE_HEADER: "stream"}}, ) assert _get_open_connections(self.client) == 0 @@ -702,7 +733,7 @@ def test_retrying_status_errors_doesnt_leak(self, respx_mock: MockRouter) -> Non model="gpt-3.5-turbo", ), cast_to=httpx.Response, - options={"headers": {"X-Stainless-Streamed-Raw-Response": "true"}}, + options={"headers": {RAW_RESPONSE_HEADER: "stream"}}, ) assert _get_open_connections(self.client) == 0 @@ -883,6 +914,7 @@ def add_leak(leaks: list[tracemalloc.StatisticDiff], diff: tracemalloc.Statistic # to_raw_response_wrapper leaks through the @functools.wraps() decorator. # # removing the decorator fixes the leak for reasons we don't understand. + "openai/_legacy_response.py", "openai/_response.py", # pydantic.BaseModel.model_dump || pydantic.BaseModel.dict leak memory for some reason. "openai/_compat.py", @@ -1288,8 +1320,9 @@ class Model(BaseModel): respx_mock.post("/foo").mock(return_value=httpx.Response(200, json={"foo": "bar"})) - response = await self.client.post("/foo", cast_to=Model, stream=True) - assert isinstance(response, AsyncStream) + stream = await self.client.post("/foo", cast_to=Model, stream=True, stream_cls=AsyncStream[Model]) + assert isinstance(stream, AsyncStream) + await stream.response.aclose() @pytest.mark.respx(base_url=base_url) @pytest.mark.asyncio @@ -1339,6 +1372,33 @@ async def test_parse_retry_after_header(self, remaining_retries: int, retry_afte calculated = client._calculate_retry_timeout(remaining_retries, options, headers) assert calculated == pytest.approx(timeout, 0.5 * 0.875) # pyright: ignore[reportUnknownMemberType] + @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) + @pytest.mark.respx(base_url=base_url) + async def test_streaming_response(self) -> None: + response = await self.client.post( + "/chat/completions", + body=dict( + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-3.5-turbo", + ), + cast_to=AsyncAPIResponse[bytes], + options={"headers": {RAW_RESPONSE_HEADER: "stream"}}, + ) + + assert not cast(Any, response.is_closed) + assert _get_open_connections(self.client) == 1 + + async for _ in response.iter_bytes(): + ... + + assert cast(Any, response.is_closed) + assert _get_open_connections(self.client) == 0 + @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) @pytest.mark.respx(base_url=base_url) async def test_retrying_timeout_errors_doesnt_leak(self, respx_mock: MockRouter) -> None: @@ -1357,7 +1417,7 @@ async def test_retrying_timeout_errors_doesnt_leak(self, respx_mock: MockRouter) model="gpt-3.5-turbo", ), cast_to=httpx.Response, - options={"headers": {"X-Stainless-Streamed-Raw-Response": "true"}}, + options={"headers": {RAW_RESPONSE_HEADER: "stream"}}, ) assert _get_open_connections(self.client) == 0 @@ -1380,7 +1440,7 @@ async def test_retrying_status_errors_doesnt_leak(self, respx_mock: MockRouter) model="gpt-3.5-turbo", ), cast_to=httpx.Response, - options={"headers": {"X-Stainless-Streamed-Raw-Response": "true"}}, + options={"headers": {RAW_RESPONSE_HEADER: "stream"}}, ) assert _get_open_connections(self.client) == 0 diff --git a/tests/test_response.py b/tests/test_response.py new file mode 100644 index 0000000000..335ca7922a --- /dev/null +++ b/tests/test_response.py @@ -0,0 +1,50 @@ +from typing import List + +import httpx +import pytest + +from openai._response import ( + APIResponse, + BaseAPIResponse, + AsyncAPIResponse, + BinaryAPIResponse, + AsyncBinaryAPIResponse, + extract_response_type, +) + + +class ConcreteBaseAPIResponse(APIResponse[bytes]): + ... + + +class ConcreteAPIResponse(APIResponse[List[str]]): + ... + + +class ConcreteAsyncAPIResponse(APIResponse[httpx.Response]): + ... + + +def test_extract_response_type_direct_classes() -> None: + assert extract_response_type(BaseAPIResponse[str]) == str + assert extract_response_type(APIResponse[str]) == str + assert extract_response_type(AsyncAPIResponse[str]) == str + + +def test_extract_response_type_direct_class_missing_type_arg() -> None: + with pytest.raises( + RuntimeError, + match="Expected type to have a type argument at index 0 but it did not", + ): + extract_response_type(AsyncAPIResponse) + + +def test_extract_response_type_concrete_subclasses() -> None: + assert extract_response_type(ConcreteBaseAPIResponse) == bytes + assert extract_response_type(ConcreteAPIResponse) == List[str] + assert extract_response_type(ConcreteAsyncAPIResponse) == httpx.Response + + +def test_extract_response_type_binary_response() -> None: + assert extract_response_type(BinaryAPIResponse) == bytes + assert extract_response_type(AsyncBinaryAPIResponse) == bytes diff --git a/tests/utils.py b/tests/utils.py index 02dd9c0acc..216b333550 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -1,6 +1,7 @@ from __future__ import annotations import os +import inspect import traceback import contextlib from typing import Any, TypeVar, Iterator, cast @@ -68,6 +69,8 @@ def assert_matches_type( assert isinstance(value, bool) elif origin == float: assert isinstance(value, float) + elif origin == bytes: + assert isinstance(value, bytes) elif origin == datetime: assert isinstance(value, datetime) elif origin == date: @@ -100,6 +103,8 @@ def assert_matches_type( elif issubclass(origin, BaseModel): assert isinstance(value, type_) assert assert_matches_model(type_, cast(Any, value), path=path) + elif inspect.isclass(origin) and origin.__name__ == "HttpxBinaryResponseContent": + assert value.__class__.__name__ == "HttpxBinaryResponseContent" else: assert None, f"Unhandled field type: {type_}" From 023a4e665150e20f77ace0bce80c399d7d766085 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 16 Jan 2024 05:50:40 -0500 Subject: [PATCH 194/816] fix(client): ensure path params are non-empty (#1075) --- src/openai/resources/audio/transcriptions.py | 2 - src/openai/resources/audio/translations.py | 2 - .../resources/beta/assistants/assistants.py | 12 ++ src/openai/resources/beta/assistants/files.py | 24 +++ .../resources/beta/threads/messages/files.py | 20 +++ .../beta/threads/messages/messages.py | 24 +++ .../resources/beta/threads/runs/runs.py | 40 +++++ .../resources/beta/threads/runs/steps.py | 20 +++ src/openai/resources/beta/threads/threads.py | 12 ++ src/openai/resources/files.py | 18 ++- src/openai/resources/fine_tuning/jobs.py | 12 ++ src/openai/resources/images.py | 4 - src/openai/resources/models.py | 8 + .../beta/assistants/test_files.py | 86 +++++++++++ tests/api_resources/beta/test_assistants.py | 42 +++++ tests/api_resources/beta/test_threads.py | 42 +++++ .../beta/threads/messages/test_files.py | 74 +++++++++ .../beta/threads/runs/test_steps.py | 74 +++++++++ .../beta/threads/test_messages.py | 88 +++++++++++ tests/api_resources/beta/threads/test_runs.py | 146 ++++++++++++++++++ tests/api_resources/fine_tuning/test_jobs.py | 42 +++++ tests/api_resources/test_files.py | 60 +++++++ tests/api_resources/test_models.py | 28 ++++ 23 files changed, 870 insertions(+), 10 deletions(-) diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index 053ac30095..868ce7725f 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -98,7 +98,6 @@ def create( # sent to the server will contain a `boundary` parameter, e.g. # multipart/form-data; boundary=---abc-- extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} - return self._post( "/audio/transcriptions", body=maybe_transform(body, transcription_create_params.TranscriptionCreateParams), @@ -187,7 +186,6 @@ async def create( # sent to the server will contain a `boundary` parameter, e.g. # multipart/form-data; boundary=---abc-- extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} - return await self._post( "/audio/transcriptions", body=maybe_transform(body, transcription_create_params.TranscriptionCreateParams), diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index db41b194b6..333abfb4cf 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -91,7 +91,6 @@ def create( # sent to the server will contain a `boundary` parameter, e.g. # multipart/form-data; boundary=---abc-- extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} - return self._post( "/audio/translations", body=maybe_transform(body, translation_create_params.TranslationCreateParams), @@ -173,7 +172,6 @@ async def create( # sent to the server will contain a `boundary` parameter, e.g. # multipart/form-data; boundary=---abc-- extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} - return await self._post( "/audio/translations", body=maybe_transform(body, translation_create_params.TranslationCreateParams), diff --git a/src/openai/resources/beta/assistants/assistants.py b/src/openai/resources/beta/assistants/assistants.py index 176bf05516..a40acfb323 100644 --- a/src/openai/resources/beta/assistants/assistants.py +++ b/src/openai/resources/beta/assistants/assistants.py @@ -148,6 +148,8 @@ def retrieve( timeout: Override the client-level default timeout for this request, in seconds """ + if not assistant_id: + raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._get( f"/assistants/{assistant_id}", @@ -215,6 +217,8 @@ def update( timeout: Override the client-level default timeout for this request, in seconds """ + if not assistant_id: + raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._post( f"/assistants/{assistant_id}", @@ -324,6 +328,8 @@ def delete( timeout: Override the client-level default timeout for this request, in seconds """ + if not assistant_id: + raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._delete( f"/assistants/{assistant_id}", @@ -445,6 +451,8 @@ async def retrieve( timeout: Override the client-level default timeout for this request, in seconds """ + if not assistant_id: + raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._get( f"/assistants/{assistant_id}", @@ -512,6 +520,8 @@ async def update( timeout: Override the client-level default timeout for this request, in seconds """ + if not assistant_id: + raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._post( f"/assistants/{assistant_id}", @@ -621,6 +631,8 @@ async def delete( timeout: Override the client-level default timeout for this request, in seconds """ + if not assistant_id: + raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._delete( f"/assistants/{assistant_id}", diff --git a/src/openai/resources/beta/assistants/files.py b/src/openai/resources/beta/assistants/files.py index 9e45ce46d3..12247044c4 100644 --- a/src/openai/resources/beta/assistants/files.py +++ b/src/openai/resources/beta/assistants/files.py @@ -61,6 +61,8 @@ def create( timeout: Override the client-level default timeout for this request, in seconds """ + if not assistant_id: + raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._post( f"/assistants/{assistant_id}/files", @@ -95,6 +97,10 @@ def retrieve( timeout: Override the client-level default timeout for this request, in seconds """ + if not assistant_id: + raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") + if not file_id: + raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._get( f"/assistants/{assistant_id}/files/{file_id}", @@ -147,6 +153,8 @@ def list( timeout: Override the client-level default timeout for this request, in seconds """ + if not assistant_id: + raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._get_api_list( f"/assistants/{assistant_id}/files", @@ -193,6 +201,10 @@ def delete( timeout: Override the client-level default timeout for this request, in seconds """ + if not assistant_id: + raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") + if not file_id: + raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._delete( f"/assistants/{assistant_id}/files/{file_id}", @@ -242,6 +254,8 @@ async def create( timeout: Override the client-level default timeout for this request, in seconds """ + if not assistant_id: + raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._post( f"/assistants/{assistant_id}/files", @@ -276,6 +290,10 @@ async def retrieve( timeout: Override the client-level default timeout for this request, in seconds """ + if not assistant_id: + raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") + if not file_id: + raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._get( f"/assistants/{assistant_id}/files/{file_id}", @@ -328,6 +346,8 @@ def list( timeout: Override the client-level default timeout for this request, in seconds """ + if not assistant_id: + raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._get_api_list( f"/assistants/{assistant_id}/files", @@ -374,6 +394,10 @@ async def delete( timeout: Override the client-level default timeout for this request, in seconds """ + if not assistant_id: + raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") + if not file_id: + raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._delete( f"/assistants/{assistant_id}/files/{file_id}", diff --git a/src/openai/resources/beta/threads/messages/files.py b/src/openai/resources/beta/threads/messages/files.py index d0a963f1ae..8b6c4581d0 100644 --- a/src/openai/resources/beta/threads/messages/files.py +++ b/src/openai/resources/beta/threads/messages/files.py @@ -56,6 +56,12 @@ def retrieve( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + if not message_id: + raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") + if not file_id: + raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._get( f"/threads/{thread_id}/messages/{message_id}/files/{file_id}", @@ -110,6 +116,10 @@ def list( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + if not message_id: + raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._get_api_list( f"/threads/{thread_id}/messages/{message_id}/files", @@ -167,6 +177,12 @@ async def retrieve( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + if not message_id: + raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") + if not file_id: + raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._get( f"/threads/{thread_id}/messages/{message_id}/files/{file_id}", @@ -221,6 +237,10 @@ def list( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + if not message_id: + raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._get_api_list( f"/threads/{thread_id}/messages/{message_id}/files", diff --git a/src/openai/resources/beta/threads/messages/messages.py b/src/openai/resources/beta/threads/messages/messages.py index 1a15dd36ca..f5a17f902f 100644 --- a/src/openai/resources/beta/threads/messages/messages.py +++ b/src/openai/resources/beta/threads/messages/messages.py @@ -86,6 +86,8 @@ def create( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._post( f"/threads/{thread_id}/messages", @@ -128,6 +130,10 @@ def retrieve( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + if not message_id: + raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._get( f"/threads/{thread_id}/messages/{message_id}", @@ -167,6 +173,10 @@ def update( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + if not message_id: + raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._post( f"/threads/{thread_id}/messages/{message_id}", @@ -220,6 +230,8 @@ def list( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._get_api_list( f"/threads/{thread_id}/messages", @@ -298,6 +310,8 @@ async def create( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._post( f"/threads/{thread_id}/messages", @@ -340,6 +354,10 @@ async def retrieve( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + if not message_id: + raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._get( f"/threads/{thread_id}/messages/{message_id}", @@ -379,6 +397,10 @@ async def update( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + if not message_id: + raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._post( f"/threads/{thread_id}/messages/{message_id}", @@ -432,6 +454,8 @@ def list( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._get_api_list( f"/threads/{thread_id}/messages", diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index eb6c974eaa..ac7a1b3330 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -104,6 +104,8 @@ def create( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._post( f"/threads/{thread_id}/runs", @@ -148,6 +150,10 @@ def retrieve( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._get( f"/threads/{thread_id}/runs/{run_id}", @@ -187,6 +193,10 @@ def update( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._post( f"/threads/{thread_id}/runs/{run_id}", @@ -240,6 +250,8 @@ def list( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._get_api_list( f"/threads/{thread_id}/runs", @@ -286,6 +298,10 @@ def cancel( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._post( f"/threads/{thread_id}/runs/{run_id}/cancel", @@ -325,6 +341,10 @@ def submit_tool_outputs( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._post( f"/threads/{thread_id}/runs/{run_id}/submit_tool_outputs", @@ -405,6 +425,8 @@ async def create( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._post( f"/threads/{thread_id}/runs", @@ -449,6 +471,10 @@ async def retrieve( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._get( f"/threads/{thread_id}/runs/{run_id}", @@ -488,6 +514,10 @@ async def update( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._post( f"/threads/{thread_id}/runs/{run_id}", @@ -541,6 +571,8 @@ def list( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._get_api_list( f"/threads/{thread_id}/runs", @@ -587,6 +619,10 @@ async def cancel( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._post( f"/threads/{thread_id}/runs/{run_id}/cancel", @@ -626,6 +662,10 @@ async def submit_tool_outputs( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._post( f"/threads/{thread_id}/runs/{run_id}/submit_tool_outputs", diff --git a/src/openai/resources/beta/threads/runs/steps.py b/src/openai/resources/beta/threads/runs/steps.py index 566ad9e4dc..9b1df10652 100644 --- a/src/openai/resources/beta/threads/runs/steps.py +++ b/src/openai/resources/beta/threads/runs/steps.py @@ -56,6 +56,12 @@ def retrieve( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") + if not step_id: + raise ValueError(f"Expected a non-empty value for `step_id` but received {step_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._get( f"/threads/{thread_id}/runs/{run_id}/steps/{step_id}", @@ -109,6 +115,10 @@ def list( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._get_api_list( f"/threads/{thread_id}/runs/{run_id}/steps", @@ -166,6 +176,12 @@ async def retrieve( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") + if not step_id: + raise ValueError(f"Expected a non-empty value for `step_id` but received {step_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._get( f"/threads/{thread_id}/runs/{run_id}/steps/{step_id}", @@ -219,6 +235,10 @@ def list( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._get_api_list( f"/threads/{thread_id}/runs/{run_id}/steps", diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 14bfbe9bba..d885404f59 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -133,6 +133,8 @@ def retrieve( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._get( f"/threads/{thread_id}", @@ -171,6 +173,8 @@ def update( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._post( f"/threads/{thread_id}", @@ -204,6 +208,8 @@ def delete( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._delete( f"/threads/{thread_id}", @@ -372,6 +378,8 @@ async def retrieve( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._get( f"/threads/{thread_id}", @@ -410,6 +418,8 @@ async def update( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._post( f"/threads/{thread_id}", @@ -443,6 +453,8 @@ async def delete( timeout: Override the client-level default timeout for this request, in seconds """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._delete( f"/threads/{thread_id}", diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index f435e70a2f..ff924340ac 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -99,7 +99,6 @@ def create( # sent to the server will contain a `boundary` parameter, e.g. # multipart/form-data; boundary=---abc-- extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} - return self._post( "/files", body=maybe_transform(body, file_create_params.FileCreateParams), @@ -133,6 +132,8 @@ def retrieve( timeout: Override the client-level default timeout for this request, in seconds """ + if not file_id: + raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") return self._get( f"/files/{file_id}", options=make_request_options( @@ -202,6 +203,8 @@ def delete( timeout: Override the client-level default timeout for this request, in seconds """ + if not file_id: + raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") return self._delete( f"/files/{file_id}", options=make_request_options( @@ -233,6 +236,8 @@ def content( timeout: Override the client-level default timeout for this request, in seconds """ + if not file_id: + raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") return self._get( f"/files/{file_id}/content", options=make_request_options( @@ -265,6 +270,8 @@ def retrieve_content( timeout: Override the client-level default timeout for this request, in seconds """ + if not file_id: + raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") extra_headers = {"Accept": "application/json", **(extra_headers or {})} return self._get( f"/files/{file_id}/content", @@ -365,7 +372,6 @@ async def create( # sent to the server will contain a `boundary` parameter, e.g. # multipart/form-data; boundary=---abc-- extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} - return await self._post( "/files", body=maybe_transform(body, file_create_params.FileCreateParams), @@ -399,6 +405,8 @@ async def retrieve( timeout: Override the client-level default timeout for this request, in seconds """ + if not file_id: + raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") return await self._get( f"/files/{file_id}", options=make_request_options( @@ -468,6 +476,8 @@ async def delete( timeout: Override the client-level default timeout for this request, in seconds """ + if not file_id: + raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") return await self._delete( f"/files/{file_id}", options=make_request_options( @@ -499,6 +509,8 @@ async def content( timeout: Override the client-level default timeout for this request, in seconds """ + if not file_id: + raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") return await self._get( f"/files/{file_id}/content", options=make_request_options( @@ -531,6 +543,8 @@ async def retrieve_content( timeout: Override the client-level default timeout for this request, in seconds """ + if not file_id: + raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") extra_headers = {"Accept": "application/json", **(extra_headers or {})} return await self._get( f"/files/{file_id}/content", diff --git a/src/openai/resources/fine_tuning/jobs.py b/src/openai/resources/fine_tuning/jobs.py index f337b136a6..208591fa47 100644 --- a/src/openai/resources/fine_tuning/jobs.py +++ b/src/openai/resources/fine_tuning/jobs.py @@ -149,6 +149,8 @@ def retrieve( timeout: Override the client-level default timeout for this request, in seconds """ + if not fine_tuning_job_id: + raise ValueError(f"Expected a non-empty value for `fine_tuning_job_id` but received {fine_tuning_job_id!r}") return self._get( f"/fine_tuning/jobs/{fine_tuning_job_id}", options=make_request_options( @@ -227,6 +229,8 @@ def cancel( timeout: Override the client-level default timeout for this request, in seconds """ + if not fine_tuning_job_id: + raise ValueError(f"Expected a non-empty value for `fine_tuning_job_id` but received {fine_tuning_job_id!r}") return self._post( f"/fine_tuning/jobs/{fine_tuning_job_id}/cancel", options=make_request_options( @@ -264,6 +268,8 @@ def list_events( timeout: Override the client-level default timeout for this request, in seconds """ + if not fine_tuning_job_id: + raise ValueError(f"Expected a non-empty value for `fine_tuning_job_id` but received {fine_tuning_job_id!r}") return self._get_api_list( f"/fine_tuning/jobs/{fine_tuning_job_id}/events", page=SyncCursorPage[FineTuningJobEvent], @@ -404,6 +410,8 @@ async def retrieve( timeout: Override the client-level default timeout for this request, in seconds """ + if not fine_tuning_job_id: + raise ValueError(f"Expected a non-empty value for `fine_tuning_job_id` but received {fine_tuning_job_id!r}") return await self._get( f"/fine_tuning/jobs/{fine_tuning_job_id}", options=make_request_options( @@ -482,6 +490,8 @@ async def cancel( timeout: Override the client-level default timeout for this request, in seconds """ + if not fine_tuning_job_id: + raise ValueError(f"Expected a non-empty value for `fine_tuning_job_id` but received {fine_tuning_job_id!r}") return await self._post( f"/fine_tuning/jobs/{fine_tuning_job_id}/cancel", options=make_request_options( @@ -519,6 +529,8 @@ def list_events( timeout: Override the client-level default timeout for this request, in seconds """ + if not fine_tuning_job_id: + raise ValueError(f"Expected a non-empty value for `fine_tuning_job_id` but received {fine_tuning_job_id!r}") return self._get_api_list( f"/fine_tuning/jobs/{fine_tuning_job_id}/events", page=AsyncCursorPage[FineTuningJobEvent], diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py index 6f1de221e2..a3eb98574e 100644 --- a/src/openai/resources/images.py +++ b/src/openai/resources/images.py @@ -98,7 +98,6 @@ def create_variation( # sent to the server will contain a `boundary` parameter, e.g. # multipart/form-data; boundary=---abc-- extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} - return self._post( "/images/variations", body=maybe_transform(body, image_create_variation_params.ImageCreateVariationParams), @@ -182,7 +181,6 @@ def edit( # sent to the server will contain a `boundary` parameter, e.g. # multipart/form-data; boundary=---abc-- extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} - return self._post( "/images/edits", body=maybe_transform(body, image_edit_params.ImageEditParams), @@ -345,7 +343,6 @@ async def create_variation( # sent to the server will contain a `boundary` parameter, e.g. # multipart/form-data; boundary=---abc-- extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} - return await self._post( "/images/variations", body=maybe_transform(body, image_create_variation_params.ImageCreateVariationParams), @@ -429,7 +426,6 @@ async def edit( # sent to the server will contain a `boundary` parameter, e.g. # multipart/form-data; boundary=---abc-- extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} - return await self._post( "/images/edits", body=maybe_transform(body, image_edit_params.ImageEditParams), diff --git a/src/openai/resources/models.py b/src/openai/resources/models.py index b431ef84fc..e4a0d84810 100644 --- a/src/openai/resources/models.py +++ b/src/openai/resources/models.py @@ -52,6 +52,8 @@ def retrieve( timeout: Override the client-level default timeout for this request, in seconds """ + if not model: + raise ValueError(f"Expected a non-empty value for `model` but received {model!r}") return self._get( f"/models/{model}", options=make_request_options( @@ -108,6 +110,8 @@ def delete( timeout: Override the client-level default timeout for this request, in seconds """ + if not model: + raise ValueError(f"Expected a non-empty value for `model` but received {model!r}") return self._delete( f"/models/{model}", options=make_request_options( @@ -150,6 +154,8 @@ async def retrieve( timeout: Override the client-level default timeout for this request, in seconds """ + if not model: + raise ValueError(f"Expected a non-empty value for `model` but received {model!r}") return await self._get( f"/models/{model}", options=make_request_options( @@ -206,6 +212,8 @@ async def delete( timeout: Override the client-level default timeout for this request, in seconds """ + if not model: + raise ValueError(f"Expected a non-empty value for `model` but received {model!r}") return await self._delete( f"/models/{model}", options=make_request_options( diff --git a/tests/api_resources/beta/assistants/test_files.py b/tests/api_resources/beta/assistants/test_files.py index 443408bd44..7db1368ccb 100644 --- a/tests/api_resources/beta/assistants/test_files.py +++ b/tests/api_resources/beta/assistants/test_files.py @@ -56,6 +56,14 @@ def test_streaming_response_create(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_create(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): + client.beta.assistants.files.with_raw_response.create( + "", + file_id="string", + ) + @parametrize def test_method_retrieve(self, client: OpenAI) -> None: file = client.beta.assistants.files.retrieve( @@ -90,6 +98,20 @@ def test_streaming_response_retrieve(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_retrieve(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): + client.beta.assistants.files.with_raw_response.retrieve( + "string", + assistant_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): + client.beta.assistants.files.with_raw_response.retrieve( + "", + assistant_id="string", + ) + @parametrize def test_method_list(self, client: OpenAI) -> None: file = client.beta.assistants.files.list( @@ -132,6 +154,13 @@ def test_streaming_response_list(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_list(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): + client.beta.assistants.files.with_raw_response.list( + "", + ) + @parametrize def test_method_delete(self, client: OpenAI) -> None: file = client.beta.assistants.files.delete( @@ -166,6 +195,20 @@ def test_streaming_response_delete(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_delete(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): + client.beta.assistants.files.with_raw_response.delete( + "string", + assistant_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): + client.beta.assistants.files.with_raw_response.delete( + "", + assistant_id="string", + ) + class TestAsyncFiles: strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -206,6 +249,14 @@ async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + async def test_path_params_create(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): + await client.beta.assistants.files.with_raw_response.create( + "", + file_id="string", + ) + @parametrize async def test_method_retrieve(self, client: AsyncOpenAI) -> None: file = await client.beta.assistants.files.retrieve( @@ -240,6 +291,20 @@ async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + async def test_path_params_retrieve(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): + await client.beta.assistants.files.with_raw_response.retrieve( + "string", + assistant_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): + await client.beta.assistants.files.with_raw_response.retrieve( + "", + assistant_id="string", + ) + @parametrize async def test_method_list(self, client: AsyncOpenAI) -> None: file = await client.beta.assistants.files.list( @@ -282,6 +347,13 @@ async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + async def test_path_params_list(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): + await client.beta.assistants.files.with_raw_response.list( + "", + ) + @parametrize async def test_method_delete(self, client: AsyncOpenAI) -> None: file = await client.beta.assistants.files.delete( @@ -315,3 +387,17 @@ async def test_streaming_response_delete(self, client: AsyncOpenAI) -> None: assert_matches_type(FileDeleteResponse, file, path=["response"]) assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_delete(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): + await client.beta.assistants.files.with_raw_response.delete( + "string", + assistant_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): + await client.beta.assistants.files.with_raw_response.delete( + "", + assistant_id="string", + ) diff --git a/tests/api_resources/beta/test_assistants.py b/tests/api_resources/beta/test_assistants.py index fbafac03c9..fa09769622 100644 --- a/tests/api_resources/beta/test_assistants.py +++ b/tests/api_resources/beta/test_assistants.py @@ -100,6 +100,13 @@ def test_streaming_response_retrieve(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_retrieve(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): + client.beta.assistants.with_raw_response.retrieve( + "", + ) + @parametrize def test_method_update(self, client: OpenAI) -> None: assistant = client.beta.assistants.update( @@ -145,6 +152,13 @@ def test_streaming_response_update(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_update(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): + client.beta.assistants.with_raw_response.update( + "", + ) + @parametrize def test_method_list(self, client: OpenAI) -> None: assistant = client.beta.assistants.list() @@ -211,6 +225,13 @@ def test_streaming_response_delete(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_delete(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): + client.beta.assistants.with_raw_response.delete( + "", + ) + class TestAsyncAssistants: strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -292,6 +313,13 @@ async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + async def test_path_params_retrieve(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): + await client.beta.assistants.with_raw_response.retrieve( + "", + ) + @parametrize async def test_method_update(self, client: AsyncOpenAI) -> None: assistant = await client.beta.assistants.update( @@ -337,6 +365,13 @@ async def test_streaming_response_update(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + async def test_path_params_update(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): + await client.beta.assistants.with_raw_response.update( + "", + ) + @parametrize async def test_method_list(self, client: AsyncOpenAI) -> None: assistant = await client.beta.assistants.list() @@ -402,3 +437,10 @@ async def test_streaming_response_delete(self, client: AsyncOpenAI) -> None: assert_matches_type(AssistantDeleted, assistant, path=["response"]) assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_delete(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): + await client.beta.assistants.with_raw_response.delete( + "", + ) diff --git a/tests/api_resources/beta/test_threads.py b/tests/api_resources/beta/test_threads.py index 488ce38c1b..ba55cc85da 100644 --- a/tests/api_resources/beta/test_threads.py +++ b/tests/api_resources/beta/test_threads.py @@ -108,6 +108,13 @@ def test_streaming_response_retrieve(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_retrieve(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + client.beta.threads.with_raw_response.retrieve( + "", + ) + @parametrize def test_method_update(self, client: OpenAI) -> None: thread = client.beta.threads.update( @@ -147,6 +154,13 @@ def test_streaming_response_update(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_update(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + client.beta.threads.with_raw_response.update( + "", + ) + @parametrize def test_method_delete(self, client: OpenAI) -> None: thread = client.beta.threads.delete( @@ -178,6 +192,13 @@ def test_streaming_response_delete(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_delete(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + client.beta.threads.with_raw_response.delete( + "", + ) + @parametrize def test_method_create_and_run(self, client: OpenAI) -> None: thread = client.beta.threads.create_and_run( @@ -332,6 +353,13 @@ async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + async def test_path_params_retrieve(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + await client.beta.threads.with_raw_response.retrieve( + "", + ) + @parametrize async def test_method_update(self, client: AsyncOpenAI) -> None: thread = await client.beta.threads.update( @@ -371,6 +399,13 @@ async def test_streaming_response_update(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + async def test_path_params_update(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + await client.beta.threads.with_raw_response.update( + "", + ) + @parametrize async def test_method_delete(self, client: AsyncOpenAI) -> None: thread = await client.beta.threads.delete( @@ -402,6 +437,13 @@ async def test_streaming_response_delete(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + async def test_path_params_delete(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + await client.beta.threads.with_raw_response.delete( + "", + ) + @parametrize async def test_method_create_and_run(self, client: AsyncOpenAI) -> None: thread = await client.beta.threads.create_and_run( diff --git a/tests/api_resources/beta/threads/messages/test_files.py b/tests/api_resources/beta/threads/messages/test_files.py index 5de352c0d2..2d248642e9 100644 --- a/tests/api_resources/beta/threads/messages/test_files.py +++ b/tests/api_resources/beta/threads/messages/test_files.py @@ -59,6 +59,29 @@ def test_streaming_response_retrieve(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_retrieve(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + client.beta.threads.messages.files.with_raw_response.retrieve( + "file-abc123", + thread_id="", + message_id="msg_abc123", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): + client.beta.threads.messages.files.with_raw_response.retrieve( + "file-abc123", + thread_id="thread_abc123", + message_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): + client.beta.threads.messages.files.with_raw_response.retrieve( + "", + thread_id="thread_abc123", + message_id="msg_abc123", + ) + @parametrize def test_method_list(self, client: OpenAI) -> None: file = client.beta.threads.messages.files.list( @@ -105,6 +128,20 @@ def test_streaming_response_list(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_list(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + client.beta.threads.messages.files.with_raw_response.list( + "string", + thread_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): + client.beta.threads.messages.files.with_raw_response.list( + "", + thread_id="string", + ) + class TestAsyncFiles: strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -148,6 +185,29 @@ async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + async def test_path_params_retrieve(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + await client.beta.threads.messages.files.with_raw_response.retrieve( + "file-abc123", + thread_id="", + message_id="msg_abc123", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): + await client.beta.threads.messages.files.with_raw_response.retrieve( + "file-abc123", + thread_id="thread_abc123", + message_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): + await client.beta.threads.messages.files.with_raw_response.retrieve( + "", + thread_id="thread_abc123", + message_id="msg_abc123", + ) + @parametrize async def test_method_list(self, client: AsyncOpenAI) -> None: file = await client.beta.threads.messages.files.list( @@ -193,3 +253,17 @@ async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: assert_matches_type(AsyncCursorPage[MessageFile], file, path=["response"]) assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_list(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + await client.beta.threads.messages.files.with_raw_response.list( + "string", + thread_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): + await client.beta.threads.messages.files.with_raw_response.list( + "", + thread_id="string", + ) diff --git a/tests/api_resources/beta/threads/runs/test_steps.py b/tests/api_resources/beta/threads/runs/test_steps.py index f13970fc14..2ec164a535 100644 --- a/tests/api_resources/beta/threads/runs/test_steps.py +++ b/tests/api_resources/beta/threads/runs/test_steps.py @@ -59,6 +59,29 @@ def test_streaming_response_retrieve(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_retrieve(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + client.beta.threads.runs.steps.with_raw_response.retrieve( + "string", + thread_id="", + run_id="string", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): + client.beta.threads.runs.steps.with_raw_response.retrieve( + "string", + thread_id="string", + run_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `step_id` but received ''"): + client.beta.threads.runs.steps.with_raw_response.retrieve( + "", + thread_id="string", + run_id="string", + ) + @parametrize def test_method_list(self, client: OpenAI) -> None: step = client.beta.threads.runs.steps.list( @@ -105,6 +128,20 @@ def test_streaming_response_list(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_list(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + client.beta.threads.runs.steps.with_raw_response.list( + "string", + thread_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): + client.beta.threads.runs.steps.with_raw_response.list( + "", + thread_id="string", + ) + class TestAsyncSteps: strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -148,6 +185,29 @@ async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + async def test_path_params_retrieve(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + await client.beta.threads.runs.steps.with_raw_response.retrieve( + "string", + thread_id="", + run_id="string", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): + await client.beta.threads.runs.steps.with_raw_response.retrieve( + "string", + thread_id="string", + run_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `step_id` but received ''"): + await client.beta.threads.runs.steps.with_raw_response.retrieve( + "", + thread_id="string", + run_id="string", + ) + @parametrize async def test_method_list(self, client: AsyncOpenAI) -> None: step = await client.beta.threads.runs.steps.list( @@ -193,3 +253,17 @@ async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: assert_matches_type(AsyncCursorPage[RunStep], step, path=["response"]) assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_list(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + await client.beta.threads.runs.steps.with_raw_response.list( + "string", + thread_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): + await client.beta.threads.runs.steps.with_raw_response.list( + "", + thread_id="string", + ) diff --git a/tests/api_resources/beta/threads/test_messages.py b/tests/api_resources/beta/threads/test_messages.py index 87b6eca03a..508e9b96c9 100644 --- a/tests/api_resources/beta/threads/test_messages.py +++ b/tests/api_resources/beta/threads/test_messages.py @@ -70,6 +70,15 @@ def test_streaming_response_create(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_create(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + client.beta.threads.messages.with_raw_response.create( + "", + content="x", + role="user", + ) + @parametrize def test_method_retrieve(self, client: OpenAI) -> None: message = client.beta.threads.messages.retrieve( @@ -104,6 +113,20 @@ def test_streaming_response_retrieve(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_retrieve(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + client.beta.threads.messages.with_raw_response.retrieve( + "string", + thread_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): + client.beta.threads.messages.with_raw_response.retrieve( + "", + thread_id="string", + ) + @parametrize def test_method_update(self, client: OpenAI) -> None: message = client.beta.threads.messages.update( @@ -147,6 +170,20 @@ def test_streaming_response_update(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_update(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + client.beta.threads.messages.with_raw_response.update( + "string", + thread_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): + client.beta.threads.messages.with_raw_response.update( + "", + thread_id="string", + ) + @parametrize def test_method_list(self, client: OpenAI) -> None: message = client.beta.threads.messages.list( @@ -189,6 +226,13 @@ def test_streaming_response_list(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_list(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + client.beta.threads.messages.with_raw_response.list( + "", + ) + class TestAsyncMessages: strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -243,6 +287,15 @@ async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + async def test_path_params_create(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + await client.beta.threads.messages.with_raw_response.create( + "", + content="x", + role="user", + ) + @parametrize async def test_method_retrieve(self, client: AsyncOpenAI) -> None: message = await client.beta.threads.messages.retrieve( @@ -277,6 +330,20 @@ async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + async def test_path_params_retrieve(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + await client.beta.threads.messages.with_raw_response.retrieve( + "string", + thread_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): + await client.beta.threads.messages.with_raw_response.retrieve( + "", + thread_id="string", + ) + @parametrize async def test_method_update(self, client: AsyncOpenAI) -> None: message = await client.beta.threads.messages.update( @@ -320,6 +387,20 @@ async def test_streaming_response_update(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + async def test_path_params_update(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + await client.beta.threads.messages.with_raw_response.update( + "string", + thread_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): + await client.beta.threads.messages.with_raw_response.update( + "", + thread_id="string", + ) + @parametrize async def test_method_list(self, client: AsyncOpenAI) -> None: message = await client.beta.threads.messages.list( @@ -361,3 +442,10 @@ async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: assert_matches_type(AsyncCursorPage[ThreadMessage], message, path=["response"]) assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_list(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + await client.beta.threads.messages.with_raw_response.list( + "", + ) diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index e0070c3395..66a9edd5c0 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -71,6 +71,14 @@ def test_streaming_response_create(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_create(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + client.beta.threads.runs.with_raw_response.create( + "", + assistant_id="string", + ) + @parametrize def test_method_retrieve(self, client: OpenAI) -> None: run = client.beta.threads.runs.retrieve( @@ -105,6 +113,20 @@ def test_streaming_response_retrieve(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_retrieve(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + client.beta.threads.runs.with_raw_response.retrieve( + "string", + thread_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): + client.beta.threads.runs.with_raw_response.retrieve( + "", + thread_id="string", + ) + @parametrize def test_method_update(self, client: OpenAI) -> None: run = client.beta.threads.runs.update( @@ -148,6 +170,20 @@ def test_streaming_response_update(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_update(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + client.beta.threads.runs.with_raw_response.update( + "string", + thread_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): + client.beta.threads.runs.with_raw_response.update( + "", + thread_id="string", + ) + @parametrize def test_method_list(self, client: OpenAI) -> None: run = client.beta.threads.runs.list( @@ -190,6 +226,13 @@ def test_streaming_response_list(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_list(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + client.beta.threads.runs.with_raw_response.list( + "", + ) + @parametrize def test_method_cancel(self, client: OpenAI) -> None: run = client.beta.threads.runs.cancel( @@ -224,6 +267,20 @@ def test_streaming_response_cancel(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_cancel(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + client.beta.threads.runs.with_raw_response.cancel( + "string", + thread_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): + client.beta.threads.runs.with_raw_response.cancel( + "", + thread_id="string", + ) + @parametrize def test_method_submit_tool_outputs(self, client: OpenAI) -> None: run = client.beta.threads.runs.submit_tool_outputs( @@ -261,6 +318,22 @@ def test_streaming_response_submit_tool_outputs(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_submit_tool_outputs(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + client.beta.threads.runs.with_raw_response.submit_tool_outputs( + "string", + thread_id="", + tool_outputs=[{}, {}, {}], + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): + client.beta.threads.runs.with_raw_response.submit_tool_outputs( + "", + thread_id="string", + tool_outputs=[{}, {}, {}], + ) + class TestAsyncRuns: strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -314,6 +387,14 @@ async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + async def test_path_params_create(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + await client.beta.threads.runs.with_raw_response.create( + "", + assistant_id="string", + ) + @parametrize async def test_method_retrieve(self, client: AsyncOpenAI) -> None: run = await client.beta.threads.runs.retrieve( @@ -348,6 +429,20 @@ async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + async def test_path_params_retrieve(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + await client.beta.threads.runs.with_raw_response.retrieve( + "string", + thread_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): + await client.beta.threads.runs.with_raw_response.retrieve( + "", + thread_id="string", + ) + @parametrize async def test_method_update(self, client: AsyncOpenAI) -> None: run = await client.beta.threads.runs.update( @@ -391,6 +486,20 @@ async def test_streaming_response_update(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + async def test_path_params_update(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + await client.beta.threads.runs.with_raw_response.update( + "string", + thread_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): + await client.beta.threads.runs.with_raw_response.update( + "", + thread_id="string", + ) + @parametrize async def test_method_list(self, client: AsyncOpenAI) -> None: run = await client.beta.threads.runs.list( @@ -433,6 +542,13 @@ async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + async def test_path_params_list(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + await client.beta.threads.runs.with_raw_response.list( + "", + ) + @parametrize async def test_method_cancel(self, client: AsyncOpenAI) -> None: run = await client.beta.threads.runs.cancel( @@ -467,6 +583,20 @@ async def test_streaming_response_cancel(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + async def test_path_params_cancel(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + await client.beta.threads.runs.with_raw_response.cancel( + "string", + thread_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): + await client.beta.threads.runs.with_raw_response.cancel( + "", + thread_id="string", + ) + @parametrize async def test_method_submit_tool_outputs(self, client: AsyncOpenAI) -> None: run = await client.beta.threads.runs.submit_tool_outputs( @@ -503,3 +633,19 @@ async def test_streaming_response_submit_tool_outputs(self, client: AsyncOpenAI) assert_matches_type(Run, run, path=["response"]) assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_submit_tool_outputs(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + await client.beta.threads.runs.with_raw_response.submit_tool_outputs( + "string", + thread_id="", + tool_outputs=[{}, {}, {}], + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): + await client.beta.threads.runs.with_raw_response.submit_tool_outputs( + "", + thread_id="string", + tool_outputs=[{}, {}, {}], + ) diff --git a/tests/api_resources/fine_tuning/test_jobs.py b/tests/api_resources/fine_tuning/test_jobs.py index 3db0cdc0a5..50c7278855 100644 --- a/tests/api_resources/fine_tuning/test_jobs.py +++ b/tests/api_resources/fine_tuning/test_jobs.py @@ -105,6 +105,13 @@ def test_streaming_response_retrieve(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_retrieve(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `fine_tuning_job_id` but received ''"): + client.fine_tuning.jobs.with_raw_response.retrieve( + "", + ) + @parametrize def test_method_list(self, client: OpenAI) -> None: job = client.fine_tuning.jobs.list() @@ -169,6 +176,13 @@ def test_streaming_response_cancel(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_cancel(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `fine_tuning_job_id` but received ''"): + client.fine_tuning.jobs.with_raw_response.cancel( + "", + ) + @parametrize def test_method_list_events(self, client: OpenAI) -> None: job = client.fine_tuning.jobs.list_events( @@ -209,6 +223,13 @@ def test_streaming_response_list_events(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_list_events(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `fine_tuning_job_id` but received ''"): + client.fine_tuning.jobs.with_raw_response.list_events( + "", + ) + class TestAsyncJobs: strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -295,6 +316,13 @@ async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + async def test_path_params_retrieve(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `fine_tuning_job_id` but received ''"): + await client.fine_tuning.jobs.with_raw_response.retrieve( + "", + ) + @parametrize async def test_method_list(self, client: AsyncOpenAI) -> None: job = await client.fine_tuning.jobs.list() @@ -359,6 +387,13 @@ async def test_streaming_response_cancel(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + async def test_path_params_cancel(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `fine_tuning_job_id` but received ''"): + await client.fine_tuning.jobs.with_raw_response.cancel( + "", + ) + @parametrize async def test_method_list_events(self, client: AsyncOpenAI) -> None: job = await client.fine_tuning.jobs.list_events( @@ -398,3 +433,10 @@ async def test_streaming_response_list_events(self, client: AsyncOpenAI) -> None assert_matches_type(AsyncCursorPage[FineTuningJobEvent], job, path=["response"]) assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_list_events(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `fine_tuning_job_id` but received ''"): + await client.fine_tuning.jobs.with_raw_response.list_events( + "", + ) diff --git a/tests/api_resources/test_files.py b/tests/api_resources/test_files.py index e36a7839f2..89ad9e222f 100644 --- a/tests/api_resources/test_files.py +++ b/tests/api_resources/test_files.py @@ -92,6 +92,13 @@ def test_streaming_response_retrieve(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_retrieve(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): + client.files.with_raw_response.retrieve( + "", + ) + @parametrize def test_method_list(self, client: OpenAI) -> None: file = client.files.list() @@ -155,6 +162,13 @@ def test_streaming_response_delete(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_delete(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): + client.files.with_raw_response.delete( + "", + ) + @parametrize @pytest.mark.respx(base_url=base_url) def test_method_content(self, client: OpenAI, respx_mock: MockRouter) -> None: @@ -194,6 +208,14 @@ def test_streaming_response_content(self, client: OpenAI, respx_mock: MockRouter assert cast(Any, response.is_closed) is True + @parametrize + @pytest.mark.respx(base_url=base_url) + def test_path_params_content(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): + client.files.with_raw_response.content( + "", + ) + @parametrize def test_method_retrieve_content(self, client: OpenAI) -> None: with pytest.warns(DeprecationWarning): @@ -229,6 +251,14 @@ def test_streaming_response_retrieve_content(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_retrieve_content(self, client: OpenAI) -> None: + with pytest.warns(DeprecationWarning): + with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): + client.files.with_raw_response.retrieve_content( + "", + ) + class TestAsyncFiles: strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -300,6 +330,13 @@ async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + async def test_path_params_retrieve(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): + await client.files.with_raw_response.retrieve( + "", + ) + @parametrize async def test_method_list(self, client: AsyncOpenAI) -> None: file = await client.files.list() @@ -363,6 +400,13 @@ async def test_streaming_response_delete(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + async def test_path_params_delete(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): + await client.files.with_raw_response.delete( + "", + ) + @parametrize @pytest.mark.respx(base_url=base_url) async def test_method_content(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: @@ -402,6 +446,14 @@ async def test_streaming_response_content(self, client: AsyncOpenAI, respx_mock: assert cast(Any, response.is_closed) is True + @parametrize + @pytest.mark.respx(base_url=base_url) + async def test_path_params_content(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): + await client.files.with_raw_response.content( + "", + ) + @parametrize async def test_method_retrieve_content(self, client: AsyncOpenAI) -> None: with pytest.warns(DeprecationWarning): @@ -436,3 +488,11 @@ async def test_streaming_response_retrieve_content(self, client: AsyncOpenAI) -> assert_matches_type(str, file, path=["response"]) assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_retrieve_content(self, client: AsyncOpenAI) -> None: + with pytest.warns(DeprecationWarning): + with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): + await client.files.with_raw_response.retrieve_content( + "", + ) diff --git a/tests/api_resources/test_models.py b/tests/api_resources/test_models.py index 5afda86a7a..b41e50eb71 100644 --- a/tests/api_resources/test_models.py +++ b/tests/api_resources/test_models.py @@ -53,6 +53,13 @@ def test_streaming_response_retrieve(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_retrieve(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `model` but received ''"): + client.models.with_raw_response.retrieve( + "", + ) + @parametrize def test_method_list(self, client: OpenAI) -> None: model = client.models.list() @@ -109,6 +116,13 @@ def test_streaming_response_delete(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_path_params_delete(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `model` but received ''"): + client.models.with_raw_response.delete( + "", + ) + class TestAsyncModels: strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -146,6 +160,13 @@ async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + async def test_path_params_retrieve(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `model` but received ''"): + await client.models.with_raw_response.retrieve( + "", + ) + @parametrize async def test_method_list(self, client: AsyncOpenAI) -> None: model = await client.models.list() @@ -201,3 +222,10 @@ async def test_streaming_response_delete(self, client: AsyncOpenAI) -> None: assert_matches_type(ModelDeleted, model, path=["response"]) assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_delete(self, client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `model` but received ''"): + await client.models.with_raw_response.delete( + "", + ) From a05b1607440d1b5917a015e6e761acbb15f47cf4 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 16 Jan 2024 11:47:21 -0500 Subject: [PATCH 195/816] fix(proxy): prevent recursion errors when debugging pycharm (#1076) https://github.com/openai/openai-python/issues/906 --- src/openai/_extras/numpy_proxy.py | 4 +--- src/openai/_extras/pandas_proxy.py | 4 +--- src/openai/_utils/_proxy.py | 20 ++------------------ 3 files changed, 4 insertions(+), 24 deletions(-) diff --git a/src/openai/_extras/numpy_proxy.py b/src/openai/_extras/numpy_proxy.py index 3809991c46..27880bf132 100644 --- a/src/openai/_extras/numpy_proxy.py +++ b/src/openai/_extras/numpy_proxy.py @@ -1,7 +1,7 @@ from __future__ import annotations from typing import TYPE_CHECKING, Any -from typing_extensions import ClassVar, override +from typing_extensions import override from .._utils import LazyProxy from ._common import MissingDependencyError, format_instructions @@ -14,8 +14,6 @@ class NumpyProxy(LazyProxy[Any]): - should_cache: ClassVar[bool] = True - @override def __load__(self) -> Any: try: diff --git a/src/openai/_extras/pandas_proxy.py b/src/openai/_extras/pandas_proxy.py index a24f7fb604..686377bade 100644 --- a/src/openai/_extras/pandas_proxy.py +++ b/src/openai/_extras/pandas_proxy.py @@ -1,7 +1,7 @@ from __future__ import annotations from typing import TYPE_CHECKING, Any -from typing_extensions import ClassVar, override +from typing_extensions import override from .._utils import LazyProxy from ._common import MissingDependencyError, format_instructions @@ -14,8 +14,6 @@ class PandasProxy(LazyProxy[Any]): - should_cache: ClassVar[bool] = True - @override def __load__(self) -> Any: try: diff --git a/src/openai/_utils/_proxy.py b/src/openai/_utils/_proxy.py index 3c9e790a25..6f05efcd21 100644 --- a/src/openai/_utils/_proxy.py +++ b/src/openai/_utils/_proxy.py @@ -2,7 +2,7 @@ from abc import ABC, abstractmethod from typing import Generic, TypeVar, Iterable, cast -from typing_extensions import ClassVar, override +from typing_extensions import override T = TypeVar("T") @@ -13,11 +13,6 @@ class LazyProxy(Generic[T], ABC): This includes forwarding attribute access and othe methods. """ - should_cache: ClassVar[bool] = False - - def __init__(self) -> None: - self.__proxied: T | None = None - # Note: we have to special case proxies that themselves return proxies # to support using a proxy as a catch-all for any random access, e.g. `proxy.foo.bar.baz` @@ -57,18 +52,7 @@ def __class__(self) -> type: return proxied.__class__ def __get_proxied__(self) -> T: - if not self.should_cache: - return self.__load__() - - proxied = self.__proxied - if proxied is not None: - return proxied - - self.__proxied = proxied = self.__load__() - return proxied - - def __set_proxied__(self, value: T) -> None: - self.__proxied = value + return self.__load__() def __as_proxied__(self) -> T: """Helper method that returns the current proxy, typed as the loaded object""" From 8866b7227e46361220828ac9d2fb4fc14c236b35 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 16 Jan 2024 13:20:40 -0500 Subject: [PATCH 196/816] chore: add write_to_file binary helper method (#1077) --- src/openai/_legacy_response.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/openai/_legacy_response.py b/src/openai/_legacy_response.py index 5a398efebf..c36c94f165 100644 --- a/src/openai/_legacy_response.py +++ b/src/openai/_legacy_response.py @@ -336,6 +336,22 @@ def iter_lines(self) -> Iterator[str]: def iter_raw(self, chunk_size: int | None = None) -> Iterator[bytes]: return self.response.iter_raw(chunk_size) + def write_to_file( + self, + file: str | os.PathLike[str], + ) -> None: + """Write the output to the given file. + + Accepts a filename or any path-like object, e.g. pathlib.Path + + Note: if you want to stream the data to the file instead of writing + all at once then you should use `.with_streaming_response` when making + the API request, e.g. `client.with_streaming_response.foo().stream_to_file('my_filename.txt')` + """ + with open(file, mode="wb") as f: + for data in self.response.iter_bytes(): + f.write(data) + @deprecated( "Due to a bug, this method doesn't actually stream the response content, `.with_streaming_response.method()` should be used instead" ) From 3d61ed42aba652b547029095a7eb269ad4e1e957 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 16 Jan 2024 13:21:22 -0500 Subject: [PATCH 197/816] release: 1.8.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 19 +++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 22 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index b08a26cbda..c523ce19f0 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.7.2" + ".": "1.8.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index ab502f8137..c2ac83cdeb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,24 @@ # Changelog +## 1.8.0 (2024-01-16) + +Full Changelog: [v1.7.2...v1.8.0](https://github.com/openai/openai-python/compare/v1.7.2...v1.8.0) + +### Features + +* **client:** add support for streaming raw responses ([#1072](https://github.com/openai/openai-python/issues/1072)) ([0e93c3b](https://github.com/openai/openai-python/commit/0e93c3b5bc9cfa041e91962fd82c0d9358125024)) + + +### Bug Fixes + +* **client:** ensure path params are non-empty ([#1075](https://github.com/openai/openai-python/issues/1075)) ([9a25149](https://github.com/openai/openai-python/commit/9a2514997c2ddccbec9df8be3773e83271f1dab8)) +* **proxy:** prevent recursion errors when debugging pycharm ([#1076](https://github.com/openai/openai-python/issues/1076)) ([3d78798](https://github.com/openai/openai-python/commit/3d787987cf7625b5b502cb0b63a37d55956eaf1d)) + + +### Chores + +* add write_to_file binary helper method ([#1077](https://github.com/openai/openai-python/issues/1077)) ([c622c6a](https://github.com/openai/openai-python/commit/c622c6aaf2ae7dc62bd6cdfc053204c5dc3293ac)) + ## 1.7.2 (2024-01-12) Full Changelog: [v1.7.1...v1.7.2](https://github.com/openai/openai-python/compare/v1.7.1...v1.7.2) diff --git a/pyproject.toml b/pyproject.toml index 354d763812..5019e6cf7e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.7.2" +version = "1.8.0" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 0b4aa63ffe..311cab2540 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.7.2" # x-release-please-version +__version__ = "1.8.0" # x-release-please-version From 42d1ab6434f7bc62ad774be1ba5b43e36917239f Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 17 Jan 2024 09:15:25 -0500 Subject: [PATCH 198/816] chore(internal): fix typing util function (#1083) --- src/openai/_utils/_typing.py | 31 ++++++++++++- tests/test_utils/test_typing.py | 78 +++++++++++++++++++++++++++++++++ 2 files changed, 107 insertions(+), 2 deletions(-) create mode 100644 tests/test_utils/test_typing.py diff --git a/src/openai/_utils/_typing.py b/src/openai/_utils/_typing.py index b5e2c2e397..a020822bc0 100644 --- a/src/openai/_utils/_typing.py +++ b/src/openai/_utils/_typing.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import Any, cast +from typing import Any, TypeVar, cast from typing_extensions import Required, Annotated, get_args, get_origin from .._types import InheritsGeneric @@ -23,6 +23,12 @@ def is_required_type(typ: type) -> bool: return get_origin(typ) == Required +def is_typevar(typ: type) -> bool: + # type ignore is required because type checkers + # think this expression will always return False + return type(typ) == TypeVar # type: ignore + + # Extracts T from Annotated[T, ...] or from Required[Annotated[T, ...]] def strip_annotated_type(typ: type) -> type: if is_required_type(typ) or is_annotated_type(typ): @@ -49,6 +55,15 @@ class MyResponse(Foo[bytes]): extract_type_var(MyResponse, bases=(Foo,), index=0) -> bytes ``` + + And where a generic subclass is given: + ```py + _T = TypeVar('_T') + class MyResponse(Foo[_T]): + ... + + extract_type_var(MyResponse[bytes], bases=(Foo,), index=0) -> bytes + ``` """ cls = cast(object, get_origin(typ) or typ) if cls in generic_bases: @@ -75,6 +90,18 @@ class MyResponse(Foo[bytes]): f"Does {cls} inherit from one of {generic_bases} ?" ) - return extract_type_arg(target_base_class, index) + extracted = extract_type_arg(target_base_class, index) + if is_typevar(extracted): + # If the extracted type argument is itself a type variable + # then that means the subclass itself is generic, so we have + # to resolve the type argument from the class itself, not + # the base class. + # + # Note: if there is more than 1 type argument, the subclass could + # change the ordering of the type arguments, this is not currently + # supported. + return extract_type_arg(typ, index) + + return extracted raise RuntimeError(f"Could not resolve inner type variable at index {index} for {typ}") diff --git a/tests/test_utils/test_typing.py b/tests/test_utils/test_typing.py new file mode 100644 index 0000000000..690960802a --- /dev/null +++ b/tests/test_utils/test_typing.py @@ -0,0 +1,78 @@ +from __future__ import annotations + +from typing import Generic, TypeVar, cast + +from openai._utils import extract_type_var_from_base + +_T = TypeVar("_T") +_T2 = TypeVar("_T2") +_T3 = TypeVar("_T3") + + +class BaseGeneric(Generic[_T]): + ... + + +class SubclassGeneric(BaseGeneric[_T]): + ... + + +class BaseGenericMultipleTypeArgs(Generic[_T, _T2, _T3]): + ... + + +class SubclassGenericMultipleTypeArgs(BaseGenericMultipleTypeArgs[_T, _T2, _T3]): + ... + + +class SubclassDifferentOrderGenericMultipleTypeArgs(BaseGenericMultipleTypeArgs[_T2, _T, _T3]): + ... + + +def test_extract_type_var() -> None: + assert ( + extract_type_var_from_base( + BaseGeneric[int], + index=0, + generic_bases=cast("tuple[type, ...]", (BaseGeneric,)), + ) + == int + ) + + +def test_extract_type_var_generic_subclass() -> None: + assert ( + extract_type_var_from_base( + SubclassGeneric[int], + index=0, + generic_bases=cast("tuple[type, ...]", (BaseGeneric,)), + ) + == int + ) + + +def test_extract_type_var_multiple() -> None: + typ = BaseGenericMultipleTypeArgs[int, str, None] + + generic_bases = cast("tuple[type, ...]", (BaseGenericMultipleTypeArgs,)) + assert extract_type_var_from_base(typ, index=0, generic_bases=generic_bases) == int + assert extract_type_var_from_base(typ, index=1, generic_bases=generic_bases) == str + assert extract_type_var_from_base(typ, index=2, generic_bases=generic_bases) == type(None) + + +def test_extract_type_var_generic_subclass_multiple() -> None: + typ = SubclassGenericMultipleTypeArgs[int, str, None] + + generic_bases = cast("tuple[type, ...]", (BaseGenericMultipleTypeArgs,)) + assert extract_type_var_from_base(typ, index=0, generic_bases=generic_bases) == int + assert extract_type_var_from_base(typ, index=1, generic_bases=generic_bases) == str + assert extract_type_var_from_base(typ, index=2, generic_bases=generic_bases) == type(None) + + +def test_extract_type_var_generic_subclass_different_ordering_multiple() -> None: + typ = SubclassDifferentOrderGenericMultipleTypeArgs[int, str, None] + + generic_bases = cast("tuple[type, ...]", (BaseGenericMultipleTypeArgs,)) + assert extract_type_var_from_base(typ, index=0, generic_bases=generic_bases) == int + assert extract_type_var_from_base(typ, index=1, generic_bases=generic_bases) == str + assert extract_type_var_from_base(typ, index=2, generic_bases=generic_bases) == type(None) From d9e9d7adbf2f3c615a9ba2125974cf8b8ee6a91d Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 17 Jan 2024 10:55:22 -0500 Subject: [PATCH 199/816] chore(internal): remove redundant client test (#1085) --- tests/test_client.py | 55 -------------------------------------------- 1 file changed, 55 deletions(-) diff --git a/tests/test_client.py b/tests/test_client.py index 7aa473fe9b..3d2dd35821 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -19,7 +19,6 @@ from openai import OpenAI, AsyncOpenAI, APIResponseValidationError from openai._client import OpenAI, AsyncOpenAI from openai._models import BaseModel, FinalRequestOptions -from openai._response import APIResponse, AsyncAPIResponse from openai._constants import RAW_RESPONSE_HEADER from openai._streaming import Stream, AsyncStream from openai._exceptions import OpenAIError, APIStatusError, APITimeoutError, APIResponseValidationError @@ -665,33 +664,6 @@ def test_parse_retry_after_header(self, remaining_retries: int, retry_after: str calculated = client._calculate_retry_timeout(remaining_retries, options, headers) assert calculated == pytest.approx(timeout, 0.5 * 0.875) # pyright: ignore[reportUnknownMemberType] - @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) - @pytest.mark.respx(base_url=base_url) - def test_streaming_response(self) -> None: - response = self.client.post( - "/chat/completions", - body=dict( - messages=[ - { - "role": "user", - "content": "Say this is a test", - } - ], - model="gpt-3.5-turbo", - ), - cast_to=APIResponse[bytes], - options={"headers": {RAW_RESPONSE_HEADER: "stream"}}, - ) - - assert not cast(Any, response.is_closed) - assert _get_open_connections(self.client) == 1 - - for _ in response.iter_bytes(): - ... - - assert cast(Any, response.is_closed) - assert _get_open_connections(self.client) == 0 - @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) @pytest.mark.respx(base_url=base_url) def test_retrying_timeout_errors_doesnt_leak(self, respx_mock: MockRouter) -> None: @@ -1372,33 +1344,6 @@ async def test_parse_retry_after_header(self, remaining_retries: int, retry_afte calculated = client._calculate_retry_timeout(remaining_retries, options, headers) assert calculated == pytest.approx(timeout, 0.5 * 0.875) # pyright: ignore[reportUnknownMemberType] - @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) - @pytest.mark.respx(base_url=base_url) - async def test_streaming_response(self) -> None: - response = await self.client.post( - "/chat/completions", - body=dict( - messages=[ - { - "role": "user", - "content": "Say this is a test", - } - ], - model="gpt-3.5-turbo", - ), - cast_to=AsyncAPIResponse[bytes], - options={"headers": {RAW_RESPONSE_HEADER: "stream"}}, - ) - - assert not cast(Any, response.is_closed) - assert _get_open_connections(self.client) == 1 - - async for _ in response.iter_bytes(): - ... - - assert cast(Any, response.is_closed) - assert _get_open_connections(self.client) == 0 - @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) @pytest.mark.respx(base_url=base_url) async def test_retrying_timeout_errors_doesnt_leak(self, respx_mock: MockRouter) -> None: From d5abe79ea102949335067d4bacb4cce811f1d982 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 17 Jan 2024 11:19:44 -0500 Subject: [PATCH 200/816] chore(internal): speculative retry-after-ms support (#1086) Fixes https://github.com/openai/openai-python/issues/957. --- src/openai/_base_client.py | 66 ++++++++++++++++++++++---------------- src/openai/_constants.py | 3 ++ 2 files changed, 42 insertions(+), 27 deletions(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 1dfbd7dfb3..43fad0603d 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -73,7 +73,9 @@ from ._constants import ( DEFAULT_LIMITS, DEFAULT_TIMEOUT, + MAX_RETRY_DELAY, DEFAULT_MAX_RETRIES, + INITIAL_RETRY_DELAY, RAW_RESPONSE_HEADER, OVERRIDE_CAST_TO_HEADER, ) @@ -590,6 +592,40 @@ def base_url(http://github.com/self,%20url:%20URL%20|%20str) -> None: def platform_headers(self) -> Dict[str, str]: return platform_headers(self._version) + def _parse_retry_after_header(self, response_headers: Optional[httpx.Headers] = None) -> float | None: + """Returns a float of the number of seconds (not milliseconds) to wait after retrying, or None if unspecified. + + About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After + See also https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#syntax + """ + if response_headers is None: + return None + + # First, try the non-standard `retry-after-ms` header for milliseconds, + # which is more precise than integer-seconds `retry-after` + try: + retry_ms_header = response_headers.get("retry-after-ms", None) + return float(retry_ms_header) / 1000 + except (TypeError, ValueError): + pass + + # Next, try parsing `retry-after` header as seconds (allowing nonstandard floats). + retry_header = response_headers.get("retry-after") + try: + # note: the spec indicates that this should only ever be an integer + # but if someone sends a float there's no reason for us to not respect it + return float(retry_header) + except (TypeError, ValueError): + pass + + # Last, try parsing `retry-after` as a date. + retry_date_tuple = email.utils.parsedate_tz(retry_header) + if retry_date_tuple is None: + return None + + retry_date = email.utils.mktime_tz(retry_date_tuple) + return float(retry_date - time.time()) + def _calculate_retry_timeout( self, remaining_retries: int, @@ -597,40 +633,16 @@ def _calculate_retry_timeout( response_headers: Optional[httpx.Headers] = None, ) -> float: max_retries = options.get_max_retries(self.max_retries) - try: - # About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After - # - # ". See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#syntax for - # details. - if response_headers is not None: - retry_header = response_headers.get("retry-after") - try: - # note: the spec indicates that this should only ever be an integer - # but if someone sends a float there's no reason for us to not respect it - retry_after = float(retry_header) - except Exception: - retry_date_tuple = email.utils.parsedate_tz(retry_header) - if retry_date_tuple is None: - retry_after = -1 - else: - retry_date = email.utils.mktime_tz(retry_date_tuple) - retry_after = int(retry_date - time.time()) - else: - retry_after = -1 - - except Exception: - retry_after = -1 # If the API asks us to wait a certain amount of time (and it's a reasonable amount), just do what it says. - if 0 < retry_after <= 60: + retry_after = self._parse_retry_after_header(response_headers) + if retry_after is not None and 0 < retry_after <= 60: return retry_after - initial_retry_delay = 0.5 - max_retry_delay = 8.0 nb_retries = max_retries - remaining_retries # Apply exponential backoff, but not more than the max. - sleep_seconds = min(initial_retry_delay * pow(2.0, nb_retries), max_retry_delay) + sleep_seconds = min(INITIAL_RETRY_DELAY * pow(2.0, nb_retries), MAX_RETRY_DELAY) # Apply some jitter, plus-or-minus half a second. jitter = 1 - 0.25 * random() diff --git a/src/openai/_constants.py b/src/openai/_constants.py index af9a04b80c..dffb8ecfb6 100644 --- a/src/openai/_constants.py +++ b/src/openai/_constants.py @@ -9,3 +9,6 @@ DEFAULT_TIMEOUT = httpx.Timeout(timeout=600.0, connect=5.0) DEFAULT_MAX_RETRIES = 2 DEFAULT_LIMITS = httpx.Limits(max_connections=100, max_keepalive_connections=20) + +INITIAL_RETRY_DELAY = 0.5 +MAX_RETRY_DELAY = 8.0 From c484e0ca903e5e0b7cd8dadfb825c0359744c9eb Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 17 Jan 2024 12:25:14 -0500 Subject: [PATCH 201/816] chore: lazy load raw resource class properties (#1087) --- src/openai/resources/audio/audio.py | 64 +++++++++++++++---- src/openai/resources/audio/speech.py | 8 +++ src/openai/resources/audio/transcriptions.py | 8 +++ src/openai/resources/audio/translations.py | 8 +++ .../resources/beta/assistants/assistants.py | 24 +++++-- src/openai/resources/beta/assistants/files.py | 8 +++ src/openai/resources/beta/beta.py | 44 ++++++++++--- .../resources/beta/threads/messages/files.py | 8 +++ .../beta/threads/messages/messages.py | 24 +++++-- .../resources/beta/threads/runs/runs.py | 24 +++++-- .../resources/beta/threads/runs/steps.py | 8 +++ src/openai/resources/beta/threads/threads.py | 44 ++++++++++--- src/openai/resources/chat/chat.py | 24 +++++-- src/openai/resources/chat/completions.py | 8 +++ src/openai/resources/completions.py | 8 +++ src/openai/resources/embeddings.py | 8 +++ src/openai/resources/files.py | 8 +++ .../resources/fine_tuning/fine_tuning.py | 24 +++++-- src/openai/resources/fine_tuning/jobs.py | 8 +++ src/openai/resources/images.py | 8 +++ src/openai/resources/models.py | 8 +++ src/openai/resources/moderations.py | 8 +++ 22 files changed, 336 insertions(+), 48 deletions(-) diff --git a/src/openai/resources/audio/audio.py b/src/openai/resources/audio/audio.py index b14e64cff6..bafacf4422 100644 --- a/src/openai/resources/audio/audio.py +++ b/src/openai/resources/audio/audio.py @@ -78,27 +78,67 @@ def with_streaming_response(self) -> AsyncAudioWithStreamingResponse: class AudioWithRawResponse: def __init__(self, audio: Audio) -> None: - self.transcriptions = TranscriptionsWithRawResponse(audio.transcriptions) - self.translations = TranslationsWithRawResponse(audio.translations) - self.speech = SpeechWithRawResponse(audio.speech) + self._audio = audio + + @cached_property + def transcriptions(self) -> TranscriptionsWithRawResponse: + return TranscriptionsWithRawResponse(self._audio.transcriptions) + + @cached_property + def translations(self) -> TranslationsWithRawResponse: + return TranslationsWithRawResponse(self._audio.translations) + + @cached_property + def speech(self) -> SpeechWithRawResponse: + return SpeechWithRawResponse(self._audio.speech) class AsyncAudioWithRawResponse: def __init__(self, audio: AsyncAudio) -> None: - self.transcriptions = AsyncTranscriptionsWithRawResponse(audio.transcriptions) - self.translations = AsyncTranslationsWithRawResponse(audio.translations) - self.speech = AsyncSpeechWithRawResponse(audio.speech) + self._audio = audio + + @cached_property + def transcriptions(self) -> AsyncTranscriptionsWithRawResponse: + return AsyncTranscriptionsWithRawResponse(self._audio.transcriptions) + + @cached_property + def translations(self) -> AsyncTranslationsWithRawResponse: + return AsyncTranslationsWithRawResponse(self._audio.translations) + + @cached_property + def speech(self) -> AsyncSpeechWithRawResponse: + return AsyncSpeechWithRawResponse(self._audio.speech) class AudioWithStreamingResponse: def __init__(self, audio: Audio) -> None: - self.transcriptions = TranscriptionsWithStreamingResponse(audio.transcriptions) - self.translations = TranslationsWithStreamingResponse(audio.translations) - self.speech = SpeechWithStreamingResponse(audio.speech) + self._audio = audio + + @cached_property + def transcriptions(self) -> TranscriptionsWithStreamingResponse: + return TranscriptionsWithStreamingResponse(self._audio.transcriptions) + + @cached_property + def translations(self) -> TranslationsWithStreamingResponse: + return TranslationsWithStreamingResponse(self._audio.translations) + + @cached_property + def speech(self) -> SpeechWithStreamingResponse: + return SpeechWithStreamingResponse(self._audio.speech) class AsyncAudioWithStreamingResponse: def __init__(self, audio: AsyncAudio) -> None: - self.transcriptions = AsyncTranscriptionsWithStreamingResponse(audio.transcriptions) - self.translations = AsyncTranslationsWithStreamingResponse(audio.translations) - self.speech = AsyncSpeechWithStreamingResponse(audio.speech) + self._audio = audio + + @cached_property + def transcriptions(self) -> AsyncTranscriptionsWithStreamingResponse: + return AsyncTranscriptionsWithStreamingResponse(self._audio.transcriptions) + + @cached_property + def translations(self) -> AsyncTranslationsWithStreamingResponse: + return AsyncTranslationsWithStreamingResponse(self._audio.translations) + + @cached_property + def speech(self) -> AsyncSpeechWithStreamingResponse: + return AsyncSpeechWithStreamingResponse(self._audio.speech) diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index 9c051624d5..4e94d4aaef 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -170,6 +170,8 @@ async def create( class SpeechWithRawResponse: def __init__(self, speech: Speech) -> None: + self._speech = speech + self.create = _legacy_response.to_raw_response_wrapper( speech.create, ) @@ -177,6 +179,8 @@ def __init__(self, speech: Speech) -> None: class AsyncSpeechWithRawResponse: def __init__(self, speech: AsyncSpeech) -> None: + self._speech = speech + self.create = _legacy_response.async_to_raw_response_wrapper( speech.create, ) @@ -184,6 +188,8 @@ def __init__(self, speech: AsyncSpeech) -> None: class SpeechWithStreamingResponse: def __init__(self, speech: Speech) -> None: + self._speech = speech + self.create = to_custom_streamed_response_wrapper( speech.create, StreamedBinaryAPIResponse, @@ -192,6 +198,8 @@ def __init__(self, speech: Speech) -> None: class AsyncSpeechWithStreamingResponse: def __init__(self, speech: AsyncSpeech) -> None: + self._speech = speech + self.create = async_to_custom_streamed_response_wrapper( speech.create, AsyncStreamedBinaryAPIResponse, diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index 868ce7725f..2c167be395 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -199,6 +199,8 @@ async def create( class TranscriptionsWithRawResponse: def __init__(self, transcriptions: Transcriptions) -> None: + self._transcriptions = transcriptions + self.create = _legacy_response.to_raw_response_wrapper( transcriptions.create, ) @@ -206,6 +208,8 @@ def __init__(self, transcriptions: Transcriptions) -> None: class AsyncTranscriptionsWithRawResponse: def __init__(self, transcriptions: AsyncTranscriptions) -> None: + self._transcriptions = transcriptions + self.create = _legacy_response.async_to_raw_response_wrapper( transcriptions.create, ) @@ -213,6 +217,8 @@ def __init__(self, transcriptions: AsyncTranscriptions) -> None: class TranscriptionsWithStreamingResponse: def __init__(self, transcriptions: Transcriptions) -> None: + self._transcriptions = transcriptions + self.create = to_streamed_response_wrapper( transcriptions.create, ) @@ -220,6 +226,8 @@ def __init__(self, transcriptions: Transcriptions) -> None: class AsyncTranscriptionsWithStreamingResponse: def __init__(self, transcriptions: AsyncTranscriptions) -> None: + self._transcriptions = transcriptions + self.create = async_to_streamed_response_wrapper( transcriptions.create, ) diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index 333abfb4cf..d6cbc75886 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -185,6 +185,8 @@ async def create( class TranslationsWithRawResponse: def __init__(self, translations: Translations) -> None: + self._translations = translations + self.create = _legacy_response.to_raw_response_wrapper( translations.create, ) @@ -192,6 +194,8 @@ def __init__(self, translations: Translations) -> None: class AsyncTranslationsWithRawResponse: def __init__(self, translations: AsyncTranslations) -> None: + self._translations = translations + self.create = _legacy_response.async_to_raw_response_wrapper( translations.create, ) @@ -199,6 +203,8 @@ def __init__(self, translations: AsyncTranslations) -> None: class TranslationsWithStreamingResponse: def __init__(self, translations: Translations) -> None: + self._translations = translations + self.create = to_streamed_response_wrapper( translations.create, ) @@ -206,6 +212,8 @@ def __init__(self, translations: Translations) -> None: class AsyncTranslationsWithStreamingResponse: def __init__(self, translations: AsyncTranslations) -> None: + self._translations = translations + self.create = async_to_streamed_response_wrapper( translations.create, ) diff --git a/src/openai/resources/beta/assistants/assistants.py b/src/openai/resources/beta/assistants/assistants.py index a40acfb323..3a2418ad90 100644 --- a/src/openai/resources/beta/assistants/assistants.py +++ b/src/openai/resources/beta/assistants/assistants.py @@ -645,7 +645,7 @@ async def delete( class AssistantsWithRawResponse: def __init__(self, assistants: Assistants) -> None: - self.files = FilesWithRawResponse(assistants.files) + self._assistants = assistants self.create = _legacy_response.to_raw_response_wrapper( assistants.create, @@ -663,10 +663,14 @@ def __init__(self, assistants: Assistants) -> None: assistants.delete, ) + @cached_property + def files(self) -> FilesWithRawResponse: + return FilesWithRawResponse(self._assistants.files) + class AsyncAssistantsWithRawResponse: def __init__(self, assistants: AsyncAssistants) -> None: - self.files = AsyncFilesWithRawResponse(assistants.files) + self._assistants = assistants self.create = _legacy_response.async_to_raw_response_wrapper( assistants.create, @@ -684,10 +688,14 @@ def __init__(self, assistants: AsyncAssistants) -> None: assistants.delete, ) + @cached_property + def files(self) -> AsyncFilesWithRawResponse: + return AsyncFilesWithRawResponse(self._assistants.files) + class AssistantsWithStreamingResponse: def __init__(self, assistants: Assistants) -> None: - self.files = FilesWithStreamingResponse(assistants.files) + self._assistants = assistants self.create = to_streamed_response_wrapper( assistants.create, @@ -705,10 +713,14 @@ def __init__(self, assistants: Assistants) -> None: assistants.delete, ) + @cached_property + def files(self) -> FilesWithStreamingResponse: + return FilesWithStreamingResponse(self._assistants.files) + class AsyncAssistantsWithStreamingResponse: def __init__(self, assistants: AsyncAssistants) -> None: - self.files = AsyncFilesWithStreamingResponse(assistants.files) + self._assistants = assistants self.create = async_to_streamed_response_wrapper( assistants.create, @@ -725,3 +737,7 @@ def __init__(self, assistants: AsyncAssistants) -> None: self.delete = async_to_streamed_response_wrapper( assistants.delete, ) + + @cached_property + def files(self) -> AsyncFilesWithStreamingResponse: + return AsyncFilesWithStreamingResponse(self._assistants.files) diff --git a/src/openai/resources/beta/assistants/files.py b/src/openai/resources/beta/assistants/files.py index 12247044c4..c21465036a 100644 --- a/src/openai/resources/beta/assistants/files.py +++ b/src/openai/resources/beta/assistants/files.py @@ -410,6 +410,8 @@ async def delete( class FilesWithRawResponse: def __init__(self, files: Files) -> None: + self._files = files + self.create = _legacy_response.to_raw_response_wrapper( files.create, ) @@ -426,6 +428,8 @@ def __init__(self, files: Files) -> None: class AsyncFilesWithRawResponse: def __init__(self, files: AsyncFiles) -> None: + self._files = files + self.create = _legacy_response.async_to_raw_response_wrapper( files.create, ) @@ -442,6 +446,8 @@ def __init__(self, files: AsyncFiles) -> None: class FilesWithStreamingResponse: def __init__(self, files: Files) -> None: + self._files = files + self.create = to_streamed_response_wrapper( files.create, ) @@ -458,6 +464,8 @@ def __init__(self, files: Files) -> None: class AsyncFilesWithStreamingResponse: def __init__(self, files: AsyncFiles) -> None: + self._files = files + self.create = async_to_streamed_response_wrapper( files.create, ) diff --git a/src/openai/resources/beta/beta.py b/src/openai/resources/beta/beta.py index b11a706d5d..7081cff305 100644 --- a/src/openai/resources/beta/beta.py +++ b/src/openai/resources/beta/beta.py @@ -64,23 +64,51 @@ def with_streaming_response(self) -> AsyncBetaWithStreamingResponse: class BetaWithRawResponse: def __init__(self, beta: Beta) -> None: - self.assistants = AssistantsWithRawResponse(beta.assistants) - self.threads = ThreadsWithRawResponse(beta.threads) + self._beta = beta + + @cached_property + def assistants(self) -> AssistantsWithRawResponse: + return AssistantsWithRawResponse(self._beta.assistants) + + @cached_property + def threads(self) -> ThreadsWithRawResponse: + return ThreadsWithRawResponse(self._beta.threads) class AsyncBetaWithRawResponse: def __init__(self, beta: AsyncBeta) -> None: - self.assistants = AsyncAssistantsWithRawResponse(beta.assistants) - self.threads = AsyncThreadsWithRawResponse(beta.threads) + self._beta = beta + + @cached_property + def assistants(self) -> AsyncAssistantsWithRawResponse: + return AsyncAssistantsWithRawResponse(self._beta.assistants) + + @cached_property + def threads(self) -> AsyncThreadsWithRawResponse: + return AsyncThreadsWithRawResponse(self._beta.threads) class BetaWithStreamingResponse: def __init__(self, beta: Beta) -> None: - self.assistants = AssistantsWithStreamingResponse(beta.assistants) - self.threads = ThreadsWithStreamingResponse(beta.threads) + self._beta = beta + + @cached_property + def assistants(self) -> AssistantsWithStreamingResponse: + return AssistantsWithStreamingResponse(self._beta.assistants) + + @cached_property + def threads(self) -> ThreadsWithStreamingResponse: + return ThreadsWithStreamingResponse(self._beta.threads) class AsyncBetaWithStreamingResponse: def __init__(self, beta: AsyncBeta) -> None: - self.assistants = AsyncAssistantsWithStreamingResponse(beta.assistants) - self.threads = AsyncThreadsWithStreamingResponse(beta.threads) + self._beta = beta + + @cached_property + def assistants(self) -> AsyncAssistantsWithStreamingResponse: + return AsyncAssistantsWithStreamingResponse(self._beta.assistants) + + @cached_property + def threads(self) -> AsyncThreadsWithStreamingResponse: + return AsyncThreadsWithStreamingResponse(self._beta.threads) diff --git a/src/openai/resources/beta/threads/messages/files.py b/src/openai/resources/beta/threads/messages/files.py index 8b6c4581d0..fc8b894d72 100644 --- a/src/openai/resources/beta/threads/messages/files.py +++ b/src/openai/resources/beta/threads/messages/files.py @@ -266,6 +266,8 @@ def list( class FilesWithRawResponse: def __init__(self, files: Files) -> None: + self._files = files + self.retrieve = _legacy_response.to_raw_response_wrapper( files.retrieve, ) @@ -276,6 +278,8 @@ def __init__(self, files: Files) -> None: class AsyncFilesWithRawResponse: def __init__(self, files: AsyncFiles) -> None: + self._files = files + self.retrieve = _legacy_response.async_to_raw_response_wrapper( files.retrieve, ) @@ -286,6 +290,8 @@ def __init__(self, files: AsyncFiles) -> None: class FilesWithStreamingResponse: def __init__(self, files: Files) -> None: + self._files = files + self.retrieve = to_streamed_response_wrapper( files.retrieve, ) @@ -296,6 +302,8 @@ def __init__(self, files: Files) -> None: class AsyncFilesWithStreamingResponse: def __init__(self, files: AsyncFiles) -> None: + self._files = files + self.retrieve = async_to_streamed_response_wrapper( files.retrieve, ) diff --git a/src/openai/resources/beta/threads/messages/messages.py b/src/openai/resources/beta/threads/messages/messages.py index f5a17f902f..c95cdd5d00 100644 --- a/src/openai/resources/beta/threads/messages/messages.py +++ b/src/openai/resources/beta/threads/messages/messages.py @@ -481,7 +481,7 @@ def list( class MessagesWithRawResponse: def __init__(self, messages: Messages) -> None: - self.files = FilesWithRawResponse(messages.files) + self._messages = messages self.create = _legacy_response.to_raw_response_wrapper( messages.create, @@ -496,10 +496,14 @@ def __init__(self, messages: Messages) -> None: messages.list, ) + @cached_property + def files(self) -> FilesWithRawResponse: + return FilesWithRawResponse(self._messages.files) + class AsyncMessagesWithRawResponse: def __init__(self, messages: AsyncMessages) -> None: - self.files = AsyncFilesWithRawResponse(messages.files) + self._messages = messages self.create = _legacy_response.async_to_raw_response_wrapper( messages.create, @@ -514,10 +518,14 @@ def __init__(self, messages: AsyncMessages) -> None: messages.list, ) + @cached_property + def files(self) -> AsyncFilesWithRawResponse: + return AsyncFilesWithRawResponse(self._messages.files) + class MessagesWithStreamingResponse: def __init__(self, messages: Messages) -> None: - self.files = FilesWithStreamingResponse(messages.files) + self._messages = messages self.create = to_streamed_response_wrapper( messages.create, @@ -532,10 +540,14 @@ def __init__(self, messages: Messages) -> None: messages.list, ) + @cached_property + def files(self) -> FilesWithStreamingResponse: + return FilesWithStreamingResponse(self._messages.files) + class AsyncMessagesWithStreamingResponse: def __init__(self, messages: AsyncMessages) -> None: - self.files = AsyncFilesWithStreamingResponse(messages.files) + self._messages = messages self.create = async_to_streamed_response_wrapper( messages.create, @@ -549,3 +561,7 @@ def __init__(self, messages: AsyncMessages) -> None: self.list = async_to_streamed_response_wrapper( messages.list, ) + + @cached_property + def files(self) -> AsyncFilesWithStreamingResponse: + return AsyncFilesWithStreamingResponse(self._messages.files) diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index ac7a1b3330..0ed48b4792 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -681,7 +681,7 @@ async def submit_tool_outputs( class RunsWithRawResponse: def __init__(self, runs: Runs) -> None: - self.steps = StepsWithRawResponse(runs.steps) + self._runs = runs self.create = _legacy_response.to_raw_response_wrapper( runs.create, @@ -702,10 +702,14 @@ def __init__(self, runs: Runs) -> None: runs.submit_tool_outputs, ) + @cached_property + def steps(self) -> StepsWithRawResponse: + return StepsWithRawResponse(self._runs.steps) + class AsyncRunsWithRawResponse: def __init__(self, runs: AsyncRuns) -> None: - self.steps = AsyncStepsWithRawResponse(runs.steps) + self._runs = runs self.create = _legacy_response.async_to_raw_response_wrapper( runs.create, @@ -726,10 +730,14 @@ def __init__(self, runs: AsyncRuns) -> None: runs.submit_tool_outputs, ) + @cached_property + def steps(self) -> AsyncStepsWithRawResponse: + return AsyncStepsWithRawResponse(self._runs.steps) + class RunsWithStreamingResponse: def __init__(self, runs: Runs) -> None: - self.steps = StepsWithStreamingResponse(runs.steps) + self._runs = runs self.create = to_streamed_response_wrapper( runs.create, @@ -750,10 +758,14 @@ def __init__(self, runs: Runs) -> None: runs.submit_tool_outputs, ) + @cached_property + def steps(self) -> StepsWithStreamingResponse: + return StepsWithStreamingResponse(self._runs.steps) + class AsyncRunsWithStreamingResponse: def __init__(self, runs: AsyncRuns) -> None: - self.steps = AsyncStepsWithStreamingResponse(runs.steps) + self._runs = runs self.create = async_to_streamed_response_wrapper( runs.create, @@ -773,3 +785,7 @@ def __init__(self, runs: AsyncRuns) -> None: self.submit_tool_outputs = async_to_streamed_response_wrapper( runs.submit_tool_outputs, ) + + @cached_property + def steps(self) -> AsyncStepsWithStreamingResponse: + return AsyncStepsWithStreamingResponse(self._runs.steps) diff --git a/src/openai/resources/beta/threads/runs/steps.py b/src/openai/resources/beta/threads/runs/steps.py index 9b1df10652..539745a594 100644 --- a/src/openai/resources/beta/threads/runs/steps.py +++ b/src/openai/resources/beta/threads/runs/steps.py @@ -264,6 +264,8 @@ def list( class StepsWithRawResponse: def __init__(self, steps: Steps) -> None: + self._steps = steps + self.retrieve = _legacy_response.to_raw_response_wrapper( steps.retrieve, ) @@ -274,6 +276,8 @@ def __init__(self, steps: Steps) -> None: class AsyncStepsWithRawResponse: def __init__(self, steps: AsyncSteps) -> None: + self._steps = steps + self.retrieve = _legacy_response.async_to_raw_response_wrapper( steps.retrieve, ) @@ -284,6 +288,8 @@ def __init__(self, steps: AsyncSteps) -> None: class StepsWithStreamingResponse: def __init__(self, steps: Steps) -> None: + self._steps = steps + self.retrieve = to_streamed_response_wrapper( steps.retrieve, ) @@ -294,6 +300,8 @@ def __init__(self, steps: Steps) -> None: class AsyncStepsWithStreamingResponse: def __init__(self, steps: AsyncSteps) -> None: + self._steps = steps + self.retrieve = async_to_streamed_response_wrapper( steps.retrieve, ) diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index d885404f59..0372ae2f66 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -537,8 +537,7 @@ async def create_and_run( class ThreadsWithRawResponse: def __init__(self, threads: Threads) -> None: - self.runs = RunsWithRawResponse(threads.runs) - self.messages = MessagesWithRawResponse(threads.messages) + self._threads = threads self.create = _legacy_response.to_raw_response_wrapper( threads.create, @@ -556,11 +555,18 @@ def __init__(self, threads: Threads) -> None: threads.create_and_run, ) + @cached_property + def runs(self) -> RunsWithRawResponse: + return RunsWithRawResponse(self._threads.runs) + + @cached_property + def messages(self) -> MessagesWithRawResponse: + return MessagesWithRawResponse(self._threads.messages) + class AsyncThreadsWithRawResponse: def __init__(self, threads: AsyncThreads) -> None: - self.runs = AsyncRunsWithRawResponse(threads.runs) - self.messages = AsyncMessagesWithRawResponse(threads.messages) + self._threads = threads self.create = _legacy_response.async_to_raw_response_wrapper( threads.create, @@ -578,11 +584,18 @@ def __init__(self, threads: AsyncThreads) -> None: threads.create_and_run, ) + @cached_property + def runs(self) -> AsyncRunsWithRawResponse: + return AsyncRunsWithRawResponse(self._threads.runs) + + @cached_property + def messages(self) -> AsyncMessagesWithRawResponse: + return AsyncMessagesWithRawResponse(self._threads.messages) + class ThreadsWithStreamingResponse: def __init__(self, threads: Threads) -> None: - self.runs = RunsWithStreamingResponse(threads.runs) - self.messages = MessagesWithStreamingResponse(threads.messages) + self._threads = threads self.create = to_streamed_response_wrapper( threads.create, @@ -600,11 +613,18 @@ def __init__(self, threads: Threads) -> None: threads.create_and_run, ) + @cached_property + def runs(self) -> RunsWithStreamingResponse: + return RunsWithStreamingResponse(self._threads.runs) + + @cached_property + def messages(self) -> MessagesWithStreamingResponse: + return MessagesWithStreamingResponse(self._threads.messages) + class AsyncThreadsWithStreamingResponse: def __init__(self, threads: AsyncThreads) -> None: - self.runs = AsyncRunsWithStreamingResponse(threads.runs) - self.messages = AsyncMessagesWithStreamingResponse(threads.messages) + self._threads = threads self.create = async_to_streamed_response_wrapper( threads.create, @@ -621,3 +641,11 @@ def __init__(self, threads: AsyncThreads) -> None: self.create_and_run = async_to_streamed_response_wrapper( threads.create_and_run, ) + + @cached_property + def runs(self) -> AsyncRunsWithStreamingResponse: + return AsyncRunsWithStreamingResponse(self._threads.runs) + + @cached_property + def messages(self) -> AsyncMessagesWithStreamingResponse: + return AsyncMessagesWithStreamingResponse(self._threads.messages) diff --git a/src/openai/resources/chat/chat.py b/src/openai/resources/chat/chat.py index 467a5e401b..b6effa4e63 100644 --- a/src/openai/resources/chat/chat.py +++ b/src/openai/resources/chat/chat.py @@ -46,19 +46,35 @@ def with_streaming_response(self) -> AsyncChatWithStreamingResponse: class ChatWithRawResponse: def __init__(self, chat: Chat) -> None: - self.completions = CompletionsWithRawResponse(chat.completions) + self._chat = chat + + @cached_property + def completions(self) -> CompletionsWithRawResponse: + return CompletionsWithRawResponse(self._chat.completions) class AsyncChatWithRawResponse: def __init__(self, chat: AsyncChat) -> None: - self.completions = AsyncCompletionsWithRawResponse(chat.completions) + self._chat = chat + + @cached_property + def completions(self) -> AsyncCompletionsWithRawResponse: + return AsyncCompletionsWithRawResponse(self._chat.completions) class ChatWithStreamingResponse: def __init__(self, chat: Chat) -> None: - self.completions = CompletionsWithStreamingResponse(chat.completions) + self._chat = chat + + @cached_property + def completions(self) -> CompletionsWithStreamingResponse: + return CompletionsWithStreamingResponse(self._chat.completions) class AsyncChatWithStreamingResponse: def __init__(self, chat: AsyncChat) -> None: - self.completions = AsyncCompletionsWithStreamingResponse(chat.completions) + self._chat = chat + + @cached_property + def completions(self) -> AsyncCompletionsWithStreamingResponse: + return AsyncCompletionsWithStreamingResponse(self._chat.completions) diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index 53645a9eb9..f461161ab7 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -1335,6 +1335,8 @@ async def create( class CompletionsWithRawResponse: def __init__(self, completions: Completions) -> None: + self._completions = completions + self.create = _legacy_response.to_raw_response_wrapper( completions.create, ) @@ -1342,6 +1344,8 @@ def __init__(self, completions: Completions) -> None: class AsyncCompletionsWithRawResponse: def __init__(self, completions: AsyncCompletions) -> None: + self._completions = completions + self.create = _legacy_response.async_to_raw_response_wrapper( completions.create, ) @@ -1349,6 +1353,8 @@ def __init__(self, completions: AsyncCompletions) -> None: class CompletionsWithStreamingResponse: def __init__(self, completions: Completions) -> None: + self._completions = completions + self.create = to_streamed_response_wrapper( completions.create, ) @@ -1356,6 +1362,8 @@ def __init__(self, completions: Completions) -> None: class AsyncCompletionsWithStreamingResponse: def __init__(self, completions: AsyncCompletions) -> None: + self._completions = completions + self.create = async_to_streamed_response_wrapper( completions.create, ) diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index 43a9947524..3d2e10230a 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -1052,6 +1052,8 @@ async def create( class CompletionsWithRawResponse: def __init__(self, completions: Completions) -> None: + self._completions = completions + self.create = _legacy_response.to_raw_response_wrapper( completions.create, ) @@ -1059,6 +1061,8 @@ def __init__(self, completions: Completions) -> None: class AsyncCompletionsWithRawResponse: def __init__(self, completions: AsyncCompletions) -> None: + self._completions = completions + self.create = _legacy_response.async_to_raw_response_wrapper( completions.create, ) @@ -1066,6 +1070,8 @@ def __init__(self, completions: AsyncCompletions) -> None: class CompletionsWithStreamingResponse: def __init__(self, completions: Completions) -> None: + self._completions = completions + self.create = to_streamed_response_wrapper( completions.create, ) @@ -1073,6 +1079,8 @@ def __init__(self, completions: Completions) -> None: class AsyncCompletionsWithStreamingResponse: def __init__(self, completions: AsyncCompletions) -> None: + self._completions = completions + self.create = async_to_streamed_response_wrapper( completions.create, ) diff --git a/src/openai/resources/embeddings.py b/src/openai/resources/embeddings.py index 49ce0f2fc8..5bc7ed855e 100644 --- a/src/openai/resources/embeddings.py +++ b/src/openai/resources/embeddings.py @@ -217,6 +217,8 @@ def parser(obj: CreateEmbeddingResponse) -> CreateEmbeddingResponse: class EmbeddingsWithRawResponse: def __init__(self, embeddings: Embeddings) -> None: + self._embeddings = embeddings + self.create = _legacy_response.to_raw_response_wrapper( embeddings.create, ) @@ -224,6 +226,8 @@ def __init__(self, embeddings: Embeddings) -> None: class AsyncEmbeddingsWithRawResponse: def __init__(self, embeddings: AsyncEmbeddings) -> None: + self._embeddings = embeddings + self.create = _legacy_response.async_to_raw_response_wrapper( embeddings.create, ) @@ -231,6 +235,8 @@ def __init__(self, embeddings: AsyncEmbeddings) -> None: class EmbeddingsWithStreamingResponse: def __init__(self, embeddings: Embeddings) -> None: + self._embeddings = embeddings + self.create = to_streamed_response_wrapper( embeddings.create, ) @@ -238,6 +244,8 @@ def __init__(self, embeddings: Embeddings) -> None: class AsyncEmbeddingsWithStreamingResponse: def __init__(self, embeddings: AsyncEmbeddings) -> None: + self._embeddings = embeddings + self.create = async_to_streamed_response_wrapper( embeddings.create, ) diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index ff924340ac..58a2a217c7 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -580,6 +580,8 @@ async def wait_for_processing( class FilesWithRawResponse: def __init__(self, files: Files) -> None: + self._files = files + self.create = _legacy_response.to_raw_response_wrapper( files.create, ) @@ -604,6 +606,8 @@ def __init__(self, files: Files) -> None: class AsyncFilesWithRawResponse: def __init__(self, files: AsyncFiles) -> None: + self._files = files + self.create = _legacy_response.async_to_raw_response_wrapper( files.create, ) @@ -628,6 +632,8 @@ def __init__(self, files: AsyncFiles) -> None: class FilesWithStreamingResponse: def __init__(self, files: Files) -> None: + self._files = files + self.create = to_streamed_response_wrapper( files.create, ) @@ -653,6 +659,8 @@ def __init__(self, files: Files) -> None: class AsyncFilesWithStreamingResponse: def __init__(self, files: AsyncFiles) -> None: + self._files = files + self.create = async_to_streamed_response_wrapper( files.create, ) diff --git a/src/openai/resources/fine_tuning/fine_tuning.py b/src/openai/resources/fine_tuning/fine_tuning.py index 197d46fb83..33b25baec9 100644 --- a/src/openai/resources/fine_tuning/fine_tuning.py +++ b/src/openai/resources/fine_tuning/fine_tuning.py @@ -46,19 +46,35 @@ def with_streaming_response(self) -> AsyncFineTuningWithStreamingResponse: class FineTuningWithRawResponse: def __init__(self, fine_tuning: FineTuning) -> None: - self.jobs = JobsWithRawResponse(fine_tuning.jobs) + self._fine_tuning = fine_tuning + + @cached_property + def jobs(self) -> JobsWithRawResponse: + return JobsWithRawResponse(self._fine_tuning.jobs) class AsyncFineTuningWithRawResponse: def __init__(self, fine_tuning: AsyncFineTuning) -> None: - self.jobs = AsyncJobsWithRawResponse(fine_tuning.jobs) + self._fine_tuning = fine_tuning + + @cached_property + def jobs(self) -> AsyncJobsWithRawResponse: + return AsyncJobsWithRawResponse(self._fine_tuning.jobs) class FineTuningWithStreamingResponse: def __init__(self, fine_tuning: FineTuning) -> None: - self.jobs = JobsWithStreamingResponse(fine_tuning.jobs) + self._fine_tuning = fine_tuning + + @cached_property + def jobs(self) -> JobsWithStreamingResponse: + return JobsWithStreamingResponse(self._fine_tuning.jobs) class AsyncFineTuningWithStreamingResponse: def __init__(self, fine_tuning: AsyncFineTuning) -> None: - self.jobs = AsyncJobsWithStreamingResponse(fine_tuning.jobs) + self._fine_tuning = fine_tuning + + @cached_property + def jobs(self) -> AsyncJobsWithStreamingResponse: + return AsyncJobsWithStreamingResponse(self._fine_tuning.jobs) diff --git a/src/openai/resources/fine_tuning/jobs.py b/src/openai/resources/fine_tuning/jobs.py index 208591fa47..6b59932982 100644 --- a/src/openai/resources/fine_tuning/jobs.py +++ b/src/openai/resources/fine_tuning/jobs.py @@ -553,6 +553,8 @@ def list_events( class JobsWithRawResponse: def __init__(self, jobs: Jobs) -> None: + self._jobs = jobs + self.create = _legacy_response.to_raw_response_wrapper( jobs.create, ) @@ -572,6 +574,8 @@ def __init__(self, jobs: Jobs) -> None: class AsyncJobsWithRawResponse: def __init__(self, jobs: AsyncJobs) -> None: + self._jobs = jobs + self.create = _legacy_response.async_to_raw_response_wrapper( jobs.create, ) @@ -591,6 +595,8 @@ def __init__(self, jobs: AsyncJobs) -> None: class JobsWithStreamingResponse: def __init__(self, jobs: Jobs) -> None: + self._jobs = jobs + self.create = to_streamed_response_wrapper( jobs.create, ) @@ -610,6 +616,8 @@ def __init__(self, jobs: Jobs) -> None: class AsyncJobsWithStreamingResponse: def __init__(self, jobs: AsyncJobs) -> None: + self._jobs = jobs + self.create = async_to_streamed_response_wrapper( jobs.create, ) diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py index a3eb98574e..91530e47ca 100644 --- a/src/openai/resources/images.py +++ b/src/openai/resources/images.py @@ -518,6 +518,8 @@ async def generate( class ImagesWithRawResponse: def __init__(self, images: Images) -> None: + self._images = images + self.create_variation = _legacy_response.to_raw_response_wrapper( images.create_variation, ) @@ -531,6 +533,8 @@ def __init__(self, images: Images) -> None: class AsyncImagesWithRawResponse: def __init__(self, images: AsyncImages) -> None: + self._images = images + self.create_variation = _legacy_response.async_to_raw_response_wrapper( images.create_variation, ) @@ -544,6 +548,8 @@ def __init__(self, images: AsyncImages) -> None: class ImagesWithStreamingResponse: def __init__(self, images: Images) -> None: + self._images = images + self.create_variation = to_streamed_response_wrapper( images.create_variation, ) @@ -557,6 +563,8 @@ def __init__(self, images: Images) -> None: class AsyncImagesWithStreamingResponse: def __init__(self, images: AsyncImages) -> None: + self._images = images + self.create_variation = async_to_streamed_response_wrapper( images.create_variation, ) diff --git a/src/openai/resources/models.py b/src/openai/resources/models.py index e4a0d84810..3536f083d2 100644 --- a/src/openai/resources/models.py +++ b/src/openai/resources/models.py @@ -225,6 +225,8 @@ async def delete( class ModelsWithRawResponse: def __init__(self, models: Models) -> None: + self._models = models + self.retrieve = _legacy_response.to_raw_response_wrapper( models.retrieve, ) @@ -238,6 +240,8 @@ def __init__(self, models: Models) -> None: class AsyncModelsWithRawResponse: def __init__(self, models: AsyncModels) -> None: + self._models = models + self.retrieve = _legacy_response.async_to_raw_response_wrapper( models.retrieve, ) @@ -251,6 +255,8 @@ def __init__(self, models: AsyncModels) -> None: class ModelsWithStreamingResponse: def __init__(self, models: Models) -> None: + self._models = models + self.retrieve = to_streamed_response_wrapper( models.retrieve, ) @@ -264,6 +270,8 @@ def __init__(self, models: Models) -> None: class AsyncModelsWithStreamingResponse: def __init__(self, models: AsyncModels) -> None: + self._models = models + self.retrieve = async_to_streamed_response_wrapper( models.retrieve, ) diff --git a/src/openai/resources/moderations.py b/src/openai/resources/moderations.py index e7681f6263..540d089071 100644 --- a/src/openai/resources/moderations.py +++ b/src/openai/resources/moderations.py @@ -143,6 +143,8 @@ async def create( class ModerationsWithRawResponse: def __init__(self, moderations: Moderations) -> None: + self._moderations = moderations + self.create = _legacy_response.to_raw_response_wrapper( moderations.create, ) @@ -150,6 +152,8 @@ def __init__(self, moderations: Moderations) -> None: class AsyncModerationsWithRawResponse: def __init__(self, moderations: AsyncModerations) -> None: + self._moderations = moderations + self.create = _legacy_response.async_to_raw_response_wrapper( moderations.create, ) @@ -157,6 +161,8 @@ def __init__(self, moderations: AsyncModerations) -> None: class ModerationsWithStreamingResponse: def __init__(self, moderations: Moderations) -> None: + self._moderations = moderations + self.create = to_streamed_response_wrapper( moderations.create, ) @@ -164,6 +170,8 @@ def __init__(self, moderations: Moderations) -> None: class AsyncModerationsWithStreamingResponse: def __init__(self, moderations: AsyncModerations) -> None: + self._moderations = moderations + self.create = async_to_streamed_response_wrapper( moderations.create, ) From 98d779fbfe97470c6ebd15b188ee9602ee5621bd Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 18 Jan 2024 11:41:33 -0500 Subject: [PATCH 202/816] chore(internal): share client instances between all tests (#1088) --- tests/api_resources/audio/test_speech.py | 26 ++-- .../audio/test_transcriptions.py | 26 ++-- .../api_resources/audio/test_translations.py | 26 ++-- .../beta/assistants/test_files.py | 82 ++++++------ tests/api_resources/beta/test_assistants.py | 94 ++++++------- tests/api_resources/beta/test_threads.py | 94 ++++++------- .../beta/threads/messages/test_files.py | 52 ++++---- .../beta/threads/runs/test_steps.py | 52 ++++---- .../beta/threads/test_messages.py | 90 ++++++------- tests/api_resources/beta/threads/test_runs.py | 126 +++++++++--------- tests/api_resources/chat/test_completions.py | 42 +++--- tests/api_resources/fine_tuning/test_jobs.py | 94 ++++++------- tests/api_resources/test_completions.py | 42 +++--- tests/api_resources/test_embeddings.py | 26 ++-- tests/api_resources/test_files.py | 102 +++++++------- tests/api_resources/test_images.py | 58 ++++---- tests/api_resources/test_models.py | 54 ++++---- tests/api_resources/test_moderations.py | 26 ++-- tests/conftest.py | 35 ++++- 19 files changed, 536 insertions(+), 611 deletions(-) diff --git a/tests/api_resources/audio/test_speech.py b/tests/api_resources/audio/test_speech.py index a689c0d220..b1c7f79b1e 100644 --- a/tests/api_resources/audio/test_speech.py +++ b/tests/api_resources/audio/test_speech.py @@ -12,18 +12,14 @@ import openai._legacy_response as _legacy_response from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai._client import OpenAI, AsyncOpenAI # pyright: reportDeprecated=false base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") -api_key = "My API Key" class TestSpeech: - strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize @pytest.mark.respx(base_url=base_url) @@ -86,15 +82,13 @@ def test_streaming_response_create(self, client: OpenAI, respx_mock: MockRouter) class TestAsyncSpeech: - strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize @pytest.mark.respx(base_url=base_url) - async def test_method_create(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: + async def test_method_create(self, async_client: AsyncOpenAI, respx_mock: MockRouter) -> None: respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) - speech = await client.audio.speech.create( + speech = await async_client.audio.speech.create( input="string", model="string", voice="alloy", @@ -104,9 +98,9 @@ async def test_method_create(self, client: AsyncOpenAI, respx_mock: MockRouter) @parametrize @pytest.mark.respx(base_url=base_url) - async def test_method_create_with_all_params(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: + async def test_method_create_with_all_params(self, async_client: AsyncOpenAI, respx_mock: MockRouter) -> None: respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) - speech = await client.audio.speech.create( + speech = await async_client.audio.speech.create( input="string", model="string", voice="alloy", @@ -118,10 +112,10 @@ async def test_method_create_with_all_params(self, client: AsyncOpenAI, respx_mo @parametrize @pytest.mark.respx(base_url=base_url) - async def test_raw_response_create(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: + async def test_raw_response_create(self, async_client: AsyncOpenAI, respx_mock: MockRouter) -> None: respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) - response = await client.audio.speech.with_raw_response.create( + response = await async_client.audio.speech.with_raw_response.create( input="string", model="string", voice="alloy", @@ -134,9 +128,9 @@ async def test_raw_response_create(self, client: AsyncOpenAI, respx_mock: MockRo @parametrize @pytest.mark.respx(base_url=base_url) - async def test_streaming_response_create(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: + async def test_streaming_response_create(self, async_client: AsyncOpenAI, respx_mock: MockRouter) -> None: respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) - async with client.audio.speech.with_streaming_response.create( + async with async_client.audio.speech.with_streaming_response.create( input="string", model="string", voice="alloy", diff --git a/tests/api_resources/audio/test_transcriptions.py b/tests/api_resources/audio/test_transcriptions.py index 992adbabd9..d957871abc 100644 --- a/tests/api_resources/audio/test_transcriptions.py +++ b/tests/api_resources/audio/test_transcriptions.py @@ -9,17 +9,13 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai._client import OpenAI, AsyncOpenAI from openai.types.audio import Transcription base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") -api_key = "My API Key" class TestTranscriptions: - strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize def test_method_create(self, client: OpenAI) -> None: @@ -69,21 +65,19 @@ def test_streaming_response_create(self, client: OpenAI) -> None: class TestAsyncTranscriptions: - strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize - async def test_method_create(self, client: AsyncOpenAI) -> None: - transcription = await client.audio.transcriptions.create( + async def test_method_create(self, async_client: AsyncOpenAI) -> None: + transcription = await async_client.audio.transcriptions.create( file=b"raw file contents", model="whisper-1", ) assert_matches_type(Transcription, transcription, path=["response"]) @parametrize - async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: - transcription = await client.audio.transcriptions.create( + async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: + transcription = await async_client.audio.transcriptions.create( file=b"raw file contents", model="whisper-1", language="string", @@ -94,8 +88,8 @@ async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: assert_matches_type(Transcription, transcription, path=["response"]) @parametrize - async def test_raw_response_create(self, client: AsyncOpenAI) -> None: - response = await client.audio.transcriptions.with_raw_response.create( + async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: + response = await async_client.audio.transcriptions.with_raw_response.create( file=b"raw file contents", model="whisper-1", ) @@ -106,8 +100,8 @@ async def test_raw_response_create(self, client: AsyncOpenAI) -> None: assert_matches_type(Transcription, transcription, path=["response"]) @parametrize - async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: - async with client.audio.transcriptions.with_streaming_response.create( + async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: + async with async_client.audio.transcriptions.with_streaming_response.create( file=b"raw file contents", model="whisper-1", ) as response: diff --git a/tests/api_resources/audio/test_translations.py b/tests/api_resources/audio/test_translations.py index 913c443a79..72960c3249 100644 --- a/tests/api_resources/audio/test_translations.py +++ b/tests/api_resources/audio/test_translations.py @@ -9,17 +9,13 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai._client import OpenAI, AsyncOpenAI from openai.types.audio import Translation base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") -api_key = "My API Key" class TestTranslations: - strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize def test_method_create(self, client: OpenAI) -> None: @@ -68,21 +64,19 @@ def test_streaming_response_create(self, client: OpenAI) -> None: class TestAsyncTranslations: - strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize - async def test_method_create(self, client: AsyncOpenAI) -> None: - translation = await client.audio.translations.create( + async def test_method_create(self, async_client: AsyncOpenAI) -> None: + translation = await async_client.audio.translations.create( file=b"raw file contents", model="whisper-1", ) assert_matches_type(Translation, translation, path=["response"]) @parametrize - async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: - translation = await client.audio.translations.create( + async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: + translation = await async_client.audio.translations.create( file=b"raw file contents", model="whisper-1", prompt="string", @@ -92,8 +86,8 @@ async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: assert_matches_type(Translation, translation, path=["response"]) @parametrize - async def test_raw_response_create(self, client: AsyncOpenAI) -> None: - response = await client.audio.translations.with_raw_response.create( + async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: + response = await async_client.audio.translations.with_raw_response.create( file=b"raw file contents", model="whisper-1", ) @@ -104,8 +98,8 @@ async def test_raw_response_create(self, client: AsyncOpenAI) -> None: assert_matches_type(Translation, translation, path=["response"]) @parametrize - async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: - async with client.audio.translations.with_streaming_response.create( + async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: + async with async_client.audio.translations.with_streaming_response.create( file=b"raw file contents", model="whisper-1", ) as response: diff --git a/tests/api_resources/beta/assistants/test_files.py b/tests/api_resources/beta/assistants/test_files.py index 7db1368ccb..66e3e2efe6 100644 --- a/tests/api_resources/beta/assistants/test_files.py +++ b/tests/api_resources/beta/assistants/test_files.py @@ -9,18 +9,14 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai._client import OpenAI, AsyncOpenAI from openai.pagination import SyncCursorPage, AsyncCursorPage from openai.types.beta.assistants import AssistantFile, FileDeleteResponse base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") -api_key = "My API Key" class TestFiles: - strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize def test_method_create(self, client: OpenAI) -> None: @@ -211,21 +207,19 @@ def test_path_params_delete(self, client: OpenAI) -> None: class TestAsyncFiles: - strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize - async def test_method_create(self, client: AsyncOpenAI) -> None: - file = await client.beta.assistants.files.create( + async def test_method_create(self, async_client: AsyncOpenAI) -> None: + file = await async_client.beta.assistants.files.create( "file-abc123", file_id="string", ) assert_matches_type(AssistantFile, file, path=["response"]) @parametrize - async def test_raw_response_create(self, client: AsyncOpenAI) -> None: - response = await client.beta.assistants.files.with_raw_response.create( + async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.assistants.files.with_raw_response.create( "file-abc123", file_id="string", ) @@ -236,8 +230,8 @@ async def test_raw_response_create(self, client: AsyncOpenAI) -> None: assert_matches_type(AssistantFile, file, path=["response"]) @parametrize - async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: - async with client.beta.assistants.files.with_streaming_response.create( + async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.assistants.files.with_streaming_response.create( "file-abc123", file_id="string", ) as response: @@ -250,24 +244,24 @@ async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_create(self, client: AsyncOpenAI) -> None: + async def test_path_params_create(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): - await client.beta.assistants.files.with_raw_response.create( + await async_client.beta.assistants.files.with_raw_response.create( "", file_id="string", ) @parametrize - async def test_method_retrieve(self, client: AsyncOpenAI) -> None: - file = await client.beta.assistants.files.retrieve( + async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: + file = await async_client.beta.assistants.files.retrieve( "string", assistant_id="string", ) assert_matches_type(AssistantFile, file, path=["response"]) @parametrize - async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: - response = await client.beta.assistants.files.with_raw_response.retrieve( + async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.assistants.files.with_raw_response.retrieve( "string", assistant_id="string", ) @@ -278,8 +272,8 @@ async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: assert_matches_type(AssistantFile, file, path=["response"]) @parametrize - async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: - async with client.beta.assistants.files.with_streaming_response.retrieve( + async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.assistants.files.with_streaming_response.retrieve( "string", assistant_id="string", ) as response: @@ -292,29 +286,29 @@ async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_retrieve(self, client: AsyncOpenAI) -> None: + async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): - await client.beta.assistants.files.with_raw_response.retrieve( + await async_client.beta.assistants.files.with_raw_response.retrieve( "string", assistant_id="", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): - await client.beta.assistants.files.with_raw_response.retrieve( + await async_client.beta.assistants.files.with_raw_response.retrieve( "", assistant_id="string", ) @parametrize - async def test_method_list(self, client: AsyncOpenAI) -> None: - file = await client.beta.assistants.files.list( + async def test_method_list(self, async_client: AsyncOpenAI) -> None: + file = await async_client.beta.assistants.files.list( "string", ) assert_matches_type(AsyncCursorPage[AssistantFile], file, path=["response"]) @parametrize - async def test_method_list_with_all_params(self, client: AsyncOpenAI) -> None: - file = await client.beta.assistants.files.list( + async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: + file = await async_client.beta.assistants.files.list( "string", after="string", before="string", @@ -324,8 +318,8 @@ async def test_method_list_with_all_params(self, client: AsyncOpenAI) -> None: assert_matches_type(AsyncCursorPage[AssistantFile], file, path=["response"]) @parametrize - async def test_raw_response_list(self, client: AsyncOpenAI) -> None: - response = await client.beta.assistants.files.with_raw_response.list( + async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.assistants.files.with_raw_response.list( "string", ) @@ -335,8 +329,8 @@ async def test_raw_response_list(self, client: AsyncOpenAI) -> None: assert_matches_type(AsyncCursorPage[AssistantFile], file, path=["response"]) @parametrize - async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: - async with client.beta.assistants.files.with_streaming_response.list( + async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.assistants.files.with_streaming_response.list( "string", ) as response: assert not response.is_closed @@ -348,23 +342,23 @@ async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_list(self, client: AsyncOpenAI) -> None: + async def test_path_params_list(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): - await client.beta.assistants.files.with_raw_response.list( + await async_client.beta.assistants.files.with_raw_response.list( "", ) @parametrize - async def test_method_delete(self, client: AsyncOpenAI) -> None: - file = await client.beta.assistants.files.delete( + async def test_method_delete(self, async_client: AsyncOpenAI) -> None: + file = await async_client.beta.assistants.files.delete( "string", assistant_id="string", ) assert_matches_type(FileDeleteResponse, file, path=["response"]) @parametrize - async def test_raw_response_delete(self, client: AsyncOpenAI) -> None: - response = await client.beta.assistants.files.with_raw_response.delete( + async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.assistants.files.with_raw_response.delete( "string", assistant_id="string", ) @@ -375,8 +369,8 @@ async def test_raw_response_delete(self, client: AsyncOpenAI) -> None: assert_matches_type(FileDeleteResponse, file, path=["response"]) @parametrize - async def test_streaming_response_delete(self, client: AsyncOpenAI) -> None: - async with client.beta.assistants.files.with_streaming_response.delete( + async def test_streaming_response_delete(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.assistants.files.with_streaming_response.delete( "string", assistant_id="string", ) as response: @@ -389,15 +383,15 @@ async def test_streaming_response_delete(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_delete(self, client: AsyncOpenAI) -> None: + async def test_path_params_delete(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): - await client.beta.assistants.files.with_raw_response.delete( + await async_client.beta.assistants.files.with_raw_response.delete( "string", assistant_id="", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): - await client.beta.assistants.files.with_raw_response.delete( + await async_client.beta.assistants.files.with_raw_response.delete( "", assistant_id="string", ) diff --git a/tests/api_resources/beta/test_assistants.py b/tests/api_resources/beta/test_assistants.py index fa09769622..8db40bde93 100644 --- a/tests/api_resources/beta/test_assistants.py +++ b/tests/api_resources/beta/test_assistants.py @@ -9,7 +9,6 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai._client import OpenAI, AsyncOpenAI from openai.pagination import SyncCursorPage, AsyncCursorPage from openai.types.beta import ( Assistant, @@ -17,13 +16,10 @@ ) base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") -api_key = "My API Key" class TestAssistants: - strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize def test_method_create(self, client: OpenAI) -> None: @@ -234,20 +230,18 @@ def test_path_params_delete(self, client: OpenAI) -> None: class TestAsyncAssistants: - strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize - async def test_method_create(self, client: AsyncOpenAI) -> None: - assistant = await client.beta.assistants.create( + async def test_method_create(self, async_client: AsyncOpenAI) -> None: + assistant = await async_client.beta.assistants.create( model="string", ) assert_matches_type(Assistant, assistant, path=["response"]) @parametrize - async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: - assistant = await client.beta.assistants.create( + async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: + assistant = await async_client.beta.assistants.create( model="string", description="string", file_ids=["string", "string", "string"], @@ -259,8 +253,8 @@ async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: assert_matches_type(Assistant, assistant, path=["response"]) @parametrize - async def test_raw_response_create(self, client: AsyncOpenAI) -> None: - response = await client.beta.assistants.with_raw_response.create( + async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.assistants.with_raw_response.create( model="string", ) @@ -270,8 +264,8 @@ async def test_raw_response_create(self, client: AsyncOpenAI) -> None: assert_matches_type(Assistant, assistant, path=["response"]) @parametrize - async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: - async with client.beta.assistants.with_streaming_response.create( + async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.assistants.with_streaming_response.create( model="string", ) as response: assert not response.is_closed @@ -283,15 +277,15 @@ async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_method_retrieve(self, client: AsyncOpenAI) -> None: - assistant = await client.beta.assistants.retrieve( + async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: + assistant = await async_client.beta.assistants.retrieve( "string", ) assert_matches_type(Assistant, assistant, path=["response"]) @parametrize - async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: - response = await client.beta.assistants.with_raw_response.retrieve( + async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.assistants.with_raw_response.retrieve( "string", ) @@ -301,8 +295,8 @@ async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: assert_matches_type(Assistant, assistant, path=["response"]) @parametrize - async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: - async with client.beta.assistants.with_streaming_response.retrieve( + async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.assistants.with_streaming_response.retrieve( "string", ) as response: assert not response.is_closed @@ -314,22 +308,22 @@ async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_retrieve(self, client: AsyncOpenAI) -> None: + async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): - await client.beta.assistants.with_raw_response.retrieve( + await async_client.beta.assistants.with_raw_response.retrieve( "", ) @parametrize - async def test_method_update(self, client: AsyncOpenAI) -> None: - assistant = await client.beta.assistants.update( + async def test_method_update(self, async_client: AsyncOpenAI) -> None: + assistant = await async_client.beta.assistants.update( "string", ) assert_matches_type(Assistant, assistant, path=["response"]) @parametrize - async def test_method_update_with_all_params(self, client: AsyncOpenAI) -> None: - assistant = await client.beta.assistants.update( + async def test_method_update_with_all_params(self, async_client: AsyncOpenAI) -> None: + assistant = await async_client.beta.assistants.update( "string", description="string", file_ids=["string", "string", "string"], @@ -342,8 +336,8 @@ async def test_method_update_with_all_params(self, client: AsyncOpenAI) -> None: assert_matches_type(Assistant, assistant, path=["response"]) @parametrize - async def test_raw_response_update(self, client: AsyncOpenAI) -> None: - response = await client.beta.assistants.with_raw_response.update( + async def test_raw_response_update(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.assistants.with_raw_response.update( "string", ) @@ -353,8 +347,8 @@ async def test_raw_response_update(self, client: AsyncOpenAI) -> None: assert_matches_type(Assistant, assistant, path=["response"]) @parametrize - async def test_streaming_response_update(self, client: AsyncOpenAI) -> None: - async with client.beta.assistants.with_streaming_response.update( + async def test_streaming_response_update(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.assistants.with_streaming_response.update( "string", ) as response: assert not response.is_closed @@ -366,20 +360,20 @@ async def test_streaming_response_update(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_update(self, client: AsyncOpenAI) -> None: + async def test_path_params_update(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): - await client.beta.assistants.with_raw_response.update( + await async_client.beta.assistants.with_raw_response.update( "", ) @parametrize - async def test_method_list(self, client: AsyncOpenAI) -> None: - assistant = await client.beta.assistants.list() + async def test_method_list(self, async_client: AsyncOpenAI) -> None: + assistant = await async_client.beta.assistants.list() assert_matches_type(AsyncCursorPage[Assistant], assistant, path=["response"]) @parametrize - async def test_method_list_with_all_params(self, client: AsyncOpenAI) -> None: - assistant = await client.beta.assistants.list( + async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: + assistant = await async_client.beta.assistants.list( after="string", before="string", limit=0, @@ -388,8 +382,8 @@ async def test_method_list_with_all_params(self, client: AsyncOpenAI) -> None: assert_matches_type(AsyncCursorPage[Assistant], assistant, path=["response"]) @parametrize - async def test_raw_response_list(self, client: AsyncOpenAI) -> None: - response = await client.beta.assistants.with_raw_response.list() + async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.assistants.with_raw_response.list() assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -397,8 +391,8 @@ async def test_raw_response_list(self, client: AsyncOpenAI) -> None: assert_matches_type(AsyncCursorPage[Assistant], assistant, path=["response"]) @parametrize - async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: - async with client.beta.assistants.with_streaming_response.list() as response: + async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.assistants.with_streaming_response.list() as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -408,15 +402,15 @@ async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_method_delete(self, client: AsyncOpenAI) -> None: - assistant = await client.beta.assistants.delete( + async def test_method_delete(self, async_client: AsyncOpenAI) -> None: + assistant = await async_client.beta.assistants.delete( "string", ) assert_matches_type(AssistantDeleted, assistant, path=["response"]) @parametrize - async def test_raw_response_delete(self, client: AsyncOpenAI) -> None: - response = await client.beta.assistants.with_raw_response.delete( + async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.assistants.with_raw_response.delete( "string", ) @@ -426,8 +420,8 @@ async def test_raw_response_delete(self, client: AsyncOpenAI) -> None: assert_matches_type(AssistantDeleted, assistant, path=["response"]) @parametrize - async def test_streaming_response_delete(self, client: AsyncOpenAI) -> None: - async with client.beta.assistants.with_streaming_response.delete( + async def test_streaming_response_delete(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.assistants.with_streaming_response.delete( "string", ) as response: assert not response.is_closed @@ -439,8 +433,8 @@ async def test_streaming_response_delete(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_delete(self, client: AsyncOpenAI) -> None: + async def test_path_params_delete(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): - await client.beta.assistants.with_raw_response.delete( + await async_client.beta.assistants.with_raw_response.delete( "", ) diff --git a/tests/api_resources/beta/test_threads.py b/tests/api_resources/beta/test_threads.py index ba55cc85da..5b347de1f0 100644 --- a/tests/api_resources/beta/test_threads.py +++ b/tests/api_resources/beta/test_threads.py @@ -9,7 +9,6 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai._client import OpenAI, AsyncOpenAI from openai.types.beta import ( Thread, ThreadDeleted, @@ -17,13 +16,10 @@ from openai.types.beta.threads import Run base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") -api_key = "My API Key" class TestThreads: - strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize def test_method_create(self, client: OpenAI) -> None: @@ -266,18 +262,16 @@ def test_streaming_response_create_and_run(self, client: OpenAI) -> None: class TestAsyncThreads: - strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize - async def test_method_create(self, client: AsyncOpenAI) -> None: - thread = await client.beta.threads.create() + async def test_method_create(self, async_client: AsyncOpenAI) -> None: + thread = await async_client.beta.threads.create() assert_matches_type(Thread, thread, path=["response"]) @parametrize - async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: - thread = await client.beta.threads.create( + async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: + thread = await async_client.beta.threads.create( messages=[ { "role": "user", @@ -303,8 +297,8 @@ async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: assert_matches_type(Thread, thread, path=["response"]) @parametrize - async def test_raw_response_create(self, client: AsyncOpenAI) -> None: - response = await client.beta.threads.with_raw_response.create() + async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.threads.with_raw_response.create() assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -312,8 +306,8 @@ async def test_raw_response_create(self, client: AsyncOpenAI) -> None: assert_matches_type(Thread, thread, path=["response"]) @parametrize - async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: - async with client.beta.threads.with_streaming_response.create() as response: + async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.threads.with_streaming_response.create() as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -323,15 +317,15 @@ async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_method_retrieve(self, client: AsyncOpenAI) -> None: - thread = await client.beta.threads.retrieve( + async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: + thread = await async_client.beta.threads.retrieve( "string", ) assert_matches_type(Thread, thread, path=["response"]) @parametrize - async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: - response = await client.beta.threads.with_raw_response.retrieve( + async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.threads.with_raw_response.retrieve( "string", ) @@ -341,8 +335,8 @@ async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: assert_matches_type(Thread, thread, path=["response"]) @parametrize - async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: - async with client.beta.threads.with_streaming_response.retrieve( + async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.threads.with_streaming_response.retrieve( "string", ) as response: assert not response.is_closed @@ -354,30 +348,30 @@ async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_retrieve(self, client: AsyncOpenAI) -> None: + async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): - await client.beta.threads.with_raw_response.retrieve( + await async_client.beta.threads.with_raw_response.retrieve( "", ) @parametrize - async def test_method_update(self, client: AsyncOpenAI) -> None: - thread = await client.beta.threads.update( + async def test_method_update(self, async_client: AsyncOpenAI) -> None: + thread = await async_client.beta.threads.update( "string", ) assert_matches_type(Thread, thread, path=["response"]) @parametrize - async def test_method_update_with_all_params(self, client: AsyncOpenAI) -> None: - thread = await client.beta.threads.update( + async def test_method_update_with_all_params(self, async_client: AsyncOpenAI) -> None: + thread = await async_client.beta.threads.update( "string", metadata={}, ) assert_matches_type(Thread, thread, path=["response"]) @parametrize - async def test_raw_response_update(self, client: AsyncOpenAI) -> None: - response = await client.beta.threads.with_raw_response.update( + async def test_raw_response_update(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.threads.with_raw_response.update( "string", ) @@ -387,8 +381,8 @@ async def test_raw_response_update(self, client: AsyncOpenAI) -> None: assert_matches_type(Thread, thread, path=["response"]) @parametrize - async def test_streaming_response_update(self, client: AsyncOpenAI) -> None: - async with client.beta.threads.with_streaming_response.update( + async def test_streaming_response_update(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.threads.with_streaming_response.update( "string", ) as response: assert not response.is_closed @@ -400,22 +394,22 @@ async def test_streaming_response_update(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_update(self, client: AsyncOpenAI) -> None: + async def test_path_params_update(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): - await client.beta.threads.with_raw_response.update( + await async_client.beta.threads.with_raw_response.update( "", ) @parametrize - async def test_method_delete(self, client: AsyncOpenAI) -> None: - thread = await client.beta.threads.delete( + async def test_method_delete(self, async_client: AsyncOpenAI) -> None: + thread = await async_client.beta.threads.delete( "string", ) assert_matches_type(ThreadDeleted, thread, path=["response"]) @parametrize - async def test_raw_response_delete(self, client: AsyncOpenAI) -> None: - response = await client.beta.threads.with_raw_response.delete( + async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.threads.with_raw_response.delete( "string", ) @@ -425,8 +419,8 @@ async def test_raw_response_delete(self, client: AsyncOpenAI) -> None: assert_matches_type(ThreadDeleted, thread, path=["response"]) @parametrize - async def test_streaming_response_delete(self, client: AsyncOpenAI) -> None: - async with client.beta.threads.with_streaming_response.delete( + async def test_streaming_response_delete(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.threads.with_streaming_response.delete( "string", ) as response: assert not response.is_closed @@ -438,22 +432,22 @@ async def test_streaming_response_delete(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_delete(self, client: AsyncOpenAI) -> None: + async def test_path_params_delete(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): - await client.beta.threads.with_raw_response.delete( + await async_client.beta.threads.with_raw_response.delete( "", ) @parametrize - async def test_method_create_and_run(self, client: AsyncOpenAI) -> None: - thread = await client.beta.threads.create_and_run( + async def test_method_create_and_run(self, async_client: AsyncOpenAI) -> None: + thread = await async_client.beta.threads.create_and_run( assistant_id="string", ) assert_matches_type(Run, thread, path=["response"]) @parametrize - async def test_method_create_and_run_with_all_params(self, client: AsyncOpenAI) -> None: - thread = await client.beta.threads.create_and_run( + async def test_method_create_and_run_with_all_params(self, async_client: AsyncOpenAI) -> None: + thread = await async_client.beta.threads.create_and_run( assistant_id="string", instructions="string", metadata={}, @@ -486,8 +480,8 @@ async def test_method_create_and_run_with_all_params(self, client: AsyncOpenAI) assert_matches_type(Run, thread, path=["response"]) @parametrize - async def test_raw_response_create_and_run(self, client: AsyncOpenAI) -> None: - response = await client.beta.threads.with_raw_response.create_and_run( + async def test_raw_response_create_and_run(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.threads.with_raw_response.create_and_run( assistant_id="string", ) @@ -497,8 +491,8 @@ async def test_raw_response_create_and_run(self, client: AsyncOpenAI) -> None: assert_matches_type(Run, thread, path=["response"]) @parametrize - async def test_streaming_response_create_and_run(self, client: AsyncOpenAI) -> None: - async with client.beta.threads.with_streaming_response.create_and_run( + async def test_streaming_response_create_and_run(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.threads.with_streaming_response.create_and_run( assistant_id="string", ) as response: assert not response.is_closed diff --git a/tests/api_resources/beta/threads/messages/test_files.py b/tests/api_resources/beta/threads/messages/test_files.py index 2d248642e9..4d0613fd2f 100644 --- a/tests/api_resources/beta/threads/messages/test_files.py +++ b/tests/api_resources/beta/threads/messages/test_files.py @@ -9,18 +9,14 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai._client import OpenAI, AsyncOpenAI from openai.pagination import SyncCursorPage, AsyncCursorPage from openai.types.beta.threads.messages import MessageFile base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") -api_key = "My API Key" class TestFiles: - strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize def test_method_retrieve(self, client: OpenAI) -> None: @@ -144,13 +140,11 @@ def test_path_params_list(self, client: OpenAI) -> None: class TestAsyncFiles: - strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize - async def test_method_retrieve(self, client: AsyncOpenAI) -> None: - file = await client.beta.threads.messages.files.retrieve( + async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: + file = await async_client.beta.threads.messages.files.retrieve( "file-abc123", thread_id="thread_abc123", message_id="msg_abc123", @@ -158,8 +152,8 @@ async def test_method_retrieve(self, client: AsyncOpenAI) -> None: assert_matches_type(MessageFile, file, path=["response"]) @parametrize - async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: - response = await client.beta.threads.messages.files.with_raw_response.retrieve( + async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.threads.messages.files.with_raw_response.retrieve( "file-abc123", thread_id="thread_abc123", message_id="msg_abc123", @@ -171,8 +165,8 @@ async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: assert_matches_type(MessageFile, file, path=["response"]) @parametrize - async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: - async with client.beta.threads.messages.files.with_streaming_response.retrieve( + async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.threads.messages.files.with_streaming_response.retrieve( "file-abc123", thread_id="thread_abc123", message_id="msg_abc123", @@ -186,39 +180,39 @@ async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_retrieve(self, client: AsyncOpenAI) -> None: + async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): - await client.beta.threads.messages.files.with_raw_response.retrieve( + await async_client.beta.threads.messages.files.with_raw_response.retrieve( "file-abc123", thread_id="", message_id="msg_abc123", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): - await client.beta.threads.messages.files.with_raw_response.retrieve( + await async_client.beta.threads.messages.files.with_raw_response.retrieve( "file-abc123", thread_id="thread_abc123", message_id="", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): - await client.beta.threads.messages.files.with_raw_response.retrieve( + await async_client.beta.threads.messages.files.with_raw_response.retrieve( "", thread_id="thread_abc123", message_id="msg_abc123", ) @parametrize - async def test_method_list(self, client: AsyncOpenAI) -> None: - file = await client.beta.threads.messages.files.list( + async def test_method_list(self, async_client: AsyncOpenAI) -> None: + file = await async_client.beta.threads.messages.files.list( "string", thread_id="string", ) assert_matches_type(AsyncCursorPage[MessageFile], file, path=["response"]) @parametrize - async def test_method_list_with_all_params(self, client: AsyncOpenAI) -> None: - file = await client.beta.threads.messages.files.list( + async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: + file = await async_client.beta.threads.messages.files.list( "string", thread_id="string", after="string", @@ -229,8 +223,8 @@ async def test_method_list_with_all_params(self, client: AsyncOpenAI) -> None: assert_matches_type(AsyncCursorPage[MessageFile], file, path=["response"]) @parametrize - async def test_raw_response_list(self, client: AsyncOpenAI) -> None: - response = await client.beta.threads.messages.files.with_raw_response.list( + async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.threads.messages.files.with_raw_response.list( "string", thread_id="string", ) @@ -241,8 +235,8 @@ async def test_raw_response_list(self, client: AsyncOpenAI) -> None: assert_matches_type(AsyncCursorPage[MessageFile], file, path=["response"]) @parametrize - async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: - async with client.beta.threads.messages.files.with_streaming_response.list( + async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.threads.messages.files.with_streaming_response.list( "string", thread_id="string", ) as response: @@ -255,15 +249,15 @@ async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_list(self, client: AsyncOpenAI) -> None: + async def test_path_params_list(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): - await client.beta.threads.messages.files.with_raw_response.list( + await async_client.beta.threads.messages.files.with_raw_response.list( "string", thread_id="", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): - await client.beta.threads.messages.files.with_raw_response.list( + await async_client.beta.threads.messages.files.with_raw_response.list( "", thread_id="string", ) diff --git a/tests/api_resources/beta/threads/runs/test_steps.py b/tests/api_resources/beta/threads/runs/test_steps.py index 2ec164a535..c15848cd70 100644 --- a/tests/api_resources/beta/threads/runs/test_steps.py +++ b/tests/api_resources/beta/threads/runs/test_steps.py @@ -9,18 +9,14 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai._client import OpenAI, AsyncOpenAI from openai.pagination import SyncCursorPage, AsyncCursorPage from openai.types.beta.threads.runs import RunStep base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") -api_key = "My API Key" class TestSteps: - strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize def test_method_retrieve(self, client: OpenAI) -> None: @@ -144,13 +140,11 @@ def test_path_params_list(self, client: OpenAI) -> None: class TestAsyncSteps: - strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize - async def test_method_retrieve(self, client: AsyncOpenAI) -> None: - step = await client.beta.threads.runs.steps.retrieve( + async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: + step = await async_client.beta.threads.runs.steps.retrieve( "string", thread_id="string", run_id="string", @@ -158,8 +152,8 @@ async def test_method_retrieve(self, client: AsyncOpenAI) -> None: assert_matches_type(RunStep, step, path=["response"]) @parametrize - async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: - response = await client.beta.threads.runs.steps.with_raw_response.retrieve( + async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.threads.runs.steps.with_raw_response.retrieve( "string", thread_id="string", run_id="string", @@ -171,8 +165,8 @@ async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: assert_matches_type(RunStep, step, path=["response"]) @parametrize - async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: - async with client.beta.threads.runs.steps.with_streaming_response.retrieve( + async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.threads.runs.steps.with_streaming_response.retrieve( "string", thread_id="string", run_id="string", @@ -186,39 +180,39 @@ async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_retrieve(self, client: AsyncOpenAI) -> None: + async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): - await client.beta.threads.runs.steps.with_raw_response.retrieve( + await async_client.beta.threads.runs.steps.with_raw_response.retrieve( "string", thread_id="", run_id="string", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): - await client.beta.threads.runs.steps.with_raw_response.retrieve( + await async_client.beta.threads.runs.steps.with_raw_response.retrieve( "string", thread_id="string", run_id="", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `step_id` but received ''"): - await client.beta.threads.runs.steps.with_raw_response.retrieve( + await async_client.beta.threads.runs.steps.with_raw_response.retrieve( "", thread_id="string", run_id="string", ) @parametrize - async def test_method_list(self, client: AsyncOpenAI) -> None: - step = await client.beta.threads.runs.steps.list( + async def test_method_list(self, async_client: AsyncOpenAI) -> None: + step = await async_client.beta.threads.runs.steps.list( "string", thread_id="string", ) assert_matches_type(AsyncCursorPage[RunStep], step, path=["response"]) @parametrize - async def test_method_list_with_all_params(self, client: AsyncOpenAI) -> None: - step = await client.beta.threads.runs.steps.list( + async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: + step = await async_client.beta.threads.runs.steps.list( "string", thread_id="string", after="string", @@ -229,8 +223,8 @@ async def test_method_list_with_all_params(self, client: AsyncOpenAI) -> None: assert_matches_type(AsyncCursorPage[RunStep], step, path=["response"]) @parametrize - async def test_raw_response_list(self, client: AsyncOpenAI) -> None: - response = await client.beta.threads.runs.steps.with_raw_response.list( + async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.threads.runs.steps.with_raw_response.list( "string", thread_id="string", ) @@ -241,8 +235,8 @@ async def test_raw_response_list(self, client: AsyncOpenAI) -> None: assert_matches_type(AsyncCursorPage[RunStep], step, path=["response"]) @parametrize - async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: - async with client.beta.threads.runs.steps.with_streaming_response.list( + async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.threads.runs.steps.with_streaming_response.list( "string", thread_id="string", ) as response: @@ -255,15 +249,15 @@ async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_list(self, client: AsyncOpenAI) -> None: + async def test_path_params_list(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): - await client.beta.threads.runs.steps.with_raw_response.list( + await async_client.beta.threads.runs.steps.with_raw_response.list( "string", thread_id="", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): - await client.beta.threads.runs.steps.with_raw_response.list( + await async_client.beta.threads.runs.steps.with_raw_response.list( "", thread_id="string", ) diff --git a/tests/api_resources/beta/threads/test_messages.py b/tests/api_resources/beta/threads/test_messages.py index 508e9b96c9..538d2f4c2a 100644 --- a/tests/api_resources/beta/threads/test_messages.py +++ b/tests/api_resources/beta/threads/test_messages.py @@ -9,18 +9,14 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai._client import OpenAI, AsyncOpenAI from openai.pagination import SyncCursorPage, AsyncCursorPage from openai.types.beta.threads import ThreadMessage base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") -api_key = "My API Key" class TestMessages: - strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize def test_method_create(self, client: OpenAI) -> None: @@ -235,13 +231,11 @@ def test_path_params_list(self, client: OpenAI) -> None: class TestAsyncMessages: - strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize - async def test_method_create(self, client: AsyncOpenAI) -> None: - message = await client.beta.threads.messages.create( + async def test_method_create(self, async_client: AsyncOpenAI) -> None: + message = await async_client.beta.threads.messages.create( "string", content="x", role="user", @@ -249,8 +243,8 @@ async def test_method_create(self, client: AsyncOpenAI) -> None: assert_matches_type(ThreadMessage, message, path=["response"]) @parametrize - async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: - message = await client.beta.threads.messages.create( + async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: + message = await async_client.beta.threads.messages.create( "string", content="x", role="user", @@ -260,8 +254,8 @@ async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: assert_matches_type(ThreadMessage, message, path=["response"]) @parametrize - async def test_raw_response_create(self, client: AsyncOpenAI) -> None: - response = await client.beta.threads.messages.with_raw_response.create( + async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.threads.messages.with_raw_response.create( "string", content="x", role="user", @@ -273,8 +267,8 @@ async def test_raw_response_create(self, client: AsyncOpenAI) -> None: assert_matches_type(ThreadMessage, message, path=["response"]) @parametrize - async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: - async with client.beta.threads.messages.with_streaming_response.create( + async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.threads.messages.with_streaming_response.create( "string", content="x", role="user", @@ -288,25 +282,25 @@ async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_create(self, client: AsyncOpenAI) -> None: + async def test_path_params_create(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): - await client.beta.threads.messages.with_raw_response.create( + await async_client.beta.threads.messages.with_raw_response.create( "", content="x", role="user", ) @parametrize - async def test_method_retrieve(self, client: AsyncOpenAI) -> None: - message = await client.beta.threads.messages.retrieve( + async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: + message = await async_client.beta.threads.messages.retrieve( "string", thread_id="string", ) assert_matches_type(ThreadMessage, message, path=["response"]) @parametrize - async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: - response = await client.beta.threads.messages.with_raw_response.retrieve( + async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.threads.messages.with_raw_response.retrieve( "string", thread_id="string", ) @@ -317,8 +311,8 @@ async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: assert_matches_type(ThreadMessage, message, path=["response"]) @parametrize - async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: - async with client.beta.threads.messages.with_streaming_response.retrieve( + async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.threads.messages.with_streaming_response.retrieve( "string", thread_id="string", ) as response: @@ -331,30 +325,30 @@ async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_retrieve(self, client: AsyncOpenAI) -> None: + async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): - await client.beta.threads.messages.with_raw_response.retrieve( + await async_client.beta.threads.messages.with_raw_response.retrieve( "string", thread_id="", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): - await client.beta.threads.messages.with_raw_response.retrieve( + await async_client.beta.threads.messages.with_raw_response.retrieve( "", thread_id="string", ) @parametrize - async def test_method_update(self, client: AsyncOpenAI) -> None: - message = await client.beta.threads.messages.update( + async def test_method_update(self, async_client: AsyncOpenAI) -> None: + message = await async_client.beta.threads.messages.update( "string", thread_id="string", ) assert_matches_type(ThreadMessage, message, path=["response"]) @parametrize - async def test_method_update_with_all_params(self, client: AsyncOpenAI) -> None: - message = await client.beta.threads.messages.update( + async def test_method_update_with_all_params(self, async_client: AsyncOpenAI) -> None: + message = await async_client.beta.threads.messages.update( "string", thread_id="string", metadata={}, @@ -362,8 +356,8 @@ async def test_method_update_with_all_params(self, client: AsyncOpenAI) -> None: assert_matches_type(ThreadMessage, message, path=["response"]) @parametrize - async def test_raw_response_update(self, client: AsyncOpenAI) -> None: - response = await client.beta.threads.messages.with_raw_response.update( + async def test_raw_response_update(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.threads.messages.with_raw_response.update( "string", thread_id="string", ) @@ -374,8 +368,8 @@ async def test_raw_response_update(self, client: AsyncOpenAI) -> None: assert_matches_type(ThreadMessage, message, path=["response"]) @parametrize - async def test_streaming_response_update(self, client: AsyncOpenAI) -> None: - async with client.beta.threads.messages.with_streaming_response.update( + async def test_streaming_response_update(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.threads.messages.with_streaming_response.update( "string", thread_id="string", ) as response: @@ -388,29 +382,29 @@ async def test_streaming_response_update(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_update(self, client: AsyncOpenAI) -> None: + async def test_path_params_update(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): - await client.beta.threads.messages.with_raw_response.update( + await async_client.beta.threads.messages.with_raw_response.update( "string", thread_id="", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): - await client.beta.threads.messages.with_raw_response.update( + await async_client.beta.threads.messages.with_raw_response.update( "", thread_id="string", ) @parametrize - async def test_method_list(self, client: AsyncOpenAI) -> None: - message = await client.beta.threads.messages.list( + async def test_method_list(self, async_client: AsyncOpenAI) -> None: + message = await async_client.beta.threads.messages.list( "string", ) assert_matches_type(AsyncCursorPage[ThreadMessage], message, path=["response"]) @parametrize - async def test_method_list_with_all_params(self, client: AsyncOpenAI) -> None: - message = await client.beta.threads.messages.list( + async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: + message = await async_client.beta.threads.messages.list( "string", after="string", before="string", @@ -420,8 +414,8 @@ async def test_method_list_with_all_params(self, client: AsyncOpenAI) -> None: assert_matches_type(AsyncCursorPage[ThreadMessage], message, path=["response"]) @parametrize - async def test_raw_response_list(self, client: AsyncOpenAI) -> None: - response = await client.beta.threads.messages.with_raw_response.list( + async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.threads.messages.with_raw_response.list( "string", ) @@ -431,8 +425,8 @@ async def test_raw_response_list(self, client: AsyncOpenAI) -> None: assert_matches_type(AsyncCursorPage[ThreadMessage], message, path=["response"]) @parametrize - async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: - async with client.beta.threads.messages.with_streaming_response.list( + async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.threads.messages.with_streaming_response.list( "string", ) as response: assert not response.is_closed @@ -444,8 +438,8 @@ async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_list(self, client: AsyncOpenAI) -> None: + async def test_path_params_list(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): - await client.beta.threads.messages.with_raw_response.list( + await async_client.beta.threads.messages.with_raw_response.list( "", ) diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index 66a9edd5c0..9e88d65eaf 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -9,20 +9,16 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai._client import OpenAI, AsyncOpenAI from openai.pagination import SyncCursorPage, AsyncCursorPage from openai.types.beta.threads import ( Run, ) base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") -api_key = "My API Key" class TestRuns: - strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize def test_method_create(self, client: OpenAI) -> None: @@ -336,21 +332,19 @@ def test_path_params_submit_tool_outputs(self, client: OpenAI) -> None: class TestAsyncRuns: - strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize - async def test_method_create(self, client: AsyncOpenAI) -> None: - run = await client.beta.threads.runs.create( + async def test_method_create(self, async_client: AsyncOpenAI) -> None: + run = await async_client.beta.threads.runs.create( "string", assistant_id="string", ) assert_matches_type(Run, run, path=["response"]) @parametrize - async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: - run = await client.beta.threads.runs.create( + async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: + run = await async_client.beta.threads.runs.create( "string", assistant_id="string", additional_instructions="string", @@ -362,8 +356,8 @@ async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: assert_matches_type(Run, run, path=["response"]) @parametrize - async def test_raw_response_create(self, client: AsyncOpenAI) -> None: - response = await client.beta.threads.runs.with_raw_response.create( + async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.threads.runs.with_raw_response.create( "string", assistant_id="string", ) @@ -374,8 +368,8 @@ async def test_raw_response_create(self, client: AsyncOpenAI) -> None: assert_matches_type(Run, run, path=["response"]) @parametrize - async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: - async with client.beta.threads.runs.with_streaming_response.create( + async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.threads.runs.with_streaming_response.create( "string", assistant_id="string", ) as response: @@ -388,24 +382,24 @@ async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_create(self, client: AsyncOpenAI) -> None: + async def test_path_params_create(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): - await client.beta.threads.runs.with_raw_response.create( + await async_client.beta.threads.runs.with_raw_response.create( "", assistant_id="string", ) @parametrize - async def test_method_retrieve(self, client: AsyncOpenAI) -> None: - run = await client.beta.threads.runs.retrieve( + async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: + run = await async_client.beta.threads.runs.retrieve( "string", thread_id="string", ) assert_matches_type(Run, run, path=["response"]) @parametrize - async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: - response = await client.beta.threads.runs.with_raw_response.retrieve( + async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.threads.runs.with_raw_response.retrieve( "string", thread_id="string", ) @@ -416,8 +410,8 @@ async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: assert_matches_type(Run, run, path=["response"]) @parametrize - async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: - async with client.beta.threads.runs.with_streaming_response.retrieve( + async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.threads.runs.with_streaming_response.retrieve( "string", thread_id="string", ) as response: @@ -430,30 +424,30 @@ async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_retrieve(self, client: AsyncOpenAI) -> None: + async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): - await client.beta.threads.runs.with_raw_response.retrieve( + await async_client.beta.threads.runs.with_raw_response.retrieve( "string", thread_id="", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): - await client.beta.threads.runs.with_raw_response.retrieve( + await async_client.beta.threads.runs.with_raw_response.retrieve( "", thread_id="string", ) @parametrize - async def test_method_update(self, client: AsyncOpenAI) -> None: - run = await client.beta.threads.runs.update( + async def test_method_update(self, async_client: AsyncOpenAI) -> None: + run = await async_client.beta.threads.runs.update( "string", thread_id="string", ) assert_matches_type(Run, run, path=["response"]) @parametrize - async def test_method_update_with_all_params(self, client: AsyncOpenAI) -> None: - run = await client.beta.threads.runs.update( + async def test_method_update_with_all_params(self, async_client: AsyncOpenAI) -> None: + run = await async_client.beta.threads.runs.update( "string", thread_id="string", metadata={}, @@ -461,8 +455,8 @@ async def test_method_update_with_all_params(self, client: AsyncOpenAI) -> None: assert_matches_type(Run, run, path=["response"]) @parametrize - async def test_raw_response_update(self, client: AsyncOpenAI) -> None: - response = await client.beta.threads.runs.with_raw_response.update( + async def test_raw_response_update(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.threads.runs.with_raw_response.update( "string", thread_id="string", ) @@ -473,8 +467,8 @@ async def test_raw_response_update(self, client: AsyncOpenAI) -> None: assert_matches_type(Run, run, path=["response"]) @parametrize - async def test_streaming_response_update(self, client: AsyncOpenAI) -> None: - async with client.beta.threads.runs.with_streaming_response.update( + async def test_streaming_response_update(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.threads.runs.with_streaming_response.update( "string", thread_id="string", ) as response: @@ -487,29 +481,29 @@ async def test_streaming_response_update(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_update(self, client: AsyncOpenAI) -> None: + async def test_path_params_update(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): - await client.beta.threads.runs.with_raw_response.update( + await async_client.beta.threads.runs.with_raw_response.update( "string", thread_id="", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): - await client.beta.threads.runs.with_raw_response.update( + await async_client.beta.threads.runs.with_raw_response.update( "", thread_id="string", ) @parametrize - async def test_method_list(self, client: AsyncOpenAI) -> None: - run = await client.beta.threads.runs.list( + async def test_method_list(self, async_client: AsyncOpenAI) -> None: + run = await async_client.beta.threads.runs.list( "string", ) assert_matches_type(AsyncCursorPage[Run], run, path=["response"]) @parametrize - async def test_method_list_with_all_params(self, client: AsyncOpenAI) -> None: - run = await client.beta.threads.runs.list( + async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: + run = await async_client.beta.threads.runs.list( "string", after="string", before="string", @@ -519,8 +513,8 @@ async def test_method_list_with_all_params(self, client: AsyncOpenAI) -> None: assert_matches_type(AsyncCursorPage[Run], run, path=["response"]) @parametrize - async def test_raw_response_list(self, client: AsyncOpenAI) -> None: - response = await client.beta.threads.runs.with_raw_response.list( + async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.threads.runs.with_raw_response.list( "string", ) @@ -530,8 +524,8 @@ async def test_raw_response_list(self, client: AsyncOpenAI) -> None: assert_matches_type(AsyncCursorPage[Run], run, path=["response"]) @parametrize - async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: - async with client.beta.threads.runs.with_streaming_response.list( + async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.threads.runs.with_streaming_response.list( "string", ) as response: assert not response.is_closed @@ -543,23 +537,23 @@ async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_list(self, client: AsyncOpenAI) -> None: + async def test_path_params_list(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): - await client.beta.threads.runs.with_raw_response.list( + await async_client.beta.threads.runs.with_raw_response.list( "", ) @parametrize - async def test_method_cancel(self, client: AsyncOpenAI) -> None: - run = await client.beta.threads.runs.cancel( + async def test_method_cancel(self, async_client: AsyncOpenAI) -> None: + run = await async_client.beta.threads.runs.cancel( "string", thread_id="string", ) assert_matches_type(Run, run, path=["response"]) @parametrize - async def test_raw_response_cancel(self, client: AsyncOpenAI) -> None: - response = await client.beta.threads.runs.with_raw_response.cancel( + async def test_raw_response_cancel(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.threads.runs.with_raw_response.cancel( "string", thread_id="string", ) @@ -570,8 +564,8 @@ async def test_raw_response_cancel(self, client: AsyncOpenAI) -> None: assert_matches_type(Run, run, path=["response"]) @parametrize - async def test_streaming_response_cancel(self, client: AsyncOpenAI) -> None: - async with client.beta.threads.runs.with_streaming_response.cancel( + async def test_streaming_response_cancel(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.threads.runs.with_streaming_response.cancel( "string", thread_id="string", ) as response: @@ -584,22 +578,22 @@ async def test_streaming_response_cancel(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_cancel(self, client: AsyncOpenAI) -> None: + async def test_path_params_cancel(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): - await client.beta.threads.runs.with_raw_response.cancel( + await async_client.beta.threads.runs.with_raw_response.cancel( "string", thread_id="", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): - await client.beta.threads.runs.with_raw_response.cancel( + await async_client.beta.threads.runs.with_raw_response.cancel( "", thread_id="string", ) @parametrize - async def test_method_submit_tool_outputs(self, client: AsyncOpenAI) -> None: - run = await client.beta.threads.runs.submit_tool_outputs( + async def test_method_submit_tool_outputs(self, async_client: AsyncOpenAI) -> None: + run = await async_client.beta.threads.runs.submit_tool_outputs( "string", thread_id="string", tool_outputs=[{}, {}, {}], @@ -607,8 +601,8 @@ async def test_method_submit_tool_outputs(self, client: AsyncOpenAI) -> None: assert_matches_type(Run, run, path=["response"]) @parametrize - async def test_raw_response_submit_tool_outputs(self, client: AsyncOpenAI) -> None: - response = await client.beta.threads.runs.with_raw_response.submit_tool_outputs( + async def test_raw_response_submit_tool_outputs(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.threads.runs.with_raw_response.submit_tool_outputs( "string", thread_id="string", tool_outputs=[{}, {}, {}], @@ -620,8 +614,8 @@ async def test_raw_response_submit_tool_outputs(self, client: AsyncOpenAI) -> No assert_matches_type(Run, run, path=["response"]) @parametrize - async def test_streaming_response_submit_tool_outputs(self, client: AsyncOpenAI) -> None: - async with client.beta.threads.runs.with_streaming_response.submit_tool_outputs( + async def test_streaming_response_submit_tool_outputs(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.threads.runs.with_streaming_response.submit_tool_outputs( "string", thread_id="string", tool_outputs=[{}, {}, {}], @@ -635,16 +629,16 @@ async def test_streaming_response_submit_tool_outputs(self, client: AsyncOpenAI) assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_submit_tool_outputs(self, client: AsyncOpenAI) -> None: + async def test_path_params_submit_tool_outputs(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): - await client.beta.threads.runs.with_raw_response.submit_tool_outputs( + await async_client.beta.threads.runs.with_raw_response.submit_tool_outputs( "string", thread_id="", tool_outputs=[{}, {}, {}], ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): - await client.beta.threads.runs.with_raw_response.submit_tool_outputs( + await async_client.beta.threads.runs.with_raw_response.submit_tool_outputs( "", thread_id="string", tool_outputs=[{}, {}, {}], diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index 860ec80f48..4fa069ba2e 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -9,17 +9,13 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai._client import OpenAI, AsyncOpenAI from openai.types.chat import ChatCompletion base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") -api_key = "My API Key" class TestCompletions: - strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize def test_method_create_overload_1(self, client: OpenAI) -> None: @@ -249,13 +245,11 @@ def test_streaming_response_create_overload_2(self, client: OpenAI) -> None: class TestAsyncCompletions: - strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize - async def test_method_create_overload_1(self, client: AsyncOpenAI) -> None: - completion = await client.chat.completions.create( + async def test_method_create_overload_1(self, async_client: AsyncOpenAI) -> None: + completion = await async_client.chat.completions.create( messages=[ { "content": "string", @@ -267,8 +261,8 @@ async def test_method_create_overload_1(self, client: AsyncOpenAI) -> None: assert_matches_type(ChatCompletion, completion, path=["response"]) @parametrize - async def test_method_create_with_all_params_overload_1(self, client: AsyncOpenAI) -> None: - completion = await client.chat.completions.create( + async def test_method_create_with_all_params_overload_1(self, async_client: AsyncOpenAI) -> None: + completion = await async_client.chat.completions.create( messages=[ { "content": "string", @@ -330,8 +324,8 @@ async def test_method_create_with_all_params_overload_1(self, client: AsyncOpenA assert_matches_type(ChatCompletion, completion, path=["response"]) @parametrize - async def test_raw_response_create_overload_1(self, client: AsyncOpenAI) -> None: - response = await client.chat.completions.with_raw_response.create( + async def test_raw_response_create_overload_1(self, async_client: AsyncOpenAI) -> None: + response = await async_client.chat.completions.with_raw_response.create( messages=[ { "content": "string", @@ -347,8 +341,8 @@ async def test_raw_response_create_overload_1(self, client: AsyncOpenAI) -> None assert_matches_type(ChatCompletion, completion, path=["response"]) @parametrize - async def test_streaming_response_create_overload_1(self, client: AsyncOpenAI) -> None: - async with client.chat.completions.with_streaming_response.create( + async def test_streaming_response_create_overload_1(self, async_client: AsyncOpenAI) -> None: + async with async_client.chat.completions.with_streaming_response.create( messages=[ { "content": "string", @@ -366,8 +360,8 @@ async def test_streaming_response_create_overload_1(self, client: AsyncOpenAI) - assert cast(Any, response.is_closed) is True @parametrize - async def test_method_create_overload_2(self, client: AsyncOpenAI) -> None: - completion_stream = await client.chat.completions.create( + async def test_method_create_overload_2(self, async_client: AsyncOpenAI) -> None: + completion_stream = await async_client.chat.completions.create( messages=[ { "content": "string", @@ -380,8 +374,8 @@ async def test_method_create_overload_2(self, client: AsyncOpenAI) -> None: await completion_stream.response.aclose() @parametrize - async def test_method_create_with_all_params_overload_2(self, client: AsyncOpenAI) -> None: - completion_stream = await client.chat.completions.create( + async def test_method_create_with_all_params_overload_2(self, async_client: AsyncOpenAI) -> None: + completion_stream = await async_client.chat.completions.create( messages=[ { "content": "string", @@ -443,8 +437,8 @@ async def test_method_create_with_all_params_overload_2(self, client: AsyncOpenA await completion_stream.response.aclose() @parametrize - async def test_raw_response_create_overload_2(self, client: AsyncOpenAI) -> None: - response = await client.chat.completions.with_raw_response.create( + async def test_raw_response_create_overload_2(self, async_client: AsyncOpenAI) -> None: + response = await async_client.chat.completions.with_raw_response.create( messages=[ { "content": "string", @@ -460,8 +454,8 @@ async def test_raw_response_create_overload_2(self, client: AsyncOpenAI) -> None await stream.close() @parametrize - async def test_streaming_response_create_overload_2(self, client: AsyncOpenAI) -> None: - async with client.chat.completions.with_streaming_response.create( + async def test_streaming_response_create_overload_2(self, async_client: AsyncOpenAI) -> None: + async with async_client.chat.completions.with_streaming_response.create( messages=[ { "content": "string", diff --git a/tests/api_resources/fine_tuning/test_jobs.py b/tests/api_resources/fine_tuning/test_jobs.py index 50c7278855..204cc3b1f5 100644 --- a/tests/api_resources/fine_tuning/test_jobs.py +++ b/tests/api_resources/fine_tuning/test_jobs.py @@ -9,7 +9,6 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai._client import OpenAI, AsyncOpenAI from openai.pagination import SyncCursorPage, AsyncCursorPage from openai.types.fine_tuning import ( FineTuningJob, @@ -17,13 +16,10 @@ ) base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") -api_key = "My API Key" class TestJobs: - strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize def test_method_create(self, client: OpenAI) -> None: @@ -232,21 +228,19 @@ def test_path_params_list_events(self, client: OpenAI) -> None: class TestAsyncJobs: - strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize - async def test_method_create(self, client: AsyncOpenAI) -> None: - job = await client.fine_tuning.jobs.create( + async def test_method_create(self, async_client: AsyncOpenAI) -> None: + job = await async_client.fine_tuning.jobs.create( model="gpt-3.5-turbo", training_file="file-abc123", ) assert_matches_type(FineTuningJob, job, path=["response"]) @parametrize - async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: - job = await client.fine_tuning.jobs.create( + async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: + job = await async_client.fine_tuning.jobs.create( model="gpt-3.5-turbo", training_file="file-abc123", hyperparameters={ @@ -260,8 +254,8 @@ async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: assert_matches_type(FineTuningJob, job, path=["response"]) @parametrize - async def test_raw_response_create(self, client: AsyncOpenAI) -> None: - response = await client.fine_tuning.jobs.with_raw_response.create( + async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: + response = await async_client.fine_tuning.jobs.with_raw_response.create( model="gpt-3.5-turbo", training_file="file-abc123", ) @@ -272,8 +266,8 @@ async def test_raw_response_create(self, client: AsyncOpenAI) -> None: assert_matches_type(FineTuningJob, job, path=["response"]) @parametrize - async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: - async with client.fine_tuning.jobs.with_streaming_response.create( + async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: + async with async_client.fine_tuning.jobs.with_streaming_response.create( model="gpt-3.5-turbo", training_file="file-abc123", ) as response: @@ -286,15 +280,15 @@ async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_method_retrieve(self, client: AsyncOpenAI) -> None: - job = await client.fine_tuning.jobs.retrieve( + async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: + job = await async_client.fine_tuning.jobs.retrieve( "ft-AF1WoRqd3aJAHsqc9NY7iL8F", ) assert_matches_type(FineTuningJob, job, path=["response"]) @parametrize - async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: - response = await client.fine_tuning.jobs.with_raw_response.retrieve( + async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: + response = await async_client.fine_tuning.jobs.with_raw_response.retrieve( "ft-AF1WoRqd3aJAHsqc9NY7iL8F", ) @@ -304,8 +298,8 @@ async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: assert_matches_type(FineTuningJob, job, path=["response"]) @parametrize - async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: - async with client.fine_tuning.jobs.with_streaming_response.retrieve( + async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: + async with async_client.fine_tuning.jobs.with_streaming_response.retrieve( "ft-AF1WoRqd3aJAHsqc9NY7iL8F", ) as response: assert not response.is_closed @@ -317,28 +311,28 @@ async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_retrieve(self, client: AsyncOpenAI) -> None: + async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `fine_tuning_job_id` but received ''"): - await client.fine_tuning.jobs.with_raw_response.retrieve( + await async_client.fine_tuning.jobs.with_raw_response.retrieve( "", ) @parametrize - async def test_method_list(self, client: AsyncOpenAI) -> None: - job = await client.fine_tuning.jobs.list() + async def test_method_list(self, async_client: AsyncOpenAI) -> None: + job = await async_client.fine_tuning.jobs.list() assert_matches_type(AsyncCursorPage[FineTuningJob], job, path=["response"]) @parametrize - async def test_method_list_with_all_params(self, client: AsyncOpenAI) -> None: - job = await client.fine_tuning.jobs.list( + async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: + job = await async_client.fine_tuning.jobs.list( after="string", limit=0, ) assert_matches_type(AsyncCursorPage[FineTuningJob], job, path=["response"]) @parametrize - async def test_raw_response_list(self, client: AsyncOpenAI) -> None: - response = await client.fine_tuning.jobs.with_raw_response.list() + async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: + response = await async_client.fine_tuning.jobs.with_raw_response.list() assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -346,8 +340,8 @@ async def test_raw_response_list(self, client: AsyncOpenAI) -> None: assert_matches_type(AsyncCursorPage[FineTuningJob], job, path=["response"]) @parametrize - async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: - async with client.fine_tuning.jobs.with_streaming_response.list() as response: + async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: + async with async_client.fine_tuning.jobs.with_streaming_response.list() as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -357,15 +351,15 @@ async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_method_cancel(self, client: AsyncOpenAI) -> None: - job = await client.fine_tuning.jobs.cancel( + async def test_method_cancel(self, async_client: AsyncOpenAI) -> None: + job = await async_client.fine_tuning.jobs.cancel( "ft-AF1WoRqd3aJAHsqc9NY7iL8F", ) assert_matches_type(FineTuningJob, job, path=["response"]) @parametrize - async def test_raw_response_cancel(self, client: AsyncOpenAI) -> None: - response = await client.fine_tuning.jobs.with_raw_response.cancel( + async def test_raw_response_cancel(self, async_client: AsyncOpenAI) -> None: + response = await async_client.fine_tuning.jobs.with_raw_response.cancel( "ft-AF1WoRqd3aJAHsqc9NY7iL8F", ) @@ -375,8 +369,8 @@ async def test_raw_response_cancel(self, client: AsyncOpenAI) -> None: assert_matches_type(FineTuningJob, job, path=["response"]) @parametrize - async def test_streaming_response_cancel(self, client: AsyncOpenAI) -> None: - async with client.fine_tuning.jobs.with_streaming_response.cancel( + async def test_streaming_response_cancel(self, async_client: AsyncOpenAI) -> None: + async with async_client.fine_tuning.jobs.with_streaming_response.cancel( "ft-AF1WoRqd3aJAHsqc9NY7iL8F", ) as response: assert not response.is_closed @@ -388,22 +382,22 @@ async def test_streaming_response_cancel(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_cancel(self, client: AsyncOpenAI) -> None: + async def test_path_params_cancel(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `fine_tuning_job_id` but received ''"): - await client.fine_tuning.jobs.with_raw_response.cancel( + await async_client.fine_tuning.jobs.with_raw_response.cancel( "", ) @parametrize - async def test_method_list_events(self, client: AsyncOpenAI) -> None: - job = await client.fine_tuning.jobs.list_events( + async def test_method_list_events(self, async_client: AsyncOpenAI) -> None: + job = await async_client.fine_tuning.jobs.list_events( "ft-AF1WoRqd3aJAHsqc9NY7iL8F", ) assert_matches_type(AsyncCursorPage[FineTuningJobEvent], job, path=["response"]) @parametrize - async def test_method_list_events_with_all_params(self, client: AsyncOpenAI) -> None: - job = await client.fine_tuning.jobs.list_events( + async def test_method_list_events_with_all_params(self, async_client: AsyncOpenAI) -> None: + job = await async_client.fine_tuning.jobs.list_events( "ft-AF1WoRqd3aJAHsqc9NY7iL8F", after="string", limit=0, @@ -411,8 +405,8 @@ async def test_method_list_events_with_all_params(self, client: AsyncOpenAI) -> assert_matches_type(AsyncCursorPage[FineTuningJobEvent], job, path=["response"]) @parametrize - async def test_raw_response_list_events(self, client: AsyncOpenAI) -> None: - response = await client.fine_tuning.jobs.with_raw_response.list_events( + async def test_raw_response_list_events(self, async_client: AsyncOpenAI) -> None: + response = await async_client.fine_tuning.jobs.with_raw_response.list_events( "ft-AF1WoRqd3aJAHsqc9NY7iL8F", ) @@ -422,8 +416,8 @@ async def test_raw_response_list_events(self, client: AsyncOpenAI) -> None: assert_matches_type(AsyncCursorPage[FineTuningJobEvent], job, path=["response"]) @parametrize - async def test_streaming_response_list_events(self, client: AsyncOpenAI) -> None: - async with client.fine_tuning.jobs.with_streaming_response.list_events( + async def test_streaming_response_list_events(self, async_client: AsyncOpenAI) -> None: + async with async_client.fine_tuning.jobs.with_streaming_response.list_events( "ft-AF1WoRqd3aJAHsqc9NY7iL8F", ) as response: assert not response.is_closed @@ -435,8 +429,8 @@ async def test_streaming_response_list_events(self, client: AsyncOpenAI) -> None assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_list_events(self, client: AsyncOpenAI) -> None: + async def test_path_params_list_events(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `fine_tuning_job_id` but received ''"): - await client.fine_tuning.jobs.with_raw_response.list_events( + await async_client.fine_tuning.jobs.with_raw_response.list_events( "", ) diff --git a/tests/api_resources/test_completions.py b/tests/api_resources/test_completions.py index a5e8dc809a..916cdd3cb6 100644 --- a/tests/api_resources/test_completions.py +++ b/tests/api_resources/test_completions.py @@ -10,16 +10,12 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.types import Completion -from openai._client import OpenAI, AsyncOpenAI base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") -api_key = "My API Key" class TestCompletions: - strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize def test_method_create_overload_1(self, client: OpenAI) -> None: @@ -139,21 +135,19 @@ def test_streaming_response_create_overload_2(self, client: OpenAI) -> None: class TestAsyncCompletions: - strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize - async def test_method_create_overload_1(self, client: AsyncOpenAI) -> None: - completion = await client.completions.create( + async def test_method_create_overload_1(self, async_client: AsyncOpenAI) -> None: + completion = await async_client.completions.create( model="string", prompt="This is a test.", ) assert_matches_type(Completion, completion, path=["response"]) @parametrize - async def test_method_create_with_all_params_overload_1(self, client: AsyncOpenAI) -> None: - completion = await client.completions.create( + async def test_method_create_with_all_params_overload_1(self, async_client: AsyncOpenAI) -> None: + completion = await async_client.completions.create( model="string", prompt="This is a test.", best_of=0, @@ -175,8 +169,8 @@ async def test_method_create_with_all_params_overload_1(self, client: AsyncOpenA assert_matches_type(Completion, completion, path=["response"]) @parametrize - async def test_raw_response_create_overload_1(self, client: AsyncOpenAI) -> None: - response = await client.completions.with_raw_response.create( + async def test_raw_response_create_overload_1(self, async_client: AsyncOpenAI) -> None: + response = await async_client.completions.with_raw_response.create( model="string", prompt="This is a test.", ) @@ -187,8 +181,8 @@ async def test_raw_response_create_overload_1(self, client: AsyncOpenAI) -> None assert_matches_type(Completion, completion, path=["response"]) @parametrize - async def test_streaming_response_create_overload_1(self, client: AsyncOpenAI) -> None: - async with client.completions.with_streaming_response.create( + async def test_streaming_response_create_overload_1(self, async_client: AsyncOpenAI) -> None: + async with async_client.completions.with_streaming_response.create( model="string", prompt="This is a test.", ) as response: @@ -201,8 +195,8 @@ async def test_streaming_response_create_overload_1(self, client: AsyncOpenAI) - assert cast(Any, response.is_closed) is True @parametrize - async def test_method_create_overload_2(self, client: AsyncOpenAI) -> None: - completion_stream = await client.completions.create( + async def test_method_create_overload_2(self, async_client: AsyncOpenAI) -> None: + completion_stream = await async_client.completions.create( model="string", prompt="This is a test.", stream=True, @@ -210,8 +204,8 @@ async def test_method_create_overload_2(self, client: AsyncOpenAI) -> None: await completion_stream.response.aclose() @parametrize - async def test_method_create_with_all_params_overload_2(self, client: AsyncOpenAI) -> None: - completion_stream = await client.completions.create( + async def test_method_create_with_all_params_overload_2(self, async_client: AsyncOpenAI) -> None: + completion_stream = await async_client.completions.create( model="string", prompt="This is a test.", stream=True, @@ -233,8 +227,8 @@ async def test_method_create_with_all_params_overload_2(self, client: AsyncOpenA await completion_stream.response.aclose() @parametrize - async def test_raw_response_create_overload_2(self, client: AsyncOpenAI) -> None: - response = await client.completions.with_raw_response.create( + async def test_raw_response_create_overload_2(self, async_client: AsyncOpenAI) -> None: + response = await async_client.completions.with_raw_response.create( model="string", prompt="This is a test.", stream=True, @@ -245,8 +239,8 @@ async def test_raw_response_create_overload_2(self, client: AsyncOpenAI) -> None await stream.close() @parametrize - async def test_streaming_response_create_overload_2(self, client: AsyncOpenAI) -> None: - async with client.completions.with_streaming_response.create( + async def test_streaming_response_create_overload_2(self, async_client: AsyncOpenAI) -> None: + async with async_client.completions.with_streaming_response.create( model="string", prompt="This is a test.", stream=True, diff --git a/tests/api_resources/test_embeddings.py b/tests/api_resources/test_embeddings.py index 77875fc46f..cd4ff8e391 100644 --- a/tests/api_resources/test_embeddings.py +++ b/tests/api_resources/test_embeddings.py @@ -10,16 +10,12 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.types import CreateEmbeddingResponse -from openai._client import OpenAI, AsyncOpenAI base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") -api_key = "My API Key" class TestEmbeddings: - strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize def test_method_create(self, client: OpenAI) -> None: @@ -67,21 +63,19 @@ def test_streaming_response_create(self, client: OpenAI) -> None: class TestAsyncEmbeddings: - strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize - async def test_method_create(self, client: AsyncOpenAI) -> None: - embedding = await client.embeddings.create( + async def test_method_create(self, async_client: AsyncOpenAI) -> None: + embedding = await async_client.embeddings.create( input="The quick brown fox jumped over the lazy dog", model="text-embedding-ada-002", ) assert_matches_type(CreateEmbeddingResponse, embedding, path=["response"]) @parametrize - async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: - embedding = await client.embeddings.create( + async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: + embedding = await async_client.embeddings.create( input="The quick brown fox jumped over the lazy dog", model="text-embedding-ada-002", encoding_format="float", @@ -90,8 +84,8 @@ async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: assert_matches_type(CreateEmbeddingResponse, embedding, path=["response"]) @parametrize - async def test_raw_response_create(self, client: AsyncOpenAI) -> None: - response = await client.embeddings.with_raw_response.create( + async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: + response = await async_client.embeddings.with_raw_response.create( input="The quick brown fox jumped over the lazy dog", model="text-embedding-ada-002", ) @@ -102,8 +96,8 @@ async def test_raw_response_create(self, client: AsyncOpenAI) -> None: assert_matches_type(CreateEmbeddingResponse, embedding, path=["response"]) @parametrize - async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: - async with client.embeddings.with_streaming_response.create( + async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: + async with async_client.embeddings.with_streaming_response.create( input="The quick brown fox jumped over the lazy dog", model="text-embedding-ada-002", ) as response: diff --git a/tests/api_resources/test_files.py b/tests/api_resources/test_files.py index 89ad9e222f..d1a17923a6 100644 --- a/tests/api_resources/test_files.py +++ b/tests/api_resources/test_files.py @@ -13,19 +13,15 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.types import FileObject, FileDeleted -from openai._client import OpenAI, AsyncOpenAI from openai.pagination import SyncPage, AsyncPage # pyright: reportDeprecated=false base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") -api_key = "My API Key" class TestFiles: - strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize def test_method_create(self, client: OpenAI) -> None: @@ -261,21 +257,19 @@ def test_path_params_retrieve_content(self, client: OpenAI) -> None: class TestAsyncFiles: - strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize - async def test_method_create(self, client: AsyncOpenAI) -> None: - file = await client.files.create( + async def test_method_create(self, async_client: AsyncOpenAI) -> None: + file = await async_client.files.create( file=b"raw file contents", purpose="fine-tune", ) assert_matches_type(FileObject, file, path=["response"]) @parametrize - async def test_raw_response_create(self, client: AsyncOpenAI) -> None: - response = await client.files.with_raw_response.create( + async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: + response = await async_client.files.with_raw_response.create( file=b"raw file contents", purpose="fine-tune", ) @@ -286,8 +280,8 @@ async def test_raw_response_create(self, client: AsyncOpenAI) -> None: assert_matches_type(FileObject, file, path=["response"]) @parametrize - async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: - async with client.files.with_streaming_response.create( + async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: + async with async_client.files.with_streaming_response.create( file=b"raw file contents", purpose="fine-tune", ) as response: @@ -300,15 +294,15 @@ async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_method_retrieve(self, client: AsyncOpenAI) -> None: - file = await client.files.retrieve( + async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: + file = await async_client.files.retrieve( "string", ) assert_matches_type(FileObject, file, path=["response"]) @parametrize - async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: - response = await client.files.with_raw_response.retrieve( + async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: + response = await async_client.files.with_raw_response.retrieve( "string", ) @@ -318,8 +312,8 @@ async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: assert_matches_type(FileObject, file, path=["response"]) @parametrize - async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: - async with client.files.with_streaming_response.retrieve( + async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: + async with async_client.files.with_streaming_response.retrieve( "string", ) as response: assert not response.is_closed @@ -331,27 +325,27 @@ async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_retrieve(self, client: AsyncOpenAI) -> None: + async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): - await client.files.with_raw_response.retrieve( + await async_client.files.with_raw_response.retrieve( "", ) @parametrize - async def test_method_list(self, client: AsyncOpenAI) -> None: - file = await client.files.list() + async def test_method_list(self, async_client: AsyncOpenAI) -> None: + file = await async_client.files.list() assert_matches_type(AsyncPage[FileObject], file, path=["response"]) @parametrize - async def test_method_list_with_all_params(self, client: AsyncOpenAI) -> None: - file = await client.files.list( + async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: + file = await async_client.files.list( purpose="string", ) assert_matches_type(AsyncPage[FileObject], file, path=["response"]) @parametrize - async def test_raw_response_list(self, client: AsyncOpenAI) -> None: - response = await client.files.with_raw_response.list() + async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: + response = await async_client.files.with_raw_response.list() assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -359,8 +353,8 @@ async def test_raw_response_list(self, client: AsyncOpenAI) -> None: assert_matches_type(AsyncPage[FileObject], file, path=["response"]) @parametrize - async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: - async with client.files.with_streaming_response.list() as response: + async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: + async with async_client.files.with_streaming_response.list() as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -370,15 +364,15 @@ async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_method_delete(self, client: AsyncOpenAI) -> None: - file = await client.files.delete( + async def test_method_delete(self, async_client: AsyncOpenAI) -> None: + file = await async_client.files.delete( "string", ) assert_matches_type(FileDeleted, file, path=["response"]) @parametrize - async def test_raw_response_delete(self, client: AsyncOpenAI) -> None: - response = await client.files.with_raw_response.delete( + async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None: + response = await async_client.files.with_raw_response.delete( "string", ) @@ -388,8 +382,8 @@ async def test_raw_response_delete(self, client: AsyncOpenAI) -> None: assert_matches_type(FileDeleted, file, path=["response"]) @parametrize - async def test_streaming_response_delete(self, client: AsyncOpenAI) -> None: - async with client.files.with_streaming_response.delete( + async def test_streaming_response_delete(self, async_client: AsyncOpenAI) -> None: + async with async_client.files.with_streaming_response.delete( "string", ) as response: assert not response.is_closed @@ -401,17 +395,17 @@ async def test_streaming_response_delete(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_delete(self, client: AsyncOpenAI) -> None: + async def test_path_params_delete(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): - await client.files.with_raw_response.delete( + await async_client.files.with_raw_response.delete( "", ) @parametrize @pytest.mark.respx(base_url=base_url) - async def test_method_content(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: + async def test_method_content(self, async_client: AsyncOpenAI, respx_mock: MockRouter) -> None: respx_mock.get("/files/string/content").mock(return_value=httpx.Response(200, json={"foo": "bar"})) - file = await client.files.content( + file = await async_client.files.content( "string", ) assert isinstance(file, _legacy_response.HttpxBinaryResponseContent) @@ -419,10 +413,10 @@ async def test_method_content(self, client: AsyncOpenAI, respx_mock: MockRouter) @parametrize @pytest.mark.respx(base_url=base_url) - async def test_raw_response_content(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: + async def test_raw_response_content(self, async_client: AsyncOpenAI, respx_mock: MockRouter) -> None: respx_mock.get("/files/string/content").mock(return_value=httpx.Response(200, json={"foo": "bar"})) - response = await client.files.with_raw_response.content( + response = await async_client.files.with_raw_response.content( "string", ) @@ -433,9 +427,9 @@ async def test_raw_response_content(self, client: AsyncOpenAI, respx_mock: MockR @parametrize @pytest.mark.respx(base_url=base_url) - async def test_streaming_response_content(self, client: AsyncOpenAI, respx_mock: MockRouter) -> None: + async def test_streaming_response_content(self, async_client: AsyncOpenAI, respx_mock: MockRouter) -> None: respx_mock.get("/files/string/content").mock(return_value=httpx.Response(200, json={"foo": "bar"})) - async with client.files.with_streaming_response.content( + async with async_client.files.with_streaming_response.content( "string", ) as response: assert not response.is_closed @@ -448,25 +442,25 @@ async def test_streaming_response_content(self, client: AsyncOpenAI, respx_mock: @parametrize @pytest.mark.respx(base_url=base_url) - async def test_path_params_content(self, client: AsyncOpenAI) -> None: + async def test_path_params_content(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): - await client.files.with_raw_response.content( + await async_client.files.with_raw_response.content( "", ) @parametrize - async def test_method_retrieve_content(self, client: AsyncOpenAI) -> None: + async def test_method_retrieve_content(self, async_client: AsyncOpenAI) -> None: with pytest.warns(DeprecationWarning): - file = await client.files.retrieve_content( + file = await async_client.files.retrieve_content( "string", ) assert_matches_type(str, file, path=["response"]) @parametrize - async def test_raw_response_retrieve_content(self, client: AsyncOpenAI) -> None: + async def test_raw_response_retrieve_content(self, async_client: AsyncOpenAI) -> None: with pytest.warns(DeprecationWarning): - response = await client.files.with_raw_response.retrieve_content( + response = await async_client.files.with_raw_response.retrieve_content( "string", ) @@ -476,9 +470,9 @@ async def test_raw_response_retrieve_content(self, client: AsyncOpenAI) -> None: assert_matches_type(str, file, path=["response"]) @parametrize - async def test_streaming_response_retrieve_content(self, client: AsyncOpenAI) -> None: + async def test_streaming_response_retrieve_content(self, async_client: AsyncOpenAI) -> None: with pytest.warns(DeprecationWarning): - async with client.files.with_streaming_response.retrieve_content( + async with async_client.files.with_streaming_response.retrieve_content( "string", ) as response: assert not response.is_closed @@ -490,9 +484,9 @@ async def test_streaming_response_retrieve_content(self, client: AsyncOpenAI) -> assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_retrieve_content(self, client: AsyncOpenAI) -> None: + async def test_path_params_retrieve_content(self, async_client: AsyncOpenAI) -> None: with pytest.warns(DeprecationWarning): with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): - await client.files.with_raw_response.retrieve_content( + await async_client.files.with_raw_response.retrieve_content( "", ) diff --git a/tests/api_resources/test_images.py b/tests/api_resources/test_images.py index 553bd018ee..b6cb2572ab 100644 --- a/tests/api_resources/test_images.py +++ b/tests/api_resources/test_images.py @@ -10,16 +10,12 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.types import ImagesResponse -from openai._client import OpenAI, AsyncOpenAI base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") -api_key = "My API Key" class TestImages: - strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize def test_method_create_variation(self, client: OpenAI) -> None: @@ -159,20 +155,18 @@ def test_streaming_response_generate(self, client: OpenAI) -> None: class TestAsyncImages: - strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize - async def test_method_create_variation(self, client: AsyncOpenAI) -> None: - image = await client.images.create_variation( + async def test_method_create_variation(self, async_client: AsyncOpenAI) -> None: + image = await async_client.images.create_variation( image=b"raw file contents", ) assert_matches_type(ImagesResponse, image, path=["response"]) @parametrize - async def test_method_create_variation_with_all_params(self, client: AsyncOpenAI) -> None: - image = await client.images.create_variation( + async def test_method_create_variation_with_all_params(self, async_client: AsyncOpenAI) -> None: + image = await async_client.images.create_variation( image=b"raw file contents", model="dall-e-2", n=1, @@ -183,8 +177,8 @@ async def test_method_create_variation_with_all_params(self, client: AsyncOpenAI assert_matches_type(ImagesResponse, image, path=["response"]) @parametrize - async def test_raw_response_create_variation(self, client: AsyncOpenAI) -> None: - response = await client.images.with_raw_response.create_variation( + async def test_raw_response_create_variation(self, async_client: AsyncOpenAI) -> None: + response = await async_client.images.with_raw_response.create_variation( image=b"raw file contents", ) @@ -194,8 +188,8 @@ async def test_raw_response_create_variation(self, client: AsyncOpenAI) -> None: assert_matches_type(ImagesResponse, image, path=["response"]) @parametrize - async def test_streaming_response_create_variation(self, client: AsyncOpenAI) -> None: - async with client.images.with_streaming_response.create_variation( + async def test_streaming_response_create_variation(self, async_client: AsyncOpenAI) -> None: + async with async_client.images.with_streaming_response.create_variation( image=b"raw file contents", ) as response: assert not response.is_closed @@ -207,16 +201,16 @@ async def test_streaming_response_create_variation(self, client: AsyncOpenAI) -> assert cast(Any, response.is_closed) is True @parametrize - async def test_method_edit(self, client: AsyncOpenAI) -> None: - image = await client.images.edit( + async def test_method_edit(self, async_client: AsyncOpenAI) -> None: + image = await async_client.images.edit( image=b"raw file contents", prompt="A cute baby sea otter wearing a beret", ) assert_matches_type(ImagesResponse, image, path=["response"]) @parametrize - async def test_method_edit_with_all_params(self, client: AsyncOpenAI) -> None: - image = await client.images.edit( + async def test_method_edit_with_all_params(self, async_client: AsyncOpenAI) -> None: + image = await async_client.images.edit( image=b"raw file contents", prompt="A cute baby sea otter wearing a beret", mask=b"raw file contents", @@ -229,8 +223,8 @@ async def test_method_edit_with_all_params(self, client: AsyncOpenAI) -> None: assert_matches_type(ImagesResponse, image, path=["response"]) @parametrize - async def test_raw_response_edit(self, client: AsyncOpenAI) -> None: - response = await client.images.with_raw_response.edit( + async def test_raw_response_edit(self, async_client: AsyncOpenAI) -> None: + response = await async_client.images.with_raw_response.edit( image=b"raw file contents", prompt="A cute baby sea otter wearing a beret", ) @@ -241,8 +235,8 @@ async def test_raw_response_edit(self, client: AsyncOpenAI) -> None: assert_matches_type(ImagesResponse, image, path=["response"]) @parametrize - async def test_streaming_response_edit(self, client: AsyncOpenAI) -> None: - async with client.images.with_streaming_response.edit( + async def test_streaming_response_edit(self, async_client: AsyncOpenAI) -> None: + async with async_client.images.with_streaming_response.edit( image=b"raw file contents", prompt="A cute baby sea otter wearing a beret", ) as response: @@ -255,15 +249,15 @@ async def test_streaming_response_edit(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_method_generate(self, client: AsyncOpenAI) -> None: - image = await client.images.generate( + async def test_method_generate(self, async_client: AsyncOpenAI) -> None: + image = await async_client.images.generate( prompt="A cute baby sea otter", ) assert_matches_type(ImagesResponse, image, path=["response"]) @parametrize - async def test_method_generate_with_all_params(self, client: AsyncOpenAI) -> None: - image = await client.images.generate( + async def test_method_generate_with_all_params(self, async_client: AsyncOpenAI) -> None: + image = await async_client.images.generate( prompt="A cute baby sea otter", model="dall-e-3", n=1, @@ -276,8 +270,8 @@ async def test_method_generate_with_all_params(self, client: AsyncOpenAI) -> Non assert_matches_type(ImagesResponse, image, path=["response"]) @parametrize - async def test_raw_response_generate(self, client: AsyncOpenAI) -> None: - response = await client.images.with_raw_response.generate( + async def test_raw_response_generate(self, async_client: AsyncOpenAI) -> None: + response = await async_client.images.with_raw_response.generate( prompt="A cute baby sea otter", ) @@ -287,8 +281,8 @@ async def test_raw_response_generate(self, client: AsyncOpenAI) -> None: assert_matches_type(ImagesResponse, image, path=["response"]) @parametrize - async def test_streaming_response_generate(self, client: AsyncOpenAI) -> None: - async with client.images.with_streaming_response.generate( + async def test_streaming_response_generate(self, async_client: AsyncOpenAI) -> None: + async with async_client.images.with_streaming_response.generate( prompt="A cute baby sea otter", ) as response: assert not response.is_closed diff --git a/tests/api_resources/test_models.py b/tests/api_resources/test_models.py index b41e50eb71..d031d54f6a 100644 --- a/tests/api_resources/test_models.py +++ b/tests/api_resources/test_models.py @@ -10,17 +10,13 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.types import Model, ModelDeleted -from openai._client import OpenAI, AsyncOpenAI from openai.pagination import SyncPage, AsyncPage base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") -api_key = "My API Key" class TestModels: - strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize def test_method_retrieve(self, client: OpenAI) -> None: @@ -125,20 +121,18 @@ def test_path_params_delete(self, client: OpenAI) -> None: class TestAsyncModels: - strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize - async def test_method_retrieve(self, client: AsyncOpenAI) -> None: - model = await client.models.retrieve( + async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: + model = await async_client.models.retrieve( "gpt-3.5-turbo", ) assert_matches_type(Model, model, path=["response"]) @parametrize - async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: - response = await client.models.with_raw_response.retrieve( + async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: + response = await async_client.models.with_raw_response.retrieve( "gpt-3.5-turbo", ) @@ -148,8 +142,8 @@ async def test_raw_response_retrieve(self, client: AsyncOpenAI) -> None: assert_matches_type(Model, model, path=["response"]) @parametrize - async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: - async with client.models.with_streaming_response.retrieve( + async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: + async with async_client.models.with_streaming_response.retrieve( "gpt-3.5-turbo", ) as response: assert not response.is_closed @@ -161,20 +155,20 @@ async def test_streaming_response_retrieve(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_retrieve(self, client: AsyncOpenAI) -> None: + async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `model` but received ''"): - await client.models.with_raw_response.retrieve( + await async_client.models.with_raw_response.retrieve( "", ) @parametrize - async def test_method_list(self, client: AsyncOpenAI) -> None: - model = await client.models.list() + async def test_method_list(self, async_client: AsyncOpenAI) -> None: + model = await async_client.models.list() assert_matches_type(AsyncPage[Model], model, path=["response"]) @parametrize - async def test_raw_response_list(self, client: AsyncOpenAI) -> None: - response = await client.models.with_raw_response.list() + async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: + response = await async_client.models.with_raw_response.list() assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -182,8 +176,8 @@ async def test_raw_response_list(self, client: AsyncOpenAI) -> None: assert_matches_type(AsyncPage[Model], model, path=["response"]) @parametrize - async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: - async with client.models.with_streaming_response.list() as response: + async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: + async with async_client.models.with_streaming_response.list() as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -193,15 +187,15 @@ async def test_streaming_response_list(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_method_delete(self, client: AsyncOpenAI) -> None: - model = await client.models.delete( + async def test_method_delete(self, async_client: AsyncOpenAI) -> None: + model = await async_client.models.delete( "ft:gpt-3.5-turbo:acemeco:suffix:abc123", ) assert_matches_type(ModelDeleted, model, path=["response"]) @parametrize - async def test_raw_response_delete(self, client: AsyncOpenAI) -> None: - response = await client.models.with_raw_response.delete( + async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None: + response = await async_client.models.with_raw_response.delete( "ft:gpt-3.5-turbo:acemeco:suffix:abc123", ) @@ -211,8 +205,8 @@ async def test_raw_response_delete(self, client: AsyncOpenAI) -> None: assert_matches_type(ModelDeleted, model, path=["response"]) @parametrize - async def test_streaming_response_delete(self, client: AsyncOpenAI) -> None: - async with client.models.with_streaming_response.delete( + async def test_streaming_response_delete(self, async_client: AsyncOpenAI) -> None: + async with async_client.models.with_streaming_response.delete( "ft:gpt-3.5-turbo:acemeco:suffix:abc123", ) as response: assert not response.is_closed @@ -224,8 +218,8 @@ async def test_streaming_response_delete(self, client: AsyncOpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_delete(self, client: AsyncOpenAI) -> None: + async def test_path_params_delete(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `model` but received ''"): - await client.models.with_raw_response.delete( + await async_client.models.with_raw_response.delete( "", ) diff --git a/tests/api_resources/test_moderations.py b/tests/api_resources/test_moderations.py index 88d35f003d..285e738c0e 100644 --- a/tests/api_resources/test_moderations.py +++ b/tests/api_resources/test_moderations.py @@ -10,16 +10,12 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.types import ModerationCreateResponse -from openai._client import OpenAI, AsyncOpenAI base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") -api_key = "My API Key" class TestModerations: - strict_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize def test_method_create(self, client: OpenAI) -> None: @@ -62,28 +58,26 @@ def test_streaming_response_create(self, client: OpenAI) -> None: class TestAsyncModerations: - strict_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) - loose_client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=False) - parametrize = pytest.mark.parametrize("client", [strict_client, loose_client], ids=["strict", "loose"]) + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize - async def test_method_create(self, client: AsyncOpenAI) -> None: - moderation = await client.moderations.create( + async def test_method_create(self, async_client: AsyncOpenAI) -> None: + moderation = await async_client.moderations.create( input="I want to kill them.", ) assert_matches_type(ModerationCreateResponse, moderation, path=["response"]) @parametrize - async def test_method_create_with_all_params(self, client: AsyncOpenAI) -> None: - moderation = await client.moderations.create( + async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: + moderation = await async_client.moderations.create( input="I want to kill them.", model="text-moderation-stable", ) assert_matches_type(ModerationCreateResponse, moderation, path=["response"]) @parametrize - async def test_raw_response_create(self, client: AsyncOpenAI) -> None: - response = await client.moderations.with_raw_response.create( + async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: + response = await async_client.moderations.with_raw_response.create( input="I want to kill them.", ) @@ -93,8 +87,8 @@ async def test_raw_response_create(self, client: AsyncOpenAI) -> None: assert_matches_type(ModerationCreateResponse, moderation, path=["response"]) @parametrize - async def test_streaming_response_create(self, client: AsyncOpenAI) -> None: - async with client.moderations.with_streaming_response.create( + async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: + async with async_client.moderations.with_streaming_response.create( input="I want to kill them.", ) as response: assert not response.is_closed diff --git a/tests/conftest.py b/tests/conftest.py index c3a1efe9df..15af57e770 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,9 +1,17 @@ +from __future__ import annotations + +import os import asyncio import logging -from typing import Iterator +from typing import TYPE_CHECKING, Iterator, AsyncIterator import pytest +from openai import OpenAI, AsyncOpenAI + +if TYPE_CHECKING: + from _pytest.fixtures import FixtureRequest + pytest.register_assert_rewrite("tests.utils") logging.getLogger("openai").setLevel(logging.DEBUG) @@ -14,3 +22,28 @@ def event_loop() -> Iterator[asyncio.AbstractEventLoop]: loop = asyncio.new_event_loop() yield loop loop.close() + + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") + +api_key = "My API Key" + + +@pytest.fixture(scope="session") +def client(request: FixtureRequest) -> Iterator[OpenAI]: + strict = getattr(request, "param", True) + if not isinstance(strict, bool): + raise TypeError(f"Unexpected fixture parameter type {type(strict)}, expected {bool}") + + with OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=strict) as client: + yield client + + +@pytest.fixture(scope="session") +async def async_client(request: FixtureRequest) -> AsyncIterator[AsyncOpenAI]: + strict = getattr(request, "param", True) + if not isinstance(strict, bool): + raise TypeError(f"Unexpected fixture parameter type {type(strict)}, expected {bool}") + + async with AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=strict) as client: + yield client From 7f18183fe329eb94dcdcb7ddb34447699b3ce70e Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 19 Jan 2024 21:21:49 -0500 Subject: [PATCH 203/816] feat(api): add usage to runs and run steps (#1090) --- src/openai/types/beta/threads/run.py | 19 +++++++++++++++++++ .../types/beta/threads/runs/run_step.py | 19 ++++++++++++++++++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/src/openai/types/beta/threads/run.py b/src/openai/types/beta/threads/run.py index b6d66bd8dd..db4bc0e07d 100644 --- a/src/openai/types/beta/threads/run.py +++ b/src/openai/types/beta/threads/run.py @@ -17,6 +17,7 @@ "ToolAssistantToolsCode", "ToolAssistantToolsRetrieval", "ToolAssistantToolsFunction", + "Usage", ] @@ -61,6 +62,17 @@ class ToolAssistantToolsFunction(BaseModel): Tool = Union[ToolAssistantToolsCode, ToolAssistantToolsRetrieval, ToolAssistantToolsFunction] +class Usage(BaseModel): + completion_tokens: int + """Number of completion tokens used over the course of the run.""" + + prompt_tokens: int + """Number of prompt tokens used over the course of the run.""" + + total_tokens: int + """Total number of tokens used (prompt + completion).""" + + class Run(BaseModel): id: str """The identifier, which can be referenced in API endpoints.""" @@ -152,3 +164,10 @@ class Run(BaseModel): [assistant](https://platform.openai.com/docs/api-reference/assistants) used for this run. """ + + usage: Optional[Usage] = None + """Usage statistics related to the run. + + This value will be `null` if the run is not in a terminal state (i.e. + `in_progress`, `queued`, etc.). + """ diff --git a/src/openai/types/beta/threads/runs/run_step.py b/src/openai/types/beta/threads/runs/run_step.py index 1d95e9d6eb..5f3e29a312 100644 --- a/src/openai/types/beta/threads/runs/run_step.py +++ b/src/openai/types/beta/threads/runs/run_step.py @@ -8,7 +8,7 @@ from .tool_calls_step_details import ToolCallsStepDetails from .message_creation_step_details import MessageCreationStepDetails -__all__ = ["RunStep", "LastError", "StepDetails"] +__all__ = ["RunStep", "LastError", "StepDetails", "Usage"] class LastError(BaseModel): @@ -22,6 +22,17 @@ class LastError(BaseModel): StepDetails = Union[MessageCreationStepDetails, ToolCallsStepDetails] +class Usage(BaseModel): + completion_tokens: int + """Number of completion tokens used over the course of the run step.""" + + prompt_tokens: int + """Number of prompt tokens used over the course of the run step.""" + + total_tokens: int + """Total number of tokens used (prompt + completion).""" + + class RunStep(BaseModel): id: str """The identifier of the run step, which can be referenced in API endpoints.""" @@ -91,3 +102,9 @@ class RunStep(BaseModel): type: Literal["message_creation", "tool_calls"] """The type of run step, which can be either `message_creation` or `tool_calls`.""" + + usage: Optional[Usage] = None + """Usage statistics related to the run step. + + This value will be `null` while the run step's status is `in_progress`. + """ From 15488ce07cb97535d8564e82dd5cda3481bc1a81 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Sun, 21 Jan 2024 00:41:08 -0500 Subject: [PATCH 204/816] release: 1.9.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 17 +++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 20 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index c523ce19f0..c3c95522a6 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.8.0" + ".": "1.9.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index c2ac83cdeb..14771f603b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,22 @@ # Changelog +## 1.9.0 (2024-01-21) + +Full Changelog: [v1.8.0...v1.9.0](https://github.com/openai/openai-python/compare/v1.8.0...v1.9.0) + +### Features + +* **api:** add usage to runs and run steps ([#1090](https://github.com/openai/openai-python/issues/1090)) ([6c116df](https://github.com/openai/openai-python/commit/6c116dfbb0065d15050450df70e0e98fc8c80349)) + + +### Chores + +* **internal:** fix typing util function ([#1083](https://github.com/openai/openai-python/issues/1083)) ([3e60db6](https://github.com/openai/openai-python/commit/3e60db69f5d9187c4eb38451967259f534a36a82)) +* **internal:** remove redundant client test ([#1085](https://github.com/openai/openai-python/issues/1085)) ([947974f](https://github.com/openai/openai-python/commit/947974f5af726e252b7b12c863743e50f41b79d3)) +* **internal:** share client instances between all tests ([#1088](https://github.com/openai/openai-python/issues/1088)) ([05cd753](https://github.com/openai/openai-python/commit/05cd7531d40774d05c52b14dee54d137ac1452a3)) +* **internal:** speculative retry-after-ms support ([#1086](https://github.com/openai/openai-python/issues/1086)) ([36a7576](https://github.com/openai/openai-python/commit/36a7576a913be8509a3cf6f262543083b485136e)) +* lazy load raw resource class properties ([#1087](https://github.com/openai/openai-python/issues/1087)) ([d307127](https://github.com/openai/openai-python/commit/d30712744be07461e86763705c03c3495eadfc35)) + ## 1.8.0 (2024-01-16) Full Changelog: [v1.7.2...v1.8.0](https://github.com/openai/openai-python/compare/v1.7.2...v1.8.0) diff --git a/pyproject.toml b/pyproject.toml index 5019e6cf7e..82f4c7e068 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.8.0" +version = "1.9.0" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 311cab2540..b4e6d226ea 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.8.0" # x-release-please-version +__version__ = "1.9.0" # x-release-please-version From ad87ea4061fd8a9785e10a520d513bdb0897a8a2 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 22 Jan 2024 10:48:42 -0500 Subject: [PATCH 205/816] chore(internal): add internal helpers (#1092) --- src/openai/_compat.py | 39 ++++++++++++++++++++- src/openai/_utils/__init__.py | 1 + src/openai/_utils/_sync.py | 64 +++++++++++++++++++++++++++++++++++ 3 files changed, 103 insertions(+), 1 deletion(-) create mode 100644 src/openai/_utils/_sync.py diff --git a/src/openai/_compat.py b/src/openai/_compat.py index 3cda39909b..74c7639b4c 100644 --- a/src/openai/_compat.py +++ b/src/openai/_compat.py @@ -1,13 +1,15 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Union, TypeVar, cast +from typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, cast, overload from datetime import date, datetime +from typing_extensions import Self import pydantic from pydantic.fields import FieldInfo from ._types import StrBytesIntFloat +_T = TypeVar("_T") _ModelT = TypeVar("_ModelT", bound=pydantic.BaseModel) # --------------- Pydantic v2 compatibility --------------- @@ -178,8 +180,43 @@ class GenericModel(pydantic.generics.GenericModel, pydantic.BaseModel): # cached properties if TYPE_CHECKING: cached_property = property + + # we define a separate type (copied from typeshed) + # that represents that `cached_property` is `set`able + # at runtime, which differs from `@property`. + # + # this is a separate type as editors likely special case + # `@property` and we don't want to cause issues just to have + # more helpful internal types. + + class typed_cached_property(Generic[_T]): + func: Callable[[Any], _T] + attrname: str | None + + def __init__(self, func: Callable[[Any], _T]) -> None: + ... + + @overload + def __get__(self, instance: None, owner: type[Any] | None = None) -> Self: + ... + + @overload + def __get__(self, instance: object, owner: type[Any] | None = None) -> _T: + ... + + def __get__(self, instance: object, owner: type[Any] | None = None) -> _T | Self: + raise NotImplementedError() + + def __set_name__(self, owner: type[Any], name: str) -> None: + ... + + # __set__ is not defined at runtime, but @cached_property is designed to be settable + def __set__(self, instance: object, value: _T) -> None: + ... else: try: from functools import cached_property as cached_property except ImportError: from cached_property import cached_property as cached_property + + typed_cached_property = cached_property diff --git a/src/openai/_utils/__init__.py b/src/openai/_utils/__init__.py index 2dcfc122f1..0fb811a945 100644 --- a/src/openai/_utils/__init__.py +++ b/src/openai/_utils/__init__.py @@ -1,3 +1,4 @@ +from ._sync import asyncify as asyncify from ._proxy import LazyProxy as LazyProxy from ._utils import ( flatten as flatten, diff --git a/src/openai/_utils/_sync.py b/src/openai/_utils/_sync.py new file mode 100644 index 0000000000..595924e5b1 --- /dev/null +++ b/src/openai/_utils/_sync.py @@ -0,0 +1,64 @@ +from __future__ import annotations + +import functools +from typing import TypeVar, Callable, Awaitable +from typing_extensions import ParamSpec + +import anyio +import anyio.to_thread + +T_Retval = TypeVar("T_Retval") +T_ParamSpec = ParamSpec("T_ParamSpec") + + +# copied from `asyncer`, https://github.com/tiangolo/asyncer +def asyncify( + function: Callable[T_ParamSpec, T_Retval], + *, + cancellable: bool = False, + limiter: anyio.CapacityLimiter | None = None, +) -> Callable[T_ParamSpec, Awaitable[T_Retval]]: + """ + Take a blocking function and create an async one that receives the same + positional and keyword arguments, and that when called, calls the original function + in a worker thread using `anyio.to_thread.run_sync()`. Internally, + `asyncer.asyncify()` uses the same `anyio.to_thread.run_sync()`, but it supports + keyword arguments additional to positional arguments and it adds better support for + autocompletion and inline errors for the arguments of the function called and the + return value. + + If the `cancellable` option is enabled and the task waiting for its completion is + cancelled, the thread will still run its course but its return value (or any raised + exception) will be ignored. + + Use it like this: + + ```Python + def do_work(arg1, arg2, kwarg1="", kwarg2="") -> str: + # Do work + return "Some result" + + + result = await to_thread.asyncify(do_work)("spam", "ham", kwarg1="a", kwarg2="b") + print(result) + ``` + + ## Arguments + + `function`: a blocking regular callable (e.g. a function) + `cancellable`: `True` to allow cancellation of the operation + `limiter`: capacity limiter to use to limit the total amount of threads running + (if omitted, the default limiter is used) + + ## Return + + An async function that takes the same positional and keyword arguments as the + original one, that when called runs the same original function in a thread worker + and returns the result. + """ + + async def wrapper(*args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs) -> T_Retval: + partial_f = functools.partial(function, *args, **kwargs) + return await anyio.to_thread.run_sync(partial_f, cancellable=cancellable, limiter=limiter) + + return wrapper From dd808c0f453375db16706dff42b097724110642a Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 22 Jan 2024 19:36:36 +0100 Subject: [PATCH 206/816] refactor: remove unnecessary builtin import (#1094) --- src/openai/types/beta/assistant.py | 3 +-- src/openai/types/beta/thread.py | 3 +-- src/openai/types/beta/threads/run.py | 3 +-- src/openai/types/beta/threads/runs/run_step.py | 3 +-- src/openai/types/beta/threads/thread_message.py | 3 +-- 5 files changed, 5 insertions(+), 10 deletions(-) diff --git a/src/openai/types/beta/assistant.py b/src/openai/types/beta/assistant.py index 89e45d4806..7a29984b50 100644 --- a/src/openai/types/beta/assistant.py +++ b/src/openai/types/beta/assistant.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. -import builtins from typing import List, Union, Optional from typing_extensions import Literal @@ -53,7 +52,7 @@ class Assistant(BaseModel): The maximum length is 32768 characters. """ - metadata: Optional[builtins.object] = None + metadata: Optional[object] = None """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a diff --git a/src/openai/types/beta/thread.py b/src/openai/types/beta/thread.py index 474527033a..a0002a21ef 100644 --- a/src/openai/types/beta/thread.py +++ b/src/openai/types/beta/thread.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. -import builtins from typing import Optional from typing_extensions import Literal @@ -16,7 +15,7 @@ class Thread(BaseModel): created_at: int """The Unix timestamp (in seconds) for when the thread was created.""" - metadata: Optional[builtins.object] = None + metadata: Optional[object] = None """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a diff --git a/src/openai/types/beta/threads/run.py b/src/openai/types/beta/threads/run.py index db4bc0e07d..9c875a9242 100644 --- a/src/openai/types/beta/threads/run.py +++ b/src/openai/types/beta/threads/run.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. -import builtins from typing import List, Union, Optional from typing_extensions import Literal @@ -116,7 +115,7 @@ class Run(BaseModel): last_error: Optional[LastError] = None """The last error associated with this run. Will be `null` if there are no errors.""" - metadata: Optional[builtins.object] = None + metadata: Optional[object] = None """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a diff --git a/src/openai/types/beta/threads/runs/run_step.py b/src/openai/types/beta/threads/runs/run_step.py index 5f3e29a312..01aab8e9a6 100644 --- a/src/openai/types/beta/threads/runs/run_step.py +++ b/src/openai/types/beta/threads/runs/run_step.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. -import builtins from typing import Union, Optional from typing_extensions import Literal @@ -68,7 +67,7 @@ class RunStep(BaseModel): Will be `null` if there are no errors. """ - metadata: Optional[builtins.object] = None + metadata: Optional[object] = None """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a diff --git a/src/openai/types/beta/threads/thread_message.py b/src/openai/types/beta/threads/thread_message.py index 8f1ac07d0a..25b3a199f7 100644 --- a/src/openai/types/beta/threads/thread_message.py +++ b/src/openai/types/beta/threads/thread_message.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. -import builtins from typing import List, Union, Optional from typing_extensions import Literal @@ -37,7 +36,7 @@ class ThreadMessage(BaseModel): that can access files. A maximum of 10 files can be attached to a message. """ - metadata: Optional[builtins.object] = None + metadata: Optional[object] = None """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a From f66d33e4a6c3e75add6c367f4d032bac036dffe1 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 24 Jan 2024 11:02:02 +0100 Subject: [PATCH 207/816] feat(azure): proactively add audio/speech to deployment endpoints (#1099) --- src/openai/lib/azure.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/openai/lib/azure.py b/src/openai/lib/azure.py index 27bebd8cab..2c8b4dcd88 100644 --- a/src/openai/lib/azure.py +++ b/src/openai/lib/azure.py @@ -22,6 +22,7 @@ "/embeddings", "/audio/transcriptions", "/audio/translations", + "/audio/speech", "/images/generations", ] ) From 62cd46330374c8ec0db9821b1e967fa87fde3c29 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 24 Jan 2024 17:06:53 +0100 Subject: [PATCH 208/816] feat(client): enable follow redirects by default (#1100) --- src/openai/_base_client.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 43fad0603d..7a1562461f 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -777,6 +777,7 @@ def __init__( proxies=proxies, transport=transport, limits=limits, + follow_redirects=True, ) def is_closed(self) -> bool: @@ -1318,6 +1319,7 @@ def __init__( proxies=proxies, transport=transport, limits=limits, + follow_redirects=True, ) def is_closed(self) -> bool: From 20d97ef0deb4e415b232d041bb6c0bede32a1553 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 25 Jan 2024 20:15:58 +0100 Subject: [PATCH 209/816] feat(api): add text embeddings dimensions param (#1103) --- src/openai/resources/chat/completions.py | 34 +++++++++++++++---- src/openai/resources/embeddings.py | 14 ++++++-- .../types/chat/completion_create_params.py | 6 +++- src/openai/types/embedding_create_params.py | 8 ++++- tests/api_resources/test_embeddings.py | 18 +++++----- 5 files changed, 62 insertions(+), 18 deletions(-) diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index f461161ab7..45521833ad 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -46,6 +46,8 @@ def create( model: Union[ str, Literal[ + "gpt-4-0125-preview", + "gpt-4-turbo-preview", "gpt-4-1106-preview", "gpt-4-vision-preview", "gpt-4", @@ -152,7 +154,8 @@ def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) response_format: An object specifying the format that the model must output. Compatible with - `gpt-4-1106-preview` and `gpt-3.5-turbo-1106`. + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -232,6 +235,8 @@ def create( model: Union[ str, Literal[ + "gpt-4-0125-preview", + "gpt-4-turbo-preview", "gpt-4-1106-preview", "gpt-4-vision-preview", "gpt-4", @@ -345,7 +350,8 @@ def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) response_format: An object specifying the format that the model must output. Compatible with - `gpt-4-1106-preview` and `gpt-3.5-turbo-1106`. + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -418,6 +424,8 @@ def create( model: Union[ str, Literal[ + "gpt-4-0125-preview", + "gpt-4-turbo-preview", "gpt-4-1106-preview", "gpt-4-vision-preview", "gpt-4", @@ -531,7 +539,8 @@ def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) response_format: An object specifying the format that the model must output. Compatible with - `gpt-4-1106-preview` and `gpt-3.5-turbo-1106`. + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -604,6 +613,8 @@ def create( model: Union[ str, Literal[ + "gpt-4-0125-preview", + "gpt-4-turbo-preview", "gpt-4-1106-preview", "gpt-4-vision-preview", "gpt-4", @@ -698,6 +709,8 @@ async def create( model: Union[ str, Literal[ + "gpt-4-0125-preview", + "gpt-4-turbo-preview", "gpt-4-1106-preview", "gpt-4-vision-preview", "gpt-4", @@ -804,7 +817,8 @@ async def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) response_format: An object specifying the format that the model must output. Compatible with - `gpt-4-1106-preview` and `gpt-3.5-turbo-1106`. + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -884,6 +898,8 @@ async def create( model: Union[ str, Literal[ + "gpt-4-0125-preview", + "gpt-4-turbo-preview", "gpt-4-1106-preview", "gpt-4-vision-preview", "gpt-4", @@ -997,7 +1013,8 @@ async def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) response_format: An object specifying the format that the model must output. Compatible with - `gpt-4-1106-preview` and `gpt-3.5-turbo-1106`. + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -1070,6 +1087,8 @@ async def create( model: Union[ str, Literal[ + "gpt-4-0125-preview", + "gpt-4-turbo-preview", "gpt-4-1106-preview", "gpt-4-vision-preview", "gpt-4", @@ -1183,7 +1202,8 @@ async def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) response_format: An object specifying the format that the model must output. Compatible with - `gpt-4-1106-preview` and `gpt-3.5-turbo-1106`. + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -1256,6 +1276,8 @@ async def create( model: Union[ str, Literal[ + "gpt-4-0125-preview", + "gpt-4-turbo-preview", "gpt-4-1106-preview", "gpt-4-vision-preview", "gpt-4", diff --git a/src/openai/resources/embeddings.py b/src/openai/resources/embeddings.py index 5bc7ed855e..857bfc7702 100644 --- a/src/openai/resources/embeddings.py +++ b/src/openai/resources/embeddings.py @@ -36,7 +36,8 @@ def create( self, *, input: Union[str, List[str], List[int], List[List[int]]], - model: Union[str, Literal["text-embedding-ada-002"]], + model: Union[str, Literal["text-embedding-ada-002", "text-embedding-3-small", "text-embedding-3-large"]], + dimensions: int | NotGiven = NOT_GIVEN, encoding_format: Literal["float", "base64"] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -64,6 +65,9 @@ def create( [Model overview](https://platform.openai.com/docs/models/overview) for descriptions of them. + dimensions: The number of dimensions the resulting output embeddings should have. Only + supported in `text-embedding-3` and later models. + encoding_format: The format to return the embeddings in. Can be either `float` or [`base64`](https://pypi.org/project/pybase64/). @@ -83,6 +87,7 @@ def create( "input": input, "model": model, "user": user, + "dimensions": dimensions, "encoding_format": encoding_format, } if not is_given(encoding_format) and has_numpy(): @@ -132,7 +137,8 @@ async def create( self, *, input: Union[str, List[str], List[int], List[List[int]]], - model: Union[str, Literal["text-embedding-ada-002"]], + model: Union[str, Literal["text-embedding-ada-002", "text-embedding-3-small", "text-embedding-3-large"]], + dimensions: int | NotGiven = NOT_GIVEN, encoding_format: Literal["float", "base64"] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -160,6 +166,9 @@ async def create( [Model overview](https://platform.openai.com/docs/models/overview) for descriptions of them. + dimensions: The number of dimensions the resulting output embeddings should have. Only + supported in `text-embedding-3` and later models. + encoding_format: The format to return the embeddings in. Can be either `float` or [`base64`](https://pypi.org/project/pybase64/). @@ -179,6 +188,7 @@ async def create( "input": input, "model": model, "user": user, + "dimensions": dimensions, "encoding_format": encoding_format, } if not is_given(encoding_format) and has_numpy(): diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 6b38a89263..3ea14d82b3 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -32,6 +32,8 @@ class CompletionCreateParamsBase(TypedDict, total=False): Union[ str, Literal[ + "gpt-4-0125-preview", + "gpt-4-turbo-preview", "gpt-4-1106-preview", "gpt-4-vision-preview", "gpt-4", @@ -133,7 +135,9 @@ class CompletionCreateParamsBase(TypedDict, total=False): response_format: ResponseFormat """An object specifying the format that the model must output. - Compatible with `gpt-4-1106-preview` and `gpt-3.5-turbo-1106`. + Compatible with + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. diff --git a/src/openai/types/embedding_create_params.py b/src/openai/types/embedding_create_params.py index fd2fc5b48d..66ac60511c 100644 --- a/src/openai/types/embedding_create_params.py +++ b/src/openai/types/embedding_create_params.py @@ -20,7 +20,7 @@ class EmbeddingCreateParams(TypedDict, total=False): for counting tokens. """ - model: Required[Union[str, Literal["text-embedding-ada-002"]]] + model: Required[Union[str, Literal["text-embedding-ada-002", "text-embedding-3-small", "text-embedding-3-large"]]] """ID of the model to use. You can use the @@ -30,6 +30,12 @@ class EmbeddingCreateParams(TypedDict, total=False): descriptions of them. """ + dimensions: int + """The number of dimensions the resulting output embeddings should have. + + Only supported in `text-embedding-3` and later models. + """ + encoding_format: Literal["float", "base64"] """The format to return the embeddings in. diff --git a/tests/api_resources/test_embeddings.py b/tests/api_resources/test_embeddings.py index cd4ff8e391..42599219f3 100644 --- a/tests/api_resources/test_embeddings.py +++ b/tests/api_resources/test_embeddings.py @@ -21,7 +21,7 @@ class TestEmbeddings: def test_method_create(self, client: OpenAI) -> None: embedding = client.embeddings.create( input="The quick brown fox jumped over the lazy dog", - model="text-embedding-ada-002", + model="text-embedding-3-small", ) assert_matches_type(CreateEmbeddingResponse, embedding, path=["response"]) @@ -29,7 +29,8 @@ def test_method_create(self, client: OpenAI) -> None: def test_method_create_with_all_params(self, client: OpenAI) -> None: embedding = client.embeddings.create( input="The quick brown fox jumped over the lazy dog", - model="text-embedding-ada-002", + model="text-embedding-3-small", + dimensions=1, encoding_format="float", user="user-1234", ) @@ -39,7 +40,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: def test_raw_response_create(self, client: OpenAI) -> None: response = client.embeddings.with_raw_response.create( input="The quick brown fox jumped over the lazy dog", - model="text-embedding-ada-002", + model="text-embedding-3-small", ) assert response.is_closed is True @@ -51,7 +52,7 @@ def test_raw_response_create(self, client: OpenAI) -> None: def test_streaming_response_create(self, client: OpenAI) -> None: with client.embeddings.with_streaming_response.create( input="The quick brown fox jumped over the lazy dog", - model="text-embedding-ada-002", + model="text-embedding-3-small", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -69,7 +70,7 @@ class TestAsyncEmbeddings: async def test_method_create(self, async_client: AsyncOpenAI) -> None: embedding = await async_client.embeddings.create( input="The quick brown fox jumped over the lazy dog", - model="text-embedding-ada-002", + model="text-embedding-3-small", ) assert_matches_type(CreateEmbeddingResponse, embedding, path=["response"]) @@ -77,7 +78,8 @@ async def test_method_create(self, async_client: AsyncOpenAI) -> None: async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: embedding = await async_client.embeddings.create( input="The quick brown fox jumped over the lazy dog", - model="text-embedding-ada-002", + model="text-embedding-3-small", + dimensions=1, encoding_format="float", user="user-1234", ) @@ -87,7 +89,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: response = await async_client.embeddings.with_raw_response.create( input="The quick brown fox jumped over the lazy dog", - model="text-embedding-ada-002", + model="text-embedding-3-small", ) assert response.is_closed is True @@ -99,7 +101,7 @@ async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: async with async_client.embeddings.with_streaming_response.create( input="The quick brown fox jumped over the lazy dog", - model="text-embedding-ada-002", + model="text-embedding-3-small", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" From 0c1e58d511bd60c4dd47ea8a8c0820dc2d013d1d Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 25 Jan 2024 20:16:44 +0100 Subject: [PATCH 210/816] release: 1.10.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 20 ++++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 23 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index c3c95522a6..eb4e0dba72 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.9.0" + ".": "1.10.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 14771f603b..1a22e062dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,25 @@ # Changelog +## 1.10.0 (2024-01-25) + +Full Changelog: [v1.9.0...v1.10.0](https://github.com/openai/openai-python/compare/v1.9.0...v1.10.0) + +### Features + +* **api:** add text embeddings dimensions param ([#1103](https://github.com/openai/openai-python/issues/1103)) ([94abfa0](https://github.com/openai/openai-python/commit/94abfa0f988c199ea95a9c870c4ae9808823186d)) +* **azure:** proactively add audio/speech to deployment endpoints ([#1099](https://github.com/openai/openai-python/issues/1099)) ([fdf8742](https://github.com/openai/openai-python/commit/fdf87429b45ceb47ae6fd068ab70cc07bcb8da44)) +* **client:** enable follow redirects by default ([#1100](https://github.com/openai/openai-python/issues/1100)) ([d325b7c](https://github.com/openai/openai-python/commit/d325b7ca594c2abaada536249b5633b106943333)) + + +### Chores + +* **internal:** add internal helpers ([#1092](https://github.com/openai/openai-python/issues/1092)) ([629bde5](https://github.com/openai/openai-python/commit/629bde5800d84735e22d924db23109a141f48644)) + + +### Refactors + +* remove unnecessary builtin import ([#1094](https://github.com/openai/openai-python/issues/1094)) ([504b7d4](https://github.com/openai/openai-python/commit/504b7d4a0b4715bd49a1a076a8d4868e51fb3351)) + ## 1.9.0 (2024-01-21) Full Changelog: [v1.8.0...v1.9.0](https://github.com/openai/openai-python/compare/v1.8.0...v1.9.0) diff --git a/pyproject.toml b/pyproject.toml index 82f4c7e068..b3448f1aeb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.9.0" +version = "1.10.0" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index b4e6d226ea..e9a863539d 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.9.0" # x-release-please-version +__version__ = "1.10.0" # x-release-please-version From 22713fd02a31c1dfe332a691190db5ecae1e39f4 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 26 Jan 2024 11:47:48 +0100 Subject: [PATCH 211/816] chore(internal): support multipart data with overlapping keys (#1104) --- src/openai/_base_client.py | 32 +++++++++++++++++---- tests/test_client.py | 58 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 6 deletions(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 7a1562461f..d7e5127dd8 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -61,7 +61,7 @@ RequestOptions, ModelBuilderProtocol, ) -from ._utils import is_dict, is_given, is_mapping +from ._utils import is_dict, is_list, is_given, is_mapping from ._compat import model_copy, model_dump from ._models import GenericModel, FinalRequestOptions, validate_type, construct_type from ._response import ( @@ -451,14 +451,18 @@ def _build_request( headers = self._build_headers(options) params = _merge_mappings(self._custom_query, options.params) + content_type = headers.get("Content-Type") # If the given Content-Type header is multipart/form-data then it # has to be removed so that httpx can generate the header with # additional information for us as it has to be in this form # for the server to be able to correctly parse the request: # multipart/form-data; boundary=---abc-- - if headers.get("Content-Type") == "multipart/form-data": - headers.pop("Content-Type") + if content_type is not None and content_type.startswith("multipart/form-data"): + if "boundary" not in content_type: + # only remove the header if the boundary hasn't been explicitly set + # as the caller doesn't want httpx to come up with their own boundary + headers.pop("Content-Type") # As we are now sending multipart/form-data instead of application/json # we need to tell httpx to use it, https://www.python-httpx.org/advanced/#multipart-file-encoding @@ -494,9 +498,25 @@ def _serialize_multipartform(self, data: Mapping[object, object]) -> dict[str, o ) serialized: dict[str, object] = {} for key, value in items: - if key in serialized: - raise ValueError(f"Duplicate key encountered: {key}; This behaviour is not supported") - serialized[key] = value + existing = serialized.get(key) + + if not existing: + serialized[key] = value + continue + + # If a value has already been set for this key then that + # means we're sending data like `array[]=[1, 2, 3]` and we + # need to tell httpx that we want to send multiple values with + # the same key which is done by using a list or a tuple. + # + # Note: 2d arrays should never result in the same key at both + # levels so it's safe to assume that if the value is a list, + # it was because we changed it to be a list. + if is_list(existing): + existing.append(value) + else: + serialized[key] = [existing, value] + return serialized def _maybe_override_cast_to(self, cast_to: type[ResponseT], options: FinalRequestOptions) -> type[ResponseT]: diff --git a/tests/test_client.py b/tests/test_client.py index 3d2dd35821..24933456bd 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -437,6 +437,35 @@ def test_request_extra_query(self) -> None: params = dict(request.url.params) assert params == {"foo": "2"} + def test_multipart_repeating_array(self, client: OpenAI) -> None: + request = client._build_request( + FinalRequestOptions.construct( + method="get", + url="/foo", + headers={"Content-Type": "multipart/form-data; boundary=6b7ba517decee4a450543ea6ae821c82"}, + json_data={"array": ["foo", "bar"]}, + files=[("foo.txt", b"hello world")], + ) + ) + + assert request.read().split(b"\r\n") == [ + b"--6b7ba517decee4a450543ea6ae821c82", + b'Content-Disposition: form-data; name="array[]"', + b"", + b"foo", + b"--6b7ba517decee4a450543ea6ae821c82", + b'Content-Disposition: form-data; name="array[]"', + b"", + b"bar", + b"--6b7ba517decee4a450543ea6ae821c82", + b'Content-Disposition: form-data; name="foo.txt"; filename="upload"', + b"Content-Type: application/octet-stream", + b"", + b"hello world", + b"--6b7ba517decee4a450543ea6ae821c82--", + b"", + ] + @pytest.mark.respx(base_url=base_url) def test_basic_union_response(self, respx_mock: MockRouter) -> None: class Model1(BaseModel): @@ -1104,6 +1133,35 @@ def test_request_extra_query(self) -> None: params = dict(request.url.params) assert params == {"foo": "2"} + def test_multipart_repeating_array(self, async_client: AsyncOpenAI) -> None: + request = async_client._build_request( + FinalRequestOptions.construct( + method="get", + url="/foo", + headers={"Content-Type": "multipart/form-data; boundary=6b7ba517decee4a450543ea6ae821c82"}, + json_data={"array": ["foo", "bar"]}, + files=[("foo.txt", b"hello world")], + ) + ) + + assert request.read().split(b"\r\n") == [ + b"--6b7ba517decee4a450543ea6ae821c82", + b'Content-Disposition: form-data; name="array[]"', + b"", + b"foo", + b"--6b7ba517decee4a450543ea6ae821c82", + b'Content-Disposition: form-data; name="array[]"', + b"", + b"bar", + b"--6b7ba517decee4a450543ea6ae821c82", + b'Content-Disposition: form-data; name="foo.txt"; filename="upload"', + b"Content-Type: application/octet-stream", + b"", + b"hello world", + b"--6b7ba517decee4a450543ea6ae821c82--", + b"", + ] + @pytest.mark.respx(base_url=base_url) async def test_basic_union_response(self, respx_mock: MockRouter) -> None: class Model1(BaseModel): From 63de8ef4229ba92fb05ac15efb1a07b3ab2a79ee Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 26 Jan 2024 14:55:41 +0100 Subject: [PATCH 212/816] chore(internal): enable ruff type checking misuse lint rule (#1106) This catches the case where a typing import is used at runtime --- pyproject.toml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index b3448f1aeb..c088e19264 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -147,6 +147,8 @@ select = [ # print statements "T201", "T203", + # misuse of typing.TYPE_CHECKING + "TCH004" ] ignore = [ # mutable defaults From 61f3346b4c6fec20a4109ad884c998e706593137 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 29 Jan 2024 13:05:32 +0100 Subject: [PATCH 213/816] feat(client): support parsing custom response types (#1111) --- src/openai/__init__.py | 2 + src/openai/_legacy_response.py | 102 ++++++++++++++++------- src/openai/_response.py | 147 +++++++++++++++++++++++---------- src/openai/_streaming.py | 36 +++++++- src/openai/_utils/_typing.py | 10 ++- tests/test_legacy_response.py | 65 +++++++++++++++ tests/test_response.py | 109 ++++++++++++++++++++++++ 7 files changed, 392 insertions(+), 79 deletions(-) create mode 100644 tests/test_legacy_response.py diff --git a/src/openai/__init__.py b/src/openai/__init__.py index 0de58b3327..118fe8ee93 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -9,6 +9,7 @@ from ._types import NoneType, Transport, ProxiesTypes from ._utils import file_from_path from ._client import Client, OpenAI, Stream, Timeout, Transport, AsyncClient, AsyncOpenAI, AsyncStream, RequestOptions +from ._models import BaseModel from ._version import __title__, __version__ from ._response import APIResponse as APIResponse, AsyncAPIResponse as AsyncAPIResponse from ._exceptions import ( @@ -59,6 +60,7 @@ "OpenAI", "AsyncOpenAI", "file_from_path", + "BaseModel", ] from .lib import azure as _azure diff --git a/src/openai/_legacy_response.py b/src/openai/_legacy_response.py index c36c94f165..6eaa691d9f 100644 --- a/src/openai/_legacy_response.py +++ b/src/openai/_legacy_response.py @@ -5,25 +5,28 @@ import logging import datetime import functools -from typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, Iterator, AsyncIterator, cast -from typing_extensions import Awaitable, ParamSpec, get_args, override, deprecated, get_origin +from typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, Iterator, AsyncIterator, cast, overload +from typing_extensions import Awaitable, ParamSpec, override, deprecated, get_origin import anyio import httpx +import pydantic from ._types import NoneType from ._utils import is_given from ._models import BaseModel, is_basemodel from ._constants import RAW_RESPONSE_HEADER +from ._streaming import Stream, AsyncStream, is_stream_class_type, extract_stream_chunk_type from ._exceptions import APIResponseValidationError if TYPE_CHECKING: from ._models import FinalRequestOptions - from ._base_client import Stream, BaseClient, AsyncStream + from ._base_client import BaseClient P = ParamSpec("P") R = TypeVar("R") +_T = TypeVar("_T") log: logging.Logger = logging.getLogger(__name__) @@ -43,7 +46,7 @@ class LegacyAPIResponse(Generic[R]): _cast_to: type[R] _client: BaseClient[Any, Any] - _parsed: R | None + _parsed_by_type: dict[type[Any], Any] _stream: bool _stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None _options: FinalRequestOptions @@ -62,27 +65,60 @@ def __init__( ) -> None: self._cast_to = cast_to self._client = client - self._parsed = None + self._parsed_by_type = {} self._stream = stream self._stream_cls = stream_cls self._options = options self.http_response = raw + @overload + def parse(self, *, to: type[_T]) -> _T: + ... + + @overload def parse(self) -> R: + ... + + def parse(self, *, to: type[_T] | None = None) -> R | _T: """Returns the rich python representation of this response's data. + NOTE: For the async client: this will become a coroutine in the next major version. + For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`. - NOTE: For the async client: this will become a coroutine in the next major version. + You can customise the type that the response is parsed into through + the `to` argument, e.g. + + ```py + from openai import BaseModel + + + class MyModel(BaseModel): + foo: str + + + obj = response.parse(to=MyModel) + print(obj.foo) + ``` + + We support parsing: + - `BaseModel` + - `dict` + - `list` + - `Union` + - `str` + - `httpx.Response` """ - if self._parsed is not None: - return self._parsed + cache_key = to if to is not None else self._cast_to + cached = self._parsed_by_type.get(cache_key) + if cached is not None: + return cached # type: ignore[no-any-return] - parsed = self._parse() + parsed = self._parse(to=to) if is_given(self._options.post_parser): parsed = self._options.post_parser(parsed) - self._parsed = parsed + self._parsed_by_type[cache_key] = parsed return parsed @property @@ -135,13 +171,29 @@ def elapsed(self) -> datetime.timedelta: """The time taken for the complete request/response cycle to complete.""" return self.http_response.elapsed - def _parse(self) -> R: + def _parse(self, *, to: type[_T] | None = None) -> R | _T: if self._stream: + if to: + if not is_stream_class_type(to): + raise TypeError(f"Expected custom parse type to be a subclass of {Stream} or {AsyncStream}") + + return cast( + _T, + to( + cast_to=extract_stream_chunk_type( + to, + failure_message="Expected custom stream type to be passed with a type argument, e.g. Stream[ChunkType]", + ), + response=self.http_response, + client=cast(Any, self._client), + ), + ) + if self._stream_cls: return cast( R, self._stream_cls( - cast_to=_extract_stream_chunk_type(self._stream_cls), + cast_to=extract_stream_chunk_type(self._stream_cls), response=self.http_response, client=cast(Any, self._client), ), @@ -160,7 +212,7 @@ def _parse(self) -> R: ), ) - cast_to = self._cast_to + cast_to = to if to is not None else self._cast_to if cast_to is NoneType: return cast(R, None) @@ -186,14 +238,9 @@ def _parse(self) -> R: raise ValueError(f"Subclasses of httpx.Response cannot be passed to `cast_to`") return cast(R, response) - # The check here is necessary as we are subverting the the type system - # with casts as the relationship between TypeVars and Types are very strict - # which means we must return *exactly* what was input or transform it in a - # way that retains the TypeVar state. As we cannot do that in this function - # then we have to resort to using `cast`. At the time of writing, we know this - # to be safe as we have handled all the types that could be bound to the - # `ResponseT` TypeVar, however if that TypeVar is ever updated in the future, then - # this function would become unsafe but a type checker would not report an error. + if inspect.isclass(origin) and not issubclass(origin, BaseModel) and issubclass(origin, pydantic.BaseModel): + raise TypeError("Pydantic models must subclass our base model type, e.g. `from openai import BaseModel`") + if ( cast_to is not object and not origin is list @@ -202,12 +249,12 @@ def _parse(self) -> R: and not issubclass(origin, BaseModel) ): raise RuntimeError( - f"Invalid state, expected {cast_to} to be a subclass type of {BaseModel}, {dict}, {list} or {Union}." + f"Unsupported type, expected {cast_to} to be a subclass of {BaseModel}, {dict}, {list}, {Union}, {NoneType}, {str} or {httpx.Response}." ) # split is required to handle cases where additional information is included # in the response, e.g. application/json; charset=utf-8 - content_type, *_ = response.headers.get("content-type").split(";") + content_type, *_ = response.headers.get("content-type", "*").split(";") if content_type != "application/json": if is_basemodel(cast_to): try: @@ -253,15 +300,6 @@ def __init__(self) -> None: ) -def _extract_stream_chunk_type(stream_cls: type) -> type: - args = get_args(stream_cls) - if not args: - raise TypeError( - f"Expected stream_cls to have been given a generic type argument, e.g. Stream[Foo] but received {stream_cls}", - ) - return cast(type, args[0]) - - def to_raw_response_wrapper(func: Callable[P, R]) -> Callable[P, LegacyAPIResponse[R]]: """Higher order function that takes one of our bound API methods and wraps it to support returning the raw `APIResponse` object directly. diff --git a/src/openai/_response.py b/src/openai/_response.py index 15a323afa4..b1e070122f 100644 --- a/src/openai/_response.py +++ b/src/openai/_response.py @@ -16,25 +16,29 @@ Iterator, AsyncIterator, cast, + overload, ) from typing_extensions import Awaitable, ParamSpec, override, get_origin import anyio import httpx +import pydantic from ._types import NoneType from ._utils import is_given, extract_type_var_from_base from ._models import BaseModel, is_basemodel from ._constants import RAW_RESPONSE_HEADER, OVERRIDE_CAST_TO_HEADER +from ._streaming import Stream, AsyncStream, is_stream_class_type, extract_stream_chunk_type from ._exceptions import OpenAIError, APIResponseValidationError if TYPE_CHECKING: from ._models import FinalRequestOptions - from ._base_client import Stream, BaseClient, AsyncStream + from ._base_client import BaseClient P = ParamSpec("P") R = TypeVar("R") +_T = TypeVar("_T") _APIResponseT = TypeVar("_APIResponseT", bound="APIResponse[Any]") _AsyncAPIResponseT = TypeVar("_AsyncAPIResponseT", bound="AsyncAPIResponse[Any]") @@ -44,7 +48,7 @@ class BaseAPIResponse(Generic[R]): _cast_to: type[R] _client: BaseClient[Any, Any] - _parsed: R | None + _parsed_by_type: dict[type[Any], Any] _is_sse_stream: bool _stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None _options: FinalRequestOptions @@ -63,7 +67,7 @@ def __init__( ) -> None: self._cast_to = cast_to self._client = client - self._parsed = None + self._parsed_by_type = {} self._is_sse_stream = stream self._stream_cls = stream_cls self._options = options @@ -116,8 +120,24 @@ def __repr__(self) -> str: f"<{self.__class__.__name__} [{self.status_code} {self.http_response.reason_phrase}] type={self._cast_to}>" ) - def _parse(self) -> R: + def _parse(self, *, to: type[_T] | None = None) -> R | _T: if self._is_sse_stream: + if to: + if not is_stream_class_type(to): + raise TypeError(f"Expected custom parse type to be a subclass of {Stream} or {AsyncStream}") + + return cast( + _T, + to( + cast_to=extract_stream_chunk_type( + to, + failure_message="Expected custom stream type to be passed with a type argument, e.g. Stream[ChunkType]", + ), + response=self.http_response, + client=cast(Any, self._client), + ), + ) + if self._stream_cls: return cast( R, @@ -141,7 +161,7 @@ def _parse(self) -> R: ), ) - cast_to = self._cast_to + cast_to = to if to is not None else self._cast_to if cast_to is NoneType: return cast(R, None) @@ -171,14 +191,9 @@ def _parse(self) -> R: raise ValueError(f"Subclasses of httpx.Response cannot be passed to `cast_to`") return cast(R, response) - # The check here is necessary as we are subverting the the type system - # with casts as the relationship between TypeVars and Types are very strict - # which means we must return *exactly* what was input or transform it in a - # way that retains the TypeVar state. As we cannot do that in this function - # then we have to resort to using `cast`. At the time of writing, we know this - # to be safe as we have handled all the types that could be bound to the - # `ResponseT` TypeVar, however if that TypeVar is ever updated in the future, then - # this function would become unsafe but a type checker would not report an error. + if inspect.isclass(origin) and not issubclass(origin, BaseModel) and issubclass(origin, pydantic.BaseModel): + raise TypeError("Pydantic models must subclass our base model type, e.g. `from openai import BaseModel`") + if ( cast_to is not object and not origin is list @@ -187,12 +202,12 @@ def _parse(self) -> R: and not issubclass(origin, BaseModel) ): raise RuntimeError( - f"Invalid state, expected {cast_to} to be a subclass type of {BaseModel}, {dict}, {list} or {Union}." + f"Unsupported type, expected {cast_to} to be a subclass of {BaseModel}, {dict}, {list}, {Union}, {NoneType}, {str} or {httpx.Response}." ) # split is required to handle cases where additional information is included # in the response, e.g. application/json; charset=utf-8 - content_type, *_ = response.headers.get("content-type").split(";") + content_type, *_ = response.headers.get("content-type", "*").split(";") if content_type != "application/json": if is_basemodel(cast_to): try: @@ -228,22 +243,55 @@ def _parse(self) -> R: class APIResponse(BaseAPIResponse[R]): + @overload + def parse(self, *, to: type[_T]) -> _T: + ... + + @overload def parse(self) -> R: + ... + + def parse(self, *, to: type[_T] | None = None) -> R | _T: """Returns the rich python representation of this response's data. For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`. + + You can customise the type that the response is parsed into through + the `to` argument, e.g. + + ```py + from openai import BaseModel + + + class MyModel(BaseModel): + foo: str + + + obj = response.parse(to=MyModel) + print(obj.foo) + ``` + + We support parsing: + - `BaseModel` + - `dict` + - `list` + - `Union` + - `str` + - `httpx.Response` """ - if self._parsed is not None: - return self._parsed + cache_key = to if to is not None else self._cast_to + cached = self._parsed_by_type.get(cache_key) + if cached is not None: + return cached # type: ignore[no-any-return] if not self._is_sse_stream: self.read() - parsed = self._parse() + parsed = self._parse(to=to) if is_given(self._options.post_parser): parsed = self._options.post_parser(parsed) - self._parsed = parsed + self._parsed_by_type[cache_key] = parsed return parsed def read(self) -> bytes: @@ -297,22 +345,55 @@ def iter_lines(self) -> Iterator[str]: class AsyncAPIResponse(BaseAPIResponse[R]): + @overload + async def parse(self, *, to: type[_T]) -> _T: + ... + + @overload async def parse(self) -> R: + ... + + async def parse(self, *, to: type[_T] | None = None) -> R | _T: """Returns the rich python representation of this response's data. For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`. + + You can customise the type that the response is parsed into through + the `to` argument, e.g. + + ```py + from openai import BaseModel + + + class MyModel(BaseModel): + foo: str + + + obj = response.parse(to=MyModel) + print(obj.foo) + ``` + + We support parsing: + - `BaseModel` + - `dict` + - `list` + - `Union` + - `str` + - `httpx.Response` """ - if self._parsed is not None: - return self._parsed + cache_key = to if to is not None else self._cast_to + cached = self._parsed_by_type.get(cache_key) + if cached is not None: + return cached # type: ignore[no-any-return] if not self._is_sse_stream: await self.read() - parsed = self._parse() + parsed = self._parse(to=to) if is_given(self._options.post_parser): parsed = self._options.post_parser(parsed) - self._parsed = parsed + self._parsed_by_type[cache_key] = parsed return parsed async def read(self) -> bytes: @@ -708,26 +789,6 @@ def wrapped(*args: P.args, **kwargs: P.kwargs) -> Awaitable[_AsyncAPIResponseT]: return wrapped -def extract_stream_chunk_type(stream_cls: type) -> type: - """Given a type like `Stream[T]`, returns the generic type variable `T`. - - This also handles the case where a concrete subclass is given, e.g. - ```py - class MyStream(Stream[bytes]): - ... - - extract_stream_chunk_type(MyStream) -> bytes - ``` - """ - from ._base_client import Stream, AsyncStream - - return extract_type_var_from_base( - stream_cls, - index=0, - generic_bases=cast("tuple[type, ...]", (Stream, AsyncStream)), - ) - - def extract_response_type(typ: type[BaseAPIResponse[Any]]) -> type: """Given a type like `APIResponse[T]`, returns the generic type variable `T`. diff --git a/src/openai/_streaming.py b/src/openai/_streaming.py index 85cec70c11..74878fd0a0 100644 --- a/src/openai/_streaming.py +++ b/src/openai/_streaming.py @@ -2,13 +2,14 @@ from __future__ import annotations import json +import inspect from types import TracebackType from typing import TYPE_CHECKING, Any, Generic, TypeVar, Iterator, AsyncIterator, cast -from typing_extensions import Self, override +from typing_extensions import Self, TypeGuard, override, get_origin import httpx -from ._utils import is_mapping +from ._utils import is_mapping, extract_type_var_from_base from ._exceptions import APIError if TYPE_CHECKING: @@ -281,3 +282,34 @@ def decode(self, line: str) -> ServerSentEvent | None: pass # Field is ignored. return None + + +def is_stream_class_type(typ: type) -> TypeGuard[type[Stream[object]] | type[AsyncStream[object]]]: + """TypeGuard for determining whether or not the given type is a subclass of `Stream` / `AsyncStream`""" + origin = get_origin(typ) or typ + return inspect.isclass(origin) and issubclass(origin, (Stream, AsyncStream)) + + +def extract_stream_chunk_type( + stream_cls: type, + *, + failure_message: str | None = None, +) -> type: + """Given a type like `Stream[T]`, returns the generic type variable `T`. + + This also handles the case where a concrete subclass is given, e.g. + ```py + class MyStream(Stream[bytes]): + ... + + extract_stream_chunk_type(MyStream) -> bytes + ``` + """ + from ._base_client import Stream, AsyncStream + + return extract_type_var_from_base( + stream_cls, + index=0, + generic_bases=cast("tuple[type, ...]", (Stream, AsyncStream)), + failure_message=failure_message, + ) diff --git a/src/openai/_utils/_typing.py b/src/openai/_utils/_typing.py index a020822bc0..c1d1ebb9a4 100644 --- a/src/openai/_utils/_typing.py +++ b/src/openai/_utils/_typing.py @@ -45,7 +45,13 @@ def extract_type_arg(typ: type, index: int) -> type: raise RuntimeError(f"Expected type {typ} to have a type argument at index {index} but it did not") from err -def extract_type_var_from_base(typ: type, *, generic_bases: tuple[type, ...], index: int) -> type: +def extract_type_var_from_base( + typ: type, + *, + generic_bases: tuple[type, ...], + index: int, + failure_message: str | None = None, +) -> type: """Given a type like `Foo[T]`, returns the generic type variable `T`. This also handles the case where a concrete subclass is given, e.g. @@ -104,4 +110,4 @@ class MyResponse(Foo[_T]): return extracted - raise RuntimeError(f"Could not resolve inner type variable at index {index} for {typ}") + raise RuntimeError(failure_message or f"Could not resolve inner type variable at index {index} for {typ}") diff --git a/tests/test_legacy_response.py b/tests/test_legacy_response.py new file mode 100644 index 0000000000..995250a58c --- /dev/null +++ b/tests/test_legacy_response.py @@ -0,0 +1,65 @@ +import json + +import httpx +import pytest +import pydantic + +from openai import OpenAI, BaseModel +from openai._streaming import Stream +from openai._base_client import FinalRequestOptions +from openai._legacy_response import LegacyAPIResponse + + +class PydanticModel(pydantic.BaseModel): + ... + + +def test_response_parse_mismatched_basemodel(client: OpenAI) -> None: + response = LegacyAPIResponse( + raw=httpx.Response(200, content=b"foo"), + client=client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + with pytest.raises( + TypeError, + match="Pydantic models must subclass our base model type, e.g. `from openai import BaseModel`", + ): + response.parse(to=PydanticModel) + + +def test_response_parse_custom_stream(client: OpenAI) -> None: + response = LegacyAPIResponse( + raw=httpx.Response(200, content=b"foo"), + client=client, + stream=True, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + stream = response.parse(to=Stream[int]) + assert stream._cast_to == int + + +class CustomModel(BaseModel): + foo: str + bar: int + + +def test_response_parse_custom_model(client: OpenAI) -> None: + response = LegacyAPIResponse( + raw=httpx.Response(200, content=json.dumps({"foo": "hello!", "bar": 2})), + client=client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + obj = response.parse(to=CustomModel) + assert obj.foo == "hello!" + assert obj.bar == 2 diff --git a/tests/test_response.py b/tests/test_response.py index 335ca7922a..7c99327b46 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -1,8 +1,11 @@ +import json from typing import List import httpx import pytest +import pydantic +from openai import OpenAI, BaseModel, AsyncOpenAI from openai._response import ( APIResponse, BaseAPIResponse, @@ -11,6 +14,8 @@ AsyncBinaryAPIResponse, extract_response_type, ) +from openai._streaming import Stream +from openai._base_client import FinalRequestOptions class ConcreteBaseAPIResponse(APIResponse[bytes]): @@ -48,3 +53,107 @@ def test_extract_response_type_concrete_subclasses() -> None: def test_extract_response_type_binary_response() -> None: assert extract_response_type(BinaryAPIResponse) == bytes assert extract_response_type(AsyncBinaryAPIResponse) == bytes + + +class PydanticModel(pydantic.BaseModel): + ... + + +def test_response_parse_mismatched_basemodel(client: OpenAI) -> None: + response = APIResponse( + raw=httpx.Response(200, content=b"foo"), + client=client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + with pytest.raises( + TypeError, + match="Pydantic models must subclass our base model type, e.g. `from openai import BaseModel`", + ): + response.parse(to=PydanticModel) + + +@pytest.mark.asyncio +async def test_async_response_parse_mismatched_basemodel(async_client: AsyncOpenAI) -> None: + response = AsyncAPIResponse( + raw=httpx.Response(200, content=b"foo"), + client=async_client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + with pytest.raises( + TypeError, + match="Pydantic models must subclass our base model type, e.g. `from openai import BaseModel`", + ): + await response.parse(to=PydanticModel) + + +def test_response_parse_custom_stream(client: OpenAI) -> None: + response = APIResponse( + raw=httpx.Response(200, content=b"foo"), + client=client, + stream=True, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + stream = response.parse(to=Stream[int]) + assert stream._cast_to == int + + +@pytest.mark.asyncio +async def test_async_response_parse_custom_stream(async_client: AsyncOpenAI) -> None: + response = AsyncAPIResponse( + raw=httpx.Response(200, content=b"foo"), + client=async_client, + stream=True, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + stream = await response.parse(to=Stream[int]) + assert stream._cast_to == int + + +class CustomModel(BaseModel): + foo: str + bar: int + + +def test_response_parse_custom_model(client: OpenAI) -> None: + response = APIResponse( + raw=httpx.Response(200, content=json.dumps({"foo": "hello!", "bar": 2})), + client=client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + obj = response.parse(to=CustomModel) + assert obj.foo == "hello!" + assert obj.bar == 2 + + +@pytest.mark.asyncio +async def test_async_response_parse_custom_model(async_client: AsyncOpenAI) -> None: + response = AsyncAPIResponse( + raw=httpx.Response(200, content=json.dumps({"foo": "hello!", "bar": 2})), + client=async_client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + obj = await response.parse(to=CustomModel) + assert obj.foo == "hello!" + assert obj.bar == 2 From 76382e3c8dcf079116743aba959c64f33274d725 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 29 Jan 2024 18:58:55 +0100 Subject: [PATCH 214/816] chore(internal): cast type in mocked test (#1112) --- tests/test_client.py | 76 +++++++++++++++++++++++++------------------- 1 file changed, 44 insertions(+), 32 deletions(-) diff --git a/tests/test_client.py b/tests/test_client.py index 24933456bd..625b822352 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -701,14 +701,17 @@ def test_retrying_timeout_errors_doesnt_leak(self, respx_mock: MockRouter) -> No with pytest.raises(APITimeoutError): self.client.post( "/chat/completions", - body=dict( - messages=[ - { - "role": "user", - "content": "Say this is a test", - } - ], - model="gpt-3.5-turbo", + body=cast( + object, + dict( + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-3.5-turbo", + ), ), cast_to=httpx.Response, options={"headers": {RAW_RESPONSE_HEADER: "stream"}}, @@ -724,14 +727,17 @@ def test_retrying_status_errors_doesnt_leak(self, respx_mock: MockRouter) -> Non with pytest.raises(APIStatusError): self.client.post( "/chat/completions", - body=dict( - messages=[ - { - "role": "user", - "content": "Say this is a test", - } - ], - model="gpt-3.5-turbo", + body=cast( + object, + dict( + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-3.5-turbo", + ), ), cast_to=httpx.Response, options={"headers": {RAW_RESPONSE_HEADER: "stream"}}, @@ -1410,14 +1416,17 @@ async def test_retrying_timeout_errors_doesnt_leak(self, respx_mock: MockRouter) with pytest.raises(APITimeoutError): await self.client.post( "/chat/completions", - body=dict( - messages=[ - { - "role": "user", - "content": "Say this is a test", - } - ], - model="gpt-3.5-turbo", + body=cast( + object, + dict( + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-3.5-turbo", + ), ), cast_to=httpx.Response, options={"headers": {RAW_RESPONSE_HEADER: "stream"}}, @@ -1433,14 +1442,17 @@ async def test_retrying_status_errors_doesnt_leak(self, respx_mock: MockRouter) with pytest.raises(APIStatusError): await self.client.post( "/chat/completions", - body=dict( - messages=[ - { - "role": "user", - "content": "Say this is a test", - } - ], - model="gpt-3.5-turbo", + body=cast( + object, + dict( + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-3.5-turbo", + ), ), cast_to=httpx.Response, options={"headers": {RAW_RESPONSE_HEADER: "stream"}}, From 336cf03092376c0b54cc2cfbd78167c1aac01af7 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 30 Jan 2024 22:09:42 +0100 Subject: [PATCH 215/816] chore(internal): support pre-release versioning (#1113) --- release-please-config.json | 2 ++ 1 file changed, 2 insertions(+) diff --git a/release-please-config.json b/release-please-config.json index 5c66d801f5..745ef5fd54 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -5,6 +5,8 @@ "$schema": "https://raw.githubusercontent.com/stainless-api/release-please/main/schemas/config.json", "include-v-in-tag": true, "include-component-in-tag": false, + "versioning": "prerelease", + "prerelease": true, "bump-minor-pre-major": true, "bump-patch-for-minor-pre-major": false, "pull-request-header": "Automated Release PR", From 986f3128f6c851ce9729e579f176de953e315248 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 2 Feb 2024 04:44:03 +0000 Subject: [PATCH 216/816] chore(interal): make link to api.md relative (#1117) --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 22e7ac795f..0e06cd5631 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ It is generated from our [OpenAPI specification](https://github.com/openai/opena ## Documentation -The REST API documentation can be found [on platform.openai.com](https://platform.openai.com/docs). The full API of this library can be found in [api.md](https://www.github.com/openai/openai-python/blob/main/api.md). +The REST API documentation can be found [on platform.openai.com](https://platform.openai.com/docs). The full API of this library can be found in [api.md](api.md). ## Installation @@ -23,7 +23,7 @@ pip install openai ## Usage -The full API of this library can be found in [api.md](https://www.github.com/openai/openai-python/blob/main/api.md). +The full API of this library can be found in [api.md](api.md). ```python import os From 66bab657c69dfebddbb4372adcdc97788cb3ceb1 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Sat, 3 Feb 2024 05:05:10 +0000 Subject: [PATCH 217/816] release: 1.11.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 17 +++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 20 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index eb4e0dba72..caf1487126 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.10.0" + ".": "1.11.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a22e062dd..0ce1f737d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,22 @@ # Changelog +## 1.11.0 (2024-02-03) + +Full Changelog: [v1.10.0...v1.11.0](https://github.com/openai/openai-python/compare/v1.10.0...v1.11.0) + +### Features + +* **client:** support parsing custom response types ([#1111](https://github.com/openai/openai-python/issues/1111)) ([da00fc3](https://github.com/openai/openai-python/commit/da00fc3f8e0ff13c6c3ca970e4bb86846304bd06)) + + +### Chores + +* **interal:** make link to api.md relative ([#1117](https://github.com/openai/openai-python/issues/1117)) ([4a10879](https://github.com/openai/openai-python/commit/4a108797e46293357601ce933e21b557a5dc6954)) +* **internal:** cast type in mocked test ([#1112](https://github.com/openai/openai-python/issues/1112)) ([99b21e1](https://github.com/openai/openai-python/commit/99b21e1fc681eb10e01d479cc043ad3c89272b1c)) +* **internal:** enable ruff type checking misuse lint rule ([#1106](https://github.com/openai/openai-python/issues/1106)) ([fa63e60](https://github.com/openai/openai-python/commit/fa63e605c82ec78f4fc27469c434b421a08fb909)) +* **internal:** support multipart data with overlapping keys ([#1104](https://github.com/openai/openai-python/issues/1104)) ([455bc9f](https://github.com/openai/openai-python/commit/455bc9f1fd018a32cd604eb4b400e05aa8d71822)) +* **internal:** support pre-release versioning ([#1113](https://github.com/openai/openai-python/issues/1113)) ([dea5b08](https://github.com/openai/openai-python/commit/dea5b08c28d47b331fd44f6920cf9fe322b68e51)) + ## 1.10.0 (2024-01-25) Full Changelog: [v1.9.0...v1.10.0](https://github.com/openai/openai-python/compare/v1.9.0...v1.10.0) diff --git a/pyproject.toml b/pyproject.toml index c088e19264..2070ca82f2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.10.0" +version = "1.11.0" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index e9a863539d..fe1bfcc852 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.10.0" # x-release-please-version +__version__ = "1.11.0" # x-release-please-version From 2384e276969d5908eebff2ca12bdfcd69b3cfa93 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Sun, 4 Feb 2024 18:57:58 +0000 Subject: [PATCH 218/816] fix: prevent crash when platform.architecture() is not allowed (#1120) --- src/openai/_base_client.py | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index d7e5127dd8..73bd2411fd 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -1836,8 +1836,12 @@ def __str__(self) -> str: def get_platform() -> Platform: - system = platform.system().lower() - platform_name = platform.platform().lower() + try: + system = platform.system().lower() + platform_name = platform.platform().lower() + except Exception: + return "Unknown" + if "iphone" in platform_name or "ipad" in platform_name: # Tested using Python3IDE on an iPhone 11 and Pythonista on an iPad 7 # system is Darwin and platform_name is a string like: @@ -1880,8 +1884,8 @@ def platform_headers(version: str) -> Dict[str, str]: "X-Stainless-Package-Version": version, "X-Stainless-OS": str(get_platform()), "X-Stainless-Arch": str(get_architecture()), - "X-Stainless-Runtime": platform.python_implementation(), - "X-Stainless-Runtime-Version": platform.python_version(), + "X-Stainless-Runtime": get_python_runtime(), + "X-Stainless-Runtime-Version": get_python_version(), } @@ -1897,9 +1901,27 @@ def __str__(self) -> str: Arch = Union[OtherArch, Literal["x32", "x64", "arm", "arm64", "unknown"]] +def get_python_runtime() -> str: + try: + return platform.python_implementation() + except Exception: + return "unknown" + + +def get_python_version() -> str: + try: + return platform.python_version() + except Exception: + return "unknown" + + def get_architecture() -> Arch: - python_bitness, _ = platform.architecture() - machine = platform.machine().lower() + try: + python_bitness, _ = platform.architecture() + machine = platform.machine().lower() + except Exception: + return "unknown" + if machine in ("arm64", "aarch64"): return "arm64" From d231d1fa783967c1d3a1db3ba1b52647fff148ac Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Sun, 4 Feb 2024 18:58:26 +0000 Subject: [PATCH 219/816] release: 1.11.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index caf1487126..271a68cfd8 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.11.0" + ".": "1.11.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ce1f737d9..4ac4be39fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.11.1 (2024-02-04) + +Full Changelog: [v1.11.0...v1.11.1](https://github.com/openai/openai-python/compare/v1.11.0...v1.11.1) + +### Bug Fixes + +* prevent crash when platform.architecture() is not allowed ([#1120](https://github.com/openai/openai-python/issues/1120)) ([9490554](https://github.com/openai/openai-python/commit/949055488488e93597cbc6c2cdd81f14f203e53b)) + ## 1.11.0 (2024-02-03) Full Changelog: [v1.10.0...v1.11.0](https://github.com/openai/openai-python/compare/v1.10.0...v1.11.0) diff --git a/pyproject.toml b/pyproject.toml index 2070ca82f2..20371e0ef9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.11.0" +version = "1.11.1" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index fe1bfcc852..8af0cd2490 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.11.0" # x-release-please-version +__version__ = "1.11.1" # x-release-please-version From 489dadfb4ddf08007c6054acf05e782f6ef4f9bb Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 6 Feb 2024 01:09:45 +0000 Subject: [PATCH 220/816] feat(api): add `timestamp_granularities`, add `gpt-3.5-turbo-0125` model (#1125) --- src/openai/resources/audio/transcriptions.py | 14 ++++++++++++- src/openai/resources/chat/completions.py | 20 +++++++++++++------ .../audio/transcription_create_params.py | 15 ++++++++++++-- .../types/chat/completion_create_params.py | 3 ++- .../audio/test_transcriptions.py | 2 ++ 5 files changed, 44 insertions(+), 10 deletions(-) diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index 2c167be395..275098ce88 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Union, Mapping, cast +from typing import List, Union, Mapping, cast from typing_extensions import Literal import httpx @@ -39,6 +39,7 @@ def create( prompt: str | NotGiven = NOT_GIVEN, response_format: Literal["json", "text", "srt", "verbose_json", "vtt"] | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, + timestamp_granularities: List[Literal["word", "segment"]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -74,6 +75,10 @@ def create( [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit. + timestamp_granularities: The timestamp granularities to populate for this transcription. Any of these + options: `word`, or `segment`. Note: There is no additional latency for segment + timestamps, but generating word timestamps incurs additional latency. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -90,6 +95,7 @@ def create( "prompt": prompt, "response_format": response_format, "temperature": temperature, + "timestamp_granularities": timestamp_granularities, } ) files = extract_files(cast(Mapping[str, object], body), paths=[["file"]]) @@ -127,6 +133,7 @@ async def create( prompt: str | NotGiven = NOT_GIVEN, response_format: Literal["json", "text", "srt", "verbose_json", "vtt"] | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, + timestamp_granularities: List[Literal["word", "segment"]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -162,6 +169,10 @@ async def create( [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit. + timestamp_granularities: The timestamp granularities to populate for this transcription. Any of these + options: `word`, or `segment`. Note: There is no additional latency for segment + timestamps, but generating word timestamps incurs additional latency. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -178,6 +189,7 @@ async def create( "prompt": prompt, "response_format": response_format, "temperature": temperature, + "timestamp_granularities": timestamp_granularities, } ) files = extract_files(cast(Mapping[str, object], body), paths=[["file"]]) diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index 45521833ad..edc243e101 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -61,6 +61,7 @@ def create( "gpt-3.5-turbo-0301", "gpt-3.5-turbo-0613", "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", "gpt-3.5-turbo-16k-0613", ], ], @@ -155,7 +156,7 @@ def create( response_format: An object specifying the format that the model must output. Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -250,6 +251,7 @@ def create( "gpt-3.5-turbo-0301", "gpt-3.5-turbo-0613", "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", "gpt-3.5-turbo-16k-0613", ], ], @@ -351,7 +353,7 @@ def create( response_format: An object specifying the format that the model must output. Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -439,6 +441,7 @@ def create( "gpt-3.5-turbo-0301", "gpt-3.5-turbo-0613", "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", "gpt-3.5-turbo-16k-0613", ], ], @@ -540,7 +543,7 @@ def create( response_format: An object specifying the format that the model must output. Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -628,6 +631,7 @@ def create( "gpt-3.5-turbo-0301", "gpt-3.5-turbo-0613", "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", "gpt-3.5-turbo-16k-0613", ], ], @@ -724,6 +728,7 @@ async def create( "gpt-3.5-turbo-0301", "gpt-3.5-turbo-0613", "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", "gpt-3.5-turbo-16k-0613", ], ], @@ -818,7 +823,7 @@ async def create( response_format: An object specifying the format that the model must output. Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -913,6 +918,7 @@ async def create( "gpt-3.5-turbo-0301", "gpt-3.5-turbo-0613", "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", "gpt-3.5-turbo-16k-0613", ], ], @@ -1014,7 +1020,7 @@ async def create( response_format: An object specifying the format that the model must output. Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -1102,6 +1108,7 @@ async def create( "gpt-3.5-turbo-0301", "gpt-3.5-turbo-0613", "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", "gpt-3.5-turbo-16k-0613", ], ], @@ -1203,7 +1210,7 @@ async def create( response_format: An object specifying the format that the model must output. Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -1291,6 +1298,7 @@ async def create( "gpt-3.5-turbo-0301", "gpt-3.5-turbo-0613", "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", "gpt-3.5-turbo-16k-0613", ], ], diff --git a/src/openai/types/audio/transcription_create_params.py b/src/openai/types/audio/transcription_create_params.py index 7bd70d7b48..2d0a218f33 100644 --- a/src/openai/types/audio/transcription_create_params.py +++ b/src/openai/types/audio/transcription_create_params.py @@ -2,10 +2,11 @@ from __future__ import annotations -from typing import Union -from typing_extensions import Literal, Required, TypedDict +from typing import List, Union +from typing_extensions import Literal, Required, Annotated, TypedDict from ..._types import FileTypes +from ..._utils import PropertyInfo __all__ = ["TranscriptionCreateParams"] @@ -50,3 +51,13 @@ class TranscriptionCreateParams(TypedDict, total=False): [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit. """ + + timestamp_granularities: Annotated[ + List[Literal["word", "segment"]], PropertyInfo(alias="timestamp_granularities[]") + ] + """The timestamp granularities to populate for this transcription. + + Any of these options: `word`, or `segment`. Note: There is no additional latency + for segment timestamps, but generating word timestamps incurs additional + latency. + """ diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 3ea14d82b3..dbc49594fe 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -47,6 +47,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): "gpt-3.5-turbo-0301", "gpt-3.5-turbo-0613", "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", "gpt-3.5-turbo-16k-0613", ], ] @@ -137,7 +138,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. diff --git a/tests/api_resources/audio/test_transcriptions.py b/tests/api_resources/audio/test_transcriptions.py index d957871abc..80e364b484 100644 --- a/tests/api_resources/audio/test_transcriptions.py +++ b/tests/api_resources/audio/test_transcriptions.py @@ -34,6 +34,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: prompt="string", response_format="json", temperature=0, + timestamp_granularities=["word", "segment"], ) assert_matches_type(Transcription, transcription, path=["response"]) @@ -84,6 +85,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> prompt="string", response_format="json", temperature=0, + timestamp_granularities=["word", "segment"], ) assert_matches_type(Transcription, transcription, path=["response"]) From adb0b31abca69eaafa0b4b40ef457913d4597ad6 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 6 Feb 2024 09:50:54 +0000 Subject: [PATCH 221/816] chore(internal): support serialising iterable types (#1127) --- src/openai/_utils/__init__.py | 2 ++ src/openai/_utils/_transform.py | 9 ++++++++- src/openai/_utils/_typing.py | 9 ++++++++- src/openai/_utils/_utils.py | 4 ++++ tests/test_transform.py | 34 ++++++++++++++++++++++++++++++++- 5 files changed, 55 insertions(+), 3 deletions(-) diff --git a/src/openai/_utils/__init__.py b/src/openai/_utils/__init__.py index 0fb811a945..b5790a879f 100644 --- a/src/openai/_utils/__init__.py +++ b/src/openai/_utils/__init__.py @@ -9,6 +9,7 @@ is_mapping as is_mapping, is_tuple_t as is_tuple_t, parse_date as parse_date, + is_iterable as is_iterable, is_sequence as is_sequence, coerce_float as coerce_float, is_mapping_t as is_mapping_t, @@ -33,6 +34,7 @@ is_list_type as is_list_type, is_union_type as is_union_type, extract_type_arg as extract_type_arg, + is_iterable_type as is_iterable_type, is_required_type as is_required_type, is_annotated_type as is_annotated_type, strip_annotated_type as strip_annotated_type, diff --git a/src/openai/_utils/_transform.py b/src/openai/_utils/_transform.py index 3a1c14969b..2cb7726c73 100644 --- a/src/openai/_utils/_transform.py +++ b/src/openai/_utils/_transform.py @@ -9,11 +9,13 @@ from ._utils import ( is_list, is_mapping, + is_iterable, ) from ._typing import ( is_list_type, is_union_type, extract_type_arg, + is_iterable_type, is_required_type, is_annotated_type, strip_annotated_type, @@ -157,7 +159,12 @@ def _transform_recursive( if is_typeddict(stripped_type) and is_mapping(data): return _transform_typeddict(data, stripped_type) - if is_list_type(stripped_type) and is_list(data): + if ( + # List[T] + (is_list_type(stripped_type) and is_list(data)) + # Iterable[T] + or (is_iterable_type(stripped_type) and is_iterable(data) and not isinstance(data, str)) + ): inner_type = extract_type_arg(stripped_type, 0) return [_transform_recursive(d, annotation=annotation, inner_type=inner_type) for d in data] diff --git a/src/openai/_utils/_typing.py b/src/openai/_utils/_typing.py index c1d1ebb9a4..c036991f04 100644 --- a/src/openai/_utils/_typing.py +++ b/src/openai/_utils/_typing.py @@ -1,6 +1,7 @@ from __future__ import annotations -from typing import Any, TypeVar, cast +from typing import Any, TypeVar, Iterable, cast +from collections import abc as _c_abc from typing_extensions import Required, Annotated, get_args, get_origin from .._types import InheritsGeneric @@ -15,6 +16,12 @@ def is_list_type(typ: type) -> bool: return (get_origin(typ) or typ) == list +def is_iterable_type(typ: type) -> bool: + """If the given type is `typing.Iterable[T]`""" + origin = get_origin(typ) or typ + return origin == Iterable or origin == _c_abc.Iterable + + def is_union_type(typ: type) -> bool: return _is_union(get_origin(typ)) diff --git a/src/openai/_utils/_utils.py b/src/openai/_utils/_utils.py index 1c5c21a8ea..93c95517a9 100644 --- a/src/openai/_utils/_utils.py +++ b/src/openai/_utils/_utils.py @@ -164,6 +164,10 @@ def is_list(obj: object) -> TypeGuard[list[object]]: return isinstance(obj, list) +def is_iterable(obj: object) -> TypeGuard[Iterable[object]]: + return isinstance(obj, Iterable) + + def deepcopy_minimal(item: _T) -> _T: """Minimal reimplementation of copy.deepcopy() that will only copy certain object types: diff --git a/tests/test_transform.py b/tests/test_transform.py index c4dffb3bb0..6ed67d49a7 100644 --- a/tests/test_transform.py +++ b/tests/test_transform.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import Any, List, Union, Optional +from typing import Any, List, Union, Iterable, Optional, cast from datetime import date, datetime from typing_extensions import Required, Annotated, TypedDict @@ -265,3 +265,35 @@ def test_pydantic_default_field() -> None: assert model.with_none_default == "bar" assert model.with_str_default == "baz" assert transform(model, Any) == {"with_none_default": "bar", "with_str_default": "baz"} + + +class TypedDictIterableUnion(TypedDict): + foo: Annotated[Union[Bar8, Iterable[Baz8]], PropertyInfo(alias="FOO")] + + +class Bar8(TypedDict): + foo_bar: Annotated[str, PropertyInfo(alias="fooBar")] + + +class Baz8(TypedDict): + foo_baz: Annotated[str, PropertyInfo(alias="fooBaz")] + + +def test_iterable_of_dictionaries() -> None: + assert transform({"foo": [{"foo_baz": "bar"}]}, TypedDictIterableUnion) == {"FOO": [{"fooBaz": "bar"}]} + assert cast(Any, transform({"foo": ({"foo_baz": "bar"},)}, TypedDictIterableUnion)) == {"FOO": [{"fooBaz": "bar"}]} + + def my_iter() -> Iterable[Baz8]: + yield {"foo_baz": "hello"} + yield {"foo_baz": "world"} + + assert transform({"foo": my_iter()}, TypedDictIterableUnion) == {"FOO": [{"fooBaz": "hello"}, {"fooBaz": "world"}]} + + +class TypedDictIterableUnionStr(TypedDict): + foo: Annotated[Union[str, Iterable[Baz8]], PropertyInfo(alias="FOO")] + + +def test_iterable_union_str() -> None: + assert transform({"foo": "bar"}, TypedDictIterableUnionStr) == {"FOO": "bar"} + assert cast(Any, transform(iter([{"foo_baz": "bar"}]), Union[str, Iterable[Baz8]])) == [{"fooBaz": "bar"}] From 0f0934699ddb22de152a71c2b1d2d2382006a934 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 6 Feb 2024 10:29:51 +0000 Subject: [PATCH 222/816] chore(internal): add lint command (#1128) --- pyproject.toml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index 20371e0ef9..af7950f58a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -75,6 +75,10 @@ format = { chain = [ "format:ruff" = "ruff format" "format:isort" = "isort ." +"lint" = { chain = [ + "check:ruff", + "typecheck", +]} "check:ruff" = "ruff ." "fix:ruff" = "ruff --fix ." From 2dc397628a7e13734086a5fe703f0e7d0c891e90 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 6 Feb 2024 15:21:59 +0000 Subject: [PATCH 223/816] fix(types): loosen most List params types to Iterable (#1129) --- .../resources/beta/assistants/assistants.py | 10 ++-- .../resources/beta/threads/runs/runs.py | 10 ++-- src/openai/resources/beta/threads/threads.py | 10 ++-- src/openai/resources/chat/completions.py | 50 +++++++++---------- src/openai/resources/completions.py | 18 +++---- src/openai/resources/embeddings.py | 6 +-- .../types/beta/assistant_create_params.py | 4 +- .../types/beta/assistant_update_params.py | 4 +- .../beta/thread_create_and_run_params.py | 6 +-- src/openai/types/beta/thread_create_params.py | 4 +- .../types/beta/threads/run_create_params.py | 4 +- .../threads/run_submit_tool_outputs_params.py | 4 +- ...chat_completion_assistant_message_param.py | 4 +- .../chat_completion_user_message_param.py | 4 +- .../types/chat/completion_create_params.py | 8 +-- src/openai/types/completion_create_params.py | 4 +- src/openai/types/embedding_create_params.py | 4 +- 17 files changed, 77 insertions(+), 77 deletions(-) diff --git a/src/openai/resources/beta/assistants/assistants.py b/src/openai/resources/beta/assistants/assistants.py index 3a2418ad90..e926c31642 100644 --- a/src/openai/resources/beta/assistants/assistants.py +++ b/src/openai/resources/beta/assistants/assistants.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import List, Optional +from typing import List, Iterable, Optional from typing_extensions import Literal import httpx @@ -59,7 +59,7 @@ def create( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, - tools: List[assistant_create_params.Tool] | NotGiven = NOT_GIVEN, + tools: Iterable[assistant_create_params.Tool] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -169,7 +169,7 @@ def update( metadata: Optional[object] | NotGiven = NOT_GIVEN, model: str | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, - tools: List[assistant_update_params.Tool] | NotGiven = NOT_GIVEN, + tools: Iterable[assistant_update_params.Tool] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -362,7 +362,7 @@ async def create( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, - tools: List[assistant_create_params.Tool] | NotGiven = NOT_GIVEN, + tools: Iterable[assistant_create_params.Tool] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -472,7 +472,7 @@ async def update( metadata: Optional[object] | NotGiven = NOT_GIVEN, model: str | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, - tools: List[assistant_update_params.Tool] | NotGiven = NOT_GIVEN, + tools: Iterable[assistant_update_params.Tool] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 0ed48b4792..9b18336010 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import List, Optional +from typing import Iterable, Optional from typing_extensions import Literal import httpx @@ -59,7 +59,7 @@ def create( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, - tools: Optional[List[run_create_params.Tool]] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[run_create_params.Tool]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -316,7 +316,7 @@ def submit_tool_outputs( run_id: str, *, thread_id: str, - tool_outputs: List[run_submit_tool_outputs_params.ToolOutput], + tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -380,7 +380,7 @@ async def create( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, - tools: Optional[List[run_create_params.Tool]] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[run_create_params.Tool]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -637,7 +637,7 @@ async def submit_tool_outputs( run_id: str, *, thread_id: str, - tool_outputs: List[run_submit_tool_outputs_params.ToolOutput], + tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 0372ae2f66..dd079ac533 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import List, Optional +from typing import Iterable, Optional import httpx @@ -65,7 +65,7 @@ def with_streaming_response(self) -> ThreadsWithStreamingResponse: def create( self, *, - messages: List[thread_create_params.Message] | NotGiven = NOT_GIVEN, + messages: Iterable[thread_create_params.Message] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -227,7 +227,7 @@ def create_and_run( metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, - tools: Optional[List[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -310,7 +310,7 @@ def with_streaming_response(self) -> AsyncThreadsWithStreamingResponse: async def create( self, *, - messages: List[thread_create_params.Message] | NotGiven = NOT_GIVEN, + messages: Iterable[thread_create_params.Message] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -472,7 +472,7 @@ async def create_and_run( metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, - tools: Optional[List[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index edc243e101..0011d75e6e 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Dict, List, Union, Optional, overload +from typing import Dict, List, Union, Iterable, Optional, overload from typing_extensions import Literal import httpx @@ -42,7 +42,7 @@ def with_streaming_response(self) -> CompletionsWithStreamingResponse: def create( self, *, - messages: List[ChatCompletionMessageParam], + messages: Iterable[ChatCompletionMessageParam], model: Union[ str, Literal[ @@ -67,7 +67,7 @@ def create( ], frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, - functions: List[completion_create_params.Function] | NotGiven = NOT_GIVEN, + functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -79,7 +79,7 @@ def create( stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, - tools: List[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, + tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, @@ -232,7 +232,7 @@ def create( def create( self, *, - messages: List[ChatCompletionMessageParam], + messages: Iterable[ChatCompletionMessageParam], model: Union[ str, Literal[ @@ -258,7 +258,7 @@ def create( stream: Literal[True], frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, - functions: List[completion_create_params.Function] | NotGiven = NOT_GIVEN, + functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -269,7 +269,7 @@ def create( stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, - tools: List[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, + tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, @@ -422,7 +422,7 @@ def create( def create( self, *, - messages: List[ChatCompletionMessageParam], + messages: Iterable[ChatCompletionMessageParam], model: Union[ str, Literal[ @@ -448,7 +448,7 @@ def create( stream: bool, frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, - functions: List[completion_create_params.Function] | NotGiven = NOT_GIVEN, + functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -459,7 +459,7 @@ def create( stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, - tools: List[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, + tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, @@ -612,7 +612,7 @@ def create( def create( self, *, - messages: List[ChatCompletionMessageParam], + messages: Iterable[ChatCompletionMessageParam], model: Union[ str, Literal[ @@ -637,7 +637,7 @@ def create( ], frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, - functions: List[completion_create_params.Function] | NotGiven = NOT_GIVEN, + functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -649,7 +649,7 @@ def create( stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, - tools: List[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, + tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, @@ -709,7 +709,7 @@ def with_streaming_response(self) -> AsyncCompletionsWithStreamingResponse: async def create( self, *, - messages: List[ChatCompletionMessageParam], + messages: Iterable[ChatCompletionMessageParam], model: Union[ str, Literal[ @@ -734,7 +734,7 @@ async def create( ], frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, - functions: List[completion_create_params.Function] | NotGiven = NOT_GIVEN, + functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -746,7 +746,7 @@ async def create( stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, - tools: List[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, + tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, @@ -899,7 +899,7 @@ async def create( async def create( self, *, - messages: List[ChatCompletionMessageParam], + messages: Iterable[ChatCompletionMessageParam], model: Union[ str, Literal[ @@ -925,7 +925,7 @@ async def create( stream: Literal[True], frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, - functions: List[completion_create_params.Function] | NotGiven = NOT_GIVEN, + functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -936,7 +936,7 @@ async def create( stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, - tools: List[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, + tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, @@ -1089,7 +1089,7 @@ async def create( async def create( self, *, - messages: List[ChatCompletionMessageParam], + messages: Iterable[ChatCompletionMessageParam], model: Union[ str, Literal[ @@ -1115,7 +1115,7 @@ async def create( stream: bool, frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, - functions: List[completion_create_params.Function] | NotGiven = NOT_GIVEN, + functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -1126,7 +1126,7 @@ async def create( stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, - tools: List[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, + tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, @@ -1279,7 +1279,7 @@ async def create( async def create( self, *, - messages: List[ChatCompletionMessageParam], + messages: Iterable[ChatCompletionMessageParam], model: Union[ str, Literal[ @@ -1304,7 +1304,7 @@ async def create( ], frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, - functions: List[completion_create_params.Function] | NotGiven = NOT_GIVEN, + functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -1316,7 +1316,7 @@ async def create( stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, - tools: List[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, + tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index 3d2e10230a..af2d6e2e51 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Dict, List, Union, Optional, overload +from typing import Dict, List, Union, Iterable, Optional, overload from typing_extensions import Literal import httpx @@ -36,7 +36,7 @@ def create( self, *, model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]], - prompt: Union[str, List[str], List[int], List[List[int]], None], + prompt: Union[str, List[str], Iterable[int], Iterable[Iterable[int]], None], best_of: Optional[int] | NotGiven = NOT_GIVEN, echo: Optional[bool] | NotGiven = NOT_GIVEN, frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -184,7 +184,7 @@ def create( self, *, model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]], - prompt: Union[str, List[str], List[int], List[List[int]], None], + prompt: Union[str, List[str], Iterable[int], Iterable[Iterable[int]], None], stream: Literal[True], best_of: Optional[int] | NotGiven = NOT_GIVEN, echo: Optional[bool] | NotGiven = NOT_GIVEN, @@ -332,7 +332,7 @@ def create( self, *, model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]], - prompt: Union[str, List[str], List[int], List[List[int]], None], + prompt: Union[str, List[str], Iterable[int], Iterable[Iterable[int]], None], stream: bool, best_of: Optional[int] | NotGiven = NOT_GIVEN, echo: Optional[bool] | NotGiven = NOT_GIVEN, @@ -480,7 +480,7 @@ def create( self, *, model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]], - prompt: Union[str, List[str], List[int], List[List[int]], None], + prompt: Union[str, List[str], Iterable[int], Iterable[Iterable[int]], None], best_of: Optional[int] | NotGiven = NOT_GIVEN, echo: Optional[bool] | NotGiven = NOT_GIVEN, frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -550,7 +550,7 @@ async def create( self, *, model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]], - prompt: Union[str, List[str], List[int], List[List[int]], None], + prompt: Union[str, List[str], Iterable[int], Iterable[Iterable[int]], None], best_of: Optional[int] | NotGiven = NOT_GIVEN, echo: Optional[bool] | NotGiven = NOT_GIVEN, frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -698,7 +698,7 @@ async def create( self, *, model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]], - prompt: Union[str, List[str], List[int], List[List[int]], None], + prompt: Union[str, List[str], Iterable[int], Iterable[Iterable[int]], None], stream: Literal[True], best_of: Optional[int] | NotGiven = NOT_GIVEN, echo: Optional[bool] | NotGiven = NOT_GIVEN, @@ -846,7 +846,7 @@ async def create( self, *, model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]], - prompt: Union[str, List[str], List[int], List[List[int]], None], + prompt: Union[str, List[str], Iterable[int], Iterable[Iterable[int]], None], stream: bool, best_of: Optional[int] | NotGiven = NOT_GIVEN, echo: Optional[bool] | NotGiven = NOT_GIVEN, @@ -994,7 +994,7 @@ async def create( self, *, model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]], - prompt: Union[str, List[str], List[int], List[List[int]], None], + prompt: Union[str, List[str], Iterable[int], Iterable[Iterable[int]], None], best_of: Optional[int] | NotGiven = NOT_GIVEN, echo: Optional[bool] | NotGiven = NOT_GIVEN, frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, diff --git a/src/openai/resources/embeddings.py b/src/openai/resources/embeddings.py index 857bfc7702..cfef025bc2 100644 --- a/src/openai/resources/embeddings.py +++ b/src/openai/resources/embeddings.py @@ -3,7 +3,7 @@ from __future__ import annotations import base64 -from typing import List, Union, cast +from typing import List, Union, Iterable, cast from typing_extensions import Literal import httpx @@ -35,7 +35,7 @@ def with_streaming_response(self) -> EmbeddingsWithStreamingResponse: def create( self, *, - input: Union[str, List[str], List[int], List[List[int]]], + input: Union[str, List[str], Iterable[int], Iterable[Iterable[int]]], model: Union[str, Literal["text-embedding-ada-002", "text-embedding-3-small", "text-embedding-3-large"]], dimensions: int | NotGiven = NOT_GIVEN, encoding_format: Literal["float", "base64"] | NotGiven = NOT_GIVEN, @@ -136,7 +136,7 @@ def with_streaming_response(self) -> AsyncEmbeddingsWithStreamingResponse: async def create( self, *, - input: Union[str, List[str], List[int], List[List[int]]], + input: Union[str, List[str], Iterable[int], Iterable[Iterable[int]]], model: Union[str, Literal["text-embedding-ada-002", "text-embedding-3-small", "text-embedding-3-large"]], dimensions: int | NotGiven = NOT_GIVEN, encoding_format: Literal["float", "base64"] | NotGiven = NOT_GIVEN, diff --git a/src/openai/types/beta/assistant_create_params.py b/src/openai/types/beta/assistant_create_params.py index 539897a7ba..c49d6f6950 100644 --- a/src/openai/types/beta/assistant_create_params.py +++ b/src/openai/types/beta/assistant_create_params.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import List, Union, Optional +from typing import List, Union, Iterable, Optional from typing_extensions import Literal, Required, TypedDict from ...types import shared_params @@ -54,7 +54,7 @@ class AssistantCreateParams(TypedDict, total=False): name: Optional[str] """The name of the assistant. The maximum length is 256 characters.""" - tools: List[Tool] + tools: Iterable[Tool] """A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types diff --git a/src/openai/types/beta/assistant_update_params.py b/src/openai/types/beta/assistant_update_params.py index dfb5d4c553..c5ccde62c5 100644 --- a/src/openai/types/beta/assistant_update_params.py +++ b/src/openai/types/beta/assistant_update_params.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import List, Union, Optional +from typing import List, Union, Iterable, Optional from typing_extensions import Literal, Required, TypedDict from ...types import shared_params @@ -56,7 +56,7 @@ class AssistantUpdateParams(TypedDict, total=False): name: Optional[str] """The name of the assistant. The maximum length is 256 characters.""" - tools: List[Tool] + tools: Iterable[Tool] """A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index 9f58dcd875..cc1051b3d6 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import List, Union, Optional +from typing import List, Union, Iterable, Optional from typing_extensions import Literal, Required, TypedDict from ...types import shared_params @@ -51,7 +51,7 @@ class ThreadCreateAndRunParams(TypedDict, total=False): thread: Thread """If no thread is provided, an empty thread will be created.""" - tools: Optional[List[Tool]] + tools: Optional[Iterable[Tool]] """Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. @@ -86,7 +86,7 @@ class ThreadMessage(TypedDict, total=False): class Thread(TypedDict, total=False): - messages: List[ThreadMessage] + messages: Iterable[ThreadMessage] """ A list of [messages](https://platform.openai.com/docs/api-reference/messages) to start the thread with. diff --git a/src/openai/types/beta/thread_create_params.py b/src/openai/types/beta/thread_create_params.py index d2ec78bbc3..e78276e839 100644 --- a/src/openai/types/beta/thread_create_params.py +++ b/src/openai/types/beta/thread_create_params.py @@ -2,14 +2,14 @@ from __future__ import annotations -from typing import List, Optional +from typing import List, Iterable, Optional from typing_extensions import Literal, Required, TypedDict __all__ = ["ThreadCreateParams", "Message"] class ThreadCreateParams(TypedDict, total=False): - messages: List[Message] + messages: Iterable[Message] """ A list of [messages](https://platform.openai.com/docs/api-reference/messages) to start the thread with. diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index a4f41a9338..b92649aa06 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import List, Union, Optional +from typing import Union, Iterable, Optional from typing_extensions import Literal, Required, TypedDict from ....types import shared_params @@ -54,7 +54,7 @@ class RunCreateParams(TypedDict, total=False): assistant will be used. """ - tools: Optional[List[Tool]] + tools: Optional[Iterable[Tool]] """Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. diff --git a/src/openai/types/beta/threads/run_submit_tool_outputs_params.py b/src/openai/types/beta/threads/run_submit_tool_outputs_params.py index a960f0f06f..3b303a33fc 100644 --- a/src/openai/types/beta/threads/run_submit_tool_outputs_params.py +++ b/src/openai/types/beta/threads/run_submit_tool_outputs_params.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import List +from typing import Iterable from typing_extensions import Required, TypedDict __all__ = ["RunSubmitToolOutputsParams", "ToolOutput"] @@ -11,7 +11,7 @@ class RunSubmitToolOutputsParams(TypedDict, total=False): thread_id: Required[str] - tool_outputs: Required[List[ToolOutput]] + tool_outputs: Required[Iterable[ToolOutput]] """A list of tools for which the outputs are being submitted.""" diff --git a/src/openai/types/chat/chat_completion_assistant_message_param.py b/src/openai/types/chat/chat_completion_assistant_message_param.py index 72a5bff83b..7377139bf5 100644 --- a/src/openai/types/chat/chat_completion_assistant_message_param.py +++ b/src/openai/types/chat/chat_completion_assistant_message_param.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import List, Optional +from typing import Iterable, Optional from typing_extensions import Literal, Required, TypedDict from .chat_completion_message_tool_call_param import ChatCompletionMessageToolCallParam @@ -47,5 +47,5 @@ class ChatCompletionAssistantMessageParam(TypedDict, total=False): role. """ - tool_calls: List[ChatCompletionMessageToolCallParam] + tool_calls: Iterable[ChatCompletionMessageToolCallParam] """The tool calls generated by the model, such as function calls.""" diff --git a/src/openai/types/chat/chat_completion_user_message_param.py b/src/openai/types/chat/chat_completion_user_message_param.py index 07be67c405..cb8ca19bf0 100644 --- a/src/openai/types/chat/chat_completion_user_message_param.py +++ b/src/openai/types/chat/chat_completion_user_message_param.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import List, Union +from typing import Union, Iterable from typing_extensions import Literal, Required, TypedDict from .chat_completion_content_part_param import ChatCompletionContentPartParam @@ -11,7 +11,7 @@ class ChatCompletionUserMessageParam(TypedDict, total=False): - content: Required[Union[str, List[ChatCompletionContentPartParam]]] + content: Required[Union[str, Iterable[ChatCompletionContentPartParam]]] """The contents of the user message.""" role: Required[Literal["user"]] diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index dbc49594fe..e02a81bc51 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Dict, List, Union, Optional +from typing import Dict, List, Union, Iterable, Optional from typing_extensions import Literal, Required, TypedDict from ...types import shared_params @@ -22,7 +22,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): - messages: Required[List[ChatCompletionMessageParam]] + messages: Required[Iterable[ChatCompletionMessageParam]] """A list of messages comprising the conversation so far. [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models). @@ -81,7 +81,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): functions are present. """ - functions: List[Function] + functions: Iterable[Function] """Deprecated in favor of `tools`. A list of functions the model may generate JSON inputs for. @@ -186,7 +186,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): functions are present. """ - tools: List[ChatCompletionToolParam] + tools: Iterable[ChatCompletionToolParam] """A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of diff --git a/src/openai/types/completion_create_params.py b/src/openai/types/completion_create_params.py index e14c2860df..afbc9c549f 100644 --- a/src/openai/types/completion_create_params.py +++ b/src/openai/types/completion_create_params.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Dict, List, Union, Optional +from typing import Dict, List, Union, Iterable, Optional from typing_extensions import Literal, Required, TypedDict __all__ = ["CompletionCreateParamsBase", "CompletionCreateParamsNonStreaming", "CompletionCreateParamsStreaming"] @@ -19,7 +19,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): descriptions of them. """ - prompt: Required[Union[str, List[str], List[int], List[List[int]], None]] + prompt: Required[Union[str, List[str], Iterable[int], Iterable[Iterable[int]], None]] """ The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays. diff --git a/src/openai/types/embedding_create_params.py b/src/openai/types/embedding_create_params.py index 66ac60511c..a549dc94c4 100644 --- a/src/openai/types/embedding_create_params.py +++ b/src/openai/types/embedding_create_params.py @@ -2,14 +2,14 @@ from __future__ import annotations -from typing import List, Union +from typing import List, Union, Iterable from typing_extensions import Literal, Required, TypedDict __all__ = ["EmbeddingCreateParams"] class EmbeddingCreateParams(TypedDict, total=False): - input: Required[Union[str, List[str], List[int], List[List[int]]]] + input: Required[Union[str, List[str], Iterable[int], Iterable[Iterable[int]]]] """Input text to embed, encoded as a string or array of tokens. To embed multiple inputs in a single request, pass an array of strings or array From a061daf64616dba32d229f491fff009e20232645 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 7 Feb 2024 11:13:21 +0000 Subject: [PATCH 224/816] feat(cli/images): add support for `--model` arg (#1132) https://github.com/openai/openai-python/issues/1130 --- src/openai/cli/_api/image.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/openai/cli/_api/image.py b/src/openai/cli/_api/image.py index e6149eeac4..3e2a0a90f1 100644 --- a/src/openai/cli/_api/image.py +++ b/src/openai/cli/_api/image.py @@ -14,6 +14,7 @@ def register(subparser: _SubParsersAction[ArgumentParser]) -> None: sub = subparser.add_parser("images.generate") + sub.add_argument("-m", "--model", type=str) sub.add_argument("-p", "--prompt", type=str, required=True) sub.add_argument("-n", "--num-images", type=int, default=1) sub.add_argument("-s", "--size", type=str, default="1024x1024", help="Size of the output image") @@ -21,6 +22,7 @@ def register(subparser: _SubParsersAction[ArgumentParser]) -> None: sub.set_defaults(func=CLIImage.create, args_model=CLIImageCreateArgs) sub = subparser.add_parser("images.edit") + sub.add_argument("-m", "--model", type=str) sub.add_argument("-p", "--prompt", type=str, required=True) sub.add_argument("-n", "--num-images", type=int, default=1) sub.add_argument( @@ -42,6 +44,7 @@ def register(subparser: _SubParsersAction[ArgumentParser]) -> None: sub.set_defaults(func=CLIImage.edit, args_model=CLIImageEditArgs) sub = subparser.add_parser("images.create_variation") + sub.add_argument("-m", "--model", type=str) sub.add_argument("-n", "--num-images", type=int, default=1) sub.add_argument( "-I", @@ -60,6 +63,7 @@ class CLIImageCreateArgs(BaseModel): num_images: int size: str response_format: str + model: NotGivenOr[str] = NOT_GIVEN class CLIImageCreateVariationArgs(BaseModel): @@ -67,6 +71,7 @@ class CLIImageCreateVariationArgs(BaseModel): num_images: int size: str response_format: str + model: NotGivenOr[str] = NOT_GIVEN class CLIImageEditArgs(BaseModel): @@ -76,12 +81,14 @@ class CLIImageEditArgs(BaseModel): response_format: str prompt: str mask: NotGivenOr[str] = NOT_GIVEN + model: NotGivenOr[str] = NOT_GIVEN class CLIImage: @staticmethod def create(args: CLIImageCreateArgs) -> None: image = get_client().images.generate( + model=args.model, prompt=args.prompt, n=args.num_images, # casts required because the API is typed for enums @@ -97,6 +104,7 @@ def create_variation(args: CLIImageCreateVariationArgs) -> None: buffer_reader = BufferReader(file_reader.read(), desc="Upload progress") image = get_client().images.create_variation( + model=args.model, image=("image", buffer_reader), n=args.num_images, # casts required because the API is typed for enums @@ -118,6 +126,7 @@ def edit(args: CLIImageEditArgs) -> None: mask = BufferReader(file_reader.read(), desc="Mask progress") image = get_client().images.edit( + model=args.model, prompt=args.prompt, image=("image", buffer_reader), n=args.num_images, From 93f3d3c3e4cdada40d9199290a907f107c2efba3 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 8 Feb 2024 19:50:04 +0000 Subject: [PATCH 225/816] docs: add CONTRIBUTING.md (#1138) --- CONTRIBUTING.md | 125 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 CONTRIBUTING.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000000..914ab67053 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,125 @@ +## Setting up the environment + +### With Rye + +We use [Rye](https://rye-up.com/) to manage dependencies so we highly recommend [installing it](https://rye-up.com/guide/installation/) as it will automatically provision a Python environment with the expected Python version. + +After installing Rye, you'll just have to run this command: + +```sh +$ rye sync --all-features +``` + +You can then run scripts using `rye run python script.py` or by activating the virtual environment: + +```sh +$ rye shell +# or manually activate - https://docs.python.org/3/library/venv.html#how-venvs-work +$ source .venv/bin/activate + +# now you can omit the `rye run` prefix +$ python script.py +``` + +### Without Rye + +Alternatively if you don't want to install `Rye`, you can stick with the standard `pip` setup by ensuring you have the Python version specified in `.python-version`, create a virtual environment however you desire and then install dependencies using this command: + +```sh +$ pip install -r requirements-dev.lock +``` + +## Modifying/Adding code + +Most of the SDK is generated code, and any modified code will be overridden on the next generation. The +`src/openai/lib/` and `examples/` directories are exceptions and will never be overridden. + +## Adding and running examples + +All files in the `examples/` directory are not modified by the Stainless generator and can be freely edited or +added to. + +```bash +# add an example to examples/.py + +#!/usr/bin/env -S rye run python +… +``` + +``` +chmod +x examples/.py +# run the example against your api +./examples/.py +``` + +## Using the repository from source + +If you’d like to use the repository from source, you can either install from git or link to a cloned repository: + +To install via git: + +```bash +pip install git+ssh://git@github.com:openai/openai-python.git +``` + +Alternatively, you can build from source and install the wheel file: + +Building this package will create two files in the `dist/` directory, a `.tar.gz` containing the source files and a `.whl` that can be used to install the package efficiently. + +To create a distributable version of the library, all you have to do is run this command: + +```bash +rye build +# or +python -m build +``` + +Then to install: + +```sh +pip install ./path-to-wheel-file.whl +``` + +## Running tests + +Most tests will require you to [setup a mock server](https://github.com/stoplightio/prism) against the OpenAPI spec to run the tests. + +```bash +# you will need npm installed +npx prism path/to/your/openapi.yml +``` + +```bash +rye run pytest +``` + +## Linting and formatting + +This repository uses [ruff](https://github.com/astral-sh/ruff) and +[black](https://github.com/psf/black) to format the code in the repository. + +To lint: + +```bash +rye run lint +``` + +To format and fix all ruff issues automatically: + +```bash +rye run format +``` + +## Publishing and releases + +Changes made to this repository via the automated release PR pipeline should publish to PyPI automatically. If +the changes aren't made through the automated pipeline, you may want to make releases manually. + +### Publish with a GitHub workflow + +You can release to package managers by using [the `Publish PyPI` GitHub action](https://www.github.com/openai/openai-python/actions/workflows/publish-pypi.yml). This will require a setup organization or repository secret to be set up. + +### Publish manually + +If you need to manually release a package, you can run the `bin/publish-pypi` script with an `PYPI_TOKEN` set on +the environment. From d6f9334ec83711a5a6a244150782590a87054994 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 8 Feb 2024 18:38:05 -0500 Subject: [PATCH 226/816] fix: remove double brackets from timestamp_granularities param (#1140) --- src/openai/types/audio/transcription_create_params.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/openai/types/audio/transcription_create_params.py b/src/openai/types/audio/transcription_create_params.py index 2d0a218f33..5a90822144 100644 --- a/src/openai/types/audio/transcription_create_params.py +++ b/src/openai/types/audio/transcription_create_params.py @@ -3,10 +3,9 @@ from __future__ import annotations from typing import List, Union -from typing_extensions import Literal, Required, Annotated, TypedDict +from typing_extensions import Literal, Required, TypedDict from ..._types import FileTypes -from ..._utils import PropertyInfo __all__ = ["TranscriptionCreateParams"] @@ -52,9 +51,7 @@ class TranscriptionCreateParams(TypedDict, total=False): automatically increase the temperature until certain thresholds are hit. """ - timestamp_granularities: Annotated[ - List[Literal["word", "segment"]], PropertyInfo(alias="timestamp_granularities[]") - ] + timestamp_granularities: List[Literal["word", "segment"]] """The timestamp granularities to populate for this transcription. Any of these options: `word`, or `segment`. Note: There is no additional latency From 7f9e85017a0959e3ba07834880d92c748f8f67ab Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 8 Feb 2024 18:47:36 -0500 Subject: [PATCH 227/816] release: 1.12.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 26 ++++++++++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 29 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 271a68cfd8..de0960aba8 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.11.1" + ".": "1.12.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ac4be39fb..5ef0b80e87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,31 @@ # Changelog +## 1.12.0 (2024-02-08) + +Full Changelog: [v1.11.1...v1.12.0](https://github.com/openai/openai-python/compare/v1.11.1...v1.12.0) + +### Features + +* **api:** add `timestamp_granularities`, add `gpt-3.5-turbo-0125` model ([#1125](https://github.com/openai/openai-python/issues/1125)) ([1ecf8f6](https://github.com/openai/openai-python/commit/1ecf8f6b12323ed09fb6a2815c85b9533ee52a50)) +* **cli/images:** add support for `--model` arg ([#1132](https://github.com/openai/openai-python/issues/1132)) ([0d53866](https://github.com/openai/openai-python/commit/0d5386615cda7cd50d5db90de2119b84dba29519)) + + +### Bug Fixes + +* remove double brackets from timestamp_granularities param ([#1140](https://github.com/openai/openai-python/issues/1140)) ([3db0222](https://github.com/openai/openai-python/commit/3db022216a81fa86470b53ec1246669bc7b17897)) +* **types:** loosen most List params types to Iterable ([#1129](https://github.com/openai/openai-python/issues/1129)) ([bdb31a3](https://github.com/openai/openai-python/commit/bdb31a3b1db6ede4e02b3c951c4fd23f70260038)) + + +### Chores + +* **internal:** add lint command ([#1128](https://github.com/openai/openai-python/issues/1128)) ([4c021c0](https://github.com/openai/openai-python/commit/4c021c0ab0151c2ec092d860c9b60e22e658cd03)) +* **internal:** support serialising iterable types ([#1127](https://github.com/openai/openai-python/issues/1127)) ([98d4e59](https://github.com/openai/openai-python/commit/98d4e59afcf2d65d4e660d91eb9462240ef5cd63)) + + +### Documentation + +* add CONTRIBUTING.md ([#1138](https://github.com/openai/openai-python/issues/1138)) ([79c8f0e](https://github.com/openai/openai-python/commit/79c8f0e8bf5470e2e31e781e8d279331e89ddfbe)) + ## 1.11.1 (2024-02-04) Full Changelog: [v1.11.0...v1.11.1](https://github.com/openai/openai-python/compare/v1.11.0...v1.11.1) diff --git a/pyproject.toml b/pyproject.toml index af7950f58a..163297ee2b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.11.1" +version = "1.12.0" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 8af0cd2490..6db2292c7b 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.11.1" # x-release-please-version +__version__ = "1.12.0" # x-release-please-version From fc4dafceb7efde578e40c460a488e06669f8b07f Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 12 Feb 2024 09:01:35 -0500 Subject: [PATCH 228/816] feat(api): updates (#1146) --- src/openai/resources/chat/completions.py | 28 +++++++++++++++++++ .../types/chat/completion_create_params.py | 6 ++++ tests/api_resources/chat/test_completions.py | 4 +++ 3 files changed, 38 insertions(+) diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index 0011d75e6e..caf712c604 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -68,6 +68,7 @@ def create( frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, + instance_id: Optional[str] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -122,6 +123,9 @@ def create( A list of functions the model may generate JSON inputs for. + instance_id: An unique identifier to a custom instance to execute the request. The requesting + organization is required to have access to the instance. + logit_bias: Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON object that maps tokens (specified by their token ID in the @@ -259,6 +263,7 @@ def create( frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, + instance_id: Optional[str] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -319,6 +324,9 @@ def create( A list of functions the model may generate JSON inputs for. + instance_id: An unique identifier to a custom instance to execute the request. The requesting + organization is required to have access to the instance. + logit_bias: Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON object that maps tokens (specified by their token ID in the @@ -449,6 +457,7 @@ def create( frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, + instance_id: Optional[str] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -509,6 +518,9 @@ def create( A list of functions the model may generate JSON inputs for. + instance_id: An unique identifier to a custom instance to execute the request. The requesting + organization is required to have access to the instance. + logit_bias: Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON object that maps tokens (specified by their token ID in the @@ -638,6 +650,7 @@ def create( frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, + instance_id: Optional[str] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -669,6 +682,7 @@ def create( "frequency_penalty": frequency_penalty, "function_call": function_call, "functions": functions, + "instance_id": instance_id, "logit_bias": logit_bias, "logprobs": logprobs, "max_tokens": max_tokens, @@ -735,6 +749,7 @@ async def create( frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, + instance_id: Optional[str] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -789,6 +804,9 @@ async def create( A list of functions the model may generate JSON inputs for. + instance_id: An unique identifier to a custom instance to execute the request. The requesting + organization is required to have access to the instance. + logit_bias: Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON object that maps tokens (specified by their token ID in the @@ -926,6 +944,7 @@ async def create( frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, + instance_id: Optional[str] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -986,6 +1005,9 @@ async def create( A list of functions the model may generate JSON inputs for. + instance_id: An unique identifier to a custom instance to execute the request. The requesting + organization is required to have access to the instance. + logit_bias: Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON object that maps tokens (specified by their token ID in the @@ -1116,6 +1138,7 @@ async def create( frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, + instance_id: Optional[str] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -1176,6 +1199,9 @@ async def create( A list of functions the model may generate JSON inputs for. + instance_id: An unique identifier to a custom instance to execute the request. The requesting + organization is required to have access to the instance. + logit_bias: Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON object that maps tokens (specified by their token ID in the @@ -1305,6 +1331,7 @@ async def create( frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, + instance_id: Optional[str] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -1336,6 +1363,7 @@ async def create( "frequency_penalty": frequency_penalty, "function_call": function_call, "functions": functions, + "instance_id": instance_id, "logit_bias": logit_bias, "logprobs": logprobs, "max_tokens": max_tokens, diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index e02a81bc51..2c80d84e6a 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -87,6 +87,12 @@ class CompletionCreateParamsBase(TypedDict, total=False): A list of functions the model may generate JSON inputs for. """ + instance_id: Optional[str] + """An unique identifier to a custom instance to execute the request. + + The requesting organization is required to have access to the instance. + """ + logit_bias: Optional[Dict[str, int]] """Modify the likelihood of specified tokens appearing in the completion. diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index 4fa069ba2e..856b7dc12c 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -50,6 +50,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: "parameters": {"foo": "bar"}, } ], + instance_id="string", logit_bias={"foo": 0}, logprobs=True, max_tokens=0, @@ -164,6 +165,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: "parameters": {"foo": "bar"}, } ], + instance_id="string", logit_bias={"foo": 0}, logprobs=True, max_tokens=0, @@ -280,6 +282,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn "parameters": {"foo": "bar"}, } ], + instance_id="string", logit_bias={"foo": 0}, logprobs=True, max_tokens=0, @@ -394,6 +397,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn "parameters": {"foo": "bar"}, } ], + instance_id="string", logit_bias={"foo": 0}, logprobs=True, max_tokens=0, From 98ac9df81be7918216a86dd7b3f140e99493e5eb Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 14 Feb 2024 15:16:37 -0500 Subject: [PATCH 229/816] chore(ci): move github release logic to github app (#1155) --- .github/workflows/create-releases.yml | 39 --------------------------- .github/workflows/publish-pypi.yml | 8 ++++-- .github/workflows/release-doctor.yml | 1 - bin/check-release-environment | 4 --- 4 files changed, 6 insertions(+), 46 deletions(-) delete mode 100644 .github/workflows/create-releases.yml diff --git a/.github/workflows/create-releases.yml b/.github/workflows/create-releases.yml deleted file mode 100644 index c8c94db105..0000000000 --- a/.github/workflows/create-releases.yml +++ /dev/null @@ -1,39 +0,0 @@ -name: Create releases -on: - schedule: - - cron: '0 5 * * *' # every day at 5am UTC - push: - branches: - - main - -jobs: - release: - name: release - if: github.ref == 'refs/heads/main' && github.repository == 'openai/openai-python' - runs-on: ubuntu-latest - environment: publish - - steps: - - uses: actions/checkout@v3 - - - uses: stainless-api/trigger-release-please@v1 - id: release - with: - repo: ${{ github.event.repository.full_name }} - stainless-api-key: ${{ secrets.STAINLESS_API_KEY }} - - - name: Install Rye - if: ${{ steps.release.outputs.releases_created }} - run: | - curl -sSf https://rye-up.com/get | bash - echo "$HOME/.rye/shims" >> $GITHUB_PATH - env: - RYE_VERSION: 0.15.2 - RYE_INSTALL_OPTION: "--yes" - - - name: Publish to PyPI - if: ${{ steps.release.outputs.releases_created }} - run: | - bash ./bin/publish-pypi - env: - PYPI_TOKEN: ${{ secrets.OPENAI_PYPI_TOKEN || secrets.PYPI_TOKEN }} diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml index 026ed29c22..e690e0d985 100644 --- a/.github/workflows/publish-pypi.yml +++ b/.github/workflows/publish-pypi.yml @@ -1,9 +1,13 @@ -# workflow for re-running publishing to PyPI in case it fails for some reason -# you can run this workflow by navigating to https://www.github.com/openai/openai-python/actions/workflows/publish-pypi.yml +# This workflow is triggered when a GitHub release is created. +# It can also be run manually to re-publish to PyPI in case it failed for some reason. +# You can run this workflow by navigating to https://www.github.com/openai/openai-python/actions/workflows/publish-pypi.yml name: Publish PyPI on: workflow_dispatch: + release: + types: [published] + jobs: publish: name: publish diff --git a/.github/workflows/release-doctor.yml b/.github/workflows/release-doctor.yml index 108aa5973a..20af127ffc 100644 --- a/.github/workflows/release-doctor.yml +++ b/.github/workflows/release-doctor.yml @@ -19,5 +19,4 @@ jobs: run: | bash ./bin/check-release-environment env: - STAINLESS_API_KEY: ${{ secrets.STAINLESS_API_KEY }} PYPI_TOKEN: ${{ secrets.OPENAI_PYPI_TOKEN || secrets.PYPI_TOKEN }} diff --git a/bin/check-release-environment b/bin/check-release-environment index b0c8d34f0c..3c9b2dd4ed 100644 --- a/bin/check-release-environment +++ b/bin/check-release-environment @@ -2,10 +2,6 @@ errors=() -if [ -z "${STAINLESS_API_KEY}" ]; then - errors+=("The STAINLESS_API_KEY secret has not been set. Please contact Stainless for an API key & set it in your organization secrets on GitHub.") -fi - if [ -z "${PYPI_TOKEN}" ]; then errors+=("The OPENAI_PYPI_TOKEN secret has not been set. Please set it in either this repository's secrets or your organization secrets.") fi From d63eac7f0649e6c65fde946383a93ce10c7067df Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 15 Feb 2024 14:37:28 -0500 Subject: [PATCH 230/816] chore(internal): refactor release environment script (#1158) --- bin/check-release-environment | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/check-release-environment b/bin/check-release-environment index 3c9b2dd4ed..5471b69edb 100644 --- a/bin/check-release-environment +++ b/bin/check-release-environment @@ -6,9 +6,9 @@ if [ -z "${PYPI_TOKEN}" ]; then errors+=("The OPENAI_PYPI_TOKEN secret has not been set. Please set it in either this repository's secrets or your organization secrets.") fi -len=${#errors[@]} +lenErrors=${#errors[@]} -if [[ len -gt 0 ]]; then +if [[ lenErrors -gt 0 ]]; then echo -e "Found the following errors in the release environment:\n" for error in "${errors[@]}"; do From 9741b1ca0ed17bbf4669b582f6a98f65628752af Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 16 Feb 2024 19:00:54 -0500 Subject: [PATCH 231/816] chore(client): use correct accept headers for binary data (#1161) --- src/openai/resources/audio/speech.py | 2 ++ src/openai/resources/files.py | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index 4e94d4aaef..fbdc1ecff1 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -78,6 +78,7 @@ def create( timeout: Override the client-level default timeout for this request, in seconds """ + extra_headers = {"Accept": "application/octet-stream", **(extra_headers or {})} return self._post( "/audio/speech", body=maybe_transform( @@ -149,6 +150,7 @@ async def create( timeout: Override the client-level default timeout for this request, in seconds """ + extra_headers = {"Accept": "application/octet-stream", **(extra_headers or {})} return await self._post( "/audio/speech", body=maybe_transform( diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index 58a2a217c7..8b2bc4f181 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -238,6 +238,7 @@ def content( """ if not file_id: raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") + extra_headers = {"Accept": "application/binary", **(extra_headers or {})} return self._get( f"/files/{file_id}/content", options=make_request_options( @@ -272,7 +273,6 @@ def retrieve_content( """ if not file_id: raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") - extra_headers = {"Accept": "application/json", **(extra_headers or {})} return self._get( f"/files/{file_id}/content", options=make_request_options( @@ -511,6 +511,7 @@ async def content( """ if not file_id: raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") + extra_headers = {"Accept": "application/binary", **(extra_headers or {})} return await self._get( f"/files/{file_id}/content", options=make_request_options( @@ -545,7 +546,6 @@ async def retrieve_content( """ if not file_id: raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") - extra_headers = {"Accept": "application/json", **(extra_headers or {})} return await self._get( f"/files/{file_id}/content", options=make_request_options( From 7a0cfb9acf136f62ec2b3edda9d8c607cf9dd5ea Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 19 Feb 2024 10:56:59 -0500 Subject: [PATCH 232/816] fix(api): remove non-GA instance_id param (#1164) --- src/openai/resources/chat/completions.py | 28 ------------------- .../types/chat/completion_create_params.py | 6 ---- tests/api_resources/chat/test_completions.py | 4 --- 3 files changed, 38 deletions(-) diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index caf712c604..0011d75e6e 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -68,7 +68,6 @@ def create( frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, - instance_id: Optional[str] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -123,9 +122,6 @@ def create( A list of functions the model may generate JSON inputs for. - instance_id: An unique identifier to a custom instance to execute the request. The requesting - organization is required to have access to the instance. - logit_bias: Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON object that maps tokens (specified by their token ID in the @@ -263,7 +259,6 @@ def create( frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, - instance_id: Optional[str] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -324,9 +319,6 @@ def create( A list of functions the model may generate JSON inputs for. - instance_id: An unique identifier to a custom instance to execute the request. The requesting - organization is required to have access to the instance. - logit_bias: Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON object that maps tokens (specified by their token ID in the @@ -457,7 +449,6 @@ def create( frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, - instance_id: Optional[str] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -518,9 +509,6 @@ def create( A list of functions the model may generate JSON inputs for. - instance_id: An unique identifier to a custom instance to execute the request. The requesting - organization is required to have access to the instance. - logit_bias: Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON object that maps tokens (specified by their token ID in the @@ -650,7 +638,6 @@ def create( frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, - instance_id: Optional[str] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -682,7 +669,6 @@ def create( "frequency_penalty": frequency_penalty, "function_call": function_call, "functions": functions, - "instance_id": instance_id, "logit_bias": logit_bias, "logprobs": logprobs, "max_tokens": max_tokens, @@ -749,7 +735,6 @@ async def create( frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, - instance_id: Optional[str] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -804,9 +789,6 @@ async def create( A list of functions the model may generate JSON inputs for. - instance_id: An unique identifier to a custom instance to execute the request. The requesting - organization is required to have access to the instance. - logit_bias: Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON object that maps tokens (specified by their token ID in the @@ -944,7 +926,6 @@ async def create( frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, - instance_id: Optional[str] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -1005,9 +986,6 @@ async def create( A list of functions the model may generate JSON inputs for. - instance_id: An unique identifier to a custom instance to execute the request. The requesting - organization is required to have access to the instance. - logit_bias: Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON object that maps tokens (specified by their token ID in the @@ -1138,7 +1116,6 @@ async def create( frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, - instance_id: Optional[str] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -1199,9 +1176,6 @@ async def create( A list of functions the model may generate JSON inputs for. - instance_id: An unique identifier to a custom instance to execute the request. The requesting - organization is required to have access to the instance. - logit_bias: Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON object that maps tokens (specified by their token ID in the @@ -1331,7 +1305,6 @@ async def create( frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, - instance_id: Optional[str] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -1363,7 +1336,6 @@ async def create( "frequency_penalty": frequency_penalty, "function_call": function_call, "functions": functions, - "instance_id": instance_id, "logit_bias": logit_bias, "logprobs": logprobs, "max_tokens": max_tokens, diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 2c80d84e6a..e02a81bc51 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -87,12 +87,6 @@ class CompletionCreateParamsBase(TypedDict, total=False): A list of functions the model may generate JSON inputs for. """ - instance_id: Optional[str] - """An unique identifier to a custom instance to execute the request. - - The requesting organization is required to have access to the instance. - """ - logit_bias: Optional[Dict[str, int]] """Modify the likelihood of specified tokens appearing in the completion. diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index 856b7dc12c..4fa069ba2e 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -50,7 +50,6 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: "parameters": {"foo": "bar"}, } ], - instance_id="string", logit_bias={"foo": 0}, logprobs=True, max_tokens=0, @@ -165,7 +164,6 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: "parameters": {"foo": "bar"}, } ], - instance_id="string", logit_bias={"foo": 0}, logprobs=True, max_tokens=0, @@ -282,7 +280,6 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn "parameters": {"foo": "bar"}, } ], - instance_id="string", logit_bias={"foo": 0}, logprobs=True, max_tokens=0, @@ -397,7 +394,6 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn "parameters": {"foo": "bar"}, } ], - instance_id="string", logit_bias={"foo": 0}, logprobs=True, max_tokens=0, From 8ee5f33e8776e4517ef91a1cb2fafb6af2ca9310 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 19 Feb 2024 15:57:24 +0000 Subject: [PATCH 233/816] release: 1.13.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 20 ++++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 23 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index de0960aba8..f94eeca267 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.12.0" + ".": "1.13.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ef0b80e87..00c364af0e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,25 @@ # Changelog +## 1.13.0 (2024-02-19) + +Full Changelog: [v1.12.0...v1.13.0](https://github.com/openai/openai-python/compare/v1.12.0...v1.13.0) + +### Features + +* **api:** updates ([#1146](https://github.com/openai/openai-python/issues/1146)) ([79b7675](https://github.com/openai/openai-python/commit/79b7675e51fb7d269a6ea281a568bc7812ba2ace)) + + +### Bug Fixes + +* **api:** remove non-GA instance_id param ([#1164](https://github.com/openai/openai-python/issues/1164)) ([1abe139](https://github.com/openai/openai-python/commit/1abe139b1a5f5cc41263738fc12856056dce5697)) + + +### Chores + +* **ci:** move github release logic to github app ([#1155](https://github.com/openai/openai-python/issues/1155)) ([67cfac2](https://github.com/openai/openai-python/commit/67cfac2564dfb718da0465e34b90ac6928fa962a)) +* **client:** use correct accept headers for binary data ([#1161](https://github.com/openai/openai-python/issues/1161)) ([e536437](https://github.com/openai/openai-python/commit/e536437ae0b2cb0ddf2d74618722005d37403f32)) +* **internal:** refactor release environment script ([#1158](https://github.com/openai/openai-python/issues/1158)) ([7fe8ec3](https://github.com/openai/openai-python/commit/7fe8ec3bf04ecf85e3bd5adf0d9992c051f87b81)) + ## 1.12.0 (2024-02-08) Full Changelog: [v1.11.1...v1.12.0](https://github.com/openai/openai-python/compare/v1.11.1...v1.12.0) diff --git a/pyproject.toml b/pyproject.toml index 163297ee2b..d7c017f99d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.12.0" +version = "1.13.0" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 6db2292c7b..0b4a88eb78 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.12.0" # x-release-please-version +__version__ = "1.13.0" # x-release-please-version From 998e1887e1f507960cf8f49c4c28390ed90e2b01 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 20 Feb 2024 12:18:36 -0500 Subject: [PATCH 234/816] chore(internal): bump rye to v0.24.0 (#1168) --- .devcontainer/Dockerfile | 2 +- .github/workflows/ci.yml | 2 +- .github/workflows/publish-pypi.yml | 2 +- requirements-dev.lock | 88 +++++++++++++++++++++++++++--- requirements.lock | 44 +++++++++++++-- 5 files changed, 122 insertions(+), 16 deletions(-) diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index 6eb007253c..dd93962010 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -3,7 +3,7 @@ FROM mcr.microsoft.com/vscode/devcontainers/python:0-${VARIANT} USER vscode -RUN curl -sSf https://rye-up.com/get | RYE_VERSION="0.15.2" RYE_INSTALL_OPTION="--yes" bash +RUN curl -sSf https://rye-up.com/get | RYE_VERSION="0.24.0" RYE_INSTALL_OPTION="--yes" bash ENV PATH=/home/vscode/.rye/shims:$PATH RUN echo "[[ -d .venv ]] && source .venv/bin/activate" >> /home/vscode/.bashrc diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c031d9a1d1..e50bfbdd7e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,7 +21,7 @@ jobs: curl -sSf https://rye-up.com/get | bash echo "$HOME/.rye/shims" >> $GITHUB_PATH env: - RYE_VERSION: 0.15.2 + RYE_VERSION: 0.24.0 RYE_INSTALL_OPTION: "--yes" - name: Install dependencies diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml index e690e0d985..a6575165dd 100644 --- a/.github/workflows/publish-pypi.yml +++ b/.github/workflows/publish-pypi.yml @@ -21,7 +21,7 @@ jobs: curl -sSf https://rye-up.com/get | bash echo "$HOME/.rye/shims" >> $GITHUB_PATH env: - RYE_VERSION: 0.15.2 + RYE_VERSION: 0.24.0 RYE_INSTALL_OPTION: "--yes" - name: Publish to PyPI diff --git a/requirements-dev.lock b/requirements-dev.lock index 088cb2bd98..a08b9b692c 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -5,67 +5,141 @@ # pre: false # features: [] # all-features: true +# with-sources: false -e file:. annotated-types==0.6.0 + # via pydantic anyio==4.1.0 + # via httpx + # via openai argcomplete==3.1.2 + # via nox attrs==23.1.0 -azure-core==1.29.6 + # via pytest +azure-core==1.30.0 + # via azure-identity azure-identity==1.15.0 certifi==2023.7.22 + # via httpcore + # via httpx + # via requests cffi==1.16.0 + # via cryptography charset-normalizer==3.3.2 + # via requests colorlog==6.7.0 -cryptography==41.0.7 + # via nox +cryptography==42.0.3 + # via azure-identity + # via msal + # via pyjwt dirty-equals==0.6.0 distlib==0.3.7 + # via virtualenv distro==1.8.0 + # via openai exceptiongroup==1.1.3 + # via anyio filelock==3.12.4 + # via virtualenv h11==0.14.0 + # via httpcore httpcore==1.0.2 + # via httpx httpx==0.25.2 + # via openai + # via respx idna==3.4 + # via anyio + # via httpx + # via requests importlib-metadata==7.0.0 iniconfig==2.0.0 + # via pytest msal==1.26.0 + # via azure-identity + # via msal-extensions msal-extensions==1.1.0 + # via azure-identity mypy==1.7.1 mypy-extensions==1.0.0 + # via mypy nodeenv==1.8.0 + # via pyright nox==2023.4.22 numpy==1.26.3 + # via openai + # via pandas + # via pandas-stubs packaging==23.2 + # via msal-extensions + # via nox + # via pytest pandas==2.1.4 + # via openai pandas-stubs==2.1.4.231227 + # via openai platformdirs==3.11.0 + # via virtualenv pluggy==1.3.0 + # via pytest portalocker==2.8.2 + # via msal-extensions py==1.11.0 + # via pytest pycparser==2.21 + # via cffi pydantic==2.4.2 + # via openai pydantic-core==2.10.1 + # via pydantic pyjwt==2.8.0 + # via msal pyright==1.1.332 pytest==7.1.1 + # via pytest-asyncio pytest-asyncio==0.21.1 python-dateutil==2.8.2 + # via pandas + # via time-machine pytz==2023.3.post1 + # via dirty-equals + # via pandas requests==2.31.0 + # via azure-core + # via msal respx==0.20.2 ruff==0.1.9 +setuptools==68.2.2 + # via nodeenv six==1.16.0 + # via azure-core + # via python-dateutil sniffio==1.3.0 + # via anyio + # via httpx + # via openai time-machine==2.9.0 tomli==2.0.1 + # via mypy + # via pytest tqdm==4.66.1 -types-pytz==2023.3.1.1 + # via openai +types-pytz==2024.1.0.20240203 + # via pandas-stubs types-tqdm==4.66.0.2 typing-extensions==4.8.0 -tzdata==2023.4 -urllib3==2.1.0 + # via azure-core + # via mypy + # via openai + # via pydantic + # via pydantic-core +tzdata==2024.1 + # via pandas +urllib3==2.2.1 + # via requests virtualenv==20.24.5 + # via nox zipp==3.17.0 -# The following packages are considered to be unsafe in a requirements file: -setuptools==68.2.2 + # via importlib-metadata diff --git a/requirements.lock b/requirements.lock index c178f26a88..f3733bec9a 100644 --- a/requirements.lock +++ b/requirements.lock @@ -5,27 +5,59 @@ # pre: false # features: [] # all-features: true +# with-sources: false -e file:. annotated-types==0.6.0 + # via pydantic anyio==4.1.0 + # via httpx + # via openai certifi==2023.7.22 + # via httpcore + # via httpx distro==1.8.0 + # via openai exceptiongroup==1.1.3 + # via anyio h11==0.14.0 + # via httpcore httpcore==1.0.2 + # via httpx httpx==0.25.2 + # via openai idna==3.4 -numpy==1.26.2 -pandas==2.1.3 -pandas-stubs==2.1.1.230928 + # via anyio + # via httpx +numpy==1.26.4 + # via openai + # via pandas + # via pandas-stubs +pandas==2.2.0 + # via openai +pandas-stubs==2.2.0.240218 + # via openai pydantic==2.4.2 + # via openai pydantic-core==2.10.1 + # via pydantic python-dateutil==2.8.2 -pytz==2023.3.post1 + # via pandas +pytz==2024.1 + # via pandas six==1.16.0 + # via python-dateutil sniffio==1.3.0 + # via anyio + # via httpx + # via openai tqdm==4.66.1 -types-pytz==2023.3.1.1 + # via openai +types-pytz==2024.1.0.20240203 + # via pandas-stubs typing-extensions==4.8.0 -tzdata==2023.3 + # via openai + # via pydantic + # via pydantic-core +tzdata==2024.1 + # via pandas From f504384a7dcfdaffccf1bea8e32c82541908ff94 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 20 Feb 2024 17:19:01 +0000 Subject: [PATCH 235/816] release: 1.13.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index f94eeca267..734ad79c1c 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.13.0" + ".": "1.13.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 00c364af0e..f282f6e84e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.13.1 (2024-02-20) + +Full Changelog: [v1.13.0...v1.13.1](https://github.com/openai/openai-python/compare/v1.13.0...v1.13.1) + +### Chores + +* **internal:** bump rye to v0.24.0 ([#1168](https://github.com/openai/openai-python/issues/1168)) ([84c4256](https://github.com/openai/openai-python/commit/84c4256316f2a79068ecadb852e5e69b6b104a1f)) + ## 1.13.0 (2024-02-19) Full Changelog: [v1.12.0...v1.13.0](https://github.com/openai/openai-python/compare/v1.12.0...v1.13.0) diff --git a/pyproject.toml b/pyproject.toml index d7c017f99d..d7585ce5c7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.13.0" +version = "1.13.1" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 0b4a88eb78..966177053b 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.13.0" # x-release-please-version +__version__ = "1.13.1" # x-release-please-version From 63222f61d8324d1be41f660613ff84935110beab Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 20 Feb 2024 13:09:03 -0500 Subject: [PATCH 236/816] fix(ci): revert "move github release logic to github app" (#1170) --- .github/workflows/create-releases.yml | 39 +++++++++++++++++++++++++++ .github/workflows/publish-pypi.yml | 8 ++---- .github/workflows/release-doctor.yml | 1 + bin/check-release-environment | 4 +++ 4 files changed, 46 insertions(+), 6 deletions(-) create mode 100644 .github/workflows/create-releases.yml diff --git a/.github/workflows/create-releases.yml b/.github/workflows/create-releases.yml new file mode 100644 index 0000000000..9e76fcc471 --- /dev/null +++ b/.github/workflows/create-releases.yml @@ -0,0 +1,39 @@ +name: Create releases +on: + schedule: + - cron: '0 5 * * *' # every day at 5am UTC + push: + branches: + - main + +jobs: + release: + name: release + if: github.ref == 'refs/heads/main' && github.repository == 'openai/openai-python' + runs-on: ubuntu-latest + environment: publish + + steps: + - uses: actions/checkout@v3 + + - uses: stainless-api/trigger-release-please@v1 + id: release + with: + repo: ${{ github.event.repository.full_name }} + stainless-api-key: ${{ secrets.STAINLESS_API_KEY }} + + - name: Install Rye + if: ${{ steps.release.outputs.releases_created }} + run: | + curl -sSf https://rye-up.com/get | bash + echo "$HOME/.rye/shims" >> $GITHUB_PATH + env: + RYE_VERSION: 0.24.0 + RYE_INSTALL_OPTION: "--yes" + + - name: Publish to PyPI + if: ${{ steps.release.outputs.releases_created }} + run: | + bash ./bin/publish-pypi + env: + PYPI_TOKEN: ${{ secrets.OPENAI_PYPI_TOKEN || secrets.PYPI_TOKEN }} diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml index a6575165dd..f779a19ac1 100644 --- a/.github/workflows/publish-pypi.yml +++ b/.github/workflows/publish-pypi.yml @@ -1,13 +1,9 @@ -# This workflow is triggered when a GitHub release is created. -# It can also be run manually to re-publish to PyPI in case it failed for some reason. -# You can run this workflow by navigating to https://www.github.com/openai/openai-python/actions/workflows/publish-pypi.yml +# workflow for re-running publishing to PyPI in case it fails for some reason +# you can run this workflow by navigating to https://www.github.com/openai/openai-python/actions/workflows/publish-pypi.yml name: Publish PyPI on: workflow_dispatch: - release: - types: [published] - jobs: publish: name: publish diff --git a/.github/workflows/release-doctor.yml b/.github/workflows/release-doctor.yml index 20af127ffc..108aa5973a 100644 --- a/.github/workflows/release-doctor.yml +++ b/.github/workflows/release-doctor.yml @@ -19,4 +19,5 @@ jobs: run: | bash ./bin/check-release-environment env: + STAINLESS_API_KEY: ${{ secrets.STAINLESS_API_KEY }} PYPI_TOKEN: ${{ secrets.OPENAI_PYPI_TOKEN || secrets.PYPI_TOKEN }} diff --git a/bin/check-release-environment b/bin/check-release-environment index 5471b69edb..2cc5ad6352 100644 --- a/bin/check-release-environment +++ b/bin/check-release-environment @@ -2,6 +2,10 @@ errors=() +if [ -z "${STAINLESS_API_KEY}" ]; then + errors+=("The STAINLESS_API_KEY secret has not been set. Please contact Stainless for an API key & set it in your organization secrets on GitHub.") +fi + if [ -z "${PYPI_TOKEN}" ]; then errors+=("The OPENAI_PYPI_TOKEN secret has not been set. Please set it in either this repository's secrets or your organization secrets.") fi From a7115b5f33acd27326e5f78e19beb0d73bd3268e Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 20 Feb 2024 18:09:24 +0000 Subject: [PATCH 237/816] release: 1.13.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 734ad79c1c..690002df88 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.13.1" + ".": "1.13.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index f282f6e84e..1f640d2614 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.13.2 (2024-02-20) + +Full Changelog: [v1.13.1...v1.13.2](https://github.com/openai/openai-python/compare/v1.13.1...v1.13.2) + +### Bug Fixes + +* **ci:** revert "move github release logic to github app" ([#1170](https://github.com/openai/openai-python/issues/1170)) ([f1adc2e](https://github.com/openai/openai-python/commit/f1adc2e6f2f29acb4404e84137a9d3109714c585)) + ## 1.13.1 (2024-02-20) Full Changelog: [v1.13.0...v1.13.1](https://github.com/openai/openai-python/compare/v1.13.0...v1.13.1) diff --git a/pyproject.toml b/pyproject.toml index d7585ce5c7..50fac10e84 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.13.1" +version = "1.13.2" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 966177053b..7890e5b58c 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.13.1" # x-release-please-version +__version__ = "1.13.2" # x-release-please-version From f0b18239fe00d084f5ac0df71f1bb2b3e4781c56 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 22 Feb 2024 15:17:19 -0500 Subject: [PATCH 238/816] chore(types): extract run status to a named type (#1178) --- .github/workflows/ci.yml | 2 +- api.md | 2 +- src/openai/types/beta/threads/__init__.py | 1 + src/openai/types/beta/threads/run.py | 5 ++--- src/openai/types/beta/threads/run_status.py | 9 +++++++++ 5 files changed, 14 insertions(+), 5 deletions(-) create mode 100644 src/openai/types/beta/threads/run_status.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e50bfbdd7e..ec10edfe36 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,7 +14,7 @@ jobs: if: github.repository == 'openai/openai-python' steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Install Rye run: | diff --git a/api.md b/api.md index 86b972d14e..34352e6e72 100644 --- a/api.md +++ b/api.md @@ -224,7 +224,7 @@ Methods: Types: ```python -from openai.types.beta.threads import RequiredActionFunctionToolCall, Run +from openai.types.beta.threads import RequiredActionFunctionToolCall, Run, RunStatus ``` Methods: diff --git a/src/openai/types/beta/threads/__init__.py b/src/openai/types/beta/threads/__init__.py index 8c77466dec..a71cbde3e3 100644 --- a/src/openai/types/beta/threads/__init__.py +++ b/src/openai/types/beta/threads/__init__.py @@ -3,6 +3,7 @@ from __future__ import annotations from .run import Run as Run +from .run_status import RunStatus as RunStatus from .thread_message import ThreadMessage as ThreadMessage from .run_list_params import RunListParams as RunListParams from .run_create_params import RunCreateParams as RunCreateParams diff --git a/src/openai/types/beta/threads/run.py b/src/openai/types/beta/threads/run.py index 9c875a9242..79e4f6a444 100644 --- a/src/openai/types/beta/threads/run.py +++ b/src/openai/types/beta/threads/run.py @@ -5,6 +5,7 @@ from ...shared import FunctionDefinition from ...._models import BaseModel +from .run_status import RunStatus from .required_action_function_tool_call import RequiredActionFunctionToolCall __all__ = [ @@ -142,9 +143,7 @@ class Run(BaseModel): started_at: Optional[int] = None """The Unix timestamp (in seconds) for when the run was started.""" - status: Literal[ - "queued", "in_progress", "requires_action", "cancelling", "cancelled", "failed", "completed", "expired" - ] + status: RunStatus """ The status of the run, which can be either `queued`, `in_progress`, `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, or diff --git a/src/openai/types/beta/threads/run_status.py b/src/openai/types/beta/threads/run_status.py new file mode 100644 index 0000000000..587e3d7810 --- /dev/null +++ b/src/openai/types/beta/threads/run_status.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing_extensions import Literal + +__all__ = ["RunStatus"] + +RunStatus = Literal[ + "queued", "in_progress", "requires_action", "cancelling", "cancelled", "failed", "completed", "expired" +] From af02745a6a6d8e4bad44b32beafb6357396d3b93 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 23 Feb 2024 13:26:41 -0500 Subject: [PATCH 239/816] docs: add note in azure_deployment docstring (#1188) --- src/openai/lib/azure.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/openai/lib/azure.py b/src/openai/lib/azure.py index 2c8b4dcd88..b3b94de80e 100644 --- a/src/openai/lib/azure.py +++ b/src/openai/lib/azure.py @@ -155,7 +155,7 @@ def __init__( azure_ad_token_provider: A function that returns an Azure Active Directory token, will be invoked on every request. azure_deployment: A model deployment, if given sets the base client URL to include `/deployments/{azure_deployment}`. - Note: this means you won't be able to use non-deployment endpoints. + Note: this means you won't be able to use non-deployment endpoints. Not supported with Assistants APIs. """ if api_key is None: api_key = os.environ.get("AZURE_OPENAI_API_KEY") @@ -388,7 +388,7 @@ def __init__( azure_ad_token_provider: A function that returns an Azure Active Directory token, will be invoked on every request. azure_deployment: A model deployment, if given sets the base client URL to include `/deployments/{azure_deployment}`. - Note: this means you won't be able to use non-deployment endpoints. + Note: this means you won't be able to use non-deployment endpoints. Not supported with Assistants APIs. """ if api_key is None: api_key = os.environ.get("AZURE_OPENAI_API_KEY") From 6d25c6bb08b7fc26cd2a8b6295e66c709fcb68b8 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 23 Feb 2024 19:18:50 -0500 Subject: [PATCH 240/816] feat(api): add wav and pcm to response_format (#1189) --- src/openai/resources/audio/speech.py | 16 ++++++++++++---- src/openai/types/audio/speech_create_params.py | 10 ++++++++-- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index fbdc1ecff1..a569751ee5 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -41,7 +41,7 @@ def create( input: str, model: Union[str, Literal["tts-1", "tts-1-hd"]], voice: Literal["alloy", "echo", "fable", "onyx", "nova", "shimmer"], - response_format: Literal["mp3", "opus", "aac", "flac"] | NotGiven = NOT_GIVEN, + response_format: Literal["mp3", "opus", "aac", "flac", "pcm", "wav"] | NotGiven = NOT_GIVEN, speed: float | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -65,7 +65,11 @@ def create( available in the [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech/voice-options). - response_format: The format to audio in. Supported formats are `mp3`, `opus`, `aac`, and `flac`. + response_format: The format to return audio in. Supported formats are `mp3`, `opus`, `aac`, + `flac`, `pcm`, and `wav`. + + The `pcm` audio format, similar to `wav` but without a header, utilizes a 24kHz + sample rate, mono channel, and 16-bit depth in signed little-endian format. speed: The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is the default. @@ -113,7 +117,7 @@ async def create( input: str, model: Union[str, Literal["tts-1", "tts-1-hd"]], voice: Literal["alloy", "echo", "fable", "onyx", "nova", "shimmer"], - response_format: Literal["mp3", "opus", "aac", "flac"] | NotGiven = NOT_GIVEN, + response_format: Literal["mp3", "opus", "aac", "flac", "pcm", "wav"] | NotGiven = NOT_GIVEN, speed: float | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -137,7 +141,11 @@ async def create( available in the [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech/voice-options). - response_format: The format to audio in. Supported formats are `mp3`, `opus`, `aac`, and `flac`. + response_format: The format to return audio in. Supported formats are `mp3`, `opus`, `aac`, + `flac`, `pcm`, and `wav`. + + The `pcm` audio format, similar to `wav` but without a header, utilizes a 24kHz + sample rate, mono channel, and 16-bit depth in signed little-endian format. speed: The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is the default. diff --git a/src/openai/types/audio/speech_create_params.py b/src/openai/types/audio/speech_create_params.py index 6a302dd3c8..00f862272e 100644 --- a/src/openai/types/audio/speech_create_params.py +++ b/src/openai/types/audio/speech_create_params.py @@ -26,8 +26,14 @@ class SpeechCreateParams(TypedDict, total=False): [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech/voice-options). """ - response_format: Literal["mp3", "opus", "aac", "flac"] - """The format to audio in. Supported formats are `mp3`, `opus`, `aac`, and `flac`.""" + response_format: Literal["mp3", "opus", "aac", "flac", "pcm", "wav"] + """The format to return audio in. + + Supported formats are `mp3`, `opus`, `aac`, `flac`, `pcm`, and `wav`. + + The `pcm` audio format, similar to `wav` but without a header, utilizes a 24kHz + sample rate, mono channel, and 16-bit depth in signed little-endian format. + """ speed: float """The speed of the generated audio. From 9179a03e72097556b357e35b959d60fa3303c9f3 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 26 Feb 2024 12:12:48 +0100 Subject: [PATCH 241/816] chore(internal): bump pyright (#1193) --- requirements-dev.lock | 6 +++--- src/openai/_models.py | 2 +- src/openai/_utils/_proxy.py | 2 +- src/openai/cli/_tools/migrate.py | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/requirements-dev.lock b/requirements-dev.lock index a08b9b692c..97f664e7c1 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -30,7 +30,7 @@ charset-normalizer==3.3.2 # via requests colorlog==6.7.0 # via nox -cryptography==42.0.3 +cryptography==42.0.5 # via azure-identity # via msal # via pyjwt @@ -57,7 +57,7 @@ idna==3.4 importlib-metadata==7.0.0 iniconfig==2.0.0 # via pytest -msal==1.26.0 +msal==1.27.0 # via azure-identity # via msal-extensions msal-extensions==1.1.0 @@ -96,7 +96,7 @@ pydantic-core==2.10.1 # via pydantic pyjwt==2.8.0 # via msal -pyright==1.1.332 +pyright==1.1.351 pytest==7.1.1 # via pytest-asyncio pytest-asyncio==0.21.1 diff --git a/src/openai/_models.py b/src/openai/_models.py index 48d5624f64..810891497a 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -283,7 +283,7 @@ def construct_type(*, value: object, type_: type) -> object: if is_union(origin): try: - return validate_type(type_=type_, value=value) + return validate_type(type_=cast("type[object]", type_), value=value) except Exception: pass diff --git a/src/openai/_utils/_proxy.py b/src/openai/_utils/_proxy.py index 6f05efcd21..b9c12dc3f4 100644 --- a/src/openai/_utils/_proxy.py +++ b/src/openai/_utils/_proxy.py @@ -45,7 +45,7 @@ def __dir__(self) -> Iterable[str]: @property # type: ignore @override - def __class__(self) -> type: + def __class__(self) -> type: # pyright: ignore proxied = self.__get_proxied__() if issubclass(type(proxied), LazyProxy): return type(proxied) diff --git a/src/openai/cli/_tools/migrate.py b/src/openai/cli/_tools/migrate.py index 14773302e1..53073b866f 100644 --- a/src/openai/cli/_tools/migrate.py +++ b/src/openai/cli/_tools/migrate.py @@ -138,7 +138,7 @@ def install() -> Path: unpacked_dir.mkdir(parents=True, exist_ok=True) with tarfile.open(temp_file, "r:gz") as archive: - archive.extractall(unpacked_dir) + archive.extractall(unpacked_dir, filter="data") for item in unpacked_dir.iterdir(): item.rename(target_dir / item.name) From 9375d2cc3492a8328a5d645e9dd1a46efe9a55c5 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 26 Feb 2024 17:41:05 +0100 Subject: [PATCH 242/816] docs(examples): add pyaudio streaming example (#1194) --- examples/audio.py | 28 +++++++++++++++++++++++++++- pyproject.toml | 3 ++- requirements-dev.lock | 1 + 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/examples/audio.py b/examples/audio.py index 73491090f5..85f47bfb06 100755 --- a/examples/audio.py +++ b/examples/audio.py @@ -1,5 +1,6 @@ -#!/usr/bin/env python +#!/usr/bin/env rye run python +import time from pathlib import Path from openai import OpenAI @@ -11,6 +12,8 @@ def main() -> None: + stream_to_speakers() + # Create text-to-speech audio file with openai.audio.speech.with_streaming_response.create( model="tts-1", @@ -34,5 +37,28 @@ def main() -> None: print(translation.text) +def stream_to_speakers() -> None: + import pyaudio + + player_stream = pyaudio.PyAudio().open(format=pyaudio.paInt16, channels=1, rate=24000, output=True) + + start_time = time.time() + + with openai.audio.speech.with_streaming_response.create( + model="tts-1", + voice="alloy", + response_format="pcm", # similar to WAV, but without a header chunk at the start. + input="""I see skies of blue and clouds of white + The bright blessed days, the dark sacred nights + And I think to myself + What a wonderful world""", + ) as response: + print(f"Time to first byte: {int((time.time() - start_time) * 1000)}ms") + for chunk in response.iter_bytes(chunk_size=1024): + player_stream.write(chunk) + + print(f"Done in {int((time.time() - start_time) * 1000)}ms.") + + if __name__ == "__main__": main() diff --git a/pyproject.toml b/pyproject.toml index 50fac10e84..5bdca2b69d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -61,7 +61,8 @@ dev-dependencies = [ "dirty-equals>=0.6.0", "importlib-metadata>=6.7.0", "azure-identity >=1.14.1", - "types-tqdm > 4" + "types-tqdm > 4", + "types-pyaudio > 0" ] [tool.rye.scripts] diff --git a/requirements-dev.lock b/requirements-dev.lock index 97f664e7c1..fa95964d07 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -126,6 +126,7 @@ tomli==2.0.1 # via pytest tqdm==4.66.1 # via openai +types-pyaudio==0.2.16.20240106 types-pytz==2024.1.0.20240203 # via pandas-stubs types-tqdm==4.66.0.2 From cbcb9785703c626c39ed4ece60d5b046997732c1 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 27 Feb 2024 15:03:24 +0100 Subject: [PATCH 243/816] chore(client): use anyio.sleep instead of asyncio.sleep (#1198) --- src/openai/_resource.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/openai/_resource.py b/src/openai/_resource.py index db1b0fa45a..0b0703bb72 100644 --- a/src/openai/_resource.py +++ b/src/openai/_resource.py @@ -3,9 +3,10 @@ from __future__ import annotations import time -import asyncio from typing import TYPE_CHECKING +import anyio + if TYPE_CHECKING: from ._client import OpenAI, AsyncOpenAI @@ -39,4 +40,4 @@ def __init__(self, client: AsyncOpenAI) -> None: self._get_api_list = client.get_api_list async def _sleep(self, seconds: float) -> None: - await asyncio.sleep(seconds) + await anyio.sleep(seconds) From e41abf7b7dbc1e744d167f748e55d4dedfc0dca7 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 28 Feb 2024 06:04:08 +0100 Subject: [PATCH 244/816] release: 1.13.3 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 21 +++++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 24 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 690002df88..c4bf1b6c04 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.13.2" + ".": "1.13.3" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f640d2614..201757c90d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,26 @@ # Changelog +## 1.13.3 (2024-02-28) + +Full Changelog: [v1.13.2...v1.13.3](https://github.com/openai/openai-python/compare/v1.13.2...v1.13.3) + +### Features + +* **api:** add wav and pcm to response_format ([#1189](https://github.com/openai/openai-python/issues/1189)) ([dbd20fc](https://github.com/openai/openai-python/commit/dbd20fc42e93358261f71b9aa0e5f955053c3825)) + + +### Chores + +* **client:** use anyio.sleep instead of asyncio.sleep ([#1198](https://github.com/openai/openai-python/issues/1198)) ([b6d025b](https://github.com/openai/openai-python/commit/b6d025b54f091e79f5d4a0a8923f29574fd66027)) +* **internal:** bump pyright ([#1193](https://github.com/openai/openai-python/issues/1193)) ([9202e04](https://github.com/openai/openai-python/commit/9202e04d07a7c47232f39196346c734869b8f55a)) +* **types:** extract run status to a named type ([#1178](https://github.com/openai/openai-python/issues/1178)) ([249ecbd](https://github.com/openai/openai-python/commit/249ecbdeb6566a385ec46dfd5000b4eaa03965f0)) + + +### Documentation + +* add note in azure_deployment docstring ([#1188](https://github.com/openai/openai-python/issues/1188)) ([96fa995](https://github.com/openai/openai-python/commit/96fa99572dd76ee708f2bae04d11b659cdd698b2)) +* **examples:** add pyaudio streaming example ([#1194](https://github.com/openai/openai-python/issues/1194)) ([3683c5e](https://github.com/openai/openai-python/commit/3683c5e3c7f07e4b789a0c4cc417b2c59539cae2)) + ## 1.13.2 (2024-02-20) Full Changelog: [v1.13.1...v1.13.2](https://github.com/openai/openai-python/compare/v1.13.1...v1.13.2) diff --git a/pyproject.toml b/pyproject.toml index 5bdca2b69d..171ede0aa4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.13.2" +version = "1.13.3" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 7890e5b58c..503a06141f 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.13.2" # x-release-please-version +__version__ = "1.13.3" # x-release-please-version From 297796b7a067ad4b6558e416b7a75612231e68f8 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 29 Feb 2024 13:32:23 +0100 Subject: [PATCH 245/816] chore(internal): minor core client restructuring (#1199) --- src/openai/_base_client.py | 5 ++++- src/openai/_streaming.py | 34 ++++++++++++++++++++++++++++------ 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 73bd2411fd..dda280f6aa 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -79,7 +79,7 @@ RAW_RESPONSE_HEADER, OVERRIDE_CAST_TO_HEADER, ) -from ._streaming import Stream, AsyncStream +from ._streaming import Stream, SSEDecoder, AsyncStream, SSEBytesDecoder from ._exceptions import ( APIStatusError, APITimeoutError, @@ -431,6 +431,9 @@ def _prepare_url(http://github.com/self,%20url:%20str) -> URL: return merge_url + def _make_sse_decoder(self) -> SSEDecoder | SSEBytesDecoder: + return SSEDecoder() + def _build_request( self, options: FinalRequestOptions, diff --git a/src/openai/_streaming.py b/src/openai/_streaming.py index 74878fd0a0..2bc8d6a14d 100644 --- a/src/openai/_streaming.py +++ b/src/openai/_streaming.py @@ -5,7 +5,7 @@ import inspect from types import TracebackType from typing import TYPE_CHECKING, Any, Generic, TypeVar, Iterator, AsyncIterator, cast -from typing_extensions import Self, TypeGuard, override, get_origin +from typing_extensions import Self, Protocol, TypeGuard, override, get_origin, runtime_checkable import httpx @@ -24,6 +24,8 @@ class Stream(Generic[_T]): response: httpx.Response + _decoder: SSEDecoder | SSEBytesDecoder + def __init__( self, *, @@ -34,7 +36,7 @@ def __init__( self.response = response self._cast_to = cast_to self._client = client - self._decoder = SSEDecoder() + self._decoder = client._make_sse_decoder() self._iterator = self.__stream__() def __next__(self) -> _T: @@ -45,7 +47,10 @@ def __iter__(self) -> Iterator[_T]: yield item def _iter_events(self) -> Iterator[ServerSentEvent]: - yield from self._decoder.iter(self.response.iter_lines()) + if isinstance(self._decoder, SSEBytesDecoder): + yield from self._decoder.iter_bytes(self.response.iter_bytes()) + else: + yield from self._decoder.iter(self.response.iter_lines()) def __stream__(self) -> Iterator[_T]: cast_to = cast(Any, self._cast_to) @@ -97,6 +102,8 @@ class AsyncStream(Generic[_T]): response: httpx.Response + _decoder: SSEDecoder | SSEBytesDecoder + def __init__( self, *, @@ -107,7 +114,7 @@ def __init__( self.response = response self._cast_to = cast_to self._client = client - self._decoder = SSEDecoder() + self._decoder = client._make_sse_decoder() self._iterator = self.__stream__() async def __anext__(self) -> _T: @@ -118,8 +125,12 @@ async def __aiter__(self) -> AsyncIterator[_T]: yield item async def _iter_events(self) -> AsyncIterator[ServerSentEvent]: - async for sse in self._decoder.aiter(self.response.aiter_lines()): - yield sse + if isinstance(self._decoder, SSEBytesDecoder): + async for sse in self._decoder.aiter_bytes(self.response.aiter_bytes()): + yield sse + else: + async for sse in self._decoder.aiter(self.response.aiter_lines()): + yield sse async def __stream__(self) -> AsyncIterator[_T]: cast_to = cast(Any, self._cast_to) @@ -284,6 +295,17 @@ def decode(self, line: str) -> ServerSentEvent | None: return None +@runtime_checkable +class SSEBytesDecoder(Protocol): + def iter_bytes(self, iterator: Iterator[bytes]) -> Iterator[ServerSentEvent]: + """Given an iterator that yields raw binary data, iterate over it & yield every event encountered""" + ... + + def aiter_bytes(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[ServerSentEvent]: + """Given an async iterator that yields raw binary data, iterate over it & yield every event encountered""" + ... + + def is_stream_class_type(typ: type) -> TypeGuard[type[Stream[object]] | type[AsyncStream[object]]]: """TypeGuard for determining whether or not the given type is a subclass of `Stream` / `AsyncStream`""" origin = get_origin(typ) or typ From 25cef3d9d106b89d583a3a6b67e4211f74a013ba Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 29 Feb 2024 17:39:58 +0100 Subject: [PATCH 246/816] docs(contributing): improve wording (#1201) --- CONTRIBUTING.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 914ab67053..3290e13502 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -82,7 +82,7 @@ pip install ./path-to-wheel-file.whl ## Running tests -Most tests will require you to [setup a mock server](https://github.com/stoplightio/prism) against the OpenAPI spec to run the tests. +Most tests require you to [set up a mock server](https://github.com/stoplightio/prism) against the OpenAPI spec to run the tests. ```bash # you will need npm installed @@ -117,7 +117,7 @@ the changes aren't made through the automated pipeline, you may want to make rel ### Publish with a GitHub workflow -You can release to package managers by using [the `Publish PyPI` GitHub action](https://www.github.com/openai/openai-python/actions/workflows/publish-pypi.yml). This will require a setup organization or repository secret to be set up. +You can release to package managers by using [the `Publish PyPI` GitHub action](https://www.github.com/openai/openai-python/actions/workflows/publish-pypi.yml). This requires a setup organization or repository secret to be set up. ### Publish manually From 1879c97a5fb73a1609ade5e9a12a0af5e784ecba Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 1 Mar 2024 14:57:41 +0100 Subject: [PATCH 247/816] chore(docs): mention install from git repo (#1203) --- CONTRIBUTING.md | 2 +- README.md | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3290e13502..7ab73dbf4c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -59,7 +59,7 @@ If you’d like to use the repository from source, you can either install from g To install via git: ```bash -pip install git+ssh://git@github.com:openai/openai-python.git +pip install git+ssh://git@github.com/openai/openai-python.git ``` Alternatively, you can build from source and install the wheel file: diff --git a/README.md b/README.md index 0e06cd5631..7d6c896d50 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ The REST API documentation can be found [on platform.openai.com](https://platfor > The SDK was rewritten in v1, which was released November 6th 2023. See the [v1 migration guide](https://github.com/openai/openai-python/discussions/742), which includes scripts to automatically update your code. ```sh +# install from PyPI pip install openai ``` From 31bfc124e2d850f254dfb9630d44eedd7f3320cc Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 4 Mar 2024 13:52:22 +0100 Subject: [PATCH 248/816] chore(internal): split up transforms into sync / async (#1210) --- src/openai/_utils/__init__.py | 2 + src/openai/_utils/_transform.py | 128 +++++++++- src/openai/resources/audio/speech.py | 7 +- src/openai/resources/audio/transcriptions.py | 9 +- src/openai/resources/audio/translations.py | 9 +- .../resources/beta/assistants/assistants.py | 9 +- src/openai/resources/beta/assistants/files.py | 7 +- .../beta/threads/messages/messages.py | 9 +- .../resources/beta/threads/runs/runs.py | 11 +- src/openai/resources/beta/threads/threads.py | 11 +- src/openai/resources/chat/completions.py | 8 +- src/openai/resources/completions.py | 8 +- src/openai/resources/files.py | 9 +- src/openai/resources/fine_tuning/jobs.py | 7 +- src/openai/resources/images.py | 13 +- src/openai/resources/moderations.py | 7 +- tests/test_transform.py | 220 ++++++++++++------ 17 files changed, 363 insertions(+), 111 deletions(-) diff --git a/src/openai/_utils/__init__.py b/src/openai/_utils/__init__.py index b5790a879f..5697894192 100644 --- a/src/openai/_utils/__init__.py +++ b/src/openai/_utils/__init__.py @@ -44,5 +44,7 @@ from ._transform import ( PropertyInfo as PropertyInfo, transform as transform, + async_transform as async_transform, maybe_transform as maybe_transform, + async_maybe_transform as async_maybe_transform, ) diff --git a/src/openai/_utils/_transform.py b/src/openai/_utils/_transform.py index 2cb7726c73..9c76930687 100644 --- a/src/openai/_utils/_transform.py +++ b/src/openai/_utils/_transform.py @@ -180,11 +180,7 @@ def _transform_recursive( if isinstance(data, pydantic.BaseModel): return model_dump(data, exclude_unset=True) - return _transform_value(data, annotation) - - -def _transform_value(data: object, type_: type) -> object: - annotated_type = _get_annotated_type(type_) + annotated_type = _get_annotated_type(annotation) if annotated_type is None: return data @@ -222,3 +218,125 @@ def _transform_typeddict( else: result[_maybe_transform_key(key, type_)] = _transform_recursive(value, annotation=type_) return result + + +async def async_maybe_transform( + data: object, + expected_type: object, +) -> Any | None: + """Wrapper over `async_transform()` that allows `None` to be passed. + + See `async_transform()` for more details. + """ + if data is None: + return None + return await async_transform(data, expected_type) + + +async def async_transform( + data: _T, + expected_type: object, +) -> _T: + """Transform dictionaries based off of type information from the given type, for example: + + ```py + class Params(TypedDict, total=False): + card_id: Required[Annotated[str, PropertyInfo(alias="cardID")]] + + + transformed = transform({"card_id": ""}, Params) + # {'cardID': ''} + ``` + + Any keys / data that does not have type information given will be included as is. + + It should be noted that the transformations that this function does are not represented in the type system. + """ + transformed = await _async_transform_recursive(data, annotation=cast(type, expected_type)) + return cast(_T, transformed) + + +async def _async_transform_recursive( + data: object, + *, + annotation: type, + inner_type: type | None = None, +) -> object: + """Transform the given data against the expected type. + + Args: + annotation: The direct type annotation given to the particular piece of data. + This may or may not be wrapped in metadata types, e.g. `Required[T]`, `Annotated[T, ...]` etc + + inner_type: If applicable, this is the "inside" type. This is useful in certain cases where the outside type + is a container type such as `List[T]`. In that case `inner_type` should be set to `T` so that each entry in + the list can be transformed using the metadata from the container type. + + Defaults to the same value as the `annotation` argument. + """ + if inner_type is None: + inner_type = annotation + + stripped_type = strip_annotated_type(inner_type) + if is_typeddict(stripped_type) and is_mapping(data): + return await _async_transform_typeddict(data, stripped_type) + + if ( + # List[T] + (is_list_type(stripped_type) and is_list(data)) + # Iterable[T] + or (is_iterable_type(stripped_type) and is_iterable(data) and not isinstance(data, str)) + ): + inner_type = extract_type_arg(stripped_type, 0) + return [await _async_transform_recursive(d, annotation=annotation, inner_type=inner_type) for d in data] + + if is_union_type(stripped_type): + # For union types we run the transformation against all subtypes to ensure that everything is transformed. + # + # TODO: there may be edge cases where the same normalized field name will transform to two different names + # in different subtypes. + for subtype in get_args(stripped_type): + data = await _async_transform_recursive(data, annotation=annotation, inner_type=subtype) + return data + + if isinstance(data, pydantic.BaseModel): + return model_dump(data, exclude_unset=True) + + annotated_type = _get_annotated_type(annotation) + if annotated_type is None: + return data + + # ignore the first argument as it is the actual type + annotations = get_args(annotated_type)[1:] + for annotation in annotations: + if isinstance(annotation, PropertyInfo) and annotation.format is not None: + return await _async_format_data(data, annotation.format, annotation.format_template) + + return data + + +async def _async_format_data(data: object, format_: PropertyFormat, format_template: str | None) -> object: + if isinstance(data, (date, datetime)): + if format_ == "iso8601": + return data.isoformat() + + if format_ == "custom" and format_template is not None: + return data.strftime(format_template) + + return data + + +async def _async_transform_typeddict( + data: Mapping[str, object], + expected_type: type, +) -> Mapping[str, object]: + result: dict[str, object] = {} + annotations = get_type_hints(expected_type, include_extras=True) + for key, value in data.items(): + type_ = annotations.get(key) + if type_ is None: + # we do not have a type annotation for this field, leave it as is + result[key] = value + else: + result[_maybe_transform_key(key, type_)] = await _async_transform_recursive(value, annotation=type_) + return result diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index a569751ee5..6e0eb0cfdb 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -9,7 +9,10 @@ from ... import _legacy_response from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ..._utils import maybe_transform +from ..._utils import ( + maybe_transform, + async_maybe_transform, +) from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import ( @@ -161,7 +164,7 @@ async def create( extra_headers = {"Accept": "application/octet-stream", **(extra_headers or {})} return await self._post( "/audio/speech", - body=maybe_transform( + body=await async_maybe_transform( { "input": input, "model": model, diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index 275098ce88..720615f43f 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -9,7 +9,12 @@ from ... import _legacy_response from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes -from ..._utils import extract_files, maybe_transform, deepcopy_minimal +from ..._utils import ( + extract_files, + maybe_transform, + deepcopy_minimal, + async_maybe_transform, +) from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper @@ -200,7 +205,7 @@ async def create( extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} return await self._post( "/audio/transcriptions", - body=maybe_transform(body, transcription_create_params.TranscriptionCreateParams), + body=await async_maybe_transform(body, transcription_create_params.TranscriptionCreateParams), files=files, options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index d6cbc75886..a189a07380 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -9,7 +9,12 @@ from ... import _legacy_response from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes -from ..._utils import extract_files, maybe_transform, deepcopy_minimal +from ..._utils import ( + extract_files, + maybe_transform, + deepcopy_minimal, + async_maybe_transform, +) from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper @@ -174,7 +179,7 @@ async def create( extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} return await self._post( "/audio/translations", - body=maybe_transform(body, translation_create_params.TranslationCreateParams), + body=await async_maybe_transform(body, translation_create_params.TranslationCreateParams), files=files, options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout diff --git a/src/openai/resources/beta/assistants/assistants.py b/src/openai/resources/beta/assistants/assistants.py index e926c31642..3aef33c95e 100644 --- a/src/openai/resources/beta/assistants/assistants.py +++ b/src/openai/resources/beta/assistants/assistants.py @@ -17,7 +17,10 @@ AsyncFilesWithStreamingResponse, ) from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ...._utils import maybe_transform +from ...._utils import ( + maybe_transform, + async_maybe_transform, +) from ...._compat import cached_property from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper @@ -410,7 +413,7 @@ async def create( extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._post( "/assistants", - body=maybe_transform( + body=await async_maybe_transform( { "model": model, "description": description, @@ -525,7 +528,7 @@ async def update( extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._post( f"/assistants/{assistant_id}", - body=maybe_transform( + body=await async_maybe_transform( { "description": description, "file_ids": file_ids, diff --git a/src/openai/resources/beta/assistants/files.py b/src/openai/resources/beta/assistants/files.py index c21465036a..8d5657666c 100644 --- a/src/openai/resources/beta/assistants/files.py +++ b/src/openai/resources/beta/assistants/files.py @@ -8,7 +8,10 @@ from .... import _legacy_response from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ...._utils import maybe_transform +from ...._utils import ( + maybe_transform, + async_maybe_transform, +) from ...._compat import cached_property from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper @@ -259,7 +262,7 @@ async def create( extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._post( f"/assistants/{assistant_id}/files", - body=maybe_transform({"file_id": file_id}, file_create_params.FileCreateParams), + body=await async_maybe_transform({"file_id": file_id}, file_create_params.FileCreateParams), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), diff --git a/src/openai/resources/beta/threads/messages/messages.py b/src/openai/resources/beta/threads/messages/messages.py index c95cdd5d00..2c0994d1f2 100644 --- a/src/openai/resources/beta/threads/messages/messages.py +++ b/src/openai/resources/beta/threads/messages/messages.py @@ -17,7 +17,10 @@ AsyncFilesWithStreamingResponse, ) from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ....._utils import maybe_transform +from ....._utils import ( + maybe_transform, + async_maybe_transform, +) from ....._compat import cached_property from ....._resource import SyncAPIResource, AsyncAPIResource from ....._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper @@ -315,7 +318,7 @@ async def create( extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._post( f"/threads/{thread_id}/messages", - body=maybe_transform( + body=await async_maybe_transform( { "content": content, "role": role, @@ -404,7 +407,7 @@ async def update( extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._post( f"/threads/{thread_id}/messages/{message_id}", - body=maybe_transform({"metadata": metadata}, message_update_params.MessageUpdateParams), + body=await async_maybe_transform({"metadata": metadata}, message_update_params.MessageUpdateParams), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 9b18336010..62cfa6b742 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -17,7 +17,10 @@ AsyncStepsWithStreamingResponse, ) from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ....._utils import maybe_transform +from ....._utils import ( + maybe_transform, + async_maybe_transform, +) from ....._compat import cached_property from ....._resource import SyncAPIResource, AsyncAPIResource from ....._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper @@ -430,7 +433,7 @@ async def create( extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._post( f"/threads/{thread_id}/runs", - body=maybe_transform( + body=await async_maybe_transform( { "assistant_id": assistant_id, "additional_instructions": additional_instructions, @@ -521,7 +524,7 @@ async def update( extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._post( f"/threads/{thread_id}/runs/{run_id}", - body=maybe_transform({"metadata": metadata}, run_update_params.RunUpdateParams), + body=await async_maybe_transform({"metadata": metadata}, run_update_params.RunUpdateParams), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), @@ -669,7 +672,7 @@ async def submit_tool_outputs( extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._post( f"/threads/{thread_id}/runs/{run_id}/submit_tool_outputs", - body=maybe_transform( + body=await async_maybe_transform( {"tool_outputs": tool_outputs}, run_submit_tool_outputs_params.RunSubmitToolOutputsParams ), options=make_request_options( diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index dd079ac533..cc0e1c0959 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -24,7 +24,10 @@ AsyncMessagesWithStreamingResponse, ) from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ...._utils import maybe_transform +from ...._utils import ( + maybe_transform, + async_maybe_transform, +) from .runs.runs import Runs, AsyncRuns from ...._compat import cached_property from ...._resource import SyncAPIResource, AsyncAPIResource @@ -342,7 +345,7 @@ async def create( extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._post( "/threads", - body=maybe_transform( + body=await async_maybe_transform( { "messages": messages, "metadata": metadata, @@ -423,7 +426,7 @@ async def update( extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._post( f"/threads/{thread_id}", - body=maybe_transform({"metadata": metadata}, thread_update_params.ThreadUpdateParams), + body=await async_maybe_transform({"metadata": metadata}, thread_update_params.ThreadUpdateParams), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), @@ -517,7 +520,7 @@ async def create_and_run( extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._post( "/threads/runs", - body=maybe_transform( + body=await async_maybe_transform( { "assistant_id": assistant_id, "instructions": instructions, diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index 0011d75e6e..a8856a989b 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -9,7 +9,11 @@ from ... import _legacy_response from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ..._utils import required_args, maybe_transform +from ..._utils import ( + required_args, + maybe_transform, + async_maybe_transform, +) from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper @@ -1329,7 +1333,7 @@ async def create( ) -> ChatCompletion | AsyncStream[ChatCompletionChunk]: return await self._post( "/chat/completions", - body=maybe_transform( + body=await async_maybe_transform( { "messages": messages, "model": model, diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index af2d6e2e51..6d3756f6ba 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -10,7 +10,11 @@ from .. import _legacy_response from ..types import Completion, completion_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from .._utils import required_args, maybe_transform +from .._utils import ( + required_args, + maybe_transform, + async_maybe_transform, +) from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper @@ -1019,7 +1023,7 @@ async def create( ) -> Completion | AsyncStream[Completion]: return await self._post( "/completions", - body=maybe_transform( + body=await async_maybe_transform( { "model": model, "prompt": prompt, diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index 8b2bc4f181..3ea66656b3 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -12,7 +12,12 @@ from .. import _legacy_response from ..types import FileObject, FileDeleted, file_list_params, file_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes -from .._utils import extract_files, maybe_transform, deepcopy_minimal +from .._utils import ( + extract_files, + maybe_transform, + deepcopy_minimal, + async_maybe_transform, +) from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import ( @@ -374,7 +379,7 @@ async def create( extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} return await self._post( "/files", - body=maybe_transform(body, file_create_params.FileCreateParams), + body=await async_maybe_transform(body, file_create_params.FileCreateParams), files=files, options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout diff --git a/src/openai/resources/fine_tuning/jobs.py b/src/openai/resources/fine_tuning/jobs.py index 6b59932982..8338de12c4 100644 --- a/src/openai/resources/fine_tuning/jobs.py +++ b/src/openai/resources/fine_tuning/jobs.py @@ -9,7 +9,10 @@ from ... import _legacy_response from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ..._utils import maybe_transform +from ..._utils import ( + maybe_transform, + async_maybe_transform, +) from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper @@ -369,7 +372,7 @@ async def create( """ return await self._post( "/fine_tuning/jobs", - body=maybe_transform( + body=await async_maybe_transform( { "model": model, "training_file": training_file, diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py index 91530e47ca..7a7ff1225d 100644 --- a/src/openai/resources/images.py +++ b/src/openai/resources/images.py @@ -15,7 +15,12 @@ image_create_variation_params, ) from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes -from .._utils import extract_files, maybe_transform, deepcopy_minimal +from .._utils import ( + extract_files, + maybe_transform, + deepcopy_minimal, + async_maybe_transform, +) from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper @@ -345,7 +350,7 @@ async def create_variation( extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} return await self._post( "/images/variations", - body=maybe_transform(body, image_create_variation_params.ImageCreateVariationParams), + body=await async_maybe_transform(body, image_create_variation_params.ImageCreateVariationParams), files=files, options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout @@ -428,7 +433,7 @@ async def edit( extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} return await self._post( "/images/edits", - body=maybe_transform(body, image_edit_params.ImageEditParams), + body=await async_maybe_transform(body, image_edit_params.ImageEditParams), files=files, options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout @@ -496,7 +501,7 @@ async def generate( """ return await self._post( "/images/generations", - body=maybe_transform( + body=await async_maybe_transform( { "prompt": prompt, "model": model, diff --git a/src/openai/resources/moderations.py b/src/openai/resources/moderations.py index 540d089071..2b9a70d562 100644 --- a/src/openai/resources/moderations.py +++ b/src/openai/resources/moderations.py @@ -10,7 +10,10 @@ from .. import _legacy_response from ..types import ModerationCreateResponse, moderation_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from .._utils import maybe_transform +from .._utils import ( + maybe_transform, + async_maybe_transform, +) from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper @@ -127,7 +130,7 @@ async def create( """ return await self._post( "/moderations", - body=maybe_transform( + body=await async_maybe_transform( { "input": input, "model": model, diff --git a/tests/test_transform.py b/tests/test_transform.py index 6ed67d49a7..67ec4d5cc6 100644 --- a/tests/test_transform.py +++ b/tests/test_transform.py @@ -1,22 +1,45 @@ from __future__ import annotations -from typing import Any, List, Union, Iterable, Optional, cast +from typing import Any, List, Union, TypeVar, Iterable, Optional, cast from datetime import date, datetime from typing_extensions import Required, Annotated, TypedDict import pytest -from openai._utils import PropertyInfo, transform, parse_datetime +from openai._utils import ( + PropertyInfo, + transform as _transform, + parse_datetime, + async_transform as _async_transform, +) from openai._compat import PYDANTIC_V2 from openai._models import BaseModel +_T = TypeVar("_T") + + +async def transform( + data: _T, + expected_type: object, + use_async: bool, +) -> _T: + if use_async: + return await _async_transform(data, expected_type=expected_type) + + return _transform(data, expected_type=expected_type) + + +parametrize = pytest.mark.parametrize("use_async", [False, True], ids=["sync", "async"]) + class Foo1(TypedDict): foo_bar: Annotated[str, PropertyInfo(alias="fooBar")] -def test_top_level_alias() -> None: - assert transform({"foo_bar": "hello"}, expected_type=Foo1) == {"fooBar": "hello"} +@parametrize +@pytest.mark.asyncio +async def test_top_level_alias(use_async: bool) -> None: + assert await transform({"foo_bar": "hello"}, expected_type=Foo1, use_async=use_async) == {"fooBar": "hello"} class Foo2(TypedDict): @@ -32,9 +55,11 @@ class Baz2(TypedDict): my_baz: Annotated[str, PropertyInfo(alias="myBaz")] -def test_recursive_typeddict() -> None: - assert transform({"bar": {"this_thing": 1}}, Foo2) == {"bar": {"this__thing": 1}} - assert transform({"bar": {"baz": {"my_baz": "foo"}}}, Foo2) == {"bar": {"Baz": {"myBaz": "foo"}}} +@parametrize +@pytest.mark.asyncio +async def test_recursive_typeddict(use_async: bool) -> None: + assert await transform({"bar": {"this_thing": 1}}, Foo2, use_async) == {"bar": {"this__thing": 1}} + assert await transform({"bar": {"baz": {"my_baz": "foo"}}}, Foo2, use_async) == {"bar": {"Baz": {"myBaz": "foo"}}} class Foo3(TypedDict): @@ -45,8 +70,10 @@ class Bar3(TypedDict): my_field: Annotated[str, PropertyInfo(alias="myField")] -def test_list_of_typeddict() -> None: - result = transform({"things": [{"my_field": "foo"}, {"my_field": "foo2"}]}, expected_type=Foo3) +@parametrize +@pytest.mark.asyncio +async def test_list_of_typeddict(use_async: bool) -> None: + result = await transform({"things": [{"my_field": "foo"}, {"my_field": "foo2"}]}, Foo3, use_async) assert result == {"things": [{"myField": "foo"}, {"myField": "foo2"}]} @@ -62,10 +89,14 @@ class Baz4(TypedDict): foo_baz: Annotated[str, PropertyInfo(alias="fooBaz")] -def test_union_of_typeddict() -> None: - assert transform({"foo": {"foo_bar": "bar"}}, Foo4) == {"foo": {"fooBar": "bar"}} - assert transform({"foo": {"foo_baz": "baz"}}, Foo4) == {"foo": {"fooBaz": "baz"}} - assert transform({"foo": {"foo_baz": "baz", "foo_bar": "bar"}}, Foo4) == {"foo": {"fooBaz": "baz", "fooBar": "bar"}} +@parametrize +@pytest.mark.asyncio +async def test_union_of_typeddict(use_async: bool) -> None: + assert await transform({"foo": {"foo_bar": "bar"}}, Foo4, use_async) == {"foo": {"fooBar": "bar"}} + assert await transform({"foo": {"foo_baz": "baz"}}, Foo4, use_async) == {"foo": {"fooBaz": "baz"}} + assert await transform({"foo": {"foo_baz": "baz", "foo_bar": "bar"}}, Foo4, use_async) == { + "foo": {"fooBaz": "baz", "fooBar": "bar"} + } class Foo5(TypedDict): @@ -80,9 +111,11 @@ class Baz5(TypedDict): foo_baz: Annotated[str, PropertyInfo(alias="fooBaz")] -def test_union_of_list() -> None: - assert transform({"foo": {"foo_bar": "bar"}}, Foo5) == {"FOO": {"fooBar": "bar"}} - assert transform( +@parametrize +@pytest.mark.asyncio +async def test_union_of_list(use_async: bool) -> None: + assert await transform({"foo": {"foo_bar": "bar"}}, Foo5, use_async) == {"FOO": {"fooBar": "bar"}} + assert await transform( { "foo": [ {"foo_baz": "baz"}, @@ -90,6 +123,7 @@ def test_union_of_list() -> None: ] }, Foo5, + use_async, ) == {"FOO": [{"fooBaz": "baz"}, {"fooBaz": "baz"}]} @@ -97,8 +131,10 @@ class Foo6(TypedDict): bar: Annotated[str, PropertyInfo(alias="Bar")] -def test_includes_unknown_keys() -> None: - assert transform({"bar": "bar", "baz_": {"FOO": 1}}, Foo6) == { +@parametrize +@pytest.mark.asyncio +async def test_includes_unknown_keys(use_async: bool) -> None: + assert await transform({"bar": "bar", "baz_": {"FOO": 1}}, Foo6, use_async) == { "Bar": "bar", "baz_": {"FOO": 1}, } @@ -113,9 +149,11 @@ class Bar7(TypedDict): foo: str -def test_ignores_invalid_input() -> None: - assert transform({"bar": ""}, Foo7) == {"bAr": ""} - assert transform({"foo": ""}, Foo7) == {"foo": ""} +@parametrize +@pytest.mark.asyncio +async def test_ignores_invalid_input(use_async: bool) -> None: + assert await transform({"bar": ""}, Foo7, use_async) == {"bAr": ""} + assert await transform({"foo": ""}, Foo7, use_async) == {"foo": ""} class DatetimeDict(TypedDict, total=False): @@ -134,52 +172,66 @@ class DateDict(TypedDict, total=False): foo: Annotated[date, PropertyInfo(format="iso8601")] -def test_iso8601_format() -> None: +@parametrize +@pytest.mark.asyncio +async def test_iso8601_format(use_async: bool) -> None: dt = datetime.fromisoformat("2023-02-23T14:16:36.337692+00:00") - assert transform({"foo": dt}, DatetimeDict) == {"foo": "2023-02-23T14:16:36.337692+00:00"} # type: ignore[comparison-overlap] + assert await transform({"foo": dt}, DatetimeDict, use_async) == {"foo": "2023-02-23T14:16:36.337692+00:00"} # type: ignore[comparison-overlap] dt = dt.replace(tzinfo=None) - assert transform({"foo": dt}, DatetimeDict) == {"foo": "2023-02-23T14:16:36.337692"} # type: ignore[comparison-overlap] + assert await transform({"foo": dt}, DatetimeDict, use_async) == {"foo": "2023-02-23T14:16:36.337692"} # type: ignore[comparison-overlap] - assert transform({"foo": None}, DateDict) == {"foo": None} # type: ignore[comparison-overlap] - assert transform({"foo": date.fromisoformat("2023-02-23")}, DateDict) == {"foo": "2023-02-23"} # type: ignore[comparison-overlap] + assert await transform({"foo": None}, DateDict, use_async) == {"foo": None} # type: ignore[comparison-overlap] + assert await transform({"foo": date.fromisoformat("2023-02-23")}, DateDict, use_async) == {"foo": "2023-02-23"} # type: ignore[comparison-overlap] -def test_optional_iso8601_format() -> None: +@parametrize +@pytest.mark.asyncio +async def test_optional_iso8601_format(use_async: bool) -> None: dt = datetime.fromisoformat("2023-02-23T14:16:36.337692+00:00") - assert transform({"bar": dt}, DatetimeDict) == {"bar": "2023-02-23T14:16:36.337692+00:00"} # type: ignore[comparison-overlap] + assert await transform({"bar": dt}, DatetimeDict, use_async) == {"bar": "2023-02-23T14:16:36.337692+00:00"} # type: ignore[comparison-overlap] - assert transform({"bar": None}, DatetimeDict) == {"bar": None} + assert await transform({"bar": None}, DatetimeDict, use_async) == {"bar": None} -def test_required_iso8601_format() -> None: +@parametrize +@pytest.mark.asyncio +async def test_required_iso8601_format(use_async: bool) -> None: dt = datetime.fromisoformat("2023-02-23T14:16:36.337692+00:00") - assert transform({"required": dt}, DatetimeDict) == {"required": "2023-02-23T14:16:36.337692+00:00"} # type: ignore[comparison-overlap] + assert await transform({"required": dt}, DatetimeDict, use_async) == { + "required": "2023-02-23T14:16:36.337692+00:00" + } # type: ignore[comparison-overlap] - assert transform({"required": None}, DatetimeDict) == {"required": None} + assert await transform({"required": None}, DatetimeDict, use_async) == {"required": None} -def test_union_datetime() -> None: +@parametrize +@pytest.mark.asyncio +async def test_union_datetime(use_async: bool) -> None: dt = datetime.fromisoformat("2023-02-23T14:16:36.337692+00:00") - assert transform({"union": dt}, DatetimeDict) == { # type: ignore[comparison-overlap] + assert await transform({"union": dt}, DatetimeDict, use_async) == { # type: ignore[comparison-overlap] "union": "2023-02-23T14:16:36.337692+00:00" } - assert transform({"union": "foo"}, DatetimeDict) == {"union": "foo"} + assert await transform({"union": "foo"}, DatetimeDict, use_async) == {"union": "foo"} -def test_nested_list_iso6801_format() -> None: +@parametrize +@pytest.mark.asyncio +async def test_nested_list_iso6801_format(use_async: bool) -> None: dt1 = datetime.fromisoformat("2023-02-23T14:16:36.337692+00:00") dt2 = parse_datetime("2022-01-15T06:34:23Z") - assert transform({"list_": [dt1, dt2]}, DatetimeDict) == { # type: ignore[comparison-overlap] + assert await transform({"list_": [dt1, dt2]}, DatetimeDict, use_async) == { # type: ignore[comparison-overlap] "list_": ["2023-02-23T14:16:36.337692+00:00", "2022-01-15T06:34:23+00:00"] } -def test_datetime_custom_format() -> None: +@parametrize +@pytest.mark.asyncio +async def test_datetime_custom_format(use_async: bool) -> None: dt = parse_datetime("2022-01-15T06:34:23Z") - result = transform(dt, Annotated[datetime, PropertyInfo(format="custom", format_template="%H")]) + result = await transform(dt, Annotated[datetime, PropertyInfo(format="custom", format_template="%H")], use_async) assert result == "06" # type: ignore[comparison-overlap] @@ -187,47 +239,59 @@ class DateDictWithRequiredAlias(TypedDict, total=False): required_prop: Required[Annotated[date, PropertyInfo(format="iso8601", alias="prop")]] -def test_datetime_with_alias() -> None: - assert transform({"required_prop": None}, DateDictWithRequiredAlias) == {"prop": None} # type: ignore[comparison-overlap] - assert transform({"required_prop": date.fromisoformat("2023-02-23")}, DateDictWithRequiredAlias) == { - "prop": "2023-02-23" - } # type: ignore[comparison-overlap] +@parametrize +@pytest.mark.asyncio +async def test_datetime_with_alias(use_async: bool) -> None: + assert await transform({"required_prop": None}, DateDictWithRequiredAlias, use_async) == {"prop": None} # type: ignore[comparison-overlap] + assert await transform( + {"required_prop": date.fromisoformat("2023-02-23")}, DateDictWithRequiredAlias, use_async + ) == {"prop": "2023-02-23"} # type: ignore[comparison-overlap] class MyModel(BaseModel): foo: str -def test_pydantic_model_to_dictionary() -> None: - assert transform(MyModel(foo="hi!"), Any) == {"foo": "hi!"} - assert transform(MyModel.construct(foo="hi!"), Any) == {"foo": "hi!"} +@parametrize +@pytest.mark.asyncio +async def test_pydantic_model_to_dictionary(use_async: bool) -> None: + assert await transform(MyModel(foo="hi!"), Any, use_async) == {"foo": "hi!"} + assert await transform(MyModel.construct(foo="hi!"), Any, use_async) == {"foo": "hi!"} -def test_pydantic_empty_model() -> None: - assert transform(MyModel.construct(), Any) == {} +@parametrize +@pytest.mark.asyncio +async def test_pydantic_empty_model(use_async: bool) -> None: + assert await transform(MyModel.construct(), Any, use_async) == {} -def test_pydantic_unknown_field() -> None: - assert transform(MyModel.construct(my_untyped_field=True), Any) == {"my_untyped_field": True} +@parametrize +@pytest.mark.asyncio +async def test_pydantic_unknown_field(use_async: bool) -> None: + assert await transform(MyModel.construct(my_untyped_field=True), Any, use_async) == {"my_untyped_field": True} -def test_pydantic_mismatched_types() -> None: +@parametrize +@pytest.mark.asyncio +async def test_pydantic_mismatched_types(use_async: bool) -> None: model = MyModel.construct(foo=True) if PYDANTIC_V2: with pytest.warns(UserWarning): - params = transform(model, Any) + params = await transform(model, Any, use_async) else: - params = transform(model, Any) + params = await transform(model, Any, use_async) assert params == {"foo": True} -def test_pydantic_mismatched_object_type() -> None: +@parametrize +@pytest.mark.asyncio +async def test_pydantic_mismatched_object_type(use_async: bool) -> None: model = MyModel.construct(foo=MyModel.construct(hello="world")) if PYDANTIC_V2: with pytest.warns(UserWarning): - params = transform(model, Any) + params = await transform(model, Any, use_async) else: - params = transform(model, Any) + params = await transform(model, Any, use_async) assert params == {"foo": {"hello": "world"}} @@ -235,10 +299,12 @@ class ModelNestedObjects(BaseModel): nested: MyModel -def test_pydantic_nested_objects() -> None: +@parametrize +@pytest.mark.asyncio +async def test_pydantic_nested_objects(use_async: bool) -> None: model = ModelNestedObjects.construct(nested={"foo": "stainless"}) assert isinstance(model.nested, MyModel) - assert transform(model, Any) == {"nested": {"foo": "stainless"}} + assert await transform(model, Any, use_async) == {"nested": {"foo": "stainless"}} class ModelWithDefaultField(BaseModel): @@ -247,24 +313,26 @@ class ModelWithDefaultField(BaseModel): with_str_default: str = "foo" -def test_pydantic_default_field() -> None: +@parametrize +@pytest.mark.asyncio +async def test_pydantic_default_field(use_async: bool) -> None: # should be excluded when defaults are used model = ModelWithDefaultField.construct() assert model.with_none_default is None assert model.with_str_default == "foo" - assert transform(model, Any) == {} + assert await transform(model, Any, use_async) == {} # should be included when the default value is explicitly given model = ModelWithDefaultField.construct(with_none_default=None, with_str_default="foo") assert model.with_none_default is None assert model.with_str_default == "foo" - assert transform(model, Any) == {"with_none_default": None, "with_str_default": "foo"} + assert await transform(model, Any, use_async) == {"with_none_default": None, "with_str_default": "foo"} # should be included when a non-default value is explicitly given model = ModelWithDefaultField.construct(with_none_default="bar", with_str_default="baz") assert model.with_none_default == "bar" assert model.with_str_default == "baz" - assert transform(model, Any) == {"with_none_default": "bar", "with_str_default": "baz"} + assert await transform(model, Any, use_async) == {"with_none_default": "bar", "with_str_default": "baz"} class TypedDictIterableUnion(TypedDict): @@ -279,21 +347,33 @@ class Baz8(TypedDict): foo_baz: Annotated[str, PropertyInfo(alias="fooBaz")] -def test_iterable_of_dictionaries() -> None: - assert transform({"foo": [{"foo_baz": "bar"}]}, TypedDictIterableUnion) == {"FOO": [{"fooBaz": "bar"}]} - assert cast(Any, transform({"foo": ({"foo_baz": "bar"},)}, TypedDictIterableUnion)) == {"FOO": [{"fooBaz": "bar"}]} +@parametrize +@pytest.mark.asyncio +async def test_iterable_of_dictionaries(use_async: bool) -> None: + assert await transform({"foo": [{"foo_baz": "bar"}]}, TypedDictIterableUnion, use_async) == { + "FOO": [{"fooBaz": "bar"}] + } + assert cast(Any, await transform({"foo": ({"foo_baz": "bar"},)}, TypedDictIterableUnion, use_async)) == { + "FOO": [{"fooBaz": "bar"}] + } def my_iter() -> Iterable[Baz8]: yield {"foo_baz": "hello"} yield {"foo_baz": "world"} - assert transform({"foo": my_iter()}, TypedDictIterableUnion) == {"FOO": [{"fooBaz": "hello"}, {"fooBaz": "world"}]} + assert await transform({"foo": my_iter()}, TypedDictIterableUnion, use_async) == { + "FOO": [{"fooBaz": "hello"}, {"fooBaz": "world"}] + } class TypedDictIterableUnionStr(TypedDict): foo: Annotated[Union[str, Iterable[Baz8]], PropertyInfo(alias="FOO")] -def test_iterable_union_str() -> None: - assert transform({"foo": "bar"}, TypedDictIterableUnionStr) == {"FOO": "bar"} - assert cast(Any, transform(iter([{"foo_baz": "bar"}]), Union[str, Iterable[Baz8]])) == [{"fooBaz": "bar"}] +@parametrize +@pytest.mark.asyncio +async def test_iterable_union_str(use_async: bool) -> None: + assert await transform({"foo": "bar"}, TypedDictIterableUnionStr, use_async) == {"FOO": "bar"} + assert cast(Any, await transform(iter([{"foo_baz": "bar"}]), Union[str, Iterable[Baz8]], use_async)) == [ + {"fooBaz": "bar"} + ] From a0caa0907c7acd1d88010d32e6b4ce65fbe144c8 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 4 Mar 2024 14:39:15 +0100 Subject: [PATCH 249/816] chore(internal): support more input types (#1211) --- src/openai/_files.py | 5 +++++ src/openai/_types.py | 2 ++ src/openai/_utils/_transform.py | 39 ++++++++++++++++++++++++++++++++- tests/sample_file.txt | 1 + tests/test_transform.py | 29 ++++++++++++++++++++++++ 5 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 tests/sample_file.txt diff --git a/src/openai/_files.py b/src/openai/_files.py index bebfb19501..ad7b668b4b 100644 --- a/src/openai/_files.py +++ b/src/openai/_files.py @@ -13,12 +13,17 @@ FileContent, RequestFiles, HttpxFileTypes, + Base64FileInput, HttpxFileContent, HttpxRequestFiles, ) from ._utils import is_tuple_t, is_mapping_t, is_sequence_t +def is_base64_file_input(obj: object) -> TypeGuard[Base64FileInput]: + return isinstance(obj, io.IOBase) or isinstance(obj, os.PathLike) + + def is_file_content(obj: object) -> TypeGuard[FileContent]: return ( isinstance(obj, bytes) or isinstance(obj, tuple) or isinstance(obj, io.IOBase) or isinstance(obj, os.PathLike) diff --git a/src/openai/_types.py b/src/openai/_types.py index b5bf8f8af0..de9b1dd48b 100644 --- a/src/openai/_types.py +++ b/src/openai/_types.py @@ -41,8 +41,10 @@ ProxiesDict = Dict["str | URL", Union[None, str, URL, Proxy]] ProxiesTypes = Union[str, Proxy, ProxiesDict] if TYPE_CHECKING: + Base64FileInput = Union[IO[bytes], PathLike[str]] FileContent = Union[IO[bytes], bytes, PathLike[str]] else: + Base64FileInput = Union[IO[bytes], PathLike] FileContent = Union[IO[bytes], bytes, PathLike] # PathLike is not subscriptable in Python 3.8. FileTypes = Union[ # file (or bytes) diff --git a/src/openai/_utils/_transform.py b/src/openai/_utils/_transform.py index 9c76930687..1bd1330c94 100644 --- a/src/openai/_utils/_transform.py +++ b/src/openai/_utils/_transform.py @@ -1,9 +1,13 @@ from __future__ import annotations +import io +import base64 +import pathlib from typing import Any, Mapping, TypeVar, cast from datetime import date, datetime from typing_extensions import Literal, get_args, override, get_type_hints +import anyio import pydantic from ._utils import ( @@ -11,6 +15,7 @@ is_mapping, is_iterable, ) +from .._files import is_base64_file_input from ._typing import ( is_list_type, is_union_type, @@ -29,7 +34,7 @@ # TODO: ensure works correctly with forward references in all cases -PropertyFormat = Literal["iso8601", "custom"] +PropertyFormat = Literal["iso8601", "base64", "custom"] class PropertyInfo: @@ -201,6 +206,22 @@ def _format_data(data: object, format_: PropertyFormat, format_template: str | N if format_ == "custom" and format_template is not None: return data.strftime(format_template) + if format_ == "base64" and is_base64_file_input(data): + binary: str | bytes | None = None + + if isinstance(data, pathlib.Path): + binary = data.read_bytes() + elif isinstance(data, io.IOBase): + binary = data.read() + + if isinstance(binary, str): # type: ignore[unreachable] + binary = binary.encode() + + if not isinstance(binary, bytes): + raise RuntimeError(f"Could not read bytes from {data}; Received {type(binary)}") + + return base64.b64encode(binary).decode("ascii") + return data @@ -323,6 +344,22 @@ async def _async_format_data(data: object, format_: PropertyFormat, format_templ if format_ == "custom" and format_template is not None: return data.strftime(format_template) + if format_ == "base64" and is_base64_file_input(data): + binary: str | bytes | None = None + + if isinstance(data, pathlib.Path): + binary = await anyio.Path(data).read_bytes() + elif isinstance(data, io.IOBase): + binary = data.read() + + if isinstance(binary, str): # type: ignore[unreachable] + binary = binary.encode() + + if not isinstance(binary, bytes): + raise RuntimeError(f"Could not read bytes from {data}; Received {type(binary)}") + + return base64.b64encode(binary).decode("ascii") + return data diff --git a/tests/sample_file.txt b/tests/sample_file.txt new file mode 100644 index 0000000000..af5626b4a1 --- /dev/null +++ b/tests/sample_file.txt @@ -0,0 +1 @@ +Hello, world! diff --git a/tests/test_transform.py b/tests/test_transform.py index 67ec4d5cc6..0d17e8a972 100644 --- a/tests/test_transform.py +++ b/tests/test_transform.py @@ -1,11 +1,14 @@ from __future__ import annotations +import io +import pathlib from typing import Any, List, Union, TypeVar, Iterable, Optional, cast from datetime import date, datetime from typing_extensions import Required, Annotated, TypedDict import pytest +from openai._types import Base64FileInput from openai._utils import ( PropertyInfo, transform as _transform, @@ -17,6 +20,8 @@ _T = TypeVar("_T") +SAMPLE_FILE_PATH = pathlib.Path(__file__).parent.joinpath("sample_file.txt") + async def transform( data: _T, @@ -377,3 +382,27 @@ async def test_iterable_union_str(use_async: bool) -> None: assert cast(Any, await transform(iter([{"foo_baz": "bar"}]), Union[str, Iterable[Baz8]], use_async)) == [ {"fooBaz": "bar"} ] + + +class TypedDictBase64Input(TypedDict): + foo: Annotated[Union[str, Base64FileInput], PropertyInfo(format="base64")] + + +@parametrize +@pytest.mark.asyncio +async def test_base64_file_input(use_async: bool) -> None: + # strings are left as-is + assert await transform({"foo": "bar"}, TypedDictBase64Input, use_async) == {"foo": "bar"} + + # pathlib.Path is automatically converted to base64 + assert await transform({"foo": SAMPLE_FILE_PATH}, TypedDictBase64Input, use_async) == { + "foo": "SGVsbG8sIHdvcmxkIQo=" + } # type: ignore[comparison-overlap] + + # io instances are automatically converted to base64 + assert await transform({"foo": io.StringIO("Hello, world!")}, TypedDictBase64Input, use_async) == { + "foo": "SGVsbG8sIHdvcmxkIQ==" + } # type: ignore[comparison-overlap] + assert await transform({"foo": io.BytesIO(b"Hello, world!")}, TypedDictBase64Input, use_async) == { + "foo": "SGVsbG8sIHdvcmxkIQ==" + } # type: ignore[comparison-overlap] From 3208335a72cb0cec8b82be5954b54856f897cb27 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 4 Mar 2024 19:17:38 +0100 Subject: [PATCH 250/816] chore(api): update docs (#1212) --- src/openai/resources/audio/speech.py | 18 ++++------ src/openai/resources/audio/transcriptions.py | 22 +++++++----- src/openai/resources/audio/translations.py | 6 ++-- src/openai/resources/chat/completions.py | 36 +++++++++---------- src/openai/resources/images.py | 18 ++++++---- src/openai/resources/moderations.py | 4 +-- .../types/audio/speech_create_params.py | 9 ++--- src/openai/types/audio/transcription.py | 1 + .../audio/transcription_create_params.py | 13 ++++--- .../types/audio/translation_create_params.py | 6 +++- src/openai/types/beta/threads/run.py | 4 +-- .../chat/chat_completion_token_logprob.py | 14 ++++++-- .../types/chat/completion_create_params.py | 6 ++-- .../types/image_create_variation_params.py | 3 +- src/openai/types/image_edit_params.py | 3 +- src/openai/types/image_generate_params.py | 3 +- src/openai/types/moderation.py | 5 +-- 17 files changed, 98 insertions(+), 73 deletions(-) diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index 6e0eb0cfdb..bf4a0245f6 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -44,7 +44,7 @@ def create( input: str, model: Union[str, Literal["tts-1", "tts-1-hd"]], voice: Literal["alloy", "echo", "fable", "onyx", "nova", "shimmer"], - response_format: Literal["mp3", "opus", "aac", "flac", "pcm", "wav"] | NotGiven = NOT_GIVEN, + response_format: Literal["mp3", "opus", "aac", "flac", "wav", "pcm"] | NotGiven = NOT_GIVEN, speed: float | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -68,11 +68,8 @@ def create( available in the [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech/voice-options). - response_format: The format to return audio in. Supported formats are `mp3`, `opus`, `aac`, - `flac`, `pcm`, and `wav`. - - The `pcm` audio format, similar to `wav` but without a header, utilizes a 24kHz - sample rate, mono channel, and 16-bit depth in signed little-endian format. + response_format: The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, + `wav`, and `pcm`. speed: The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is the default. @@ -120,7 +117,7 @@ async def create( input: str, model: Union[str, Literal["tts-1", "tts-1-hd"]], voice: Literal["alloy", "echo", "fable", "onyx", "nova", "shimmer"], - response_format: Literal["mp3", "opus", "aac", "flac", "pcm", "wav"] | NotGiven = NOT_GIVEN, + response_format: Literal["mp3", "opus", "aac", "flac", "wav", "pcm"] | NotGiven = NOT_GIVEN, speed: float | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -144,11 +141,8 @@ async def create( available in the [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech/voice-options). - response_format: The format to return audio in. Supported formats are `mp3`, `opus`, `aac`, - `flac`, `pcm`, and `wav`. - - The `pcm` audio format, similar to `wav` but without a header, utilizes a 24kHz - sample rate, mono channel, and 16-bit depth in signed little-endian format. + response_format: The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, + `wav`, and `pcm`. speed: The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is the default. diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index 720615f43f..cfd9aae909 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -60,7 +60,8 @@ def create( The audio file object (not file name) to transcribe, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. - model: ID of the model to use. Only `whisper-1` is currently available. + model: ID of the model to use. Only `whisper-1` (which is powered by our open source + Whisper V2 model) is currently available. language: The language of the input audio. Supplying the input language in [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format will @@ -80,9 +81,11 @@ def create( [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit. - timestamp_granularities: The timestamp granularities to populate for this transcription. Any of these - options: `word`, or `segment`. Note: There is no additional latency for segment - timestamps, but generating word timestamps incurs additional latency. + timestamp_granularities: The timestamp granularities to populate for this transcription. + `response_format` must be set `verbose_json` to use timestamp granularities. + Either or both of these options are supported: `word`, or `segment`. Note: There + is no additional latency for segment timestamps, but generating word timestamps + incurs additional latency. extra_headers: Send extra headers @@ -154,7 +157,8 @@ async def create( The audio file object (not file name) to transcribe, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. - model: ID of the model to use. Only `whisper-1` is currently available. + model: ID of the model to use. Only `whisper-1` (which is powered by our open source + Whisper V2 model) is currently available. language: The language of the input audio. Supplying the input language in [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format will @@ -174,9 +178,11 @@ async def create( [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit. - timestamp_granularities: The timestamp granularities to populate for this transcription. Any of these - options: `word`, or `segment`. Note: There is no additional latency for segment - timestamps, but generating word timestamps incurs additional latency. + timestamp_granularities: The timestamp granularities to populate for this transcription. + `response_format` must be set `verbose_json` to use timestamp granularities. + Either or both of these options are supported: `word`, or `segment`. Note: There + is no additional latency for segment timestamps, but generating word timestamps + incurs additional latency. extra_headers: Send extra headers diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index a189a07380..6063522237 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -57,7 +57,8 @@ def create( file: The audio file object (not file name) translate, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. - model: ID of the model to use. Only `whisper-1` is currently available. + model: ID of the model to use. Only `whisper-1` (which is powered by our open source + Whisper V2 model) is currently available. prompt: An optional text to guide the model's style or continue a previous audio segment. The @@ -138,7 +139,8 @@ async def create( file: The audio file object (not file name) translate, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. - model: ID of the model to use. Only `whisper-1` is currently available. + model: ID of the model to use. Only `whisper-1` (which is powered by our open source + Whisper V2 model) is currently available. prompt: An optional text to guide the model's style or continue a previous audio segment. The diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index a8856a989b..20ea4cffbb 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -208,9 +208,9 @@ def create( tool. Use this to provide a list of functions the model may generate JSON inputs for. - top_logprobs: An integer between 0 and 5 specifying the number of most likely tokens to return - at each token position, each with an associated log probability. `logprobs` must - be set to `true` if this parameter is used. + top_logprobs: An integer between 0 and 20 specifying the number of most likely tokens to + return at each token position, each with an associated log probability. + `logprobs` must be set to `true` if this parameter is used. top_p: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 @@ -398,9 +398,9 @@ def create( tool. Use this to provide a list of functions the model may generate JSON inputs for. - top_logprobs: An integer between 0 and 5 specifying the number of most likely tokens to return - at each token position, each with an associated log probability. `logprobs` must - be set to `true` if this parameter is used. + top_logprobs: An integer between 0 and 20 specifying the number of most likely tokens to + return at each token position, each with an associated log probability. + `logprobs` must be set to `true` if this parameter is used. top_p: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 @@ -588,9 +588,9 @@ def create( tool. Use this to provide a list of functions the model may generate JSON inputs for. - top_logprobs: An integer between 0 and 5 specifying the number of most likely tokens to return - at each token position, each with an associated log probability. `logprobs` must - be set to `true` if this parameter is used. + top_logprobs: An integer between 0 and 20 specifying the number of most likely tokens to + return at each token position, each with an associated log probability. + `logprobs` must be set to `true` if this parameter is used. top_p: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 @@ -875,9 +875,9 @@ async def create( tool. Use this to provide a list of functions the model may generate JSON inputs for. - top_logprobs: An integer between 0 and 5 specifying the number of most likely tokens to return - at each token position, each with an associated log probability. `logprobs` must - be set to `true` if this parameter is used. + top_logprobs: An integer between 0 and 20 specifying the number of most likely tokens to + return at each token position, each with an associated log probability. + `logprobs` must be set to `true` if this parameter is used. top_p: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 @@ -1065,9 +1065,9 @@ async def create( tool. Use this to provide a list of functions the model may generate JSON inputs for. - top_logprobs: An integer between 0 and 5 specifying the number of most likely tokens to return - at each token position, each with an associated log probability. `logprobs` must - be set to `true` if this parameter is used. + top_logprobs: An integer between 0 and 20 specifying the number of most likely tokens to + return at each token position, each with an associated log probability. + `logprobs` must be set to `true` if this parameter is used. top_p: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 @@ -1255,9 +1255,9 @@ async def create( tool. Use this to provide a list of functions the model may generate JSON inputs for. - top_logprobs: An integer between 0 and 5 specifying the number of most likely tokens to return - at each token position, each with an associated log probability. `logprobs` must - be set to `true` if this parameter is used. + top_logprobs: An integer between 0 and 20 specifying the number of most likely tokens to + return at each token position, each with an associated log probability. + `logprobs` must be set to `true` if this parameter is used. top_p: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py index 7a7ff1225d..f5bbdbc338 100644 --- a/src/openai/resources/images.py +++ b/src/openai/resources/images.py @@ -70,7 +70,8 @@ def create_variation( `n=1` is supported. response_format: The format in which the generated images are returned. Must be one of `url` or - `b64_json`. + `b64_json`. URLs are only valid for 60 minutes after the image has been + generated. size: The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`. @@ -151,7 +152,8 @@ def edit( n: The number of images to generate. Must be between 1 and 10. response_format: The format in which the generated images are returned. Must be one of `url` or - `b64_json`. + `b64_json`. URLs are only valid for 60 minutes after the image has been + generated. size: The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`. @@ -231,7 +233,8 @@ def generate( for `dall-e-3`. response_format: The format in which the generated images are returned. Must be one of `url` or - `b64_json`. + `b64_json`. URLs are only valid for 60 minutes after the image has been + generated. size: The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`. Must be one of `1024x1024`, `1792x1024`, or @@ -315,7 +318,8 @@ async def create_variation( `n=1` is supported. response_format: The format in which the generated images are returned. Must be one of `url` or - `b64_json`. + `b64_json`. URLs are only valid for 60 minutes after the image has been + generated. size: The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`. @@ -396,7 +400,8 @@ async def edit( n: The number of images to generate. Must be between 1 and 10. response_format: The format in which the generated images are returned. Must be one of `url` or - `b64_json`. + `b64_json`. URLs are only valid for 60 minutes after the image has been + generated. size: The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`. @@ -476,7 +481,8 @@ async def generate( for `dall-e-3`. response_format: The format in which the generated images are returned. Must be one of `url` or - `b64_json`. + `b64_json`. URLs are only valid for 60 minutes after the image has been + generated. size: The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`. Must be one of `1024x1024`, `1792x1024`, or diff --git a/src/openai/resources/moderations.py b/src/openai/resources/moderations.py index 2b9a70d562..ac5ca1b64b 100644 --- a/src/openai/resources/moderations.py +++ b/src/openai/resources/moderations.py @@ -46,7 +46,7 @@ def create( timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ModerationCreateResponse: """ - Classifies if text violates OpenAI's Content Policy + Classifies if text is potentially harmful. Args: input: The input text to classify @@ -106,7 +106,7 @@ async def create( timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ModerationCreateResponse: """ - Classifies if text violates OpenAI's Content Policy + Classifies if text is potentially harmful. Args: input: The input text to classify diff --git a/src/openai/types/audio/speech_create_params.py b/src/openai/types/audio/speech_create_params.py index 00f862272e..0078a9d03a 100644 --- a/src/openai/types/audio/speech_create_params.py +++ b/src/openai/types/audio/speech_create_params.py @@ -26,13 +26,10 @@ class SpeechCreateParams(TypedDict, total=False): [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech/voice-options). """ - response_format: Literal["mp3", "opus", "aac", "flac", "pcm", "wav"] - """The format to return audio in. + response_format: Literal["mp3", "opus", "aac", "flac", "wav", "pcm"] + """The format to audio in. - Supported formats are `mp3`, `opus`, `aac`, `flac`, `pcm`, and `wav`. - - The `pcm` audio format, similar to `wav` but without a header, utilizes a 24kHz - sample rate, mono channel, and 16-bit depth in signed little-endian format. + Supported formats are `mp3`, `opus`, `aac`, `flac`, `wav`, and `pcm`. """ speed: float diff --git a/src/openai/types/audio/transcription.py b/src/openai/types/audio/transcription.py index d2274faa0e..6532611731 100644 --- a/src/openai/types/audio/transcription.py +++ b/src/openai/types/audio/transcription.py @@ -7,3 +7,4 @@ class Transcription(BaseModel): text: str + """The transcribed text.""" diff --git a/src/openai/types/audio/transcription_create_params.py b/src/openai/types/audio/transcription_create_params.py index 5a90822144..4164a594cc 100644 --- a/src/openai/types/audio/transcription_create_params.py +++ b/src/openai/types/audio/transcription_create_params.py @@ -18,7 +18,11 @@ class TranscriptionCreateParams(TypedDict, total=False): """ model: Required[Union[str, Literal["whisper-1"]]] - """ID of the model to use. Only `whisper-1` is currently available.""" + """ID of the model to use. + + Only `whisper-1` (which is powered by our open source Whisper V2 model) is + currently available. + """ language: str """The language of the input audio. @@ -54,7 +58,8 @@ class TranscriptionCreateParams(TypedDict, total=False): timestamp_granularities: List[Literal["word", "segment"]] """The timestamp granularities to populate for this transcription. - Any of these options: `word`, or `segment`. Note: There is no additional latency - for segment timestamps, but generating word timestamps incurs additional - latency. + `response_format` must be set `verbose_json` to use timestamp granularities. + Either or both of these options are supported: `word`, or `segment`. Note: There + is no additional latency for segment timestamps, but generating word timestamps + incurs additional latency. """ diff --git a/src/openai/types/audio/translation_create_params.py b/src/openai/types/audio/translation_create_params.py index d3cb4b9e63..1ae312da49 100644 --- a/src/openai/types/audio/translation_create_params.py +++ b/src/openai/types/audio/translation_create_params.py @@ -18,7 +18,11 @@ class TranslationCreateParams(TypedDict, total=False): """ model: Required[Union[str, Literal["whisper-1"]]] - """ID of the model to use. Only `whisper-1` is currently available.""" + """ID of the model to use. + + Only `whisper-1` (which is powered by our open source Whisper V2 model) is + currently available. + """ prompt: str """An optional text to guide the model's style or continue a previous audio diff --git a/src/openai/types/beta/threads/run.py b/src/openai/types/beta/threads/run.py index 79e4f6a444..38625d3781 100644 --- a/src/openai/types/beta/threads/run.py +++ b/src/openai/types/beta/threads/run.py @@ -22,8 +22,8 @@ class LastError(BaseModel): - code: Literal["server_error", "rate_limit_exceeded"] - """One of `server_error` or `rate_limit_exceeded`.""" + code: Literal["server_error", "rate_limit_exceeded", "invalid_prompt"] + """One of `server_error`, `rate_limit_exceeded`, or `invalid_prompt`.""" message: str """A human-readable description of the error.""" diff --git a/src/openai/types/chat/chat_completion_token_logprob.py b/src/openai/types/chat/chat_completion_token_logprob.py index 728845fb33..076ffb680c 100644 --- a/src/openai/types/chat/chat_completion_token_logprob.py +++ b/src/openai/types/chat/chat_completion_token_logprob.py @@ -20,7 +20,12 @@ class TopLogprob(BaseModel): """ logprob: float - """The log probability of this token.""" + """The log probability of this token, if it is within the top 20 most likely + tokens. + + Otherwise, the value `-9999.0` is used to signify that the token is very + unlikely. + """ class ChatCompletionTokenLogprob(BaseModel): @@ -36,7 +41,12 @@ class ChatCompletionTokenLogprob(BaseModel): """ logprob: float - """The log probability of this token.""" + """The log probability of this token, if it is within the top 20 most likely + tokens. + + Otherwise, the value `-9999.0` is used to signify that the token is very + unlikely. + """ top_logprobs: List[TopLogprob] """List of the most likely tokens and their log probability, at this token diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index e02a81bc51..9afbacb874 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -195,9 +195,9 @@ class CompletionCreateParamsBase(TypedDict, total=False): top_logprobs: Optional[int] """ - An integer between 0 and 5 specifying the number of most likely tokens to return - at each token position, each with an associated log probability. `logprobs` must - be set to `true` if this parameter is used. + An integer between 0 and 20 specifying the number of most likely tokens to + return at each token position, each with an associated log probability. + `logprobs` must be set to `true` if this parameter is used. """ top_p: Optional[float] diff --git a/src/openai/types/image_create_variation_params.py b/src/openai/types/image_create_variation_params.py index 7b015fc176..5714f97fa9 100644 --- a/src/openai/types/image_create_variation_params.py +++ b/src/openai/types/image_create_variation_params.py @@ -32,7 +32,8 @@ class ImageCreateVariationParams(TypedDict, total=False): response_format: Optional[Literal["url", "b64_json"]] """The format in which the generated images are returned. - Must be one of `url` or `b64_json`. + Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the + image has been generated. """ size: Optional[Literal["256x256", "512x512", "1024x1024"]] diff --git a/src/openai/types/image_edit_params.py b/src/openai/types/image_edit_params.py index 043885cc38..751ec4fe7a 100644 --- a/src/openai/types/image_edit_params.py +++ b/src/openai/types/image_edit_params.py @@ -43,7 +43,8 @@ class ImageEditParams(TypedDict, total=False): response_format: Optional[Literal["url", "b64_json"]] """The format in which the generated images are returned. - Must be one of `url` or `b64_json`. + Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the + image has been generated. """ size: Optional[Literal["256x256", "512x512", "1024x1024"]] diff --git a/src/openai/types/image_generate_params.py b/src/openai/types/image_generate_params.py index 7eca29a7ba..3ff1b979db 100644 --- a/src/openai/types/image_generate_params.py +++ b/src/openai/types/image_generate_params.py @@ -35,7 +35,8 @@ class ImageGenerateParams(TypedDict, total=False): response_format: Optional[Literal["url", "b64_json"]] """The format in which the generated images are returned. - Must be one of `url` or `b64_json`. + Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the + image has been generated. """ size: Optional[Literal["256x256", "512x512", "1024x1024", "1792x1024", "1024x1792"]] diff --git a/src/openai/types/moderation.py b/src/openai/types/moderation.py index 09c9a6058b..1c26ec3367 100644 --- a/src/openai/types/moderation.py +++ b/src/openai/types/moderation.py @@ -114,7 +114,4 @@ class Moderation(BaseModel): """A list of the categories along with their scores as predicted by model.""" flagged: bool - """ - Whether the content violates - [OpenAI's usage policies](/policies/usage-policies). - """ + """Whether any of the below categories are flagged.""" From dae0ec80d51d4c7677d8df010471e08a1c76fac5 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 5 Mar 2024 11:35:14 +0100 Subject: [PATCH 251/816] chore(client): improve error message for invalid http_client argument (#1216) --- src/openai/_base_client.py | 10 ++++++++++ tests/test_client.py | 20 ++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index dda280f6aa..f431128eef 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -780,6 +780,11 @@ def __init__( else: timeout = DEFAULT_TIMEOUT + if http_client is not None and not isinstance(http_client, httpx.Client): # pyright: ignore[reportUnnecessaryIsInstance] + raise TypeError( + f"Invalid `http_client` argument; Expected an instance of `httpx.Client` but got {type(http_client)}" + ) + super().__init__( version=version, limits=limits, @@ -1322,6 +1327,11 @@ def __init__( else: timeout = DEFAULT_TIMEOUT + if http_client is not None and not isinstance(http_client, httpx.AsyncClient): # pyright: ignore[reportUnnecessaryIsInstance] + raise TypeError( + f"Invalid `http_client` argument; Expected an instance of `httpx.AsyncClient` but got {type(http_client)}" + ) + super().__init__( version=version, base_url=base_url, diff --git a/tests/test_client.py b/tests/test_client.py index 625b822352..a6f936da67 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -292,6 +292,16 @@ def test_http_client_timeout_option(self) -> None: timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore assert timeout == DEFAULT_TIMEOUT # our default + async def test_invalid_http_client(self) -> None: + with pytest.raises(TypeError, match="Invalid `http_client` arg"): + async with httpx.AsyncClient() as http_client: + OpenAI( + base_url=base_url, + api_key=api_key, + _strict_response_validation=True, + http_client=cast(Any, http_client), + ) + def test_default_headers_option(self) -> None: client = OpenAI( base_url=base_url, api_key=api_key, _strict_response_validation=True, default_headers={"X-Foo": "bar"} @@ -994,6 +1004,16 @@ async def test_http_client_timeout_option(self) -> None: timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore assert timeout == DEFAULT_TIMEOUT # our default + def test_invalid_http_client(self) -> None: + with pytest.raises(TypeError, match="Invalid `http_client` arg"): + with httpx.Client() as http_client: + AsyncOpenAI( + base_url=base_url, + api_key=api_key, + _strict_response_validation=True, + http_client=cast(Any, http_client), + ) + def test_default_headers_option(self) -> None: client = AsyncOpenAI( base_url=base_url, api_key=api_key, _strict_response_validation=True, default_headers={"X-Foo": "bar"} From 7ccf0a9f4e6171e6c0e66f3f90b3bccf21605f09 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 6 Mar 2024 12:59:13 +0100 Subject: [PATCH 252/816] fix(streaming): improve error messages (#1218) https://github.com/openai/openai-python/issues/1160 --- src/openai/_streaming.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/openai/_streaming.py b/src/openai/_streaming.py index 2bc8d6a14d..41ed11074f 100644 --- a/src/openai/_streaming.py +++ b/src/openai/_streaming.py @@ -65,8 +65,15 @@ def __stream__(self) -> Iterator[_T]: if sse.event is None: data = sse.json() if is_mapping(data) and data.get("error"): + message = None + error = data.get("error") + if is_mapping(error): + message = error.get("message") + if not message or not isinstance(message, str): + message = "An error occurred during streaming" + raise APIError( - message="An error occurred during streaming", + message=message, request=self.response.request, body=data["error"], ) @@ -145,8 +152,15 @@ async def __stream__(self) -> AsyncIterator[_T]: if sse.event is None: data = sse.json() if is_mapping(data) and data.get("error"): + message = None + error = data.get("error") + if is_mapping(error): + message = error.get("message") + if not message or not isinstance(message, str): + message = "An error occurred during streaming" + raise APIError( - message="An error occurred during streaming", + message=message, request=self.response.request, body=data["error"], ) From ff8154f8308256254d5940b1d87b3bf6e9407d39 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 6 Mar 2024 22:03:07 +0100 Subject: [PATCH 253/816] chore(internal): add core support for deserializing into number response (#1219) --- src/openai/_legacy_response.py | 8 ++++++++ src/openai/_response.py | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/src/openai/_legacy_response.py b/src/openai/_legacy_response.py index 6eaa691d9f..7285053409 100644 --- a/src/openai/_legacy_response.py +++ b/src/openai/_legacy_response.py @@ -107,6 +107,8 @@ class MyModel(BaseModel): - `list` - `Union` - `str` + - `int` + - `float` - `httpx.Response` """ cache_key = to if to is not None else self._cast_to @@ -220,6 +222,12 @@ def _parse(self, *, to: type[_T] | None = None) -> R | _T: if cast_to == str: return cast(R, response.text) + if cast_to == int: + return cast(R, int(response.text)) + + if cast_to == float: + return cast(R, float(response.text)) + origin = get_origin(cast_to) or cast_to if inspect.isclass(origin) and issubclass(origin, HttpxBinaryResponseContent): diff --git a/src/openai/_response.py b/src/openai/_response.py index b1e070122f..0eaf9778b7 100644 --- a/src/openai/_response.py +++ b/src/openai/_response.py @@ -172,6 +172,12 @@ def _parse(self, *, to: type[_T] | None = None) -> R | _T: if cast_to == bytes: return cast(R, response.content) + if cast_to == int: + return cast(R, int(response.text)) + + if cast_to == float: + return cast(R, float(response.text)) + origin = get_origin(cast_to) or cast_to # handle the legacy binary response case @@ -277,6 +283,8 @@ class MyModel(BaseModel): - `list` - `Union` - `str` + - `int` + - `float` - `httpx.Response` """ cache_key = to if to is not None else self._cast_to From 6147fbe01920f21102394429288a860a9de604e4 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 8 Mar 2024 11:11:50 +0100 Subject: [PATCH 254/816] chore(internal): bump pyright (#1221) --- requirements-dev.lock | 4 ++-- src/openai/_legacy_response.py | 4 ++-- src/openai/_response.py | 16 ++++++++-------- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/requirements-dev.lock b/requirements-dev.lock index fa95964d07..0392de573f 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -17,7 +17,7 @@ argcomplete==3.1.2 # via nox attrs==23.1.0 # via pytest -azure-core==1.30.0 +azure-core==1.30.1 # via azure-identity azure-identity==1.15.0 certifi==2023.7.22 @@ -96,7 +96,7 @@ pydantic-core==2.10.1 # via pydantic pyjwt==2.8.0 # via msal -pyright==1.1.351 +pyright==1.1.353 pytest==7.1.1 # via pytest-asyncio pytest-asyncio==0.21.1 diff --git a/src/openai/_legacy_response.py b/src/openai/_legacy_response.py index 7285053409..1a08144480 100644 --- a/src/openai/_legacy_response.py +++ b/src/openai/_legacy_response.py @@ -315,7 +315,7 @@ def to_raw_response_wrapper(func: Callable[P, R]) -> Callable[P, LegacyAPIRespon @functools.wraps(func) def wrapped(*args: P.args, **kwargs: P.kwargs) -> LegacyAPIResponse[R]: - extra_headers = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})} extra_headers[RAW_RESPONSE_HEADER] = "true" kwargs["extra_headers"] = extra_headers @@ -332,7 +332,7 @@ def async_to_raw_response_wrapper(func: Callable[P, Awaitable[R]]) -> Callable[P @functools.wraps(func) async def wrapped(*args: P.args, **kwargs: P.kwargs) -> LegacyAPIResponse[R]: - extra_headers = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})} extra_headers[RAW_RESPONSE_HEADER] = "true" kwargs["extra_headers"] = extra_headers diff --git a/src/openai/_response.py b/src/openai/_response.py index 0eaf9778b7..f684b08c23 100644 --- a/src/openai/_response.py +++ b/src/openai/_response.py @@ -634,7 +634,7 @@ def to_streamed_response_wrapper(func: Callable[P, R]) -> Callable[P, ResponseCo @functools.wraps(func) def wrapped(*args: P.args, **kwargs: P.kwargs) -> ResponseContextManager[APIResponse[R]]: - extra_headers = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})} extra_headers[RAW_RESPONSE_HEADER] = "stream" kwargs["extra_headers"] = extra_headers @@ -655,7 +655,7 @@ def async_to_streamed_response_wrapper( @functools.wraps(func) def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncResponseContextManager[AsyncAPIResponse[R]]: - extra_headers = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})} extra_headers[RAW_RESPONSE_HEADER] = "stream" kwargs["extra_headers"] = extra_headers @@ -679,7 +679,7 @@ def to_custom_streamed_response_wrapper( @functools.wraps(func) def wrapped(*args: P.args, **kwargs: P.kwargs) -> ResponseContextManager[_APIResponseT]: - extra_headers = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})} extra_headers[RAW_RESPONSE_HEADER] = "stream" extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls @@ -704,7 +704,7 @@ def async_to_custom_streamed_response_wrapper( @functools.wraps(func) def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncResponseContextManager[_AsyncAPIResponseT]: - extra_headers = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})} extra_headers[RAW_RESPONSE_HEADER] = "stream" extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls @@ -724,7 +724,7 @@ def to_raw_response_wrapper(func: Callable[P, R]) -> Callable[P, APIResponse[R]] @functools.wraps(func) def wrapped(*args: P.args, **kwargs: P.kwargs) -> APIResponse[R]: - extra_headers = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})} extra_headers[RAW_RESPONSE_HEADER] = "raw" kwargs["extra_headers"] = extra_headers @@ -741,7 +741,7 @@ def async_to_raw_response_wrapper(func: Callable[P, Awaitable[R]]) -> Callable[P @functools.wraps(func) async def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncAPIResponse[R]: - extra_headers = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})} extra_headers[RAW_RESPONSE_HEADER] = "raw" kwargs["extra_headers"] = extra_headers @@ -763,7 +763,7 @@ def to_custom_raw_response_wrapper( @functools.wraps(func) def wrapped(*args: P.args, **kwargs: P.kwargs) -> _APIResponseT: - extra_headers = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})} extra_headers[RAW_RESPONSE_HEADER] = "raw" extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls @@ -786,7 +786,7 @@ def async_to_custom_raw_response_wrapper( @functools.wraps(func) def wrapped(*args: P.args, **kwargs: P.kwargs) -> Awaitable[_AsyncAPIResponseT]: - extra_headers = {**(cast(Any, kwargs.get("extra_headers")) or {})} + extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})} extra_headers[RAW_RESPONSE_HEADER] = "raw" extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls From 49cab6f25e0c815d43d5c111b5c140f4517c6721 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 8 Mar 2024 15:23:35 +0100 Subject: [PATCH 255/816] chore(internal): support parsing Annotated types (#1222) --- src/openai/_legacy_response.py | 11 +++++++++- src/openai/_models.py | 14 ++++++++++++- src/openai/_response.py | 11 +++++++++- tests/test_legacy_response.py | 19 +++++++++++++++++ tests/test_models.py | 16 +++++++++++++-- tests/test_response.py | 37 +++++++++++++++++++++++++++++++++- tests/utils.py | 6 ++++++ 7 files changed, 108 insertions(+), 6 deletions(-) diff --git a/src/openai/_legacy_response.py b/src/openai/_legacy_response.py index 1a08144480..4585cd7423 100644 --- a/src/openai/_legacy_response.py +++ b/src/openai/_legacy_response.py @@ -13,7 +13,7 @@ import pydantic from ._types import NoneType -from ._utils import is_given +from ._utils import is_given, extract_type_arg, is_annotated_type from ._models import BaseModel, is_basemodel from ._constants import RAW_RESPONSE_HEADER from ._streaming import Stream, AsyncStream, is_stream_class_type, extract_stream_chunk_type @@ -174,6 +174,10 @@ def elapsed(self) -> datetime.timedelta: return self.http_response.elapsed def _parse(self, *, to: type[_T] | None = None) -> R | _T: + # unwrap `Annotated[T, ...]` -> `T` + if to and is_annotated_type(to): + to = extract_type_arg(to, 0) + if self._stream: if to: if not is_stream_class_type(to): @@ -215,6 +219,11 @@ def _parse(self, *, to: type[_T] | None = None) -> R | _T: ) cast_to = to if to is not None else self._cast_to + + # unwrap `Annotated[T, ...]` -> `T` + if is_annotated_type(cast_to): + cast_to = extract_type_arg(cast_to, 0) + if cast_to is NoneType: return cast(R, None) diff --git a/src/openai/_models.py b/src/openai/_models.py index 810891497a..af68e6181a 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -30,7 +30,16 @@ AnyMapping, HttpxRequestFiles, ) -from ._utils import is_list, is_given, is_mapping, parse_date, parse_datetime, strip_not_given +from ._utils import ( + is_list, + is_given, + is_mapping, + parse_date, + parse_datetime, + strip_not_given, + extract_type_arg, + is_annotated_type, +) from ._compat import ( PYDANTIC_V2, ConfigDict, @@ -275,6 +284,9 @@ def construct_type(*, value: object, type_: type) -> object: If the given value does not match the expected type then it is returned as-is. """ + # unwrap `Annotated[T, ...]` -> `T` + if is_annotated_type(type_): + type_ = extract_type_arg(type_, 0) # we need to use the origin class for any types that are subscripted generics # e.g. Dict[str, object] diff --git a/src/openai/_response.py b/src/openai/_response.py index f684b08c23..47f484ef7a 100644 --- a/src/openai/_response.py +++ b/src/openai/_response.py @@ -25,7 +25,7 @@ import pydantic from ._types import NoneType -from ._utils import is_given, extract_type_var_from_base +from ._utils import is_given, extract_type_arg, is_annotated_type, extract_type_var_from_base from ._models import BaseModel, is_basemodel from ._constants import RAW_RESPONSE_HEADER, OVERRIDE_CAST_TO_HEADER from ._streaming import Stream, AsyncStream, is_stream_class_type, extract_stream_chunk_type @@ -121,6 +121,10 @@ def __repr__(self) -> str: ) def _parse(self, *, to: type[_T] | None = None) -> R | _T: + # unwrap `Annotated[T, ...]` -> `T` + if to and is_annotated_type(to): + to = extract_type_arg(to, 0) + if self._is_sse_stream: if to: if not is_stream_class_type(to): @@ -162,6 +166,11 @@ def _parse(self, *, to: type[_T] | None = None) -> R | _T: ) cast_to = to if to is not None else self._cast_to + + # unwrap `Annotated[T, ...]` -> `T` + if is_annotated_type(cast_to): + cast_to = extract_type_arg(cast_to, 0) + if cast_to is NoneType: return cast(R, None) diff --git a/tests/test_legacy_response.py b/tests/test_legacy_response.py index 995250a58c..45025f81d0 100644 --- a/tests/test_legacy_response.py +++ b/tests/test_legacy_response.py @@ -1,4 +1,6 @@ import json +from typing import cast +from typing_extensions import Annotated import httpx import pytest @@ -63,3 +65,20 @@ def test_response_parse_custom_model(client: OpenAI) -> None: obj = response.parse(to=CustomModel) assert obj.foo == "hello!" assert obj.bar == 2 + + +def test_response_parse_annotated_type(client: OpenAI) -> None: + response = LegacyAPIResponse( + raw=httpx.Response(200, content=json.dumps({"foo": "hello!", "bar": 2})), + client=client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + obj = response.parse( + to=cast("type[CustomModel]", Annotated[CustomModel, "random metadata"]), + ) + assert obj.foo == "hello!" + assert obj.bar == 2 diff --git a/tests/test_models.py b/tests/test_models.py index 713bd2cb1b..d8a3c9ca5d 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -1,14 +1,14 @@ import json from typing import Any, Dict, List, Union, Optional, cast from datetime import datetime, timezone -from typing_extensions import Literal +from typing_extensions import Literal, Annotated import pytest import pydantic from pydantic import Field from openai._compat import PYDANTIC_V2, parse_obj, model_dump, model_json -from openai._models import BaseModel +from openai._models import BaseModel, construct_type class BasicModel(BaseModel): @@ -571,3 +571,15 @@ class OurModel(BaseModel): foo: Optional[str] = None takes_pydantic(OurModel()) + + +def test_annotated_types() -> None: + class Model(BaseModel): + value: str + + m = construct_type( + value={"value": "foo"}, + type_=cast(Any, Annotated[Model, "random metadata"]), + ) + assert isinstance(m, Model) + assert m.value == "foo" diff --git a/tests/test_response.py b/tests/test_response.py index 7c99327b46..af153b67c4 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -1,5 +1,6 @@ import json -from typing import List +from typing import List, cast +from typing_extensions import Annotated import httpx import pytest @@ -157,3 +158,37 @@ async def test_async_response_parse_custom_model(async_client: AsyncOpenAI) -> N obj = await response.parse(to=CustomModel) assert obj.foo == "hello!" assert obj.bar == 2 + + +def test_response_parse_annotated_type(client: OpenAI) -> None: + response = APIResponse( + raw=httpx.Response(200, content=json.dumps({"foo": "hello!", "bar": 2})), + client=client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + obj = response.parse( + to=cast("type[CustomModel]", Annotated[CustomModel, "random metadata"]), + ) + assert obj.foo == "hello!" + assert obj.bar == 2 + + +async def test_async_response_parse_annotated_type(async_client: AsyncOpenAI) -> None: + response = AsyncAPIResponse( + raw=httpx.Response(200, content=json.dumps({"foo": "hello!", "bar": 2})), + client=async_client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + obj = await response.parse( + to=cast("type[CustomModel]", Annotated[CustomModel, "random metadata"]), + ) + assert obj.foo == "hello!" + assert obj.bar == 2 diff --git a/tests/utils.py b/tests/utils.py index 216b333550..43c3cb5cfe 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -14,6 +14,8 @@ is_list, is_list_type, is_union_type, + extract_type_arg, + is_annotated_type, ) from openai._compat import PYDANTIC_V2, field_outer_type, get_model_fields from openai._models import BaseModel @@ -49,6 +51,10 @@ def assert_matches_type( path: list[str], allow_none: bool = False, ) -> None: + # unwrap `Annotated[T, ...]` -> `T` + if is_annotated_type(type_): + type_ = extract_type_arg(type_, 0) + if allow_none and value is None: return From b3e37c8d4ff4feb608998bb2ab3378380c8d890f Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 8 Mar 2024 16:48:04 +0100 Subject: [PATCH 256/816] chore: export NOT_GIVEN sentinel value (#1223) --- src/openai/__init__.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/openai/__init__.py b/src/openai/__init__.py index 118fe8ee93..1037e3cdd5 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -6,7 +6,7 @@ from typing_extensions import override from . import types -from ._types import NoneType, Transport, ProxiesTypes +from ._types import NOT_GIVEN, NoneType, NotGiven, Transport, ProxiesTypes from ._utils import file_from_path from ._client import Client, OpenAI, Stream, Timeout, Transport, AsyncClient, AsyncOpenAI, AsyncStream, RequestOptions from ._models import BaseModel @@ -37,6 +37,8 @@ "NoneType", "Transport", "ProxiesTypes", + "NotGiven", + "NOT_GIVEN", "OpenAIError", "APIError", "APIStatusError", From 0f0aec55cf76610467ba2c8e6627ee19f19413ce Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 11 Mar 2024 14:28:46 +0100 Subject: [PATCH 257/816] chore(internal): improve deserialisation of discriminated unions (#1227) --- src/openai/_models.py | 160 +++++++++++++++++++++++++++- src/openai/_utils/_transform.py | 5 +- tests/test_models.py | 180 ++++++++++++++++++++++++++++++++ 3 files changed, 343 insertions(+), 2 deletions(-) diff --git a/src/openai/_models.py b/src/openai/_models.py index af68e6181a..88afa40810 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -10,6 +10,7 @@ Protocol, Required, TypedDict, + TypeGuard, final, override, runtime_checkable, @@ -31,6 +32,7 @@ HttpxRequestFiles, ) from ._utils import ( + PropertyInfo, is_list, is_given, is_mapping, @@ -39,6 +41,7 @@ strip_not_given, extract_type_arg, is_annotated_type, + strip_annotated_type, ) from ._compat import ( PYDANTIC_V2, @@ -55,6 +58,9 @@ ) from ._constants import RAW_RESPONSE_HEADER +if TYPE_CHECKING: + from pydantic_core.core_schema import ModelField, ModelFieldsSchema + __all__ = ["BaseModel", "GenericModel"] _T = TypeVar("_T") @@ -268,7 +274,6 @@ def _construct_field(value: object, field: FieldInfo, key: str) -> object: def is_basemodel(type_: type) -> bool: """Returns whether or not the given type is either a `BaseModel` or a union of `BaseModel`""" - origin = get_origin(type_) or type_ if is_union(type_): for variant in get_args(type_): if is_basemodel(variant): @@ -276,6 +281,11 @@ def is_basemodel(type_: type) -> bool: return False + return is_basemodel_type(type_) + + +def is_basemodel_type(type_: type) -> TypeGuard[type[BaseModel] | type[GenericModel]]: + origin = get_origin(type_) or type_ return issubclass(origin, BaseModel) or issubclass(origin, GenericModel) @@ -286,7 +296,10 @@ def construct_type(*, value: object, type_: type) -> object: """ # unwrap `Annotated[T, ...]` -> `T` if is_annotated_type(type_): + meta = get_args(type_)[1:] type_ = extract_type_arg(type_, 0) + else: + meta = tuple() # we need to use the origin class for any types that are subscripted generics # e.g. Dict[str, object] @@ -299,6 +312,28 @@ def construct_type(*, value: object, type_: type) -> object: except Exception: pass + # if the type is a discriminated union then we want to construct the right variant + # in the union, even if the data doesn't match exactly, otherwise we'd break code + # that relies on the constructed class types, e.g. + # + # class FooType: + # kind: Literal['foo'] + # value: str + # + # class BarType: + # kind: Literal['bar'] + # value: int + # + # without this block, if the data we get is something like `{'kind': 'bar', 'value': 'foo'}` then + # we'd end up constructing `FooType` when it should be `BarType`. + discriminator = _build_discriminated_union_meta(union=type_, meta_annotations=meta) + if discriminator and is_mapping(value): + variant_value = value.get(discriminator.field_alias_from or discriminator.field_name) + if variant_value and isinstance(variant_value, str): + variant_type = discriminator.mapping.get(variant_value) + if variant_type: + return construct_type(type_=variant_type, value=value) + # if the data is not valid, use the first variant that doesn't fail while deserializing for variant in args: try: @@ -356,6 +391,129 @@ def construct_type(*, value: object, type_: type) -> object: return value +@runtime_checkable +class CachedDiscriminatorType(Protocol): + __discriminator__: DiscriminatorDetails + + +class DiscriminatorDetails: + field_name: str + """The name of the discriminator field in the variant class, e.g. + + ```py + class Foo(BaseModel): + type: Literal['foo'] + ``` + + Will result in field_name='type' + """ + + field_alias_from: str | None + """The name of the discriminator field in the API response, e.g. + + ```py + class Foo(BaseModel): + type: Literal['foo'] = Field(alias='type_from_api') + ``` + + Will result in field_alias_from='type_from_api' + """ + + mapping: dict[str, type] + """Mapping of discriminator value to variant type, e.g. + + {'foo': FooVariant, 'bar': BarVariant} + """ + + def __init__( + self, + *, + mapping: dict[str, type], + discriminator_field: str, + discriminator_alias: str | None, + ) -> None: + self.mapping = mapping + self.field_name = discriminator_field + self.field_alias_from = discriminator_alias + + +def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any, ...]) -> DiscriminatorDetails | None: + if isinstance(union, CachedDiscriminatorType): + return union.__discriminator__ + + discriminator_field_name: str | None = None + + for annotation in meta_annotations: + if isinstance(annotation, PropertyInfo) and annotation.discriminator is not None: + discriminator_field_name = annotation.discriminator + break + + if not discriminator_field_name: + return None + + mapping: dict[str, type] = {} + discriminator_alias: str | None = None + + for variant in get_args(union): + variant = strip_annotated_type(variant) + if is_basemodel_type(variant): + if PYDANTIC_V2: + field = _extract_field_schema_pv2(variant, discriminator_field_name) + if not field: + continue + + # Note: if one variant defines an alias then they all should + discriminator_alias = field.get("serialization_alias") + + field_schema = field["schema"] + + if field_schema["type"] == "literal": + for entry in field_schema["expected"]: + if isinstance(entry, str): + mapping[entry] = variant + else: + field_info = cast("dict[str, FieldInfo]", variant.__fields__).get(discriminator_field_name) # pyright: ignore[reportDeprecated, reportUnnecessaryCast] + if not field_info: + continue + + # Note: if one variant defines an alias then they all should + discriminator_alias = field_info.alias + + if field_info.annotation and is_literal_type(field_info.annotation): + for entry in get_args(field_info.annotation): + if isinstance(entry, str): + mapping[entry] = variant + + if not mapping: + return None + + details = DiscriminatorDetails( + mapping=mapping, + discriminator_field=discriminator_field_name, + discriminator_alias=discriminator_alias, + ) + cast(CachedDiscriminatorType, union).__discriminator__ = details + return details + + +def _extract_field_schema_pv2(model: type[BaseModel], field_name: str) -> ModelField | None: + schema = model.__pydantic_core_schema__ + if schema["type"] != "model": + return None + + fields_schema = schema["schema"] + if fields_schema["type"] != "model-fields": + return None + + fields_schema = cast("ModelFieldsSchema", fields_schema) + + field = fields_schema["fields"].get(field_name) + if not field: + return None + + return cast("ModelField", field) # pyright: ignore[reportUnnecessaryCast] + + def validate_type(*, type_: type[_T], value: object) -> _T: """Strict validation that the given value matches the expected type""" if inspect.isclass(type_) and issubclass(type_, pydantic.BaseModel): diff --git a/src/openai/_utils/_transform.py b/src/openai/_utils/_transform.py index 1bd1330c94..47e262a515 100644 --- a/src/openai/_utils/_transform.py +++ b/src/openai/_utils/_transform.py @@ -51,6 +51,7 @@ class MyParams(TypedDict): alias: str | None format: PropertyFormat | None format_template: str | None + discriminator: str | None def __init__( self, @@ -58,14 +59,16 @@ def __init__( alias: str | None = None, format: PropertyFormat | None = None, format_template: str | None = None, + discriminator: str | None = None, ) -> None: self.alias = alias self.format = format self.format_template = format_template + self.discriminator = discriminator @override def __repr__(self) -> str: - return f"{self.__class__.__name__}(alias='{self.alias}', format={self.format}, format_template='{self.format_template}')" + return f"{self.__class__.__name__}(alias='{self.alias}', format={self.format}, format_template='{self.format_template}', discriminator='{self.discriminator}')" def maybe_transform( diff --git a/tests/test_models.py b/tests/test_models.py index d8a3c9ca5d..d003d32181 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -7,6 +7,7 @@ import pydantic from pydantic import Field +from openai._utils import PropertyInfo from openai._compat import PYDANTIC_V2, parse_obj, model_dump, model_json from openai._models import BaseModel, construct_type @@ -583,3 +584,182 @@ class Model(BaseModel): ) assert isinstance(m, Model) assert m.value == "foo" + + +def test_discriminated_unions_invalid_data() -> None: + class A(BaseModel): + type: Literal["a"] + + data: str + + class B(BaseModel): + type: Literal["b"] + + data: int + + m = construct_type( + value={"type": "b", "data": "foo"}, + type_=cast(Any, Annotated[Union[A, B], PropertyInfo(discriminator="type")]), + ) + assert isinstance(m, B) + assert m.type == "b" + assert m.data == "foo" # type: ignore[comparison-overlap] + + m = construct_type( + value={"type": "a", "data": 100}, + type_=cast(Any, Annotated[Union[A, B], PropertyInfo(discriminator="type")]), + ) + assert isinstance(m, A) + assert m.type == "a" + if PYDANTIC_V2: + assert m.data == 100 # type: ignore[comparison-overlap] + else: + # pydantic v1 automatically converts inputs to strings + # if the expected type is a str + assert m.data == "100" + + +def test_discriminated_unions_unknown_variant() -> None: + class A(BaseModel): + type: Literal["a"] + + data: str + + class B(BaseModel): + type: Literal["b"] + + data: int + + m = construct_type( + value={"type": "c", "data": None, "new_thing": "bar"}, + type_=cast(Any, Annotated[Union[A, B], PropertyInfo(discriminator="type")]), + ) + + # just chooses the first variant + assert isinstance(m, A) + assert m.type == "c" # type: ignore[comparison-overlap] + assert m.data == None # type: ignore[unreachable] + assert m.new_thing == "bar" + + +def test_discriminated_unions_invalid_data_nested_unions() -> None: + class A(BaseModel): + type: Literal["a"] + + data: str + + class B(BaseModel): + type: Literal["b"] + + data: int + + class C(BaseModel): + type: Literal["c"] + + data: bool + + m = construct_type( + value={"type": "b", "data": "foo"}, + type_=cast(Any, Annotated[Union[Union[A, B], C], PropertyInfo(discriminator="type")]), + ) + assert isinstance(m, B) + assert m.type == "b" + assert m.data == "foo" # type: ignore[comparison-overlap] + + m = construct_type( + value={"type": "c", "data": "foo"}, + type_=cast(Any, Annotated[Union[Union[A, B], C], PropertyInfo(discriminator="type")]), + ) + assert isinstance(m, C) + assert m.type == "c" + assert m.data == "foo" # type: ignore[comparison-overlap] + + +def test_discriminated_unions_with_aliases_invalid_data() -> None: + class A(BaseModel): + foo_type: Literal["a"] = Field(alias="type") + + data: str + + class B(BaseModel): + foo_type: Literal["b"] = Field(alias="type") + + data: int + + m = construct_type( + value={"type": "b", "data": "foo"}, + type_=cast(Any, Annotated[Union[A, B], PropertyInfo(discriminator="foo_type")]), + ) + assert isinstance(m, B) + assert m.foo_type == "b" + assert m.data == "foo" # type: ignore[comparison-overlap] + + m = construct_type( + value={"type": "a", "data": 100}, + type_=cast(Any, Annotated[Union[A, B], PropertyInfo(discriminator="foo_type")]), + ) + assert isinstance(m, A) + assert m.foo_type == "a" + if PYDANTIC_V2: + assert m.data == 100 # type: ignore[comparison-overlap] + else: + # pydantic v1 automatically converts inputs to strings + # if the expected type is a str + assert m.data == "100" + + +def test_discriminated_unions_overlapping_discriminators_invalid_data() -> None: + class A(BaseModel): + type: Literal["a"] + + data: bool + + class B(BaseModel): + type: Literal["a"] + + data: int + + m = construct_type( + value={"type": "a", "data": "foo"}, + type_=cast(Any, Annotated[Union[A, B], PropertyInfo(discriminator="type")]), + ) + assert isinstance(m, B) + assert m.type == "a" + assert m.data == "foo" # type: ignore[comparison-overlap] + + +def test_discriminated_unions_invalid_data_uses_cache() -> None: + class A(BaseModel): + type: Literal["a"] + + data: str + + class B(BaseModel): + type: Literal["b"] + + data: int + + UnionType = cast(Any, Union[A, B]) + + assert not hasattr(UnionType, "__discriminator__") + + m = construct_type( + value={"type": "b", "data": "foo"}, type_=cast(Any, Annotated[UnionType, PropertyInfo(discriminator="type")]) + ) + assert isinstance(m, B) + assert m.type == "b" + assert m.data == "foo" # type: ignore[comparison-overlap] + + discriminator = UnionType.__discriminator__ + assert discriminator is not None + + m = construct_type( + value={"type": "b", "data": "foo"}, type_=cast(Any, Annotated[UnionType, PropertyInfo(discriminator="type")]) + ) + assert isinstance(m, B) + assert m.type == "b" + assert m.data == "foo" # type: ignore[comparison-overlap] + + # if the discriminator details object stays the same between invocations then + # we hit the cache + assert UnionType.__discriminator__ is discriminator From b54ab2f86fd19a5b5861f87941b4a9de57bf6c7a Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 12 Mar 2024 18:25:10 +0100 Subject: [PATCH 258/816] chore(types): include discriminators in unions (#1228) --- src/openai/types/beta/assistant.py | 5 +++-- src/openai/types/beta/threads/message_content_text.py | 7 +++++-- src/openai/types/beta/threads/runs/code_tool_call.py | 7 +++++-- src/openai/types/beta/threads/runs/run_step.py | 5 +++-- .../types/beta/threads/runs/tool_calls_step_details.py | 5 +++-- src/openai/types/beta/threads/thread_message.py | 5 +++-- 6 files changed, 22 insertions(+), 12 deletions(-) diff --git a/src/openai/types/beta/assistant.py b/src/openai/types/beta/assistant.py index 7a29984b50..7ba50652aa 100644 --- a/src/openai/types/beta/assistant.py +++ b/src/openai/types/beta/assistant.py @@ -1,9 +1,10 @@ # File generated from our OpenAPI spec by Stainless. from typing import List, Union, Optional -from typing_extensions import Literal +from typing_extensions import Literal, Annotated from ..shared import FunctionDefinition +from ..._utils import PropertyInfo from ..._models import BaseModel __all__ = ["Assistant", "Tool", "ToolCodeInterpreter", "ToolRetrieval", "ToolFunction"] @@ -26,7 +27,7 @@ class ToolFunction(BaseModel): """The type of tool being defined: `function`""" -Tool = Union[ToolCodeInterpreter, ToolRetrieval, ToolFunction] +Tool = Annotated[Union[ToolCodeInterpreter, ToolRetrieval, ToolFunction], PropertyInfo(discriminator="type")] class Assistant(BaseModel): diff --git a/src/openai/types/beta/threads/message_content_text.py b/src/openai/types/beta/threads/message_content_text.py index b529a384c6..dd05ff96ca 100644 --- a/src/openai/types/beta/threads/message_content_text.py +++ b/src/openai/types/beta/threads/message_content_text.py @@ -1,8 +1,9 @@ # File generated from our OpenAPI spec by Stainless. from typing import List, Union -from typing_extensions import Literal +from typing_extensions import Literal, Annotated +from ...._utils import PropertyInfo from ...._models import BaseModel __all__ = [ @@ -57,7 +58,9 @@ class TextAnnotationFilePath(BaseModel): """Always `file_path`.""" -TextAnnotation = Union[TextAnnotationFileCitation, TextAnnotationFilePath] +TextAnnotation = Annotated[ + Union[TextAnnotationFileCitation, TextAnnotationFilePath], PropertyInfo(discriminator="type") +] class Text(BaseModel): diff --git a/src/openai/types/beta/threads/runs/code_tool_call.py b/src/openai/types/beta/threads/runs/code_tool_call.py index f808005ecb..0de47b379b 100644 --- a/src/openai/types/beta/threads/runs/code_tool_call.py +++ b/src/openai/types/beta/threads/runs/code_tool_call.py @@ -1,8 +1,9 @@ # File generated from our OpenAPI spec by Stainless. from typing import List, Union -from typing_extensions import Literal +from typing_extensions import Literal, Annotated +from ....._utils import PropertyInfo from ....._models import BaseModel __all__ = [ @@ -38,7 +39,9 @@ class CodeInterpreterOutputImage(BaseModel): """Always `image`.""" -CodeInterpreterOutput = Union[CodeInterpreterOutputLogs, CodeInterpreterOutputImage] +CodeInterpreterOutput = Annotated[ + Union[CodeInterpreterOutputLogs, CodeInterpreterOutputImage], PropertyInfo(discriminator="type") +] class CodeInterpreter(BaseModel): diff --git a/src/openai/types/beta/threads/runs/run_step.py b/src/openai/types/beta/threads/runs/run_step.py index 01aab8e9a6..899883ac2d 100644 --- a/src/openai/types/beta/threads/runs/run_step.py +++ b/src/openai/types/beta/threads/runs/run_step.py @@ -1,8 +1,9 @@ # File generated from our OpenAPI spec by Stainless. from typing import Union, Optional -from typing_extensions import Literal +from typing_extensions import Literal, Annotated +from ....._utils import PropertyInfo from ....._models import BaseModel from .tool_calls_step_details import ToolCallsStepDetails from .message_creation_step_details import MessageCreationStepDetails @@ -18,7 +19,7 @@ class LastError(BaseModel): """A human-readable description of the error.""" -StepDetails = Union[MessageCreationStepDetails, ToolCallsStepDetails] +StepDetails = Annotated[Union[MessageCreationStepDetails, ToolCallsStepDetails], PropertyInfo(discriminator="type")] class Usage(BaseModel): diff --git a/src/openai/types/beta/threads/runs/tool_calls_step_details.py b/src/openai/types/beta/threads/runs/tool_calls_step_details.py index 80eb90bf66..b1b5a72bee 100644 --- a/src/openai/types/beta/threads/runs/tool_calls_step_details.py +++ b/src/openai/types/beta/threads/runs/tool_calls_step_details.py @@ -1,8 +1,9 @@ # File generated from our OpenAPI spec by Stainless. from typing import List, Union -from typing_extensions import Literal +from typing_extensions import Literal, Annotated +from ....._utils import PropertyInfo from ....._models import BaseModel from .code_tool_call import CodeToolCall from .function_tool_call import FunctionToolCall @@ -10,7 +11,7 @@ __all__ = ["ToolCallsStepDetails", "ToolCall"] -ToolCall = Union[CodeToolCall, RetrievalToolCall, FunctionToolCall] +ToolCall = Annotated[Union[CodeToolCall, RetrievalToolCall, FunctionToolCall], PropertyInfo(discriminator="type")] class ToolCallsStepDetails(BaseModel): diff --git a/src/openai/types/beta/threads/thread_message.py b/src/openai/types/beta/threads/thread_message.py index 25b3a199f7..6ed5da1401 100644 --- a/src/openai/types/beta/threads/thread_message.py +++ b/src/openai/types/beta/threads/thread_message.py @@ -1,15 +1,16 @@ # File generated from our OpenAPI spec by Stainless. from typing import List, Union, Optional -from typing_extensions import Literal +from typing_extensions import Literal, Annotated +from ...._utils import PropertyInfo from ...._models import BaseModel from .message_content_text import MessageContentText from .message_content_image_file import MessageContentImageFile __all__ = ["ThreadMessage", "Content"] -Content = Union[MessageContentImageFile, MessageContentText] +Content = Annotated[Union[MessageContentImageFile, MessageContentText], PropertyInfo(discriminator="type")] class ThreadMessage(BaseModel): From ec104bf08587250689fcdca47ff8ab579a03960c Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 13 Mar 2024 01:03:38 -0400 Subject: [PATCH 259/816] release: 1.13.4 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 29 +++++++++++++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 32 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index c4bf1b6c04..0d3c59d336 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.13.3" + ".": "1.13.4" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 201757c90d..2c80f70cc6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,34 @@ # Changelog +## 1.13.4 (2024-03-13) + +Full Changelog: [v1.13.3...v1.13.4](https://github.com/openai/openai-python/compare/v1.13.3...v1.13.4) + +### Bug Fixes + +* **streaming:** improve error messages ([#1218](https://github.com/openai/openai-python/issues/1218)) ([4f5ff29](https://github.com/openai/openai-python/commit/4f5ff298601b5a8bfbf0a9d0c0d1329d1502a205)) + + +### Chores + +* **api:** update docs ([#1212](https://github.com/openai/openai-python/issues/1212)) ([71236e0](https://github.com/openai/openai-python/commit/71236e0de4012a249af4c1ffd95973a8ba4fa61f)) +* **client:** improve error message for invalid http_client argument ([#1216](https://github.com/openai/openai-python/issues/1216)) ([d0c928a](https://github.com/openai/openai-python/commit/d0c928abbd99020fe828350f3adfd10c638a2eed)) +* **docs:** mention install from git repo ([#1203](https://github.com/openai/openai-python/issues/1203)) ([3ab6f44](https://github.com/openai/openai-python/commit/3ab6f447ffd8d2394e58416e401e545a99ec85af)) +* export NOT_GIVEN sentinel value ([#1223](https://github.com/openai/openai-python/issues/1223)) ([8a4f76f](https://github.com/openai/openai-python/commit/8a4f76f992c66f20cd6aa070c8dc4839e4cf9f3c)) +* **internal:** add core support for deserializing into number response ([#1219](https://github.com/openai/openai-python/issues/1219)) ([004bc92](https://github.com/openai/openai-python/commit/004bc924ea579852b9266ca11aea93463cf75104)) +* **internal:** bump pyright ([#1221](https://github.com/openai/openai-python/issues/1221)) ([3c2e815](https://github.com/openai/openai-python/commit/3c2e815311ace4ff81ccd446b23ff50a4e099485)) +* **internal:** improve deserialisation of discriminated unions ([#1227](https://github.com/openai/openai-python/issues/1227)) ([4767259](https://github.com/openai/openai-python/commit/4767259d25ac135550b37b15e4c0497e5ff0330d)) +* **internal:** minor core client restructuring ([#1199](https://github.com/openai/openai-python/issues/1199)) ([4314cdc](https://github.com/openai/openai-python/commit/4314cdcd522537e6cbbd87206d5bb236f672ce05)) +* **internal:** split up transforms into sync / async ([#1210](https://github.com/openai/openai-python/issues/1210)) ([7853a83](https://github.com/openai/openai-python/commit/7853a8358864957cc183581bdf7c03810a7b2756)) +* **internal:** support more input types ([#1211](https://github.com/openai/openai-python/issues/1211)) ([d0e4baa](https://github.com/openai/openai-python/commit/d0e4baa40d32c2da0ce5ceef8e0c7193b98f2b5a)) +* **internal:** support parsing Annotated types ([#1222](https://github.com/openai/openai-python/issues/1222)) ([8598f81](https://github.com/openai/openai-python/commit/8598f81841eeab0ab00eb21fdec7e8756ffde909)) +* **types:** include discriminators in unions ([#1228](https://github.com/openai/openai-python/issues/1228)) ([3ba0dcc](https://github.com/openai/openai-python/commit/3ba0dcc19a2af0ef869c77da2805278f71ee96c2)) + + +### Documentation + +* **contributing:** improve wording ([#1201](https://github.com/openai/openai-python/issues/1201)) ([95a1e0e](https://github.com/openai/openai-python/commit/95a1e0ea8e5446c413606847ebf9e35afbc62bf9)) + ## 1.13.3 (2024-02-28) Full Changelog: [v1.13.2...v1.13.3](https://github.com/openai/openai-python/compare/v1.13.2...v1.13.3) diff --git a/pyproject.toml b/pyproject.toml index 171ede0aa4..9155a9aa22 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.13.3" +version = "1.13.4" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 503a06141f..4c59f5e629 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.13.3" # x-release-please-version +__version__ = "1.13.4" # x-release-please-version From 5429f69670e4db70f0cb7420ddb27c9bd11b9508 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 13 Mar 2024 16:35:35 -0400 Subject: [PATCH 260/816] release: 1.14.0 (#1234) * feat(assistants): add support for streaming (#1233) See the reference docs for more information: https://platform.openai.com/docs/api-reference/assistants-streaming We've also improved some of the names for the types in the assistants beta, non exhaustive list: - `CodeToolCall` -> `CodeInterpreterToolCall` - `MessageContentImageFile` -> `ImageFileContentBlock` - `MessageContentText` -> `TextContentBlock` - `ThreadMessage` -> `Message` - `ThreadMessageDeleted` -> `MessageDeleted` * release: 1.14.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 + api.md | 64 +- examples/assistant_stream.py | 33 + examples/assistant_stream_helpers.py | 78 ++ pyproject.toml | 3 +- requirements-dev.lock | 22 + src/openai/__init__.py | 4 + src/openai/_streaming.py | 38 + src/openai/_version.py | 2 +- src/openai/lib/streaming/__init__.py | 8 + src/openai/lib/streaming/_assistants.py | 1035 +++++++++++++++ .../resources/beta/assistants/assistants.py | 9 +- .../beta/threads/messages/messages.py | 38 +- .../resources/beta/threads/runs/runs.py | 1112 +++++++++++++++-- src/openai/resources/beta/threads/threads.py | 485 ++++++- src/openai/resources/chat/completions.py | 12 +- src/openai/resources/completions.py | 12 + src/openai/types/__init__.py | 6 +- src/openai/types/beta/__init__.py | 9 + src/openai/types/beta/assistant.py | 31 +- .../types/beta/assistant_create_params.py | 36 +- .../types/beta/assistant_stream_event.py | 276 ++++ src/openai/types/beta/assistant_tool.py | 13 + src/openai/types/beta/assistant_tool_param.py | 13 + .../types/beta/assistant_update_params.py | 36 +- .../types/beta/code_interpreter_tool.py | 12 + .../types/beta/code_interpreter_tool_param.py | 12 + src/openai/types/beta/function_tool.py | 15 + src/openai/types/beta/function_tool_param.py | 16 + src/openai/types/beta/retrieval_tool.py | 12 + src/openai/types/beta/retrieval_tool_param.py | 12 + .../beta/thread_create_and_run_params.py | 41 +- src/openai/types/beta/threads/__init__.py | 22 +- src/openai/types/beta/threads/annotation.py | 12 + .../types/beta/threads/annotation_delta.py | 14 + .../beta/threads/file_citation_annotation.py | 29 + .../threads/file_citation_delta_annotation.py | 33 + .../beta/threads/file_path_annotation.py | 26 + .../threads/file_path_delta_annotation.py | 30 + ...ge_content_image_file.py => image_file.py} | 11 +- .../beta/threads/image_file_content_block.py | 15 + .../types/beta/threads/image_file_delta.py | 15 + .../beta/threads/image_file_delta_block.py | 19 + .../threads/{thread_message.py => message.py} | 34 +- .../types/beta/threads/message_content.py | 12 + .../beta/threads/message_content_delta.py | 12 + .../beta/threads/message_content_text.py | 77 -- .../types/beta/threads/message_delta.py | 24 + .../types/beta/threads/message_delta_event.py | 19 + src/openai/types/beta/threads/run.py | 40 +- .../types/beta/threads/run_create_params.py | 43 +- .../threads/run_submit_tool_outputs_params.py | 34 +- .../types/beta/threads/runs/__init__.py | 13 +- .../threads/runs/code_interpreter_logs.py | 19 + .../runs/code_interpreter_output_image.py | 26 + ..._call.py => code_interpreter_tool_call.py} | 4 +- .../runs/code_interpreter_tool_call_delta.py | 44 + .../threads/runs/function_tool_call_delta.py | 41 + .../threads/runs/retrieval_tool_call_delta.py | 25 + .../types/beta/threads/runs/run_step_delta.py | 18 + .../beta/threads/runs/run_step_delta_event.py | 19 + .../runs/run_step_delta_message_delta.py | 20 + .../types/beta/threads/runs/tool_call.py | 15 + .../beta/threads/runs/tool_call_delta.py | 16 + .../threads/runs/tool_call_delta_object.py | 21 + .../threads/runs/tool_calls_step_details.py | 13 +- src/openai/types/beta/threads/text.py | 15 + .../types/beta/threads/text_content_block.py | 15 + src/openai/types/beta/threads/text_delta.py | 15 + .../types/beta/threads/text_delta_block.py | 19 + .../types/chat/completion_create_params.py | 3 +- src/openai/types/completion_create_params.py | 5 +- src/openai/types/shared/__init__.py | 1 + src/openai/types/shared/error_object.py | 17 + tests/api_resources/beta/test_threads.py | 154 ++- .../beta/threads/test_messages.py | 62 +- tests/api_resources/beta/threads/test_runs.py | 316 ++++- 78 files changed, 4454 insertions(+), 488 deletions(-) create mode 100644 examples/assistant_stream.py create mode 100644 examples/assistant_stream_helpers.py create mode 100644 src/openai/lib/streaming/__init__.py create mode 100644 src/openai/lib/streaming/_assistants.py create mode 100644 src/openai/types/beta/assistant_stream_event.py create mode 100644 src/openai/types/beta/assistant_tool.py create mode 100644 src/openai/types/beta/assistant_tool_param.py create mode 100644 src/openai/types/beta/code_interpreter_tool.py create mode 100644 src/openai/types/beta/code_interpreter_tool_param.py create mode 100644 src/openai/types/beta/function_tool.py create mode 100644 src/openai/types/beta/function_tool_param.py create mode 100644 src/openai/types/beta/retrieval_tool.py create mode 100644 src/openai/types/beta/retrieval_tool_param.py create mode 100644 src/openai/types/beta/threads/annotation.py create mode 100644 src/openai/types/beta/threads/annotation_delta.py create mode 100644 src/openai/types/beta/threads/file_citation_annotation.py create mode 100644 src/openai/types/beta/threads/file_citation_delta_annotation.py create mode 100644 src/openai/types/beta/threads/file_path_annotation.py create mode 100644 src/openai/types/beta/threads/file_path_delta_annotation.py rename src/openai/types/beta/threads/{message_content_image_file.py => image_file.py} (54%) create mode 100644 src/openai/types/beta/threads/image_file_content_block.py create mode 100644 src/openai/types/beta/threads/image_file_delta.py create mode 100644 src/openai/types/beta/threads/image_file_delta_block.py rename src/openai/types/beta/threads/{thread_message.py => message.py} (63%) create mode 100644 src/openai/types/beta/threads/message_content.py create mode 100644 src/openai/types/beta/threads/message_content_delta.py delete mode 100644 src/openai/types/beta/threads/message_content_text.py create mode 100644 src/openai/types/beta/threads/message_delta.py create mode 100644 src/openai/types/beta/threads/message_delta_event.py create mode 100644 src/openai/types/beta/threads/runs/code_interpreter_logs.py create mode 100644 src/openai/types/beta/threads/runs/code_interpreter_output_image.py rename src/openai/types/beta/threads/runs/{code_tool_call.py => code_interpreter_tool_call.py} (95%) create mode 100644 src/openai/types/beta/threads/runs/code_interpreter_tool_call_delta.py create mode 100644 src/openai/types/beta/threads/runs/function_tool_call_delta.py create mode 100644 src/openai/types/beta/threads/runs/retrieval_tool_call_delta.py create mode 100644 src/openai/types/beta/threads/runs/run_step_delta.py create mode 100644 src/openai/types/beta/threads/runs/run_step_delta_event.py create mode 100644 src/openai/types/beta/threads/runs/run_step_delta_message_delta.py create mode 100644 src/openai/types/beta/threads/runs/tool_call.py create mode 100644 src/openai/types/beta/threads/runs/tool_call_delta.py create mode 100644 src/openai/types/beta/threads/runs/tool_call_delta_object.py create mode 100644 src/openai/types/beta/threads/text.py create mode 100644 src/openai/types/beta/threads/text_content_block.py create mode 100644 src/openai/types/beta/threads/text_delta.py create mode 100644 src/openai/types/beta/threads/text_delta_block.py create mode 100644 src/openai/types/shared/error_object.py diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 0d3c59d336..e72f11310e 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.13.4" + ".": "1.14.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c80f70cc6..1f0fc7556d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.14.0 (2024-03-13) + +Full Changelog: [v1.13.4...v1.14.0](https://github.com/openai/openai-python/compare/v1.13.4...v1.14.0) + +### Features + +* **assistants:** add support for streaming ([#1233](https://github.com/openai/openai-python/issues/1233)) ([17635dc](https://github.com/openai/openai-python/commit/17635dccbeddf153f8201dbca18b44e16a1799b2)) + ## 1.13.4 (2024-03-13) Full Changelog: [v1.13.3...v1.13.4](https://github.com/openai/openai-python/compare/v1.13.3...v1.13.4) diff --git a/api.md b/api.md index 34352e6e72..29392cff13 100644 --- a/api.md +++ b/api.md @@ -1,7 +1,7 @@ # Shared Types ```python -from openai.types import FunctionDefinition, FunctionParameters +from openai.types import ErrorObject, FunctionDefinition, FunctionParameters ``` # Completions @@ -177,7 +177,19 @@ Methods: Types: ```python -from openai.types.beta import Assistant, AssistantDeleted +from openai.types.beta import ( + Assistant, + AssistantDeleted, + AssistantStreamEvent, + AssistantTool, + CodeInterpreterTool, + FunctionTool, + MessageStreamEvent, + RetrievalTool, + RunStepStreamEvent, + RunStreamEvent, + ThreadStreamEvent, +) ``` Methods: @@ -218,6 +230,7 @@ Methods: - client.beta.threads.update(thread_id, \*\*params) -> Thread - client.beta.threads.delete(thread_id) -> ThreadDeleted - client.beta.threads.create_and_run(\*\*params) -> Run +- client.beta.threads.create_and_run_stream(\*args) -> AssistantStreamManager[AssistantEventHandler] | AssistantStreamManager[AssistantEventHandlerT] ### Runs @@ -235,6 +248,8 @@ Methods: - client.beta.threads.runs.list(thread_id, \*\*params) -> SyncCursorPage[Run] - client.beta.threads.runs.cancel(run_id, \*, thread_id) -> Run - client.beta.threads.runs.submit_tool_outputs(run_id, \*, thread_id, \*\*params) -> Run +- client.beta.threads.runs.create_and_stream(\*args) -> AssistantStreamManager[AssistantEventHandler] | AssistantStreamManager[AssistantEventHandlerT] +- client.beta.threads.runs.submit_tool_outputs_stream(\*args) -> AssistantStreamManager[AssistantEventHandler] | AssistantStreamManager[AssistantEventHandlerT] #### Steps @@ -242,11 +257,22 @@ Types: ```python from openai.types.beta.threads.runs import ( - CodeToolCall, + CodeInterpreterLogs, + CodeInterpreterOutputImage, + CodeInterpreterToolCall, + CodeInterpreterToolCallDelta, FunctionToolCall, + FunctionToolCallDelta, MessageCreationStepDetails, RetrievalToolCall, + RetrievalToolCallDelta, RunStep, + RunStepDelta, + RunStepDeltaEvent, + RunStepDeltaMessageDelta, + ToolCall, + ToolCallDelta, + ToolCallDeltaObject, ToolCallsStepDetails, ) ``` @@ -262,19 +288,35 @@ Types: ```python from openai.types.beta.threads import ( - MessageContentImageFile, - MessageContentText, - ThreadMessage, - ThreadMessageDeleted, + Annotation, + AnnotationDelta, + FileCitationAnnotation, + FileCitationDeltaAnnotation, + FilePathAnnotation, + FilePathDeltaAnnotation, + ImageFile, + ImageFileContentBlock, + ImageFileDelta, + ImageFileDeltaBlock, + Message, + MessageContent, + MessageContentDelta, + MessageDeleted, + MessageDelta, + MessageDeltaEvent, + Text, + TextContentBlock, + TextDelta, + TextDeltaBlock, ) ``` Methods: -- client.beta.threads.messages.create(thread_id, \*\*params) -> ThreadMessage -- client.beta.threads.messages.retrieve(message_id, \*, thread_id) -> ThreadMessage -- client.beta.threads.messages.update(message_id, \*, thread_id, \*\*params) -> ThreadMessage -- client.beta.threads.messages.list(thread_id, \*\*params) -> SyncCursorPage[ThreadMessage] +- client.beta.threads.messages.create(thread_id, \*\*params) -> Message +- client.beta.threads.messages.retrieve(message_id, \*, thread_id) -> Message +- client.beta.threads.messages.update(message_id, \*, thread_id, \*\*params) -> Message +- client.beta.threads.messages.list(thread_id, \*\*params) -> SyncCursorPage[Message] #### Files diff --git a/examples/assistant_stream.py b/examples/assistant_stream.py new file mode 100644 index 0000000000..0465d3930f --- /dev/null +++ b/examples/assistant_stream.py @@ -0,0 +1,33 @@ +import openai + +# gets API Key from environment variable OPENAI_API_KEY +client = openai.OpenAI() + +assistant = client.beta.assistants.create( + name="Math Tutor", + instructions="You are a personal math tutor. Write and run code to answer math questions.", + tools=[{"type": "code_interpreter"}], + model="gpt-4-1106-preview", +) + +thread = client.beta.threads.create() + +message = client.beta.threads.messages.create( + thread_id=thread.id, + role="user", + content="I need to solve the equation `3x + 11 = 14`. Can you help me?", +) + +print("starting run stream") + +stream = client.beta.threads.runs.create( + thread_id=thread.id, + assistant_id=assistant.id, + instructions="Please address the user as Jane Doe. The user has a premium account.", + stream=True, +) + +for event in stream: + print(event.model_dump_json(indent=2, exclude_unset=True)) + +client.beta.assistants.delete(assistant.id) diff --git a/examples/assistant_stream_helpers.py b/examples/assistant_stream_helpers.py new file mode 100644 index 0000000000..6c2aae0b46 --- /dev/null +++ b/examples/assistant_stream_helpers.py @@ -0,0 +1,78 @@ +from __future__ import annotations + +from typing_extensions import override + +import openai +from openai import AssistantEventHandler +from openai.types.beta import AssistantStreamEvent +from openai.types.beta.threads import Text, TextDelta +from openai.types.beta.threads.runs import RunStep, RunStepDelta + + +class EventHandler(AssistantEventHandler): + @override + def on_event(self, event: AssistantStreamEvent) -> None: + if event.event == "thread.run.step.created": + details = event.data.step_details + if details.type == "tool_calls": + print("Generating code to interpret:\n\n```py") + elif event.event == "thread.message.created": + print("\nResponse:\n") + + @override + def on_text_delta(self, delta: TextDelta, snapshot: Text) -> None: + print(delta.value, end="", flush=True) + + @override + def on_run_step_done(self, run_step: RunStep) -> None: + details = run_step.step_details + if details.type == "tool_calls": + for tool in details.tool_calls: + if tool.type == "code_interpreter": + print("\n```\nExecuting code...") + + @override + def on_run_step_delta(self, delta: RunStepDelta, snapshot: RunStep) -> None: + details = delta.step_details + if details is not None and details.type == "tool_calls": + for tool in details.tool_calls or []: + if tool.type == "code_interpreter" and tool.code_interpreter and tool.code_interpreter.input: + print(tool.code_interpreter.input, end="", flush=True) + + +def main() -> None: + client = openai.OpenAI() + + assistant = client.beta.assistants.create( + name="Math Tutor", + instructions="You are a personal math tutor. Write and run code to answer math questions.", + tools=[{"type": "code_interpreter"}], + model="gpt-4-1106-preview", + ) + + try: + question = "I need to solve the equation `3x + 11 = 14`. Can you help me?" + + thread = client.beta.threads.create( + messages=[ + { + "role": "user", + "content": question, + }, + ] + ) + print(f"Question: {question}\n") + + with client.beta.threads.runs.create_and_stream( + thread_id=thread.id, + assistant_id=assistant.id, + instructions="Please address the user as Jane Doe. The user has a premium account.", + event_handler=EventHandler(), + ) as stream: + stream.until_done() + print() + finally: + client.beta.assistants.delete(assistant.id) + + +main() diff --git a/pyproject.toml b/pyproject.toml index 9155a9aa22..0856032512 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.13.4" +version = "1.14.0" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" @@ -60,6 +60,7 @@ dev-dependencies = [ "nox", "dirty-equals>=0.6.0", "importlib-metadata>=6.7.0", + "inline-snapshot >=0.7.0", "azure-identity >=1.14.1", "types-tqdm > 4", "types-pyaudio > 0" diff --git a/requirements-dev.lock b/requirements-dev.lock index 0392de573f..9d79557b3a 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -15,11 +15,15 @@ anyio==4.1.0 # via openai argcomplete==3.1.2 # via nox +asttokens==2.4.1 + # via inline-snapshot attrs==23.1.0 # via pytest azure-core==1.30.1 # via azure-identity azure-identity==1.15.0 +black==24.2.0 + # via inline-snapshot certifi==2023.7.22 # via httpcore # via httpx @@ -28,6 +32,9 @@ cffi==1.16.0 # via cryptography charset-normalizer==3.3.2 # via requests +click==8.1.7 + # via black + # via inline-snapshot colorlog==6.7.0 # via nox cryptography==42.0.5 @@ -41,6 +48,8 @@ distro==1.8.0 # via openai exceptiongroup==1.1.3 # via anyio +executing==2.0.1 + # via inline-snapshot filelock==3.12.4 # via virtualenv h11==0.14.0 @@ -57,6 +66,7 @@ idna==3.4 importlib-metadata==7.0.0 iniconfig==2.0.0 # via pytest +inline-snapshot==0.7.0 msal==1.27.0 # via azure-identity # via msal-extensions @@ -64,6 +74,7 @@ msal-extensions==1.1.0 # via azure-identity mypy==1.7.1 mypy-extensions==1.0.0 + # via black # via mypy nodeenv==1.8.0 # via pyright @@ -73,6 +84,7 @@ numpy==1.26.3 # via pandas # via pandas-stubs packaging==23.2 + # via black # via msal-extensions # via nox # via pytest @@ -80,7 +92,10 @@ pandas==2.1.4 # via openai pandas-stubs==2.1.4.231227 # via openai +pathspec==0.12.1 + # via black platformdirs==3.11.0 + # via black # via virtualenv pluggy==1.3.0 # via pytest @@ -114,6 +129,7 @@ ruff==0.1.9 setuptools==68.2.2 # via nodeenv six==1.16.0 + # via asttokens # via azure-core # via python-dateutil sniffio==1.3.0 @@ -121,7 +137,10 @@ sniffio==1.3.0 # via httpx # via openai time-machine==2.9.0 +toml==0.10.2 + # via inline-snapshot tomli==2.0.1 + # via black # via mypy # via pytest tqdm==4.66.1 @@ -129,9 +148,12 @@ tqdm==4.66.1 types-pyaudio==0.2.16.20240106 types-pytz==2024.1.0.20240203 # via pandas-stubs +types-toml==0.10.8.20240310 + # via inline-snapshot types-tqdm==4.66.0.2 typing-extensions==4.8.0 # via azure-core + # via black # via mypy # via openai # via pydantic diff --git a/src/openai/__init__.py b/src/openai/__init__.py index 1037e3cdd5..909be95c97 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -69,6 +69,10 @@ from .version import VERSION as VERSION from .lib.azure import AzureOpenAI as AzureOpenAI, AsyncAzureOpenAI as AsyncAzureOpenAI from .lib._old_api import * +from .lib.streaming import ( + AssistantEventHandler as AssistantEventHandler, + AsyncAssistantEventHandler as AsyncAssistantEventHandler, +) _setup_logging() diff --git a/src/openai/_streaming.py b/src/openai/_streaming.py index 41ed11074f..9c7cc6a573 100644 --- a/src/openai/_streaming.py +++ b/src/openai/_streaming.py @@ -80,6 +80,25 @@ def __stream__(self) -> Iterator[_T]: yield process_data(data=data, cast_to=cast_to, response=response) + else: + data = sse.json() + + if sse.event == "error" and is_mapping(data) and data.get("error"): + message = None + error = data.get("error") + if is_mapping(error): + message = error.get("message") + if not message or not isinstance(message, str): + message = "An error occurred during streaming" + + raise APIError( + message=message, + request=self.response.request, + body=data["error"], + ) + + yield process_data(data={"data": data, "event": sse.event}, cast_to=cast_to, response=response) + # Ensure the entire stream is consumed for _sse in iterator: ... @@ -167,6 +186,25 @@ async def __stream__(self) -> AsyncIterator[_T]: yield process_data(data=data, cast_to=cast_to, response=response) + else: + data = sse.json() + + if sse.event == "error" and is_mapping(data) and data.get("error"): + message = None + error = data.get("error") + if is_mapping(error): + message = error.get("message") + if not message or not isinstance(message, str): + message = "An error occurred during streaming" + + raise APIError( + message=message, + request=self.response.request, + body=data["error"], + ) + + yield process_data(data={"data": data, "event": sse.event}, cast_to=cast_to, response=response) + # Ensure the entire stream is consumed async for _sse in iterator: ... diff --git a/src/openai/_version.py b/src/openai/_version.py index 4c59f5e629..134799ff42 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.13.4" # x-release-please-version +__version__ = "1.14.0" # x-release-please-version diff --git a/src/openai/lib/streaming/__init__.py b/src/openai/lib/streaming/__init__.py new file mode 100644 index 0000000000..eb378d2561 --- /dev/null +++ b/src/openai/lib/streaming/__init__.py @@ -0,0 +1,8 @@ +from ._assistants import ( + AssistantEventHandler as AssistantEventHandler, + AssistantEventHandlerT as AssistantEventHandlerT, + AssistantStreamManager as AssistantStreamManager, + AsyncAssistantEventHandler as AsyncAssistantEventHandler, + AsyncAssistantEventHandlerT as AsyncAssistantEventHandlerT, + AsyncAssistantStreamManager as AsyncAssistantStreamManager, +) diff --git a/src/openai/lib/streaming/_assistants.py b/src/openai/lib/streaming/_assistants.py new file mode 100644 index 0000000000..03d97ec2eb --- /dev/null +++ b/src/openai/lib/streaming/_assistants.py @@ -0,0 +1,1035 @@ +from __future__ import annotations + +import asyncio +from types import TracebackType +from typing import TYPE_CHECKING, Any, Generic, TypeVar, Callable, Iterable, Iterator, cast +from typing_extensions import Awaitable, AsyncIterable, AsyncIterator, assert_never + +import httpx + +from ..._utils import is_dict, is_list, consume_sync_iterator, consume_async_iterator +from ..._models import construct_type +from ..._streaming import Stream, AsyncStream +from ...types.beta import AssistantStreamEvent +from ...types.beta.threads import ( + Run, + Text, + Message, + ImageFile, + TextDelta, + MessageDelta, + MessageContent, + MessageContentDelta, +) +from ...types.beta.threads.runs import RunStep, ToolCall, RunStepDelta, ToolCallDelta + + +class AssistantEventHandler: + text_deltas: Iterable[str] + """Iterator over just the text deltas in the stream. + + This corresponds to the `thread.message.delta` event + in the API. + + ```py + for text in stream.text_deltas: + print(text, end="", flush=True) + print() + ``` + """ + + def __init__(self) -> None: + self._current_event: AssistantStreamEvent | None = None + self._current_message_content_index: int | None = None + self._current_message_content: MessageContent | None = None + self._current_tool_call_index: int | None = None + self._current_tool_call: ToolCall | None = None + self.__current_run_step_id: str | None = None + self.__current_run: Run | None = None + self.__run_step_snapshots: dict[str, RunStep] = {} + self.__message_snapshots: dict[str, Message] = {} + self.__current_message_snapshot: Message | None = None + + self.text_deltas = self.__text_deltas__() + self._iterator = self.__stream__() + self.__stream: Stream[AssistantStreamEvent] | None = None + + def _init(self, stream: Stream[AssistantStreamEvent]) -> None: + if self.__stream: + raise RuntimeError( + "A single event handler cannot be shared between multiple streams; You will need to construct a new event handler instance" + ) + + self.__stream = stream + + def __next__(self) -> AssistantStreamEvent: + return self._iterator.__next__() + + def __iter__(self) -> Iterator[AssistantStreamEvent]: + for item in self._iterator: + yield item + + @property + def current_event(self) -> AssistantStreamEvent | None: + return self._current_event + + @property + def current_run(self) -> Run | None: + return self.__current_run + + @property + def current_run_step_snapshot(self) -> RunStep | None: + if not self.__current_run_step_id: + return None + + return self.__run_step_snapshots[self.__current_run_step_id] + + @property + def current_message_snapshot(self) -> Message | None: + return self.__current_message_snapshot + + def close(self) -> None: + """ + Close the response and release the connection. + + Automatically called when the context manager exits. + """ + if self.__stream: + self.__stream.close() + + def until_done(self) -> None: + """Waits until the stream has been consumed""" + consume_sync_iterator(self) + + def get_final_run(self) -> Run: + """Wait for the stream to finish and returns the completed Run object""" + self.until_done() + + if not self.__current_run: + raise RuntimeError("No final run object found") + + return self.__current_run + + def get_final_run_steps(self) -> list[RunStep]: + """Wait for the stream to finish and returns the steps taken in this run""" + self.until_done() + + if not self.__run_step_snapshots: + raise RuntimeError("No run steps found") + + return [step for step in self.__run_step_snapshots.values()] + + def get_final_messages(self) -> list[Message]: + """Wait for the stream to finish and returns the messages emitted in this run""" + self.until_done() + + if not self.__message_snapshots: + raise RuntimeError("No messages found") + + return [message for message in self.__message_snapshots.values()] + + def __text_deltas__(self) -> Iterator[str]: + for event in self: + if event.event != "thread.message.delta": + continue + + for content_delta in event.data.delta.content or []: + if content_delta.type == "text" and content_delta.text and content_delta.text.value: + yield content_delta.text.value + + # event handlers + + def on_end(self) -> None: + """Fires when the stream has finished. + + This happens if the stream is read to completion + or if an exception occurs during iteration. + """ + + def on_event(self, event: AssistantStreamEvent) -> None: + """Callback that is fired for every Server-Sent-Event""" + + def on_run_step_created(self, run_step: RunStep) -> None: + """Callback that is fired when a run step is created""" + + def on_run_step_delta(self, delta: RunStepDelta, snapshot: RunStep) -> None: + """Callback that is fired whenever a run step delta is returned from the API + + The first argument is just the delta as sent by the API and the second argument + is the accumulated snapshot of the run step. For example, a tool calls event may + look like this: + + # delta + tool_calls=[ + RunStepDeltaToolCallsCodeInterpreter( + index=0, + type='code_interpreter', + id=None, + code_interpreter=CodeInterpreter(input=' sympy', outputs=None) + ) + ] + # snapshot + tool_calls=[ + CodeToolCall( + id='call_wKayJlcYV12NiadiZuJXxcfx', + code_interpreter=CodeInterpreter(input='from sympy', outputs=[]), + type='code_interpreter', + index=0 + ) + ], + """ + + def on_run_step_done(self, run_step: RunStep) -> None: + """Callback that is fired when a run step is completed""" + + def on_tool_call_created(self, tool_call: ToolCall) -> None: + """Callback that is fired when a tool call is created""" + + def on_tool_call_delta(self, delta: ToolCallDelta, snapshot: ToolCall) -> None: + """Callback that is fired when a tool call delta is encountered""" + + def on_tool_call_done(self, tool_call: ToolCall) -> None: + """Callback that is fired when a tool call delta is encountered""" + + def on_exception(self, exception: Exception) -> None: + """Fired whenever an exception happens during streaming""" + + def on_timeout(self) -> None: + """Fires if the request times out""" + + def on_message_created(self, message: Message) -> None: + """Callback that is fired when a message is created""" + + def on_message_delta(self, delta: MessageDelta, snapshot: Message) -> None: + """Callback that is fired whenever a message delta is returned from the API + + The first argument is just the delta as sent by the API and the second argument + is the accumulated snapshot of the message. For example, a text content event may + look like this: + + # delta + MessageDeltaText( + index=0, + type='text', + text=Text( + value=' Jane' + ), + ) + # snapshot + MessageContentText( + index=0, + type='text', + text=Text( + value='Certainly, Jane' + ), + ) + """ + + def on_message_done(self, message: Message) -> None: + """Callback that is fired when a message is completed""" + + def on_text_created(self, text: Text) -> None: + """Callback that is fired when a text content block is created""" + + def on_text_delta(self, delta: TextDelta, snapshot: Text) -> None: + """Callback that is fired whenever a text content delta is returned + by the API. + + The first argument is just the delta as sent by the API and the second argument + is the accumulated snapshot of the text. For example: + + on_text_delta(TextDelta(value="The"), Text(value="The")), + on_text_delta(TextDelta(value=" solution"), Text(value="The solution")), + on_text_delta(TextDelta(value=" to"), Text(value="The solution to")), + on_text_delta(TextDelta(value=" the"), Text(value="The solution to the")), + on_text_delta(TextDelta(value=" equation"), Text(value="The solution to the equivalent")), + """ + + def on_text_done(self, text: Text) -> None: + """Callback that is fired when a text content block is finished""" + + def on_image_file_done(self, image_file: ImageFile) -> None: + """Callback that is fired when an image file block is finished""" + + def _emit_sse_event(self, event: AssistantStreamEvent) -> None: + self._current_event = event + self.on_event(event) + + self.__current_message_snapshot, new_content = accumulate_event( + event=event, + current_message_snapshot=self.__current_message_snapshot, + ) + if self.__current_message_snapshot is not None: + self.__message_snapshots[self.__current_message_snapshot.id] = self.__current_message_snapshot + + accumulate_run_step( + event=event, + run_step_snapshots=self.__run_step_snapshots, + ) + + for content_delta in new_content: + assert self.__current_message_snapshot is not None + + block = self.__current_message_snapshot.content[content_delta.index] + if block.type == "text": + self.on_text_created(block.text) + + if ( + event.event == "thread.run.completed" + or event.event == "thread.run.cancelled" + or event.event == "thread.run.expired" + or event.event == "thread.run.failed" + or event.event == "thread.run.requires_action" + ): + self.__current_run = event.data + if self._current_tool_call: + self.on_tool_call_done(self._current_tool_call) + elif ( + event.event == "thread.run.created" + or event.event == "thread.run.in_progress" + or event.event == "thread.run.cancelling" + or event.event == "thread.run.queued" + ): + self.__current_run = event.data + elif event.event == "thread.message.created": + self.on_message_created(event.data) + elif event.event == "thread.message.delta": + snapshot = self.__current_message_snapshot + assert snapshot is not None + + message_delta = event.data.delta + if message_delta.content is not None: + for content_delta in message_delta.content: + if content_delta.type == "text" and content_delta.text: + snapshot_content = snapshot.content[content_delta.index] + assert snapshot_content.type == "text" + self.on_text_delta(content_delta.text, snapshot_content.text) + + # If the delta is for a new message content: + # - emit on_text_done/on_image_file_done for the previous message content + # - emit on_text_created/on_image_created for the new message content + if content_delta.index != self._current_message_content_index: + if self._current_message_content is not None: + if self._current_message_content.type == "text": + self.on_text_done(self._current_message_content.text) + elif self._current_message_content.type == "image_file": + self.on_image_file_done(self._current_message_content.image_file) + + self._current_message_content_index = content_delta.index + self._current_message_content = snapshot.content[content_delta.index] + + # Update the current_message_content (delta event is correctly emitted already) + self._current_message_content = snapshot.content[content_delta.index] + + self.on_message_delta(event.data.delta, snapshot) + elif event.event == "thread.message.completed" or event.event == "thread.message.incomplete": + self.__current_message_snapshot = event.data + self.__message_snapshots[event.data.id] = event.data + + if self._current_message_content_index is not None: + content = event.data.content[self._current_message_content_index] + if content.type == "text": + self.on_text_done(content.text) + elif content.type == "image_file": + self.on_image_file_done(content.image_file) + + self.on_message_done(event.data) + elif event.event == "thread.run.step.created": + self.__current_run_step_id = event.data.id + self.on_run_step_created(event.data) + elif event.event == "thread.run.step.in_progress": + self.__current_run_step_id = event.data.id + elif event.event == "thread.run.step.delta": + step_snapshot = self.__run_step_snapshots[event.data.id] + + run_step_delta = event.data.delta + if ( + run_step_delta.step_details + and run_step_delta.step_details.type == "tool_calls" + and run_step_delta.step_details.tool_calls is not None + ): + assert step_snapshot.step_details.type == "tool_calls" + for tool_call_delta in run_step_delta.step_details.tool_calls: + if tool_call_delta.index == self._current_tool_call_index: + self.on_tool_call_delta( + tool_call_delta, + step_snapshot.step_details.tool_calls[tool_call_delta.index], + ) + + # If the delta is for a new tool call: + # - emit on_tool_call_done for the previous tool_call + # - emit on_tool_call_created for the new tool_call + if tool_call_delta.index != self._current_tool_call_index: + if self._current_tool_call is not None: + self.on_tool_call_done(self._current_tool_call) + + self._current_tool_call_index = tool_call_delta.index + self._current_tool_call = step_snapshot.step_details.tool_calls[tool_call_delta.index] + self.on_tool_call_created(self._current_tool_call) + + # Update the current_tool_call (delta event is correctly emitted already) + self._current_tool_call = step_snapshot.step_details.tool_calls[tool_call_delta.index] + + self.on_run_step_delta( + event.data.delta, + step_snapshot, + ) + elif ( + event.event == "thread.run.step.completed" + or event.event == "thread.run.step.cancelled" + or event.event == "thread.run.step.expired" + or event.event == "thread.run.step.failed" + ): + if self._current_tool_call: + self.on_tool_call_done(self._current_tool_call) + + self.on_run_step_done(event.data) + self.__current_run_step_id = None + elif event.event == "thread.created" or event.event == "thread.message.in_progress" or event.event == "error": + # currently no special handling + ... + else: + # we only want to error at build-time + if TYPE_CHECKING: # type: ignore[unreachable] + assert_never(event) + + self._current_event = None + + def __stream__(self) -> Iterator[AssistantStreamEvent]: + stream = self.__stream + if not stream: + raise RuntimeError("Stream has not been started yet") + + try: + for event in stream: + self._emit_sse_event(event) + + yield event + except (httpx.TimeoutException, asyncio.TimeoutError) as exc: + self.on_timeout() + self.on_exception(exc) + raise + except Exception as exc: + self.on_exception(exc) + raise + finally: + self.on_end() + + +AssistantEventHandlerT = TypeVar("AssistantEventHandlerT", bound=AssistantEventHandler) + + +class AssistantStreamManager(Generic[AssistantEventHandlerT]): + """Wrapper over AssistantStreamEventHandler that is returned by `.stream()` + so that a context manager can be used. + + ```py + with client.threads.create_and_run_stream(...) as stream: + for event in stream: + ... + ``` + """ + + def __init__( + self, + api_request: Callable[[], Stream[AssistantStreamEvent]], + *, + event_handler: AssistantEventHandlerT, + ) -> None: + self.__stream: Stream[AssistantStreamEvent] | None = None + self.__event_handler = event_handler + self.__api_request = api_request + + def __enter__(self) -> AssistantEventHandlerT: + self.__stream = self.__api_request() + self.__event_handler._init(self.__stream) + return self.__event_handler + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self.__stream is not None: + self.__stream.close() + + +class AsyncAssistantEventHandler: + text_deltas: AsyncIterable[str] + """Iterator over just the text deltas in the stream. + + This corresponds to the `thread.message.delta` event + in the API. + + ```py + async for text in stream.text_deltas: + print(text, end="", flush=True) + print() + ``` + """ + + def __init__(self) -> None: + self._current_event: AssistantStreamEvent | None = None + self._current_message_content_index: int | None = None + self._current_message_content: MessageContent | None = None + self._current_tool_call_index: int | None = None + self._current_tool_call: ToolCall | None = None + self.__current_run_step_id: str | None = None + self.__current_run: Run | None = None + self.__run_step_snapshots: dict[str, RunStep] = {} + self.__message_snapshots: dict[str, Message] = {} + self.__current_message_snapshot: Message | None = None + + self.text_deltas = self.__text_deltas__() + self._iterator = self.__stream__() + self.__stream: AsyncStream[AssistantStreamEvent] | None = None + + def _init(self, stream: AsyncStream[AssistantStreamEvent]) -> None: + if self.__stream: + raise RuntimeError( + "A single event handler cannot be shared between multiple streams; You will need to construct a new event handler instance" + ) + + self.__stream = stream + + async def __anext__(self) -> AssistantStreamEvent: + return await self._iterator.__anext__() + + async def __aiter__(self) -> AsyncIterator[AssistantStreamEvent]: + async for item in self._iterator: + yield item + + async def close(self) -> None: + """ + Close the response and release the connection. + + Automatically called when the context manager exits. + """ + if self.__stream: + await self.__stream.close() + + @property + def current_event(self) -> AssistantStreamEvent | None: + return self._current_event + + @property + def current_run(self) -> Run | None: + return self.__current_run + + @property + def current_run_step_snapshot(self) -> RunStep | None: + if not self.__current_run_step_id: + return None + + return self.__run_step_snapshots[self.__current_run_step_id] + + @property + def current_message_snapshot(self) -> Message | None: + return self.__current_message_snapshot + + async def until_done(self) -> None: + """Waits until the stream has been consumed""" + await consume_async_iterator(self) + + async def get_final_run(self) -> Run: + """Wait for the stream to finish and returns the completed Run object""" + await self.until_done() + + if not self.__current_run: + raise RuntimeError("No final run object found") + + return self.__current_run + + async def get_final_run_steps(self) -> list[RunStep]: + """Wait for the stream to finish and returns the steps taken in this run""" + await self.until_done() + + if not self.__run_step_snapshots: + raise RuntimeError("No run steps found") + + return [step for step in self.__run_step_snapshots.values()] + + async def get_final_messages(self) -> list[Message]: + """Wait for the stream to finish and returns the messages emitted in this run""" + await self.until_done() + + if not self.__message_snapshots: + raise RuntimeError("No messages found") + + return [message for message in self.__message_snapshots.values()] + + async def __text_deltas__(self) -> AsyncIterator[str]: + async for event in self: + if event.event != "thread.message.delta": + continue + + for content_delta in event.data.delta.content or []: + if content_delta.type == "text" and content_delta.text and content_delta.text.value: + yield content_delta.text.value + + # event handlers + + async def on_end(self) -> None: + """Fires when the stream has finished. + + This happens if the stream is read to completion + or if an exception occurs during iteration. + """ + + async def on_event(self, event: AssistantStreamEvent) -> None: + """Callback that is fired for every Server-Sent-Event""" + + async def on_run_step_created(self, run_step: RunStep) -> None: + """Callback that is fired when a run step is created""" + + async def on_run_step_delta(self, delta: RunStepDelta, snapshot: RunStep) -> None: + """Callback that is fired whenever a run step delta is returned from the API + + The first argument is just the delta as sent by the API and the second argument + is the accumulated snapshot of the run step. For example, a tool calls event may + look like this: + + # delta + tool_calls=[ + RunStepDeltaToolCallsCodeInterpreter( + index=0, + type='code_interpreter', + id=None, + code_interpreter=CodeInterpreter(input=' sympy', outputs=None) + ) + ] + # snapshot + tool_calls=[ + CodeToolCall( + id='call_wKayJlcYV12NiadiZuJXxcfx', + code_interpreter=CodeInterpreter(input='from sympy', outputs=[]), + type='code_interpreter', + index=0 + ) + ], + """ + + async def on_run_step_done(self, run_step: RunStep) -> None: + """Callback that is fired when a run step is completed""" + + async def on_tool_call_created(self, tool_call: ToolCall) -> None: + """Callback that is fired when a tool call is created""" + + async def on_tool_call_delta(self, delta: ToolCallDelta, snapshot: ToolCall) -> None: + """Callback that is fired when a tool call delta is encountered""" + + async def on_tool_call_done(self, tool_call: ToolCall) -> None: + """Callback that is fired when a tool call delta is encountered""" + + async def on_exception(self, exception: Exception) -> None: + """Fired whenever an exception happens during streaming""" + + async def on_timeout(self) -> None: + """Fires if the request times out""" + + async def on_message_created(self, message: Message) -> None: + """Callback that is fired when a message is created""" + + async def on_message_delta(self, delta: MessageDelta, snapshot: Message) -> None: + """Callback that is fired whenever a message delta is returned from the API + + The first argument is just the delta as sent by the API and the second argument + is the accumulated snapshot of the message. For example, a text content event may + look like this: + + # delta + MessageDeltaText( + index=0, + type='text', + text=Text( + value=' Jane' + ), + ) + # snapshot + MessageContentText( + index=0, + type='text', + text=Text( + value='Certainly, Jane' + ), + ) + """ + + async def on_message_done(self, message: Message) -> None: + """Callback that is fired when a message is completed""" + + async def on_text_created(self, text: Text) -> None: + """Callback that is fired when a text content block is created""" + + async def on_text_delta(self, delta: TextDelta, snapshot: Text) -> None: + """Callback that is fired whenever a text content delta is returned + by the API. + + The first argument is just the delta as sent by the API and the second argument + is the accumulated snapshot of the text. For example: + + on_text_delta(TextDelta(value="The"), Text(value="The")), + on_text_delta(TextDelta(value=" solution"), Text(value="The solution")), + on_text_delta(TextDelta(value=" to"), Text(value="The solution to")), + on_text_delta(TextDelta(value=" the"), Text(value="The solution to the")), + on_text_delta(TextDelta(value=" equation"), Text(value="The solution to the equivalent")), + """ + + async def on_text_done(self, text: Text) -> None: + """Callback that is fired when a text content block is finished""" + + async def on_image_file_done(self, image_file: ImageFile) -> None: + """Callback that is fired when an image file block is finished""" + + async def _emit_sse_event(self, event: AssistantStreamEvent) -> None: + self._current_event = event + await self.on_event(event) + + self.__current_message_snapshot, new_content = accumulate_event( + event=event, + current_message_snapshot=self.__current_message_snapshot, + ) + if self.__current_message_snapshot is not None: + self.__message_snapshots[self.__current_message_snapshot.id] = self.__current_message_snapshot + + accumulate_run_step( + event=event, + run_step_snapshots=self.__run_step_snapshots, + ) + + for content_delta in new_content: + assert self.__current_message_snapshot is not None + + block = self.__current_message_snapshot.content[content_delta.index] + if block.type == "text": + await self.on_text_created(block.text) + + if ( + event.event == "thread.run.completed" + or event.event == "thread.run.cancelled" + or event.event == "thread.run.expired" + or event.event == "thread.run.failed" + or event.event == "thread.run.requires_action" + ): + self.__current_run = event.data + if self._current_tool_call: + await self.on_tool_call_done(self._current_tool_call) + elif ( + event.event == "thread.run.created" + or event.event == "thread.run.in_progress" + or event.event == "thread.run.cancelling" + or event.event == "thread.run.queued" + ): + self.__current_run = event.data + elif event.event == "thread.message.created": + await self.on_message_created(event.data) + elif event.event == "thread.message.delta": + snapshot = self.__current_message_snapshot + assert snapshot is not None + + message_delta = event.data.delta + if message_delta.content is not None: + for content_delta in message_delta.content: + if content_delta.type == "text" and content_delta.text: + snapshot_content = snapshot.content[content_delta.index] + assert snapshot_content.type == "text" + await self.on_text_delta(content_delta.text, snapshot_content.text) + + # If the delta is for a new message content: + # - emit on_text_done/on_image_file_done for the previous message content + # - emit on_text_created/on_image_created for the new message content + if content_delta.index != self._current_message_content_index: + if self._current_message_content is not None: + if self._current_message_content.type == "text": + await self.on_text_done(self._current_message_content.text) + elif self._current_message_content.type == "image_file": + await self.on_image_file_done(self._current_message_content.image_file) + + self._current_message_content_index = content_delta.index + self._current_message_content = snapshot.content[content_delta.index] + + # Update the current_message_content (delta event is correctly emitted already) + self._current_message_content = snapshot.content[content_delta.index] + + await self.on_message_delta(event.data.delta, snapshot) + elif event.event == "thread.message.completed" or event.event == "thread.message.incomplete": + self.__current_message_snapshot = event.data + self.__message_snapshots[event.data.id] = event.data + + if self._current_message_content_index is not None: + content = event.data.content[self._current_message_content_index] + if content.type == "text": + await self.on_text_done(content.text) + elif content.type == "image_file": + await self.on_image_file_done(content.image_file) + + await self.on_message_done(event.data) + elif event.event == "thread.run.step.created": + self.__current_run_step_id = event.data.id + await self.on_run_step_created(event.data) + elif event.event == "thread.run.step.in_progress": + self.__current_run_step_id = event.data.id + elif event.event == "thread.run.step.delta": + step_snapshot = self.__run_step_snapshots[event.data.id] + + run_step_delta = event.data.delta + if ( + run_step_delta.step_details + and run_step_delta.step_details.type == "tool_calls" + and run_step_delta.step_details.tool_calls is not None + ): + assert step_snapshot.step_details.type == "tool_calls" + for tool_call_delta in run_step_delta.step_details.tool_calls: + if tool_call_delta.index == self._current_tool_call_index: + await self.on_tool_call_delta( + tool_call_delta, + step_snapshot.step_details.tool_calls[tool_call_delta.index], + ) + + # If the delta is for a new tool call: + # - emit on_tool_call_done for the previous tool_call + # - emit on_tool_call_created for the new tool_call + if tool_call_delta.index != self._current_tool_call_index: + if self._current_tool_call is not None: + await self.on_tool_call_done(self._current_tool_call) + + self._current_tool_call_index = tool_call_delta.index + self._current_tool_call = step_snapshot.step_details.tool_calls[tool_call_delta.index] + await self.on_tool_call_created(self._current_tool_call) + + # Update the current_tool_call (delta event is correctly emitted already) + self._current_tool_call = step_snapshot.step_details.tool_calls[tool_call_delta.index] + + await self.on_run_step_delta( + event.data.delta, + step_snapshot, + ) + elif ( + event.event == "thread.run.step.completed" + or event.event == "thread.run.step.cancelled" + or event.event == "thread.run.step.expired" + or event.event == "thread.run.step.failed" + ): + if self._current_tool_call: + await self.on_tool_call_done(self._current_tool_call) + + await self.on_run_step_done(event.data) + self.__current_run_step_id = None + elif event.event == "thread.created" or event.event == "thread.message.in_progress" or event.event == "error": + # currently no special handling + ... + else: + # we only want to error at build-time + if TYPE_CHECKING: # type: ignore[unreachable] + assert_never(event) + + self._current_event = None + + async def __stream__(self) -> AsyncIterator[AssistantStreamEvent]: + stream = self.__stream + if not stream: + raise RuntimeError("Stream has not been started yet") + + try: + async for event in stream: + await self._emit_sse_event(event) + + yield event + except (httpx.TimeoutException, asyncio.TimeoutError) as exc: + await self.on_timeout() + await self.on_exception(exc) + raise + except Exception as exc: + await self.on_exception(exc) + raise + finally: + await self.on_end() + + +AsyncAssistantEventHandlerT = TypeVar("AsyncAssistantEventHandlerT", bound=AsyncAssistantEventHandler) + + +class AsyncAssistantStreamManager(Generic[AsyncAssistantEventHandlerT]): + """Wrapper over AsyncAssistantStreamEventHandler that is returned by `.stream()` + so that an async context manager can be used without `await`ing the + original client call. + + ```py + async with client.threads.create_and_run_stream(...) as stream: + async for event in stream: + ... + ``` + """ + + def __init__( + self, + api_request: Awaitable[AsyncStream[AssistantStreamEvent]], + *, + event_handler: AsyncAssistantEventHandlerT, + ) -> None: + self.__stream: AsyncStream[AssistantStreamEvent] | None = None + self.__event_handler = event_handler + self.__api_request = api_request + + async def __aenter__(self) -> AsyncAssistantEventHandlerT: + self.__stream = await self.__api_request + self.__event_handler._init(self.__stream) + return self.__event_handler + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self.__stream is not None: + await self.__stream.close() + + +def accumulate_run_step( + *, + event: AssistantStreamEvent, + run_step_snapshots: dict[str, RunStep], +) -> None: + if event.event == "thread.run.step.created": + run_step_snapshots[event.data.id] = event.data + return + + if event.event == "thread.run.step.delta": + data = event.data + snapshot = run_step_snapshots[data.id] + + if data.delta: + merged = accumulate_delta( + cast( + "dict[object, object]", + snapshot.model_dump(exclude_unset=True), + ), + cast( + "dict[object, object]", + data.delta.model_dump(exclude_unset=True), + ), + ) + run_step_snapshots[snapshot.id] = cast(RunStep, construct_type(type_=RunStep, value=merged)) + + return None + + +def accumulate_event( + *, + event: AssistantStreamEvent, + current_message_snapshot: Message | None, +) -> tuple[Message | None, list[MessageContentDelta]]: + """Returns a tuple of message snapshot and newly created text message deltas""" + if event.event == "thread.message.created": + return event.data, [] + + new_content: list[MessageContentDelta] = [] + + if event.event != "thread.message.delta": + return current_message_snapshot, [] + + if not current_message_snapshot: + raise RuntimeError("Encountered a message delta with no previous snapshot") + + data = event.data + if data.delta.content: + for content_delta in data.delta.content: + try: + block = current_message_snapshot.content[content_delta.index] + except IndexError: + current_message_snapshot.content.insert( + content_delta.index, + cast( + MessageContent, + construct_type( + # mypy doesn't allow Content for some reason + type_=cast(Any, MessageContent), + value=content_delta.model_dump(exclude_unset=True), + ), + ), + ) + new_content.append(content_delta) + else: + merged = accumulate_delta( + cast( + "dict[object, object]", + block.model_dump(exclude_unset=True), + ), + cast( + "dict[object, object]", + content_delta.model_dump(exclude_unset=True), + ), + ) + current_message_snapshot.content[content_delta.index] = cast( + MessageContent, + construct_type( + # mypy doesn't allow Content for some reason + type_=cast(Any, MessageContent), + value=merged, + ), + ) + + return current_message_snapshot, new_content + + +def accumulate_delta(acc: dict[object, object], delta: dict[object, object]) -> dict[object, object]: + for key, delta_value in delta.items(): + if key not in acc: + acc[key] = delta_value + continue + + acc_value = acc[key] + if acc_value is None: + acc[key] = delta_value + continue + + # the `index` property is used in arrays of objects so it should + # not be accumulated like other values e.g. + # [{'foo': 'bar', 'index': 0}] + # + # the same applies to `type` properties as they're used for + # discriminated unions + if key == "index" or key == "type": + acc[key] = delta_value + continue + + if isinstance(acc_value, str) and isinstance(delta_value, str): + acc_value += delta_value + elif isinstance(acc_value, (int, float)) and isinstance(delta_value, (int, float)): + acc_value += delta_value + elif is_dict(acc_value) and is_dict(delta_value): + acc_value = accumulate_delta(acc_value, delta_value) + elif is_list(acc_value) and is_list(delta_value): + # for lists of non-dictionary items we'll only ever get new entries + # in the array, existing entries will never be changed + if all(isinstance(x, (str, int, float)) for x in acc_value): + acc_value.extend(delta_value) + continue + + for delta_entry in delta_value: + if not is_dict(delta_entry): + raise TypeError(f"Unexpected list delta entry is not a dictionary: {delta_entry}") + + try: + index = delta_entry["index"] + except KeyError as exc: + raise RuntimeError(f"Expected list delta entry to have an `index` key; {delta_entry}") from exc + + if not isinstance(index, int): + raise TypeError(f"Unexpected, list delta entry `index` value is not an integer; {index}") + + try: + acc_entry = acc_value[index] + except IndexError: + acc_value.insert(index, delta_entry) + else: + if not is_dict(acc_entry): + raise TypeError("not handled yet") + + acc_value[index] = accumulate_delta(acc_entry, delta_entry) + + acc[key] = acc_value + + return acc diff --git a/src/openai/resources/beta/assistants/assistants.py b/src/openai/resources/beta/assistants/assistants.py index 3aef33c95e..4698deec48 100644 --- a/src/openai/resources/beta/assistants/assistants.py +++ b/src/openai/resources/beta/assistants/assistants.py @@ -28,6 +28,7 @@ from ....types.beta import ( Assistant, AssistantDeleted, + AssistantToolParam, assistant_list_params, assistant_create_params, assistant_update_params, @@ -62,7 +63,7 @@ def create( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, - tools: Iterable[assistant_create_params.Tool] | NotGiven = NOT_GIVEN, + tools: Iterable[AssistantToolParam] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -172,7 +173,7 @@ def update( metadata: Optional[object] | NotGiven = NOT_GIVEN, model: str | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, - tools: Iterable[assistant_update_params.Tool] | NotGiven = NOT_GIVEN, + tools: Iterable[AssistantToolParam] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -365,7 +366,7 @@ async def create( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, - tools: Iterable[assistant_create_params.Tool] | NotGiven = NOT_GIVEN, + tools: Iterable[AssistantToolParam] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -475,7 +476,7 @@ async def update( metadata: Optional[object] | NotGiven = NOT_GIVEN, model: str | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, - tools: Iterable[assistant_update_params.Tool] | NotGiven = NOT_GIVEN, + tools: Iterable[AssistantToolParam] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, diff --git a/src/openai/resources/beta/threads/messages/messages.py b/src/openai/resources/beta/threads/messages/messages.py index 2c0994d1f2..600d9a72ea 100644 --- a/src/openai/resources/beta/threads/messages/messages.py +++ b/src/openai/resources/beta/threads/messages/messages.py @@ -29,7 +29,7 @@ AsyncPaginator, make_request_options, ) -from .....types.beta.threads import ThreadMessage, message_list_params, message_create_params, message_update_params +from .....types.beta.threads import Message, message_list_params, message_create_params, message_update_params __all__ = ["Messages", "AsyncMessages"] @@ -61,7 +61,7 @@ def create( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> ThreadMessage: + ) -> Message: """ Create a message. @@ -106,7 +106,7 @@ def create( options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), - cast_to=ThreadMessage, + cast_to=Message, ) def retrieve( @@ -120,7 +120,7 @@ def retrieve( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> ThreadMessage: + ) -> Message: """ Retrieve a message. @@ -143,7 +143,7 @@ def retrieve( options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), - cast_to=ThreadMessage, + cast_to=Message, ) def update( @@ -158,7 +158,7 @@ def update( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> ThreadMessage: + ) -> Message: """ Modifies a message. @@ -187,7 +187,7 @@ def update( options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), - cast_to=ThreadMessage, + cast_to=Message, ) def list( @@ -204,7 +204,7 @@ def list( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> SyncCursorPage[ThreadMessage]: + ) -> SyncCursorPage[Message]: """ Returns a list of messages for a given thread. @@ -238,7 +238,7 @@ def list( extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._get_api_list( f"/threads/{thread_id}/messages", - page=SyncCursorPage[ThreadMessage], + page=SyncCursorPage[Message], options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, @@ -254,7 +254,7 @@ def list( message_list_params.MessageListParams, ), ), - model=ThreadMessage, + model=Message, ) @@ -285,7 +285,7 @@ async def create( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> ThreadMessage: + ) -> Message: """ Create a message. @@ -330,7 +330,7 @@ async def create( options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), - cast_to=ThreadMessage, + cast_to=Message, ) async def retrieve( @@ -344,7 +344,7 @@ async def retrieve( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> ThreadMessage: + ) -> Message: """ Retrieve a message. @@ -367,7 +367,7 @@ async def retrieve( options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), - cast_to=ThreadMessage, + cast_to=Message, ) async def update( @@ -382,7 +382,7 @@ async def update( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> ThreadMessage: + ) -> Message: """ Modifies a message. @@ -411,7 +411,7 @@ async def update( options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), - cast_to=ThreadMessage, + cast_to=Message, ) def list( @@ -428,7 +428,7 @@ def list( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> AsyncPaginator[ThreadMessage, AsyncCursorPage[ThreadMessage]]: + ) -> AsyncPaginator[Message, AsyncCursorPage[Message]]: """ Returns a list of messages for a given thread. @@ -462,7 +462,7 @@ def list( extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._get_api_list( f"/threads/{thread_id}/messages", - page=AsyncCursorPage[ThreadMessage], + page=AsyncCursorPage[Message], options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, @@ -478,7 +478,7 @@ def list( message_list_params.MessageListParams, ), ), - model=ThreadMessage, + model=Message, ) diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 62cfa6b742..c5e9474002 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -2,7 +2,8 @@ from __future__ import annotations -from typing import Iterable, Optional +from typing import Iterable, Optional, overload +from functools import partial from typing_extensions import Literal import httpx @@ -18,17 +19,28 @@ ) from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import ( + required_args, maybe_transform, async_maybe_transform, ) from ....._compat import cached_property from ....._resource import SyncAPIResource, AsyncAPIResource from ....._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ....._streaming import Stream, AsyncStream from .....pagination import SyncCursorPage, AsyncCursorPage +from .....types.beta import AssistantToolParam, AssistantStreamEvent from ....._base_client import ( AsyncPaginator, make_request_options, ) +from .....lib.streaming import ( + AssistantEventHandler, + AssistantEventHandlerT, + AssistantStreamManager, + AsyncAssistantEventHandler, + AsyncAssistantEventHandlerT, + AsyncAssistantStreamManager, +) from .....types.beta.threads import ( Run, run_list_params, @@ -53,6 +65,7 @@ def with_raw_response(self) -> RunsWithRawResponse: def with_streaming_response(self) -> RunsWithStreamingResponse: return RunsWithStreamingResponse(self) + @overload def create( self, thread_id: str, @@ -62,7 +75,8 @@ def create( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, - tools: Optional[Iterable[run_create_params.Tool]] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -96,6 +110,134 @@ def create( model associated with the assistant. If not, the model associated with the assistant will be used. + stream: If `true`, returns a stream of events that happen during the Run as server-sent + events, terminating when the Run enters a terminal state with a `data: [DONE]` + message. + + tools: Override the tools the assistant can use for this run. This is useful for + modifying the behavior on a per-run basis. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + def create( + self, + thread_id: str, + *, + assistant_id: str, + stream: Literal[True], + additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Stream[AssistantStreamEvent]: + """ + Create a run. + + Args: + assistant_id: The ID of the + [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + execute this run. + + stream: If `true`, returns a stream of events that happen during the Run as server-sent + events, terminating when the Run enters a terminal state with a `data: [DONE]` + message. + + additional_instructions: Appends additional instructions at the end of the instructions for the run. This + is useful for modifying the behavior on a per-run basis without overriding other + instructions. + + instructions: Overrides the + [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) + of the assistant. This is useful for modifying the behavior on a per-run basis. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + be used to execute this run. If a value is provided here, it will override the + model associated with the assistant. If not, the model associated with the + assistant will be used. + + tools: Override the tools the assistant can use for this run. This is useful for + modifying the behavior on a per-run basis. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + def create( + self, + thread_id: str, + *, + assistant_id: str, + stream: bool, + additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Run | Stream[AssistantStreamEvent]: + """ + Create a run. + + Args: + assistant_id: The ID of the + [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + execute this run. + + stream: If `true`, returns a stream of events that happen during the Run as server-sent + events, terminating when the Run enters a terminal state with a `data: [DONE]` + message. + + additional_instructions: Appends additional instructions at the end of the instructions for the run. This + is useful for modifying the behavior on a per-run basis without overriding other + instructions. + + instructions: Overrides the + [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) + of the assistant. This is useful for modifying the behavior on a per-run basis. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + be used to execute this run. If a value is provided here, it will override the + model associated with the assistant. If not, the model associated with the + assistant will be used. + tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. @@ -107,6 +249,27 @@ def create( timeout: Override the client-level default timeout for this request, in seconds """ + ... + + @required_args(["assistant_id"], ["assistant_id", "stream"]) + def create( + self, + thread_id: str, + *, + assistant_id: str, + additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Run | Stream[AssistantStreamEvent]: if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} @@ -119,6 +282,7 @@ def create( "instructions": instructions, "metadata": metadata, "model": model, + "stream": stream, "tools": tools, }, run_create_params.RunCreateParams, @@ -127,6 +291,8 @@ def create( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=Run, + stream=stream or False, + stream_cls=Stream[AssistantStreamEvent], ) def retrieve( @@ -314,132 +480,88 @@ def cancel( cast_to=Run, ) - def submit_tool_outputs( + @overload + def create_and_stream( self, - run_id: str, *, + assistant_id: str, + additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, thread_id: str, - tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> Run: - """ - When a run has the `status: "requires_action"` and `required_action.type` is - `submit_tool_outputs`, this endpoint can be used to submit the outputs from the - tool calls once they're all completed. All outputs must be submitted in a single - request. - - Args: - tool_outputs: A list of tools for which the outputs are being submitted. - - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - if not thread_id: - raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") - if not run_id: - raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} - return self._post( - f"/threads/{thread_id}/runs/{run_id}/submit_tool_outputs", - body=maybe_transform( - {"tool_outputs": tool_outputs}, run_submit_tool_outputs_params.RunSubmitToolOutputsParams - ), - options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout - ), - cast_to=Run, - ) - - -class AsyncRuns(AsyncAPIResource): - @cached_property - def steps(self) -> AsyncSteps: - return AsyncSteps(self._client) - - @cached_property - def with_raw_response(self) -> AsyncRunsWithRawResponse: - return AsyncRunsWithRawResponse(self) + ) -> AssistantStreamManager[AssistantEventHandler]: + """Create a Run stream""" + ... - @cached_property - def with_streaming_response(self) -> AsyncRunsWithStreamingResponse: - return AsyncRunsWithStreamingResponse(self) - - async def create( + @overload + def create_and_stream( self, - thread_id: str, *, assistant_id: str, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, - tools: Optional[Iterable[run_create_params.Tool]] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + thread_id: str, + event_handler: AssistantEventHandlerT, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> Run: - """ - Create a run. - - Args: - assistant_id: The ID of the - [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to - execute this run. - - additional_instructions: Appends additional instructions at the end of the instructions for the run. This - is useful for modifying the behavior on a per-run basis without overriding other - instructions. - - instructions: Overrides the - [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) - of the assistant. This is useful for modifying the behavior on a per-run basis. - - metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 - characters long. - - model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to - be used to execute this run. If a value is provided here, it will override the - model associated with the assistant. If not, the model associated with the - assistant will be used. - - tools: Override the tools the assistant can use for this run. This is useful for - modifying the behavior on a per-run basis. - - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request + ) -> AssistantStreamManager[AssistantEventHandlerT]: + """Create a Run stream""" + ... - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ + def create_and_stream( + self, + *, + assistant_id: str, + additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + thread_id: str, + event_handler: AssistantEventHandlerT | None = None, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AssistantStreamManager[AssistantEventHandler] | AssistantStreamManager[AssistantEventHandlerT]: + """Create a Run stream""" if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} - return await self._post( + + extra_headers = { + "OpenAI-Beta": "assistants=v1", + "X-Stainless-Stream-Helper": "threads.runs.create_and_stream", + "X-Stainless-Custom-Event-Handler": "true" if event_handler else "false", + **(extra_headers or {}), + } + make_request = partial( + self._post, f"/threads/{thread_id}/runs", - body=await async_maybe_transform( + body=maybe_transform( { "assistant_id": assistant_id, "additional_instructions": additional_instructions, "instructions": instructions, "metadata": metadata, "model": model, + "stream": True, "tools": tools, }, run_create_params.RunCreateParams, @@ -448,13 +570,19 @@ async def create( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=Run, + stream=True, + stream_cls=Stream[AssistantStreamEvent], ) + return AssistantStreamManager(make_request, event_handler=event_handler or AssistantEventHandler()) - async def retrieve( + @overload + def submit_tool_outputs( self, run_id: str, *, thread_id: str, + tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], + stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -463,9 +591,18 @@ async def retrieve( timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Run: """ - Retrieves a run. + When a run has the `status: "requires_action"` and `required_action.type` is + `submit_tool_outputs`, this endpoint can be used to submit the outputs from the + tool calls once they're all completed. All outputs must be submitted in a single + request. Args: + tool_outputs: A list of tools for which the outputs are being submitted. + + stream: If `true`, returns a stream of events that happen during the Run as server-sent + events, terminating when the Run enters a terminal state with a `data: [DONE]` + message. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -474,12 +611,485 @@ async def retrieve( timeout: Override the client-level default timeout for this request, in seconds """ - if not thread_id: - raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") - if not run_id: - raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} - return await self._get( + ... + + @overload + def submit_tool_outputs( + self, + run_id: str, + *, + thread_id: str, + stream: Literal[True], + tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Stream[AssistantStreamEvent]: + """ + When a run has the `status: "requires_action"` and `required_action.type` is + `submit_tool_outputs`, this endpoint can be used to submit the outputs from the + tool calls once they're all completed. All outputs must be submitted in a single + request. + + Args: + stream: If `true`, returns a stream of events that happen during the Run as server-sent + events, terminating when the Run enters a terminal state with a `data: [DONE]` + message. + + tool_outputs: A list of tools for which the outputs are being submitted. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + def submit_tool_outputs( + self, + run_id: str, + *, + thread_id: str, + stream: bool, + tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Run | Stream[AssistantStreamEvent]: + """ + When a run has the `status: "requires_action"` and `required_action.type` is + `submit_tool_outputs`, this endpoint can be used to submit the outputs from the + tool calls once they're all completed. All outputs must be submitted in a single + request. + + Args: + stream: If `true`, returns a stream of events that happen during the Run as server-sent + events, terminating when the Run enters a terminal state with a `data: [DONE]` + message. + + tool_outputs: A list of tools for which the outputs are being submitted. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @required_args(["thread_id", "tool_outputs"], ["thread_id", "stream", "tool_outputs"]) + def submit_tool_outputs( + self, + run_id: str, + *, + thread_id: str, + tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], + stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Run | Stream[AssistantStreamEvent]: + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return self._post( + f"/threads/{thread_id}/runs/{run_id}/submit_tool_outputs", + body=maybe_transform( + { + "tool_outputs": tool_outputs, + "stream": stream, + }, + run_submit_tool_outputs_params.RunSubmitToolOutputsParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Run, + stream=stream or False, + stream_cls=Stream[AssistantStreamEvent], + ) + + @overload + def submit_tool_outputs_stream( + self, + *, + tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], + run_id: str, + thread_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AssistantStreamManager[AssistantEventHandler]: + """ + Submit the tool outputs from a previous run and stream the run to a terminal + state. + """ + ... + + @overload + def submit_tool_outputs_stream( + self, + *, + tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], + run_id: str, + thread_id: str, + event_handler: AssistantEventHandlerT, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AssistantStreamManager[AssistantEventHandlerT]: + """ + Submit the tool outputs from a previous run and stream the run to a terminal + state. + """ + ... + + def submit_tool_outputs_stream( + self, + *, + tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], + run_id: str, + thread_id: str, + event_handler: AssistantEventHandlerT | None = None, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AssistantStreamManager[AssistantEventHandler] | AssistantStreamManager[AssistantEventHandlerT]: + """ + Submit the tool outputs from a previous run and stream the run to a terminal + state. + """ + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") + + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + + extra_headers = { + "OpenAI-Beta": "assistants=v1", + "X-Stainless-Stream-Helper": "threads.runs.submit_tool_outputs_stream", + "X-Stainless-Custom-Event-Handler": "true" if event_handler else "false", + **(extra_headers or {}), + } + request = partial( + self._post, + f"/threads/{thread_id}/runs/{run_id}/submit_tool_outputs", + body=maybe_transform( + { + "tool_outputs": tool_outputs, + "stream": True, + }, + run_submit_tool_outputs_params.RunSubmitToolOutputsParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Run, + stream=True, + stream_cls=Stream[AssistantStreamEvent], + ) + return AssistantStreamManager(request, event_handler=event_handler or AssistantEventHandler()) + + +class AsyncRuns(AsyncAPIResource): + @cached_property + def steps(self) -> AsyncSteps: + return AsyncSteps(self._client) + + @cached_property + def with_raw_response(self) -> AsyncRunsWithRawResponse: + return AsyncRunsWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncRunsWithStreamingResponse: + return AsyncRunsWithStreamingResponse(self) + + @overload + async def create( + self, + thread_id: str, + *, + assistant_id: str, + additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Run: + """ + Create a run. + + Args: + assistant_id: The ID of the + [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + execute this run. + + additional_instructions: Appends additional instructions at the end of the instructions for the run. This + is useful for modifying the behavior on a per-run basis without overriding other + instructions. + + instructions: Overrides the + [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) + of the assistant. This is useful for modifying the behavior on a per-run basis. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + be used to execute this run. If a value is provided here, it will override the + model associated with the assistant. If not, the model associated with the + assistant will be used. + + stream: If `true`, returns a stream of events that happen during the Run as server-sent + events, terminating when the Run enters a terminal state with a `data: [DONE]` + message. + + tools: Override the tools the assistant can use for this run. This is useful for + modifying the behavior on a per-run basis. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + async def create( + self, + thread_id: str, + *, + assistant_id: str, + stream: Literal[True], + additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncStream[AssistantStreamEvent]: + """ + Create a run. + + Args: + assistant_id: The ID of the + [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + execute this run. + + stream: If `true`, returns a stream of events that happen during the Run as server-sent + events, terminating when the Run enters a terminal state with a `data: [DONE]` + message. + + additional_instructions: Appends additional instructions at the end of the instructions for the run. This + is useful for modifying the behavior on a per-run basis without overriding other + instructions. + + instructions: Overrides the + [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) + of the assistant. This is useful for modifying the behavior on a per-run basis. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + be used to execute this run. If a value is provided here, it will override the + model associated with the assistant. If not, the model associated with the + assistant will be used. + + tools: Override the tools the assistant can use for this run. This is useful for + modifying the behavior on a per-run basis. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + async def create( + self, + thread_id: str, + *, + assistant_id: str, + stream: bool, + additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Run | AsyncStream[AssistantStreamEvent]: + """ + Create a run. + + Args: + assistant_id: The ID of the + [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + execute this run. + + stream: If `true`, returns a stream of events that happen during the Run as server-sent + events, terminating when the Run enters a terminal state with a `data: [DONE]` + message. + + additional_instructions: Appends additional instructions at the end of the instructions for the run. This + is useful for modifying the behavior on a per-run basis without overriding other + instructions. + + instructions: Overrides the + [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) + of the assistant. This is useful for modifying the behavior on a per-run basis. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + be used to execute this run. If a value is provided here, it will override the + model associated with the assistant. If not, the model associated with the + assistant will be used. + + tools: Override the tools the assistant can use for this run. This is useful for + modifying the behavior on a per-run basis. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @required_args(["assistant_id"], ["assistant_id", "stream"]) + async def create( + self, + thread_id: str, + *, + assistant_id: str, + additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Run | AsyncStream[AssistantStreamEvent]: + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return await self._post( + f"/threads/{thread_id}/runs", + body=await async_maybe_transform( + { + "assistant_id": assistant_id, + "additional_instructions": additional_instructions, + "instructions": instructions, + "metadata": metadata, + "model": model, + "stream": stream, + "tools": tools, + }, + run_create_params.RunCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Run, + stream=stream or False, + stream_cls=AsyncStream[AssistantStreamEvent], + ) + + async def retrieve( + self, + run_id: str, + *, + thread_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Run: + """ + Retrieves a run. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + return await self._get( f"/threads/{thread_id}/runs/{run_id}", options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout @@ -635,12 +1245,111 @@ async def cancel( cast_to=Run, ) + @overload + def create_and_stream( + self, + *, + assistant_id: str, + additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + thread_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncAssistantStreamManager[AsyncAssistantEventHandler]: + """Create a Run stream""" + ... + + @overload + def create_and_stream( + self, + *, + assistant_id: str, + additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + thread_id: str, + event_handler: AsyncAssistantEventHandlerT, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncAssistantStreamManager[AsyncAssistantEventHandlerT]: + """Create a Run stream""" + ... + + def create_and_stream( + self, + *, + assistant_id: str, + additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + thread_id: str, + event_handler: AsyncAssistantEventHandlerT | None = None, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> ( + AsyncAssistantStreamManager[AsyncAssistantEventHandler] + | AsyncAssistantStreamManager[AsyncAssistantEventHandlerT] + ): + """Create a Run stream""" + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + + extra_headers = { + "OpenAI-Beta": "assistants=v1", + "X-Stainless-Stream-Helper": "threads.runs.create_and_stream", + "X-Stainless-Custom-Event-Handler": "true" if event_handler else "false", + **(extra_headers or {}), + } + request = self._post( + f"/threads/{thread_id}/runs", + body=maybe_transform( + { + "assistant_id": assistant_id, + "additional_instructions": additional_instructions, + "instructions": instructions, + "metadata": metadata, + "model": model, + "stream": True, + "tools": tools, + }, + run_create_params.RunCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Run, + stream=True, + stream_cls=AsyncStream[AssistantStreamEvent], + ) + return AsyncAssistantStreamManager(request, event_handler=event_handler or AsyncAssistantEventHandler()) + + @overload async def submit_tool_outputs( self, run_id: str, *, thread_id: str, tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], + stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -657,6 +1366,86 @@ async def submit_tool_outputs( Args: tool_outputs: A list of tools for which the outputs are being submitted. + stream: If `true`, returns a stream of events that happen during the Run as server-sent + events, terminating when the Run enters a terminal state with a `data: [DONE]` + message. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + async def submit_tool_outputs( + self, + run_id: str, + *, + thread_id: str, + stream: Literal[True], + tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncStream[AssistantStreamEvent]: + """ + When a run has the `status: "requires_action"` and `required_action.type` is + `submit_tool_outputs`, this endpoint can be used to submit the outputs from the + tool calls once they're all completed. All outputs must be submitted in a single + request. + + Args: + stream: If `true`, returns a stream of events that happen during the Run as server-sent + events, terminating when the Run enters a terminal state with a `data: [DONE]` + message. + + tool_outputs: A list of tools for which the outputs are being submitted. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + async def submit_tool_outputs( + self, + run_id: str, + *, + thread_id: str, + stream: bool, + tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Run | AsyncStream[AssistantStreamEvent]: + """ + When a run has the `status: "requires_action"` and `required_action.type` is + `submit_tool_outputs`, this endpoint can be used to submit the outputs from the + tool calls once they're all completed. All outputs must be submitted in a single + request. + + Args: + stream: If `true`, returns a stream of events that happen during the Run as server-sent + events, terminating when the Run enters a terminal state with a `data: [DONE]` + message. + + tool_outputs: A list of tools for which the outputs are being submitted. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -665,6 +1454,23 @@ async def submit_tool_outputs( timeout: Override the client-level default timeout for this request, in seconds """ + ... + + @required_args(["thread_id", "tool_outputs"], ["thread_id", "stream", "tool_outputs"]) + async def submit_tool_outputs( + self, + run_id: str, + *, + thread_id: str, + tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], + stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Run | AsyncStream[AssistantStreamEvent]: if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") if not run_id: @@ -673,13 +1479,111 @@ async def submit_tool_outputs( return await self._post( f"/threads/{thread_id}/runs/{run_id}/submit_tool_outputs", body=await async_maybe_transform( - {"tool_outputs": tool_outputs}, run_submit_tool_outputs_params.RunSubmitToolOutputsParams + { + "tool_outputs": tool_outputs, + "stream": stream, + }, + run_submit_tool_outputs_params.RunSubmitToolOutputsParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Run, + stream=stream or False, + stream_cls=AsyncStream[AssistantStreamEvent], + ) + + @overload + def submit_tool_outputs_stream( + self, + *, + tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], + run_id: str, + thread_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncAssistantStreamManager[AsyncAssistantEventHandler]: + """ + Submit the tool outputs from a previous run and stream the run to a terminal + state. + """ + ... + + @overload + def submit_tool_outputs_stream( + self, + *, + tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], + run_id: str, + thread_id: str, + event_handler: AsyncAssistantEventHandlerT, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncAssistantStreamManager[AsyncAssistantEventHandlerT]: + """ + Submit the tool outputs from a previous run and stream the run to a terminal + state. + """ + ... + + def submit_tool_outputs_stream( + self, + *, + tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], + run_id: str, + thread_id: str, + event_handler: AsyncAssistantEventHandlerT | None = None, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> ( + AsyncAssistantStreamManager[AsyncAssistantEventHandler] + | AsyncAssistantStreamManager[AsyncAssistantEventHandlerT] + ): + """ + Submit the tool outputs from a previous run and stream the run to a terminal + state. + """ + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") + + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + + extra_headers = { + "OpenAI-Beta": "assistants=v1", + "X-Stainless-Stream-Helper": "threads.runs.submit_tool_outputs_stream", + "X-Stainless-Custom-Event-Handler": "true" if event_handler else "false", + **(extra_headers or {}), + } + request = self._post( + f"/threads/{thread_id}/runs/{run_id}/submit_tool_outputs", + body=maybe_transform( + { + "tool_outputs": tool_outputs, + "stream": True, + }, + run_submit_tool_outputs_params.RunSubmitToolOutputsParams, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=Run, + stream=True, + stream_cls=AsyncStream[AssistantStreamEvent], ) + return AsyncAssistantStreamManager(request, event_handler=event_handler or AsyncAssistantEventHandler()) class RunsWithRawResponse: diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index cc0e1c0959..17afe285cc 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -2,7 +2,9 @@ from __future__ import annotations -from typing import Iterable, Optional +from typing import Iterable, Optional, overload +from functools import partial +from typing_extensions import Literal import httpx @@ -25,6 +27,7 @@ ) from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ...._utils import ( + required_args, maybe_transform, async_maybe_transform, ) @@ -32,9 +35,11 @@ from ...._compat import cached_property from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ...._streaming import Stream, AsyncStream from ....types.beta import ( Thread, ThreadDeleted, + AssistantStreamEvent, thread_create_params, thread_update_params, thread_create_and_run_params, @@ -42,6 +47,14 @@ from ...._base_client import ( make_request_options, ) +from ....lib.streaming import ( + AssistantEventHandler, + AssistantEventHandlerT, + AssistantStreamManager, + AsyncAssistantEventHandler, + AsyncAssistantEventHandlerT, + AsyncAssistantStreamManager, +) from .messages.messages import Messages, AsyncMessages from ....types.beta.threads import Run @@ -222,6 +235,7 @@ def delete( cast_to=ThreadDeleted, ) + @overload def create_and_run( self, *, @@ -229,6 +243,7 @@ def create_and_run( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -259,6 +274,126 @@ def create_and_run( model associated with the assistant. If not, the model associated with the assistant will be used. + stream: If `true`, returns a stream of events that happen during the Run as server-sent + events, terminating when the Run enters a terminal state with a `data: [DONE]` + message. + + thread: If no thread is provided, an empty thread will be created. + + tools: Override the tools the assistant can use for this run. This is useful for + modifying the behavior on a per-run basis. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + def create_and_run( + self, + *, + assistant_id: str, + stream: Literal[True], + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Stream[AssistantStreamEvent]: + """ + Create a thread and run it in one request. + + Args: + assistant_id: The ID of the + [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + execute this run. + + stream: If `true`, returns a stream of events that happen during the Run as server-sent + events, terminating when the Run enters a terminal state with a `data: [DONE]` + message. + + instructions: Override the default system message of the assistant. This is useful for + modifying the behavior on a per-run basis. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + be used to execute this run. If a value is provided here, it will override the + model associated with the assistant. If not, the model associated with the + assistant will be used. + + thread: If no thread is provided, an empty thread will be created. + + tools: Override the tools the assistant can use for this run. This is useful for + modifying the behavior on a per-run basis. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + def create_and_run( + self, + *, + assistant_id: str, + stream: bool, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Run | Stream[AssistantStreamEvent]: + """ + Create a thread and run it in one request. + + Args: + assistant_id: The ID of the + [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + execute this run. + + stream: If `true`, returns a stream of events that happen during the Run as server-sent + events, terminating when the Run enters a terminal state with a `data: [DONE]` + message. + + instructions: Override the default system message of the assistant. This is useful for + modifying the behavior on a per-run basis. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + be used to execute this run. If a value is provided here, it will override the + model associated with the assistant. If not, the model associated with the + assistant will be used. + thread: If no thread is provided, an empty thread will be created. tools: Override the tools the assistant can use for this run. This is useful for @@ -272,6 +407,26 @@ def create_and_run( timeout: Override the client-level default timeout for this request, in seconds """ + ... + + @required_args(["assistant_id"], ["assistant_id", "stream"]) + def create_and_run( + self, + *, + assistant_id: str, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Run | Stream[AssistantStreamEvent]: extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return self._post( "/threads/runs", @@ -281,6 +436,95 @@ def create_and_run( "instructions": instructions, "metadata": metadata, "model": model, + "stream": stream, + "thread": thread, + "tools": tools, + }, + thread_create_and_run_params.ThreadCreateAndRunParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Run, + stream=stream or False, + stream_cls=Stream[AssistantStreamEvent], + ) + + @overload + def create_and_run_stream( + self, + *, + assistant_id: str, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AssistantStreamManager[AssistantEventHandler]: + """Create a thread and stream the run back""" + ... + + @overload + def create_and_run_stream( + self, + *, + assistant_id: str, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + event_handler: AssistantEventHandlerT, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AssistantStreamManager[AssistantEventHandlerT]: + """Create a thread and stream the run back""" + ... + + def create_and_run_stream( + self, + *, + assistant_id: str, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + event_handler: AssistantEventHandlerT | None = None, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AssistantStreamManager[AssistantEventHandler] | AssistantStreamManager[AssistantEventHandlerT]: + """Create a thread and stream the run back""" + extra_headers = { + "OpenAI-Beta": "assistants=v1", + "X-Stainless-Stream-Helper": "threads.create_and_run_stream", + "X-Stainless-Custom-Event-Handler": "true" if event_handler else "false", + **(extra_headers or {}), + } + make_request = partial( + self._post, + "/threads/runs", + body=maybe_transform( + { + "assistant_id": assistant_id, + "instructions": instructions, + "metadata": metadata, + "model": model, + "stream": True, "thread": thread, "tools": tools, }, @@ -290,7 +534,10 @@ def create_and_run( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=Run, + stream=True, + stream_cls=Stream[AssistantStreamEvent], ) + return AssistantStreamManager(make_request, event_handler=event_handler or AssistantEventHandler()) class AsyncThreads(AsyncAPIResource): @@ -467,6 +714,7 @@ async def delete( cast_to=ThreadDeleted, ) + @overload async def create_and_run( self, *, @@ -474,6 +722,7 @@ async def create_and_run( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -504,6 +753,10 @@ async def create_and_run( model associated with the assistant. If not, the model associated with the assistant will be used. + stream: If `true`, returns a stream of events that happen during the Run as server-sent + events, terminating when the Run enters a terminal state with a `data: [DONE]` + message. + thread: If no thread is provided, an empty thread will be created. tools: Override the tools the assistant can use for this run. This is useful for @@ -517,6 +770,142 @@ async def create_and_run( timeout: Override the client-level default timeout for this request, in seconds """ + ... + + @overload + async def create_and_run( + self, + *, + assistant_id: str, + stream: Literal[True], + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncStream[AssistantStreamEvent]: + """ + Create a thread and run it in one request. + + Args: + assistant_id: The ID of the + [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + execute this run. + + stream: If `true`, returns a stream of events that happen during the Run as server-sent + events, terminating when the Run enters a terminal state with a `data: [DONE]` + message. + + instructions: Override the default system message of the assistant. This is useful for + modifying the behavior on a per-run basis. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + be used to execute this run. If a value is provided here, it will override the + model associated with the assistant. If not, the model associated with the + assistant will be used. + + thread: If no thread is provided, an empty thread will be created. + + tools: Override the tools the assistant can use for this run. This is useful for + modifying the behavior on a per-run basis. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + async def create_and_run( + self, + *, + assistant_id: str, + stream: bool, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Run | AsyncStream[AssistantStreamEvent]: + """ + Create a thread and run it in one request. + + Args: + assistant_id: The ID of the + [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to + execute this run. + + stream: If `true`, returns a stream of events that happen during the Run as server-sent + events, terminating when the Run enters a terminal state with a `data: [DONE]` + message. + + instructions: Override the default system message of the assistant. This is useful for + modifying the behavior on a per-run basis. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to + be used to execute this run. If a value is provided here, it will override the + model associated with the assistant. If not, the model associated with the + assistant will be used. + + thread: If no thread is provided, an empty thread will be created. + + tools: Override the tools the assistant can use for this run. This is useful for + modifying the behavior on a per-run basis. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @required_args(["assistant_id"], ["assistant_id", "stream"]) + async def create_and_run( + self, + *, + assistant_id: str, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Run | AsyncStream[AssistantStreamEvent]: extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} return await self._post( "/threads/runs", @@ -526,6 +915,97 @@ async def create_and_run( "instructions": instructions, "metadata": metadata, "model": model, + "stream": stream, + "thread": thread, + "tools": tools, + }, + thread_create_and_run_params.ThreadCreateAndRunParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Run, + stream=stream or False, + stream_cls=AsyncStream[AssistantStreamEvent], + ) + + @overload + def create_and_run_stream( + self, + *, + assistant_id: str, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncAssistantStreamManager[AsyncAssistantEventHandler]: + """Create a thread and stream the run back""" + ... + + @overload + def create_and_run_stream( + self, + *, + assistant_id: str, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + event_handler: AsyncAssistantEventHandlerT, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncAssistantStreamManager[AsyncAssistantEventHandlerT]: + """Create a thread and stream the run back""" + ... + + def create_and_run_stream( + self, + *, + assistant_id: str, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + event_handler: AsyncAssistantEventHandlerT | None = None, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> ( + AsyncAssistantStreamManager[AsyncAssistantEventHandler] + | AsyncAssistantStreamManager[AsyncAssistantEventHandlerT] + ): + """Create a thread and stream the run back""" + extra_headers = { + "OpenAI-Beta": "assistants=v1", + "X-Stainless-Stream-Helper": "threads.create_and_run_stream", + "X-Stainless-Custom-Event-Handler": "true" if event_handler else "false", + **(extra_headers or {}), + } + request = self._post( + "/threads/runs", + body=maybe_transform( + { + "assistant_id": assistant_id, + "instructions": instructions, + "metadata": metadata, + "model": model, + "stream": True, "thread": thread, "tools": tools, }, @@ -535,7 +1015,10 @@ async def create_and_run( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=Run, + stream=True, + stream_cls=AsyncStream[AssistantStreamEvent], ) + return AsyncAssistantStreamManager(request, event_handler=event_handler or AsyncAssistantEventHandler()) class ThreadsWithRawResponse: diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index 20ea4cffbb..abe466ef77 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -206,7 +206,7 @@ def create( tools: A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs - for. + for. A max of 128 functions are supported. top_logprobs: An integer between 0 and 20 specifying the number of most likely tokens to return at each token position, each with an associated log probability. @@ -396,7 +396,7 @@ def create( tools: A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs - for. + for. A max of 128 functions are supported. top_logprobs: An integer between 0 and 20 specifying the number of most likely tokens to return at each token position, each with an associated log probability. @@ -586,7 +586,7 @@ def create( tools: A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs - for. + for. A max of 128 functions are supported. top_logprobs: An integer between 0 and 20 specifying the number of most likely tokens to return at each token position, each with an associated log probability. @@ -873,7 +873,7 @@ async def create( tools: A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs - for. + for. A max of 128 functions are supported. top_logprobs: An integer between 0 and 20 specifying the number of most likely tokens to return at each token position, each with an associated log probability. @@ -1063,7 +1063,7 @@ async def create( tools: A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs - for. + for. A max of 128 functions are supported. top_logprobs: An integer between 0 and 20 specifying the number of most likely tokens to return at each token position, each with an associated log probability. @@ -1253,7 +1253,7 @@ async def create( tools: A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs - for. + for. A max of 128 functions are supported. top_logprobs: An integer between 0 and 20 specifying the number of most likely tokens to return at each token position, each with an associated log probability. diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index 6d3756f6ba..8a2bad5fda 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -157,6 +157,8 @@ def create( suffix: The suffix that comes after a completion of inserted text. + This parameter is only supported for `gpt-3.5-turbo-instruct`. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. @@ -305,6 +307,8 @@ def create( suffix: The suffix that comes after a completion of inserted text. + This parameter is only supported for `gpt-3.5-turbo-instruct`. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. @@ -453,6 +457,8 @@ def create( suffix: The suffix that comes after a completion of inserted text. + This parameter is only supported for `gpt-3.5-turbo-instruct`. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. @@ -671,6 +677,8 @@ async def create( suffix: The suffix that comes after a completion of inserted text. + This parameter is only supported for `gpt-3.5-turbo-instruct`. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. @@ -819,6 +827,8 @@ async def create( suffix: The suffix that comes after a completion of inserted text. + This parameter is only supported for `gpt-3.5-turbo-instruct`. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. @@ -967,6 +977,8 @@ async def create( suffix: The suffix that comes after a completion of inserted text. + This parameter is only supported for `gpt-3.5-turbo-instruct`. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index d6108e1eed..e536d0b5a7 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -4,7 +4,11 @@ from .image import Image as Image from .model import Model as Model -from .shared import FunctionDefinition as FunctionDefinition, FunctionParameters as FunctionParameters +from .shared import ( + ErrorObject as ErrorObject, + FunctionDefinition as FunctionDefinition, + FunctionParameters as FunctionParameters, +) from .embedding import Embedding as Embedding from .completion import Completion as Completion from .moderation import Moderation as Moderation diff --git a/src/openai/types/beta/__init__.py b/src/openai/types/beta/__init__.py index e6742521e9..714b3e159d 100644 --- a/src/openai/types/beta/__init__.py +++ b/src/openai/types/beta/__init__.py @@ -4,11 +4,20 @@ from .thread import Thread as Thread from .assistant import Assistant as Assistant +from .function_tool import FunctionTool as FunctionTool +from .assistant_tool import AssistantTool as AssistantTool +from .retrieval_tool import RetrievalTool as RetrievalTool from .thread_deleted import ThreadDeleted as ThreadDeleted from .assistant_deleted import AssistantDeleted as AssistantDeleted +from .function_tool_param import FunctionToolParam as FunctionToolParam +from .assistant_tool_param import AssistantToolParam as AssistantToolParam +from .retrieval_tool_param import RetrievalToolParam as RetrievalToolParam from .thread_create_params import ThreadCreateParams as ThreadCreateParams from .thread_update_params import ThreadUpdateParams as ThreadUpdateParams from .assistant_list_params import AssistantListParams as AssistantListParams +from .code_interpreter_tool import CodeInterpreterTool as CodeInterpreterTool +from .assistant_stream_event import AssistantStreamEvent as AssistantStreamEvent from .assistant_create_params import AssistantCreateParams as AssistantCreateParams from .assistant_update_params import AssistantUpdateParams as AssistantUpdateParams +from .code_interpreter_tool_param import CodeInterpreterToolParam as CodeInterpreterToolParam from .thread_create_and_run_params import ThreadCreateAndRunParams as ThreadCreateAndRunParams diff --git a/src/openai/types/beta/assistant.py b/src/openai/types/beta/assistant.py index 7ba50652aa..31b847d72c 100644 --- a/src/openai/types/beta/assistant.py +++ b/src/openai/types/beta/assistant.py @@ -1,33 +1,12 @@ # File generated from our OpenAPI spec by Stainless. -from typing import List, Union, Optional -from typing_extensions import Literal, Annotated +from typing import List, Optional +from typing_extensions import Literal -from ..shared import FunctionDefinition -from ..._utils import PropertyInfo from ..._models import BaseModel +from .assistant_tool import AssistantTool -__all__ = ["Assistant", "Tool", "ToolCodeInterpreter", "ToolRetrieval", "ToolFunction"] - - -class ToolCodeInterpreter(BaseModel): - type: Literal["code_interpreter"] - """The type of tool being defined: `code_interpreter`""" - - -class ToolRetrieval(BaseModel): - type: Literal["retrieval"] - """The type of tool being defined: `retrieval`""" - - -class ToolFunction(BaseModel): - function: FunctionDefinition - - type: Literal["function"] - """The type of tool being defined: `function`""" - - -Tool = Annotated[Union[ToolCodeInterpreter, ToolRetrieval, ToolFunction], PropertyInfo(discriminator="type")] +__all__ = ["Assistant"] class Assistant(BaseModel): @@ -77,7 +56,7 @@ class Assistant(BaseModel): object: Literal["assistant"] """The object type, which is always `assistant`.""" - tools: List[Tool] + tools: List[AssistantTool] """A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types diff --git a/src/openai/types/beta/assistant_create_params.py b/src/openai/types/beta/assistant_create_params.py index c49d6f6950..0e39619a9c 100644 --- a/src/openai/types/beta/assistant_create_params.py +++ b/src/openai/types/beta/assistant_create_params.py @@ -2,18 +2,12 @@ from __future__ import annotations -from typing import List, Union, Iterable, Optional -from typing_extensions import Literal, Required, TypedDict +from typing import List, Iterable, Optional +from typing_extensions import Required, TypedDict -from ...types import shared_params +from .assistant_tool_param import AssistantToolParam -__all__ = [ - "AssistantCreateParams", - "Tool", - "ToolAssistantToolsCode", - "ToolAssistantToolsRetrieval", - "ToolAssistantToolsFunction", -] +__all__ = ["AssistantCreateParams"] class AssistantCreateParams(TypedDict, total=False): @@ -54,29 +48,9 @@ class AssistantCreateParams(TypedDict, total=False): name: Optional[str] """The name of the assistant. The maximum length is 256 characters.""" - tools: Iterable[Tool] + tools: Iterable[AssistantToolParam] """A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `retrieval`, or `function`. """ - - -class ToolAssistantToolsCode(TypedDict, total=False): - type: Required[Literal["code_interpreter"]] - """The type of tool being defined: `code_interpreter`""" - - -class ToolAssistantToolsRetrieval(TypedDict, total=False): - type: Required[Literal["retrieval"]] - """The type of tool being defined: `retrieval`""" - - -class ToolAssistantToolsFunction(TypedDict, total=False): - function: Required[shared_params.FunctionDefinition] - - type: Required[Literal["function"]] - """The type of tool being defined: `function`""" - - -Tool = Union[ToolAssistantToolsCode, ToolAssistantToolsRetrieval, ToolAssistantToolsFunction] diff --git a/src/openai/types/beta/assistant_stream_event.py b/src/openai/types/beta/assistant_stream_event.py new file mode 100644 index 0000000000..ca7f814a8a --- /dev/null +++ b/src/openai/types/beta/assistant_stream_event.py @@ -0,0 +1,276 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Union +from typing_extensions import Literal, Annotated + +from .thread import Thread +from ..shared import ErrorObject +from .threads import Run, Message, MessageDeltaEvent +from ..._utils import PropertyInfo +from ..._models import BaseModel +from .threads.runs import RunStep, RunStepDeltaEvent + +__all__ = [ + "AssistantStreamEvent", + "ThreadCreated", + "ThreadRunCreated", + "ThreadRunQueued", + "ThreadRunInProgress", + "ThreadRunRequiresAction", + "ThreadRunCompleted", + "ThreadRunFailed", + "ThreadRunCancelling", + "ThreadRunCancelled", + "ThreadRunExpired", + "ThreadRunStepCreated", + "ThreadRunStepInProgress", + "ThreadRunStepDelta", + "ThreadRunStepCompleted", + "ThreadRunStepFailed", + "ThreadRunStepCancelled", + "ThreadRunStepExpired", + "ThreadMessageCreated", + "ThreadMessageInProgress", + "ThreadMessageDelta", + "ThreadMessageCompleted", + "ThreadMessageIncomplete", + "ErrorEvent", +] + + +class ThreadCreated(BaseModel): + data: Thread + """ + Represents a thread that contains + [messages](https://platform.openai.com/docs/api-reference/messages). + """ + + event: Literal["thread.created"] + + +class ThreadRunCreated(BaseModel): + data: Run + """ + Represents an execution run on a + [thread](https://platform.openai.com/docs/api-reference/threads). + """ + + event: Literal["thread.run.created"] + + +class ThreadRunQueued(BaseModel): + data: Run + """ + Represents an execution run on a + [thread](https://platform.openai.com/docs/api-reference/threads). + """ + + event: Literal["thread.run.queued"] + + +class ThreadRunInProgress(BaseModel): + data: Run + """ + Represents an execution run on a + [thread](https://platform.openai.com/docs/api-reference/threads). + """ + + event: Literal["thread.run.in_progress"] + + +class ThreadRunRequiresAction(BaseModel): + data: Run + """ + Represents an execution run on a + [thread](https://platform.openai.com/docs/api-reference/threads). + """ + + event: Literal["thread.run.requires_action"] + + +class ThreadRunCompleted(BaseModel): + data: Run + """ + Represents an execution run on a + [thread](https://platform.openai.com/docs/api-reference/threads). + """ + + event: Literal["thread.run.completed"] + + +class ThreadRunFailed(BaseModel): + data: Run + """ + Represents an execution run on a + [thread](https://platform.openai.com/docs/api-reference/threads). + """ + + event: Literal["thread.run.failed"] + + +class ThreadRunCancelling(BaseModel): + data: Run + """ + Represents an execution run on a + [thread](https://platform.openai.com/docs/api-reference/threads). + """ + + event: Literal["thread.run.cancelling"] + + +class ThreadRunCancelled(BaseModel): + data: Run + """ + Represents an execution run on a + [thread](https://platform.openai.com/docs/api-reference/threads). + """ + + event: Literal["thread.run.cancelled"] + + +class ThreadRunExpired(BaseModel): + data: Run + """ + Represents an execution run on a + [thread](https://platform.openai.com/docs/api-reference/threads). + """ + + event: Literal["thread.run.expired"] + + +class ThreadRunStepCreated(BaseModel): + data: RunStep + """Represents a step in execution of a run.""" + + event: Literal["thread.run.step.created"] + + +class ThreadRunStepInProgress(BaseModel): + data: RunStep + """Represents a step in execution of a run.""" + + event: Literal["thread.run.step.in_progress"] + + +class ThreadRunStepDelta(BaseModel): + data: RunStepDeltaEvent + """Represents a run step delta i.e. + + any changed fields on a run step during streaming. + """ + + event: Literal["thread.run.step.delta"] + + +class ThreadRunStepCompleted(BaseModel): + data: RunStep + """Represents a step in execution of a run.""" + + event: Literal["thread.run.step.completed"] + + +class ThreadRunStepFailed(BaseModel): + data: RunStep + """Represents a step in execution of a run.""" + + event: Literal["thread.run.step.failed"] + + +class ThreadRunStepCancelled(BaseModel): + data: RunStep + """Represents a step in execution of a run.""" + + event: Literal["thread.run.step.cancelled"] + + +class ThreadRunStepExpired(BaseModel): + data: RunStep + """Represents a step in execution of a run.""" + + event: Literal["thread.run.step.expired"] + + +class ThreadMessageCreated(BaseModel): + data: Message + """ + Represents a message within a + [thread](https://platform.openai.com/docs/api-reference/threads). + """ + + event: Literal["thread.message.created"] + + +class ThreadMessageInProgress(BaseModel): + data: Message + """ + Represents a message within a + [thread](https://platform.openai.com/docs/api-reference/threads). + """ + + event: Literal["thread.message.in_progress"] + + +class ThreadMessageDelta(BaseModel): + data: MessageDeltaEvent + """Represents a message delta i.e. + + any changed fields on a message during streaming. + """ + + event: Literal["thread.message.delta"] + + +class ThreadMessageCompleted(BaseModel): + data: Message + """ + Represents a message within a + [thread](https://platform.openai.com/docs/api-reference/threads). + """ + + event: Literal["thread.message.completed"] + + +class ThreadMessageIncomplete(BaseModel): + data: Message + """ + Represents a message within a + [thread](https://platform.openai.com/docs/api-reference/threads). + """ + + event: Literal["thread.message.incomplete"] + + +class ErrorEvent(BaseModel): + data: ErrorObject + + event: Literal["error"] + + +AssistantStreamEvent = Annotated[ + Union[ + ThreadCreated, + ThreadRunCreated, + ThreadRunQueued, + ThreadRunInProgress, + ThreadRunRequiresAction, + ThreadRunCompleted, + ThreadRunFailed, + ThreadRunCancelling, + ThreadRunCancelled, + ThreadRunExpired, + ThreadRunStepCreated, + ThreadRunStepInProgress, + ThreadRunStepDelta, + ThreadRunStepCompleted, + ThreadRunStepFailed, + ThreadRunStepCancelled, + ThreadRunStepExpired, + ThreadMessageCreated, + ThreadMessageInProgress, + ThreadMessageDelta, + ThreadMessageCompleted, + ThreadMessageIncomplete, + ErrorEvent, + ], + PropertyInfo(discriminator="event"), +] diff --git a/src/openai/types/beta/assistant_tool.py b/src/openai/types/beta/assistant_tool.py new file mode 100644 index 0000000000..9e589eae7a --- /dev/null +++ b/src/openai/types/beta/assistant_tool.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Union +from typing_extensions import Annotated + +from ..._utils import PropertyInfo +from .function_tool import FunctionTool +from .retrieval_tool import RetrievalTool +from .code_interpreter_tool import CodeInterpreterTool + +__all__ = ["AssistantTool"] + +AssistantTool = Annotated[Union[CodeInterpreterTool, RetrievalTool, FunctionTool], PropertyInfo(discriminator="type")] diff --git a/src/openai/types/beta/assistant_tool_param.py b/src/openai/types/beta/assistant_tool_param.py new file mode 100644 index 0000000000..02b56a8c5d --- /dev/null +++ b/src/openai/types/beta/assistant_tool_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing import Union + +from .function_tool_param import FunctionToolParam +from .retrieval_tool_param import RetrievalToolParam +from .code_interpreter_tool_param import CodeInterpreterToolParam + +__all__ = ["AssistantToolParam"] + +AssistantToolParam = Union[CodeInterpreterToolParam, RetrievalToolParam, FunctionToolParam] diff --git a/src/openai/types/beta/assistant_update_params.py b/src/openai/types/beta/assistant_update_params.py index c5ccde62c5..fbff50f444 100644 --- a/src/openai/types/beta/assistant_update_params.py +++ b/src/openai/types/beta/assistant_update_params.py @@ -2,18 +2,12 @@ from __future__ import annotations -from typing import List, Union, Iterable, Optional -from typing_extensions import Literal, Required, TypedDict +from typing import List, Iterable, Optional +from typing_extensions import TypedDict -from ...types import shared_params +from .assistant_tool_param import AssistantToolParam -__all__ = [ - "AssistantUpdateParams", - "Tool", - "ToolAssistantToolsCode", - "ToolAssistantToolsRetrieval", - "ToolAssistantToolsFunction", -] +__all__ = ["AssistantUpdateParams"] class AssistantUpdateParams(TypedDict, total=False): @@ -56,29 +50,9 @@ class AssistantUpdateParams(TypedDict, total=False): name: Optional[str] """The name of the assistant. The maximum length is 256 characters.""" - tools: Iterable[Tool] + tools: Iterable[AssistantToolParam] """A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `retrieval`, or `function`. """ - - -class ToolAssistantToolsCode(TypedDict, total=False): - type: Required[Literal["code_interpreter"]] - """The type of tool being defined: `code_interpreter`""" - - -class ToolAssistantToolsRetrieval(TypedDict, total=False): - type: Required[Literal["retrieval"]] - """The type of tool being defined: `retrieval`""" - - -class ToolAssistantToolsFunction(TypedDict, total=False): - function: Required[shared_params.FunctionDefinition] - - type: Required[Literal["function"]] - """The type of tool being defined: `function`""" - - -Tool = Union[ToolAssistantToolsCode, ToolAssistantToolsRetrieval, ToolAssistantToolsFunction] diff --git a/src/openai/types/beta/code_interpreter_tool.py b/src/openai/types/beta/code_interpreter_tool.py new file mode 100644 index 0000000000..4964047ba7 --- /dev/null +++ b/src/openai/types/beta/code_interpreter_tool.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["CodeInterpreterTool"] + + +class CodeInterpreterTool(BaseModel): + type: Literal["code_interpreter"] + """The type of tool being defined: `code_interpreter`""" diff --git a/src/openai/types/beta/code_interpreter_tool_param.py b/src/openai/types/beta/code_interpreter_tool_param.py new file mode 100644 index 0000000000..92d6e02dbc --- /dev/null +++ b/src/openai/types/beta/code_interpreter_tool_param.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["CodeInterpreterToolParam"] + + +class CodeInterpreterToolParam(TypedDict, total=False): + type: Required[Literal["code_interpreter"]] + """The type of tool being defined: `code_interpreter`""" diff --git a/src/openai/types/beta/function_tool.py b/src/openai/types/beta/function_tool.py new file mode 100644 index 0000000000..fa0ab3b83e --- /dev/null +++ b/src/openai/types/beta/function_tool.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing_extensions import Literal + +from ..shared import FunctionDefinition +from ..._models import BaseModel + +__all__ = ["FunctionTool"] + + +class FunctionTool(BaseModel): + function: FunctionDefinition + + type: Literal["function"] + """The type of tool being defined: `function`""" diff --git a/src/openai/types/beta/function_tool_param.py b/src/openai/types/beta/function_tool_param.py new file mode 100644 index 0000000000..e631d69e20 --- /dev/null +++ b/src/openai/types/beta/function_tool_param.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +from ...types import shared_params + +__all__ = ["FunctionToolParam"] + + +class FunctionToolParam(TypedDict, total=False): + function: Required[shared_params.FunctionDefinition] + + type: Required[Literal["function"]] + """The type of tool being defined: `function`""" diff --git a/src/openai/types/beta/retrieval_tool.py b/src/openai/types/beta/retrieval_tool.py new file mode 100644 index 0000000000..17d5bea130 --- /dev/null +++ b/src/openai/types/beta/retrieval_tool.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["RetrievalTool"] + + +class RetrievalTool(BaseModel): + type: Literal["retrieval"] + """The type of tool being defined: `retrieval`""" diff --git a/src/openai/types/beta/retrieval_tool_param.py b/src/openai/types/beta/retrieval_tool_param.py new file mode 100644 index 0000000000..6f803e4672 --- /dev/null +++ b/src/openai/types/beta/retrieval_tool_param.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["RetrievalToolParam"] + + +class RetrievalToolParam(TypedDict, total=False): + type: Required[Literal["retrieval"]] + """The type of tool being defined: `retrieval`""" diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index cc1051b3d6..5078639e6a 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -5,20 +5,21 @@ from typing import List, Union, Iterable, Optional from typing_extensions import Literal, Required, TypedDict -from ...types import shared_params +from .function_tool_param import FunctionToolParam +from .retrieval_tool_param import RetrievalToolParam +from .code_interpreter_tool_param import CodeInterpreterToolParam __all__ = [ - "ThreadCreateAndRunParams", + "ThreadCreateAndRunParamsBase", "Thread", "ThreadMessage", "Tool", - "ToolAssistantToolsCode", - "ToolAssistantToolsRetrieval", - "ToolAssistantToolsFunction", + "ThreadCreateAndRunParamsNonStreaming", + "ThreadCreateAndRunParamsStreaming", ] -class ThreadCreateAndRunParams(TypedDict, total=False): +class ThreadCreateAndRunParamsBase(TypedDict, total=False): assistant_id: Required[str] """ The ID of the @@ -101,21 +102,25 @@ class Thread(TypedDict, total=False): """ -class ToolAssistantToolsCode(TypedDict, total=False): - type: Required[Literal["code_interpreter"]] - """The type of tool being defined: `code_interpreter`""" +Tool = Union[CodeInterpreterToolParam, RetrievalToolParam, FunctionToolParam] -class ToolAssistantToolsRetrieval(TypedDict, total=False): - type: Required[Literal["retrieval"]] - """The type of tool being defined: `retrieval`""" - +class ThreadCreateAndRunParamsNonStreaming(ThreadCreateAndRunParamsBase): + stream: Optional[Literal[False]] + """ + If `true`, returns a stream of events that happen during the Run as server-sent + events, terminating when the Run enters a terminal state with a `data: [DONE]` + message. + """ -class ToolAssistantToolsFunction(TypedDict, total=False): - function: Required[shared_params.FunctionDefinition] - type: Required[Literal["function"]] - """The type of tool being defined: `function`""" +class ThreadCreateAndRunParamsStreaming(ThreadCreateAndRunParamsBase): + stream: Required[Literal[True]] + """ + If `true`, returns a stream of events that happen during the Run as server-sent + events, terminating when the Run enters a terminal state with a `data: [DONE]` + message. + """ -Tool = Union[ToolAssistantToolsCode, ToolAssistantToolsRetrieval, ToolAssistantToolsFunction] +ThreadCreateAndRunParams = Union[ThreadCreateAndRunParamsNonStreaming, ThreadCreateAndRunParamsStreaming] diff --git a/src/openai/types/beta/threads/__init__.py b/src/openai/types/beta/threads/__init__.py index a71cbde3e3..ff45871afe 100644 --- a/src/openai/types/beta/threads/__init__.py +++ b/src/openai/types/beta/threads/__init__.py @@ -3,15 +3,31 @@ from __future__ import annotations from .run import Run as Run +from .text import Text as Text +from .message import Message as Message +from .annotation import Annotation as Annotation +from .image_file import ImageFile as ImageFile from .run_status import RunStatus as RunStatus -from .thread_message import ThreadMessage as ThreadMessage +from .text_delta import TextDelta as TextDelta +from .message_delta import MessageDelta as MessageDelta +from .message_content import MessageContent as MessageContent from .run_list_params import RunListParams as RunListParams +from .annotation_delta import AnnotationDelta as AnnotationDelta +from .image_file_delta import ImageFileDelta as ImageFileDelta +from .text_delta_block import TextDeltaBlock as TextDeltaBlock from .run_create_params import RunCreateParams as RunCreateParams from .run_update_params import RunUpdateParams as RunUpdateParams +from .text_content_block import TextContentBlock as TextContentBlock +from .message_delta_event import MessageDeltaEvent as MessageDeltaEvent from .message_list_params import MessageListParams as MessageListParams -from .message_content_text import MessageContentText as MessageContentText +from .file_path_annotation import FilePathAnnotation as FilePathAnnotation +from .message_content_delta import MessageContentDelta as MessageContentDelta from .message_create_params import MessageCreateParams as MessageCreateParams from .message_update_params import MessageUpdateParams as MessageUpdateParams -from .message_content_image_file import MessageContentImageFile as MessageContentImageFile +from .image_file_delta_block import ImageFileDeltaBlock as ImageFileDeltaBlock +from .file_citation_annotation import FileCitationAnnotation as FileCitationAnnotation +from .image_file_content_block import ImageFileContentBlock as ImageFileContentBlock +from .file_path_delta_annotation import FilePathDeltaAnnotation as FilePathDeltaAnnotation +from .file_citation_delta_annotation import FileCitationDeltaAnnotation as FileCitationDeltaAnnotation from .run_submit_tool_outputs_params import RunSubmitToolOutputsParams as RunSubmitToolOutputsParams from .required_action_function_tool_call import RequiredActionFunctionToolCall as RequiredActionFunctionToolCall diff --git a/src/openai/types/beta/threads/annotation.py b/src/openai/types/beta/threads/annotation.py new file mode 100644 index 0000000000..86a2115233 --- /dev/null +++ b/src/openai/types/beta/threads/annotation.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Union +from typing_extensions import Annotated + +from ...._utils import PropertyInfo +from .file_path_annotation import FilePathAnnotation +from .file_citation_annotation import FileCitationAnnotation + +__all__ = ["Annotation"] + +Annotation = Annotated[Union[FileCitationAnnotation, FilePathAnnotation], PropertyInfo(discriminator="type")] diff --git a/src/openai/types/beta/threads/annotation_delta.py b/src/openai/types/beta/threads/annotation_delta.py new file mode 100644 index 0000000000..fdcc67c3ff --- /dev/null +++ b/src/openai/types/beta/threads/annotation_delta.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Union +from typing_extensions import Annotated + +from ...._utils import PropertyInfo +from .file_path_delta_annotation import FilePathDeltaAnnotation +from .file_citation_delta_annotation import FileCitationDeltaAnnotation + +__all__ = ["AnnotationDelta"] + +AnnotationDelta = Annotated[ + Union[FileCitationDeltaAnnotation, FilePathDeltaAnnotation], PropertyInfo(discriminator="type") +] diff --git a/src/openai/types/beta/threads/file_citation_annotation.py b/src/openai/types/beta/threads/file_citation_annotation.py new file mode 100644 index 0000000000..da63938d93 --- /dev/null +++ b/src/openai/types/beta/threads/file_citation_annotation.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["FileCitationAnnotation", "FileCitation"] + + +class FileCitation(BaseModel): + file_id: str + """The ID of the specific File the citation is from.""" + + quote: str + """The specific quote in the file.""" + + +class FileCitationAnnotation(BaseModel): + end_index: int + + file_citation: FileCitation + + start_index: int + + text: str + """The text in the message content that needs to be replaced.""" + + type: Literal["file_citation"] + """Always `file_citation`.""" diff --git a/src/openai/types/beta/threads/file_citation_delta_annotation.py b/src/openai/types/beta/threads/file_citation_delta_annotation.py new file mode 100644 index 0000000000..3b4c5950d4 --- /dev/null +++ b/src/openai/types/beta/threads/file_citation_delta_annotation.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["FileCitationDeltaAnnotation", "FileCitation"] + + +class FileCitation(BaseModel): + file_id: Optional[str] = None + """The ID of the specific File the citation is from.""" + + quote: Optional[str] = None + """The specific quote in the file.""" + + +class FileCitationDeltaAnnotation(BaseModel): + index: int + """The index of the annotation in the text content part.""" + + type: Literal["file_citation"] + """Always `file_citation`.""" + + end_index: Optional[int] = None + + file_citation: Optional[FileCitation] = None + + start_index: Optional[int] = None + + text: Optional[str] = None + """The text in the message content that needs to be replaced.""" diff --git a/src/openai/types/beta/threads/file_path_annotation.py b/src/openai/types/beta/threads/file_path_annotation.py new file mode 100644 index 0000000000..2d9cf58184 --- /dev/null +++ b/src/openai/types/beta/threads/file_path_annotation.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["FilePathAnnotation", "FilePath"] + + +class FilePath(BaseModel): + file_id: str + """The ID of the file that was generated.""" + + +class FilePathAnnotation(BaseModel): + end_index: int + + file_path: FilePath + + start_index: int + + text: str + """The text in the message content that needs to be replaced.""" + + type: Literal["file_path"] + """Always `file_path`.""" diff --git a/src/openai/types/beta/threads/file_path_delta_annotation.py b/src/openai/types/beta/threads/file_path_delta_annotation.py new file mode 100644 index 0000000000..6d89748d2c --- /dev/null +++ b/src/openai/types/beta/threads/file_path_delta_annotation.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["FilePathDeltaAnnotation", "FilePath"] + + +class FilePath(BaseModel): + file_id: Optional[str] = None + """The ID of the file that was generated.""" + + +class FilePathDeltaAnnotation(BaseModel): + index: int + """The index of the annotation in the text content part.""" + + type: Literal["file_path"] + """Always `file_path`.""" + + end_index: Optional[int] = None + + file_path: Optional[FilePath] = None + + start_index: Optional[int] = None + + text: Optional[str] = None + """The text in the message content that needs to be replaced.""" diff --git a/src/openai/types/beta/threads/message_content_image_file.py b/src/openai/types/beta/threads/image_file.py similarity index 54% rename from src/openai/types/beta/threads/message_content_image_file.py rename to src/openai/types/beta/threads/image_file.py index eeba5a633c..371055627c 100644 --- a/src/openai/types/beta/threads/message_content_image_file.py +++ b/src/openai/types/beta/threads/image_file.py @@ -1,10 +1,8 @@ # File generated from our OpenAPI spec by Stainless. -from typing_extensions import Literal - from ...._models import BaseModel -__all__ = ["MessageContentImageFile", "ImageFile"] +__all__ = ["ImageFile"] class ImageFile(BaseModel): @@ -13,10 +11,3 @@ class ImageFile(BaseModel): The [File](https://platform.openai.com/docs/api-reference/files) ID of the image in the message content. """ - - -class MessageContentImageFile(BaseModel): - image_file: ImageFile - - type: Literal["image_file"] - """Always `image_file`.""" diff --git a/src/openai/types/beta/threads/image_file_content_block.py b/src/openai/types/beta/threads/image_file_content_block.py new file mode 100644 index 0000000000..3baf8b884b --- /dev/null +++ b/src/openai/types/beta/threads/image_file_content_block.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing_extensions import Literal + +from ...._models import BaseModel +from .image_file import ImageFile + +__all__ = ["ImageFileContentBlock"] + + +class ImageFileContentBlock(BaseModel): + image_file: ImageFile + + type: Literal["image_file"] + """Always `image_file`.""" diff --git a/src/openai/types/beta/threads/image_file_delta.py b/src/openai/types/beta/threads/image_file_delta.py new file mode 100644 index 0000000000..2bda05f82b --- /dev/null +++ b/src/openai/types/beta/threads/image_file_delta.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Optional + +from ...._models import BaseModel + +__all__ = ["ImageFileDelta"] + + +class ImageFileDelta(BaseModel): + file_id: Optional[str] = None + """ + The [File](https://platform.openai.com/docs/api-reference/files) ID of the image + in the message content. + """ diff --git a/src/openai/types/beta/threads/image_file_delta_block.py b/src/openai/types/beta/threads/image_file_delta_block.py new file mode 100644 index 0000000000..97cc1c4608 --- /dev/null +++ b/src/openai/types/beta/threads/image_file_delta_block.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel +from .image_file_delta import ImageFileDelta + +__all__ = ["ImageFileDeltaBlock"] + + +class ImageFileDeltaBlock(BaseModel): + index: int + """The index of the content part in the message.""" + + type: Literal["image_file"] + """Always `image_file`.""" + + image_file: Optional[ImageFileDelta] = None diff --git a/src/openai/types/beta/threads/thread_message.py b/src/openai/types/beta/threads/message.py similarity index 63% rename from src/openai/types/beta/threads/thread_message.py rename to src/openai/types/beta/threads/message.py index 6ed5da1401..4f307928be 100644 --- a/src/openai/types/beta/threads/thread_message.py +++ b/src/openai/types/beta/threads/message.py @@ -1,19 +1,20 @@ # File generated from our OpenAPI spec by Stainless. -from typing import List, Union, Optional -from typing_extensions import Literal, Annotated +from typing import List, Optional +from typing_extensions import Literal -from ...._utils import PropertyInfo from ...._models import BaseModel -from .message_content_text import MessageContentText -from .message_content_image_file import MessageContentImageFile +from .message_content import MessageContent -__all__ = ["ThreadMessage", "Content"] +__all__ = ["Message", "IncompleteDetails"] -Content = Annotated[Union[MessageContentImageFile, MessageContentText], PropertyInfo(discriminator="type")] +class IncompleteDetails(BaseModel): + reason: Literal["content_filter", "max_tokens", "run_cancelled", "run_expired", "run_failed"] + """The reason the message is incomplete.""" -class ThreadMessage(BaseModel): + +class Message(BaseModel): id: str """The identifier, which can be referenced in API endpoints.""" @@ -24,7 +25,10 @@ class ThreadMessage(BaseModel): authored this message. """ - content: List[Content] + completed_at: Optional[int] = None + """The Unix timestamp (in seconds) for when the message was completed.""" + + content: List[MessageContent] """The content of the message in array of text and/or images.""" created_at: int @@ -37,6 +41,12 @@ class ThreadMessage(BaseModel): that can access files. A maximum of 10 files can be attached to a message. """ + incomplete_at: Optional[int] = None + """The Unix timestamp (in seconds) for when the message was marked as incomplete.""" + + incomplete_details: Optional[IncompleteDetails] = None + """On an incomplete message, details about why the message is incomplete.""" + metadata: Optional[object] = None """Set of 16 key-value pairs that can be attached to an object. @@ -58,6 +68,12 @@ class ThreadMessage(BaseModel): authoring of this message. """ + status: Literal["in_progress", "incomplete", "completed"] + """ + The status of the message, which can be either `in_progress`, `incomplete`, or + `completed`. + """ + thread_id: str """ The [thread](https://platform.openai.com/docs/api-reference/threads) ID that diff --git a/src/openai/types/beta/threads/message_content.py b/src/openai/types/beta/threads/message_content.py new file mode 100644 index 0000000000..7da6a81fb6 --- /dev/null +++ b/src/openai/types/beta/threads/message_content.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Union +from typing_extensions import Annotated + +from ...._utils import PropertyInfo +from .text_content_block import TextContentBlock +from .image_file_content_block import ImageFileContentBlock + +__all__ = ["MessageContent"] + +MessageContent = Annotated[Union[ImageFileContentBlock, TextContentBlock], PropertyInfo(discriminator="type")] diff --git a/src/openai/types/beta/threads/message_content_delta.py b/src/openai/types/beta/threads/message_content_delta.py new file mode 100644 index 0000000000..7a8266d02f --- /dev/null +++ b/src/openai/types/beta/threads/message_content_delta.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Union +from typing_extensions import Annotated + +from ...._utils import PropertyInfo +from .text_delta_block import TextDeltaBlock +from .image_file_delta_block import ImageFileDeltaBlock + +__all__ = ["MessageContentDelta"] + +MessageContentDelta = Annotated[Union[ImageFileDeltaBlock, TextDeltaBlock], PropertyInfo(discriminator="type")] diff --git a/src/openai/types/beta/threads/message_content_text.py b/src/openai/types/beta/threads/message_content_text.py deleted file mode 100644 index dd05ff96ca..0000000000 --- a/src/openai/types/beta/threads/message_content_text.py +++ /dev/null @@ -1,77 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. - -from typing import List, Union -from typing_extensions import Literal, Annotated - -from ...._utils import PropertyInfo -from ...._models import BaseModel - -__all__ = [ - "MessageContentText", - "Text", - "TextAnnotation", - "TextAnnotationFileCitation", - "TextAnnotationFileCitationFileCitation", - "TextAnnotationFilePath", - "TextAnnotationFilePathFilePath", -] - - -class TextAnnotationFileCitationFileCitation(BaseModel): - file_id: str - """The ID of the specific File the citation is from.""" - - quote: str - """The specific quote in the file.""" - - -class TextAnnotationFileCitation(BaseModel): - end_index: int - - file_citation: TextAnnotationFileCitationFileCitation - - start_index: int - - text: str - """The text in the message content that needs to be replaced.""" - - type: Literal["file_citation"] - """Always `file_citation`.""" - - -class TextAnnotationFilePathFilePath(BaseModel): - file_id: str - """The ID of the file that was generated.""" - - -class TextAnnotationFilePath(BaseModel): - end_index: int - - file_path: TextAnnotationFilePathFilePath - - start_index: int - - text: str - """The text in the message content that needs to be replaced.""" - - type: Literal["file_path"] - """Always `file_path`.""" - - -TextAnnotation = Annotated[ - Union[TextAnnotationFileCitation, TextAnnotationFilePath], PropertyInfo(discriminator="type") -] - - -class Text(BaseModel): - annotations: List[TextAnnotation] - - value: str - """The data that makes up the text.""" - - -class MessageContentText(BaseModel): - text: Text - - type: Literal["text"] - """Always `text`.""" diff --git a/src/openai/types/beta/threads/message_delta.py b/src/openai/types/beta/threads/message_delta.py new file mode 100644 index 0000000000..1113cc27fb --- /dev/null +++ b/src/openai/types/beta/threads/message_delta.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import List, Optional +from typing_extensions import Literal + +from ...._models import BaseModel +from .message_content_delta import MessageContentDelta + +__all__ = ["MessageDelta"] + + +class MessageDelta(BaseModel): + content: Optional[List[MessageContentDelta]] = None + """The content of the message in array of text and/or images.""" + + file_ids: Optional[List[str]] = None + """ + A list of [file](https://platform.openai.com/docs/api-reference/files) IDs that + the assistant should use. Useful for tools like retrieval and code_interpreter + that can access files. A maximum of 10 files can be attached to a message. + """ + + role: Optional[Literal["user", "assistant"]] = None + """The entity that produced the message. One of `user` or `assistant`.""" diff --git a/src/openai/types/beta/threads/message_delta_event.py b/src/openai/types/beta/threads/message_delta_event.py new file mode 100644 index 0000000000..07a9107a34 --- /dev/null +++ b/src/openai/types/beta/threads/message_delta_event.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing_extensions import Literal + +from ...._models import BaseModel +from .message_delta import MessageDelta + +__all__ = ["MessageDeltaEvent"] + + +class MessageDeltaEvent(BaseModel): + id: str + """The identifier of the message, which can be referenced in API endpoints.""" + + delta: MessageDelta + """The delta containing the fields that have changed on the Message.""" + + object: Literal["thread.message.delta"] + """The object type, which is always `thread.message.delta`.""" diff --git a/src/openai/types/beta/threads/run.py b/src/openai/types/beta/threads/run.py index 38625d3781..dd2842c584 100644 --- a/src/openai/types/beta/threads/run.py +++ b/src/openai/types/beta/threads/run.py @@ -1,24 +1,14 @@ # File generated from our OpenAPI spec by Stainless. -from typing import List, Union, Optional +from typing import List, Optional from typing_extensions import Literal -from ...shared import FunctionDefinition from ...._models import BaseModel from .run_status import RunStatus +from ..assistant_tool import AssistantTool from .required_action_function_tool_call import RequiredActionFunctionToolCall -__all__ = [ - "Run", - "LastError", - "RequiredAction", - "RequiredActionSubmitToolOutputs", - "Tool", - "ToolAssistantToolsCode", - "ToolAssistantToolsRetrieval", - "ToolAssistantToolsFunction", - "Usage", -] +__all__ = ["Run", "LastError", "RequiredAction", "RequiredActionSubmitToolOutputs", "Usage"] class LastError(BaseModel): @@ -42,26 +32,6 @@ class RequiredAction(BaseModel): """For now, this is always `submit_tool_outputs`.""" -class ToolAssistantToolsCode(BaseModel): - type: Literal["code_interpreter"] - """The type of tool being defined: `code_interpreter`""" - - -class ToolAssistantToolsRetrieval(BaseModel): - type: Literal["retrieval"] - """The type of tool being defined: `retrieval`""" - - -class ToolAssistantToolsFunction(BaseModel): - function: FunctionDefinition - - type: Literal["function"] - """The type of tool being defined: `function`""" - - -Tool = Union[ToolAssistantToolsCode, ToolAssistantToolsRetrieval, ToolAssistantToolsFunction] - - class Usage(BaseModel): completion_tokens: int """Number of completion tokens used over the course of the run.""" @@ -93,7 +63,7 @@ class Run(BaseModel): created_at: int """The Unix timestamp (in seconds) for when the run was created.""" - expires_at: int + expires_at: Optional[int] = None """The Unix timestamp (in seconds) for when the run will expire.""" failed_at: Optional[int] = None @@ -156,7 +126,7 @@ class Run(BaseModel): that was executed on as a part of this run. """ - tools: List[Tool] + tools: List[AssistantTool] """ The list of tools that the [assistant](https://platform.openai.com/docs/api-reference/assistants) used for diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index b92649aa06..c012390f5c 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -5,18 +5,12 @@ from typing import Union, Iterable, Optional from typing_extensions import Literal, Required, TypedDict -from ....types import shared_params +from ..assistant_tool_param import AssistantToolParam -__all__ = [ - "RunCreateParams", - "Tool", - "ToolAssistantToolsCode", - "ToolAssistantToolsRetrieval", - "ToolAssistantToolsFunction", -] +__all__ = ["RunCreateParamsBase", "RunCreateParamsNonStreaming", "RunCreateParamsStreaming"] -class RunCreateParams(TypedDict, total=False): +class RunCreateParamsBase(TypedDict, total=False): assistant_id: Required[str] """ The ID of the @@ -54,28 +48,29 @@ class RunCreateParams(TypedDict, total=False): assistant will be used. """ - tools: Optional[Iterable[Tool]] + tools: Optional[Iterable[AssistantToolParam]] """Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. """ -class ToolAssistantToolsCode(TypedDict, total=False): - type: Required[Literal["code_interpreter"]] - """The type of tool being defined: `code_interpreter`""" - - -class ToolAssistantToolsRetrieval(TypedDict, total=False): - type: Required[Literal["retrieval"]] - """The type of tool being defined: `retrieval`""" - +class RunCreateParamsNonStreaming(RunCreateParamsBase): + stream: Optional[Literal[False]] + """ + If `true`, returns a stream of events that happen during the Run as server-sent + events, terminating when the Run enters a terminal state with a `data: [DONE]` + message. + """ -class ToolAssistantToolsFunction(TypedDict, total=False): - function: Required[shared_params.FunctionDefinition] - type: Required[Literal["function"]] - """The type of tool being defined: `function`""" +class RunCreateParamsStreaming(RunCreateParamsBase): + stream: Required[Literal[True]] + """ + If `true`, returns a stream of events that happen during the Run as server-sent + events, terminating when the Run enters a terminal state with a `data: [DONE]` + message. + """ -Tool = Union[ToolAssistantToolsCode, ToolAssistantToolsRetrieval, ToolAssistantToolsFunction] +RunCreateParams = Union[RunCreateParamsNonStreaming, RunCreateParamsStreaming] diff --git a/src/openai/types/beta/threads/run_submit_tool_outputs_params.py b/src/openai/types/beta/threads/run_submit_tool_outputs_params.py index 3b303a33fc..49e1ac49ab 100644 --- a/src/openai/types/beta/threads/run_submit_tool_outputs_params.py +++ b/src/openai/types/beta/threads/run_submit_tool_outputs_params.py @@ -2,13 +2,18 @@ from __future__ import annotations -from typing import Iterable -from typing_extensions import Required, TypedDict +from typing import Union, Iterable, Optional +from typing_extensions import Literal, Required, TypedDict -__all__ = ["RunSubmitToolOutputsParams", "ToolOutput"] +__all__ = [ + "RunSubmitToolOutputsParamsBase", + "ToolOutput", + "RunSubmitToolOutputsParamsNonStreaming", + "RunSubmitToolOutputsParamsStreaming", +] -class RunSubmitToolOutputsParams(TypedDict, total=False): +class RunSubmitToolOutputsParamsBase(TypedDict, total=False): thread_id: Required[str] tool_outputs: Required[Iterable[ToolOutput]] @@ -24,3 +29,24 @@ class ToolOutput(TypedDict, total=False): The ID of the tool call in the `required_action` object within the run object the output is being submitted for. """ + + +class RunSubmitToolOutputsParamsNonStreaming(RunSubmitToolOutputsParamsBase): + stream: Optional[Literal[False]] + """ + If `true`, returns a stream of events that happen during the Run as server-sent + events, terminating when the Run enters a terminal state with a `data: [DONE]` + message. + """ + + +class RunSubmitToolOutputsParamsStreaming(RunSubmitToolOutputsParamsBase): + stream: Required[Literal[True]] + """ + If `true`, returns a stream of events that happen during the Run as server-sent + events, terminating when the Run enters a terminal state with a `data: [DONE]` + message. + """ + + +RunSubmitToolOutputsParams = Union[RunSubmitToolOutputsParamsNonStreaming, RunSubmitToolOutputsParamsStreaming] diff --git a/src/openai/types/beta/threads/runs/__init__.py b/src/openai/types/beta/threads/runs/__init__.py index 16cb852922..03ae192088 100644 --- a/src/openai/types/beta/threads/runs/__init__.py +++ b/src/openai/types/beta/threads/runs/__init__.py @@ -3,9 +3,20 @@ from __future__ import annotations from .run_step import RunStep as RunStep -from .code_tool_call import CodeToolCall as CodeToolCall +from .tool_call import ToolCall as ToolCall +from .run_step_delta import RunStepDelta as RunStepDelta +from .tool_call_delta import ToolCallDelta as ToolCallDelta from .step_list_params import StepListParams as StepListParams from .function_tool_call import FunctionToolCall as FunctionToolCall from .retrieval_tool_call import RetrievalToolCall as RetrievalToolCall +from .run_step_delta_event import RunStepDeltaEvent as RunStepDeltaEvent +from .code_interpreter_logs import CodeInterpreterLogs as CodeInterpreterLogs +from .tool_call_delta_object import ToolCallDeltaObject as ToolCallDeltaObject from .tool_calls_step_details import ToolCallsStepDetails as ToolCallsStepDetails +from .function_tool_call_delta import FunctionToolCallDelta as FunctionToolCallDelta +from .retrieval_tool_call_delta import RetrievalToolCallDelta as RetrievalToolCallDelta +from .code_interpreter_tool_call import CodeInterpreterToolCall as CodeInterpreterToolCall +from .run_step_delta_message_delta import RunStepDeltaMessageDelta as RunStepDeltaMessageDelta +from .code_interpreter_output_image import CodeInterpreterOutputImage as CodeInterpreterOutputImage from .message_creation_step_details import MessageCreationStepDetails as MessageCreationStepDetails +from .code_interpreter_tool_call_delta import CodeInterpreterToolCallDelta as CodeInterpreterToolCallDelta diff --git a/src/openai/types/beta/threads/runs/code_interpreter_logs.py b/src/openai/types/beta/threads/runs/code_interpreter_logs.py new file mode 100644 index 0000000000..c91179be22 --- /dev/null +++ b/src/openai/types/beta/threads/runs/code_interpreter_logs.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Optional +from typing_extensions import Literal + +from ....._models import BaseModel + +__all__ = ["CodeInterpreterLogs"] + + +class CodeInterpreterLogs(BaseModel): + index: int + """The index of the output in the outputs array.""" + + type: Literal["logs"] + """Always `logs`.""" + + logs: Optional[str] = None + """The text output from the Code Interpreter tool call.""" diff --git a/src/openai/types/beta/threads/runs/code_interpreter_output_image.py b/src/openai/types/beta/threads/runs/code_interpreter_output_image.py new file mode 100644 index 0000000000..0d7d26f91f --- /dev/null +++ b/src/openai/types/beta/threads/runs/code_interpreter_output_image.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Optional +from typing_extensions import Literal + +from ....._models import BaseModel + +__all__ = ["CodeInterpreterOutputImage", "Image"] + + +class Image(BaseModel): + file_id: Optional[str] = None + """ + The [file](https://platform.openai.com/docs/api-reference/files) ID of the + image. + """ + + +class CodeInterpreterOutputImage(BaseModel): + index: int + """The index of the output in the outputs array.""" + + type: Literal["image"] + """Always `image`.""" + + image: Optional[Image] = None diff --git a/src/openai/types/beta/threads/runs/code_tool_call.py b/src/openai/types/beta/threads/runs/code_interpreter_tool_call.py similarity index 95% rename from src/openai/types/beta/threads/runs/code_tool_call.py rename to src/openai/types/beta/threads/runs/code_interpreter_tool_call.py index 0de47b379b..c537562e91 100644 --- a/src/openai/types/beta/threads/runs/code_tool_call.py +++ b/src/openai/types/beta/threads/runs/code_interpreter_tool_call.py @@ -7,7 +7,7 @@ from ....._models import BaseModel __all__ = [ - "CodeToolCall", + "CodeInterpreterToolCall", "CodeInterpreter", "CodeInterpreterOutput", "CodeInterpreterOutputLogs", @@ -56,7 +56,7 @@ class CodeInterpreter(BaseModel): """ -class CodeToolCall(BaseModel): +class CodeInterpreterToolCall(BaseModel): id: str """The ID of the tool call.""" diff --git a/src/openai/types/beta/threads/runs/code_interpreter_tool_call_delta.py b/src/openai/types/beta/threads/runs/code_interpreter_tool_call_delta.py new file mode 100644 index 0000000000..b13105f840 --- /dev/null +++ b/src/openai/types/beta/threads/runs/code_interpreter_tool_call_delta.py @@ -0,0 +1,44 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import List, Union, Optional +from typing_extensions import Literal, Annotated + +from ....._utils import PropertyInfo +from ....._models import BaseModel +from .code_interpreter_logs import CodeInterpreterLogs +from .code_interpreter_output_image import CodeInterpreterOutputImage + +__all__ = ["CodeInterpreterToolCallDelta", "CodeInterpreter", "CodeInterpreterOutput"] + +CodeInterpreterOutput = Annotated[ + Union[CodeInterpreterLogs, CodeInterpreterOutputImage], PropertyInfo(discriminator="type") +] + + +class CodeInterpreter(BaseModel): + input: Optional[str] = None + """The input to the Code Interpreter tool call.""" + + outputs: Optional[List[CodeInterpreterOutput]] = None + """The outputs from the Code Interpreter tool call. + + Code Interpreter can output one or more items, including text (`logs`) or images + (`image`). Each of these are represented by a different object type. + """ + + +class CodeInterpreterToolCallDelta(BaseModel): + index: int + """The index of the tool call in the tool calls array.""" + + type: Literal["code_interpreter"] + """The type of tool call. + + This is always going to be `code_interpreter` for this type of tool call. + """ + + id: Optional[str] = None + """The ID of the tool call.""" + + code_interpreter: Optional[CodeInterpreter] = None + """The Code Interpreter tool call definition.""" diff --git a/src/openai/types/beta/threads/runs/function_tool_call_delta.py b/src/openai/types/beta/threads/runs/function_tool_call_delta.py new file mode 100644 index 0000000000..46c341bc84 --- /dev/null +++ b/src/openai/types/beta/threads/runs/function_tool_call_delta.py @@ -0,0 +1,41 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Optional +from typing_extensions import Literal + +from ....._models import BaseModel + +__all__ = ["FunctionToolCallDelta", "Function"] + + +class Function(BaseModel): + arguments: Optional[str] = None + """The arguments passed to the function.""" + + name: Optional[str] = None + """The name of the function.""" + + output: Optional[str] = None + """The output of the function. + + This will be `null` if the outputs have not been + [submitted](https://platform.openai.com/docs/api-reference/runs/submitToolOutputs) + yet. + """ + + +class FunctionToolCallDelta(BaseModel): + index: int + """The index of the tool call in the tool calls array.""" + + type: Literal["function"] + """The type of tool call. + + This is always going to be `function` for this type of tool call. + """ + + id: Optional[str] = None + """The ID of the tool call object.""" + + function: Optional[Function] = None + """The definition of the function that was called.""" diff --git a/src/openai/types/beta/threads/runs/retrieval_tool_call_delta.py b/src/openai/types/beta/threads/runs/retrieval_tool_call_delta.py new file mode 100644 index 0000000000..ac8003d3eb --- /dev/null +++ b/src/openai/types/beta/threads/runs/retrieval_tool_call_delta.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Optional +from typing_extensions import Literal + +from ....._models import BaseModel + +__all__ = ["RetrievalToolCallDelta"] + + +class RetrievalToolCallDelta(BaseModel): + index: int + """The index of the tool call in the tool calls array.""" + + type: Literal["retrieval"] + """The type of tool call. + + This is always going to be `retrieval` for this type of tool call. + """ + + id: Optional[str] = None + """The ID of the tool call object.""" + + retrieval: Optional[object] = None + """For now, this is always going to be an empty object.""" diff --git a/src/openai/types/beta/threads/runs/run_step_delta.py b/src/openai/types/beta/threads/runs/run_step_delta.py new file mode 100644 index 0000000000..fb8b869425 --- /dev/null +++ b/src/openai/types/beta/threads/runs/run_step_delta.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Union, Optional +from typing_extensions import Annotated + +from ....._utils import PropertyInfo +from ....._models import BaseModel +from .tool_call_delta_object import ToolCallDeltaObject +from .run_step_delta_message_delta import RunStepDeltaMessageDelta + +__all__ = ["RunStepDelta", "StepDetails"] + +StepDetails = Annotated[Union[RunStepDeltaMessageDelta, ToolCallDeltaObject], PropertyInfo(discriminator="type")] + + +class RunStepDelta(BaseModel): + step_details: Optional[StepDetails] = None + """The details of the run step.""" diff --git a/src/openai/types/beta/threads/runs/run_step_delta_event.py b/src/openai/types/beta/threads/runs/run_step_delta_event.py new file mode 100644 index 0000000000..ab61dd1f9a --- /dev/null +++ b/src/openai/types/beta/threads/runs/run_step_delta_event.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing_extensions import Literal + +from ....._models import BaseModel +from .run_step_delta import RunStepDelta + +__all__ = ["RunStepDeltaEvent"] + + +class RunStepDeltaEvent(BaseModel): + id: str + """The identifier of the run step, which can be referenced in API endpoints.""" + + delta: RunStepDelta + """The delta containing the fields that have changed on the run step.""" + + object: Literal["thread.run.step.delta"] + """The object type, which is always `thread.run.step.delta`.""" diff --git a/src/openai/types/beta/threads/runs/run_step_delta_message_delta.py b/src/openai/types/beta/threads/runs/run_step_delta_message_delta.py new file mode 100644 index 0000000000..52ec5d3440 --- /dev/null +++ b/src/openai/types/beta/threads/runs/run_step_delta_message_delta.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Optional +from typing_extensions import Literal + +from ....._models import BaseModel + +__all__ = ["RunStepDeltaMessageDelta", "MessageCreation"] + + +class MessageCreation(BaseModel): + message_id: Optional[str] = None + """The ID of the message that was created by this run step.""" + + +class RunStepDeltaMessageDelta(BaseModel): + type: Literal["message_creation"] + """Always `message_creation`.""" + + message_creation: Optional[MessageCreation] = None diff --git a/src/openai/types/beta/threads/runs/tool_call.py b/src/openai/types/beta/threads/runs/tool_call.py new file mode 100644 index 0000000000..a3abfa77ad --- /dev/null +++ b/src/openai/types/beta/threads/runs/tool_call.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Union +from typing_extensions import Annotated + +from ....._utils import PropertyInfo +from .function_tool_call import FunctionToolCall +from .retrieval_tool_call import RetrievalToolCall +from .code_interpreter_tool_call import CodeInterpreterToolCall + +__all__ = ["ToolCall"] + +ToolCall = Annotated[ + Union[CodeInterpreterToolCall, RetrievalToolCall, FunctionToolCall], PropertyInfo(discriminator="type") +] diff --git a/src/openai/types/beta/threads/runs/tool_call_delta.py b/src/openai/types/beta/threads/runs/tool_call_delta.py new file mode 100644 index 0000000000..a1aa4de6cf --- /dev/null +++ b/src/openai/types/beta/threads/runs/tool_call_delta.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Union +from typing_extensions import Annotated + +from ....._utils import PropertyInfo +from .function_tool_call_delta import FunctionToolCallDelta +from .retrieval_tool_call_delta import RetrievalToolCallDelta +from .code_interpreter_tool_call_delta import CodeInterpreterToolCallDelta + +__all__ = ["ToolCallDelta"] + +ToolCallDelta = Annotated[ + Union[CodeInterpreterToolCallDelta, RetrievalToolCallDelta, FunctionToolCallDelta], + PropertyInfo(discriminator="type"), +] diff --git a/src/openai/types/beta/threads/runs/tool_call_delta_object.py b/src/openai/types/beta/threads/runs/tool_call_delta_object.py new file mode 100644 index 0000000000..2ce46ab894 --- /dev/null +++ b/src/openai/types/beta/threads/runs/tool_call_delta_object.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import List, Optional +from typing_extensions import Literal + +from ....._models import BaseModel +from .tool_call_delta import ToolCallDelta + +__all__ = ["ToolCallDeltaObject"] + + +class ToolCallDeltaObject(BaseModel): + type: Literal["tool_calls"] + """Always `tool_calls`.""" + + tool_calls: Optional[List[ToolCallDelta]] = None + """An array of tool calls the run step was involved in. + + These can be associated with one of three types of tools: `code_interpreter`, + `retrieval`, or `function`. + """ diff --git a/src/openai/types/beta/threads/runs/tool_calls_step_details.py b/src/openai/types/beta/threads/runs/tool_calls_step_details.py index b1b5a72bee..6fccfc563a 100644 --- a/src/openai/types/beta/threads/runs/tool_calls_step_details.py +++ b/src/openai/types/beta/threads/runs/tool_calls_step_details.py @@ -1,17 +1,12 @@ # File generated from our OpenAPI spec by Stainless. -from typing import List, Union -from typing_extensions import Literal, Annotated +from typing import List +from typing_extensions import Literal -from ....._utils import PropertyInfo +from .tool_call import ToolCall from ....._models import BaseModel -from .code_tool_call import CodeToolCall -from .function_tool_call import FunctionToolCall -from .retrieval_tool_call import RetrievalToolCall -__all__ = ["ToolCallsStepDetails", "ToolCall"] - -ToolCall = Annotated[Union[CodeToolCall, RetrievalToolCall, FunctionToolCall], PropertyInfo(discriminator="type")] +__all__ = ["ToolCallsStepDetails"] class ToolCallsStepDetails(BaseModel): diff --git a/src/openai/types/beta/threads/text.py b/src/openai/types/beta/threads/text.py new file mode 100644 index 0000000000..a5a31c6783 --- /dev/null +++ b/src/openai/types/beta/threads/text.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import List + +from ...._models import BaseModel +from .annotation import Annotation + +__all__ = ["Text"] + + +class Text(BaseModel): + annotations: List[Annotation] + + value: str + """The data that makes up the text.""" diff --git a/src/openai/types/beta/threads/text_content_block.py b/src/openai/types/beta/threads/text_content_block.py new file mode 100644 index 0000000000..1c9187ea60 --- /dev/null +++ b/src/openai/types/beta/threads/text_content_block.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing_extensions import Literal + +from .text import Text +from ...._models import BaseModel + +__all__ = ["TextContentBlock"] + + +class TextContentBlock(BaseModel): + text: Text + + type: Literal["text"] + """Always `text`.""" diff --git a/src/openai/types/beta/threads/text_delta.py b/src/openai/types/beta/threads/text_delta.py new file mode 100644 index 0000000000..735846472a --- /dev/null +++ b/src/openai/types/beta/threads/text_delta.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import List, Optional + +from ...._models import BaseModel +from .annotation_delta import AnnotationDelta + +__all__ = ["TextDelta"] + + +class TextDelta(BaseModel): + annotations: Optional[List[AnnotationDelta]] = None + + value: Optional[str] = None + """The data that makes up the text.""" diff --git a/src/openai/types/beta/threads/text_delta_block.py b/src/openai/types/beta/threads/text_delta_block.py new file mode 100644 index 0000000000..6adbdee479 --- /dev/null +++ b/src/openai/types/beta/threads/text_delta_block.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel +from .text_delta import TextDelta + +__all__ = ["TextDeltaBlock"] + + +class TextDeltaBlock(BaseModel): + index: int + """The index of the content part in the message.""" + + type: Literal["text"] + """Always `text`.""" + + text: Optional[TextDelta] = None diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 9afbacb874..e391c63119 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -190,7 +190,8 @@ class CompletionCreateParamsBase(TypedDict, total=False): """A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of - functions the model may generate JSON inputs for. + functions the model may generate JSON inputs for. A max of 128 functions are + supported. """ top_logprobs: Optional[int] diff --git a/src/openai/types/completion_create_params.py b/src/openai/types/completion_create_params.py index afbc9c549f..08ffca760f 100644 --- a/src/openai/types/completion_create_params.py +++ b/src/openai/types/completion_create_params.py @@ -124,7 +124,10 @@ class CompletionCreateParamsBase(TypedDict, total=False): """ suffix: Optional[str] - """The suffix that comes after a completion of inserted text.""" + """The suffix that comes after a completion of inserted text. + + This parameter is only supported for `gpt-3.5-turbo-instruct`. + """ temperature: Optional[float] """What sampling temperature to use, between 0 and 2. diff --git a/src/openai/types/shared/__init__.py b/src/openai/types/shared/__init__.py index 05bc4ff9ba..c9ebb1a504 100644 --- a/src/openai/types/shared/__init__.py +++ b/src/openai/types/shared/__init__.py @@ -1,4 +1,5 @@ # File generated from our OpenAPI spec by Stainless. +from .error_object import ErrorObject as ErrorObject from .function_definition import FunctionDefinition as FunctionDefinition from .function_parameters import FunctionParameters as FunctionParameters diff --git a/src/openai/types/shared/error_object.py b/src/openai/types/shared/error_object.py new file mode 100644 index 0000000000..f18fcc1c33 --- /dev/null +++ b/src/openai/types/shared/error_object.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. + +from typing import Optional + +from ..._models import BaseModel + +__all__ = ["ErrorObject"] + + +class ErrorObject(BaseModel): + code: Optional[str] = None + + message: str + + param: Optional[str] = None + + type: str diff --git a/tests/api_resources/beta/test_threads.py b/tests/api_resources/beta/test_threads.py index 5b347de1f0..6bb8fc82de 100644 --- a/tests/api_resources/beta/test_threads.py +++ b/tests/api_resources/beta/test_threads.py @@ -196,19 +196,20 @@ def test_path_params_delete(self, client: OpenAI) -> None: ) @parametrize - def test_method_create_and_run(self, client: OpenAI) -> None: + def test_method_create_and_run_overload_1(self, client: OpenAI) -> None: thread = client.beta.threads.create_and_run( assistant_id="string", ) assert_matches_type(Run, thread, path=["response"]) @parametrize - def test_method_create_and_run_with_all_params(self, client: OpenAI) -> None: + def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) -> None: thread = client.beta.threads.create_and_run( assistant_id="string", instructions="string", metadata={}, model="string", + stream=False, thread={ "messages": [ { @@ -237,7 +238,7 @@ def test_method_create_and_run_with_all_params(self, client: OpenAI) -> None: assert_matches_type(Run, thread, path=["response"]) @parametrize - def test_raw_response_create_and_run(self, client: OpenAI) -> None: + def test_raw_response_create_and_run_overload_1(self, client: OpenAI) -> None: response = client.beta.threads.with_raw_response.create_and_run( assistant_id="string", ) @@ -248,7 +249,7 @@ def test_raw_response_create_and_run(self, client: OpenAI) -> None: assert_matches_type(Run, thread, path=["response"]) @parametrize - def test_streaming_response_create_and_run(self, client: OpenAI) -> None: + def test_streaming_response_create_and_run_overload_1(self, client: OpenAI) -> None: with client.beta.threads.with_streaming_response.create_and_run( assistant_id="string", ) as response: @@ -260,6 +261,74 @@ def test_streaming_response_create_and_run(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_method_create_and_run_overload_2(self, client: OpenAI) -> None: + thread_stream = client.beta.threads.create_and_run( + assistant_id="string", + stream=True, + ) + thread_stream.response.close() + + @parametrize + def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) -> None: + thread_stream = client.beta.threads.create_and_run( + assistant_id="string", + stream=True, + instructions="string", + metadata={}, + model="string", + thread={ + "messages": [ + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + ], + "metadata": {}, + }, + tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + ) + thread_stream.response.close() + + @parametrize + def test_raw_response_create_and_run_overload_2(self, client: OpenAI) -> None: + response = client.beta.threads.with_raw_response.create_and_run( + assistant_id="string", + stream=True, + ) + + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + stream = response.parse() + stream.close() + + @parametrize + def test_streaming_response_create_and_run_overload_2(self, client: OpenAI) -> None: + with client.beta.threads.with_streaming_response.create_and_run( + assistant_id="string", + stream=True, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + stream = response.parse() + stream.close() + + assert cast(Any, response.is_closed) is True + class TestAsyncThreads: parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) @@ -439,19 +508,20 @@ async def test_path_params_delete(self, async_client: AsyncOpenAI) -> None: ) @parametrize - async def test_method_create_and_run(self, async_client: AsyncOpenAI) -> None: + async def test_method_create_and_run_overload_1(self, async_client: AsyncOpenAI) -> None: thread = await async_client.beta.threads.create_and_run( assistant_id="string", ) assert_matches_type(Run, thread, path=["response"]) @parametrize - async def test_method_create_and_run_with_all_params(self, async_client: AsyncOpenAI) -> None: + async def test_method_create_and_run_with_all_params_overload_1(self, async_client: AsyncOpenAI) -> None: thread = await async_client.beta.threads.create_and_run( assistant_id="string", instructions="string", metadata={}, model="string", + stream=False, thread={ "messages": [ { @@ -480,7 +550,7 @@ async def test_method_create_and_run_with_all_params(self, async_client: AsyncOp assert_matches_type(Run, thread, path=["response"]) @parametrize - async def test_raw_response_create_and_run(self, async_client: AsyncOpenAI) -> None: + async def test_raw_response_create_and_run_overload_1(self, async_client: AsyncOpenAI) -> None: response = await async_client.beta.threads.with_raw_response.create_and_run( assistant_id="string", ) @@ -491,7 +561,7 @@ async def test_raw_response_create_and_run(self, async_client: AsyncOpenAI) -> N assert_matches_type(Run, thread, path=["response"]) @parametrize - async def test_streaming_response_create_and_run(self, async_client: AsyncOpenAI) -> None: + async def test_streaming_response_create_and_run_overload_1(self, async_client: AsyncOpenAI) -> None: async with async_client.beta.threads.with_streaming_response.create_and_run( assistant_id="string", ) as response: @@ -502,3 +572,71 @@ async def test_streaming_response_create_and_run(self, async_client: AsyncOpenAI assert_matches_type(Run, thread, path=["response"]) assert cast(Any, response.is_closed) is True + + @parametrize + async def test_method_create_and_run_overload_2(self, async_client: AsyncOpenAI) -> None: + thread_stream = await async_client.beta.threads.create_and_run( + assistant_id="string", + stream=True, + ) + await thread_stream.response.aclose() + + @parametrize + async def test_method_create_and_run_with_all_params_overload_2(self, async_client: AsyncOpenAI) -> None: + thread_stream = await async_client.beta.threads.create_and_run( + assistant_id="string", + stream=True, + instructions="string", + metadata={}, + model="string", + thread={ + "messages": [ + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + ], + "metadata": {}, + }, + tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + ) + await thread_stream.response.aclose() + + @parametrize + async def test_raw_response_create_and_run_overload_2(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.threads.with_raw_response.create_and_run( + assistant_id="string", + stream=True, + ) + + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + stream = response.parse() + await stream.close() + + @parametrize + async def test_streaming_response_create_and_run_overload_2(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.threads.with_streaming_response.create_and_run( + assistant_id="string", + stream=True, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + stream = await response.parse() + await stream.close() + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/beta/threads/test_messages.py b/tests/api_resources/beta/threads/test_messages.py index 538d2f4c2a..c61a9ee109 100644 --- a/tests/api_resources/beta/threads/test_messages.py +++ b/tests/api_resources/beta/threads/test_messages.py @@ -10,7 +10,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta.threads import ThreadMessage +from openai.types.beta.threads import Message base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") @@ -25,7 +25,7 @@ def test_method_create(self, client: OpenAI) -> None: content="x", role="user", ) - assert_matches_type(ThreadMessage, message, path=["response"]) + assert_matches_type(Message, message, path=["response"]) @parametrize def test_method_create_with_all_params(self, client: OpenAI) -> None: @@ -36,7 +36,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: file_ids=["string"], metadata={}, ) - assert_matches_type(ThreadMessage, message, path=["response"]) + assert_matches_type(Message, message, path=["response"]) @parametrize def test_raw_response_create(self, client: OpenAI) -> None: @@ -49,7 +49,7 @@ def test_raw_response_create(self, client: OpenAI) -> None: assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" message = response.parse() - assert_matches_type(ThreadMessage, message, path=["response"]) + assert_matches_type(Message, message, path=["response"]) @parametrize def test_streaming_response_create(self, client: OpenAI) -> None: @@ -62,7 +62,7 @@ def test_streaming_response_create(self, client: OpenAI) -> None: assert response.http_request.headers.get("X-Stainless-Lang") == "python" message = response.parse() - assert_matches_type(ThreadMessage, message, path=["response"]) + assert_matches_type(Message, message, path=["response"]) assert cast(Any, response.is_closed) is True @@ -81,7 +81,7 @@ def test_method_retrieve(self, client: OpenAI) -> None: "string", thread_id="string", ) - assert_matches_type(ThreadMessage, message, path=["response"]) + assert_matches_type(Message, message, path=["response"]) @parametrize def test_raw_response_retrieve(self, client: OpenAI) -> None: @@ -93,7 +93,7 @@ def test_raw_response_retrieve(self, client: OpenAI) -> None: assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" message = response.parse() - assert_matches_type(ThreadMessage, message, path=["response"]) + assert_matches_type(Message, message, path=["response"]) @parametrize def test_streaming_response_retrieve(self, client: OpenAI) -> None: @@ -105,7 +105,7 @@ def test_streaming_response_retrieve(self, client: OpenAI) -> None: assert response.http_request.headers.get("X-Stainless-Lang") == "python" message = response.parse() - assert_matches_type(ThreadMessage, message, path=["response"]) + assert_matches_type(Message, message, path=["response"]) assert cast(Any, response.is_closed) is True @@ -129,7 +129,7 @@ def test_method_update(self, client: OpenAI) -> None: "string", thread_id="string", ) - assert_matches_type(ThreadMessage, message, path=["response"]) + assert_matches_type(Message, message, path=["response"]) @parametrize def test_method_update_with_all_params(self, client: OpenAI) -> None: @@ -138,7 +138,7 @@ def test_method_update_with_all_params(self, client: OpenAI) -> None: thread_id="string", metadata={}, ) - assert_matches_type(ThreadMessage, message, path=["response"]) + assert_matches_type(Message, message, path=["response"]) @parametrize def test_raw_response_update(self, client: OpenAI) -> None: @@ -150,7 +150,7 @@ def test_raw_response_update(self, client: OpenAI) -> None: assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" message = response.parse() - assert_matches_type(ThreadMessage, message, path=["response"]) + assert_matches_type(Message, message, path=["response"]) @parametrize def test_streaming_response_update(self, client: OpenAI) -> None: @@ -162,7 +162,7 @@ def test_streaming_response_update(self, client: OpenAI) -> None: assert response.http_request.headers.get("X-Stainless-Lang") == "python" message = response.parse() - assert_matches_type(ThreadMessage, message, path=["response"]) + assert_matches_type(Message, message, path=["response"]) assert cast(Any, response.is_closed) is True @@ -185,7 +185,7 @@ def test_method_list(self, client: OpenAI) -> None: message = client.beta.threads.messages.list( "string", ) - assert_matches_type(SyncCursorPage[ThreadMessage], message, path=["response"]) + assert_matches_type(SyncCursorPage[Message], message, path=["response"]) @parametrize def test_method_list_with_all_params(self, client: OpenAI) -> None: @@ -196,7 +196,7 @@ def test_method_list_with_all_params(self, client: OpenAI) -> None: limit=0, order="asc", ) - assert_matches_type(SyncCursorPage[ThreadMessage], message, path=["response"]) + assert_matches_type(SyncCursorPage[Message], message, path=["response"]) @parametrize def test_raw_response_list(self, client: OpenAI) -> None: @@ -207,7 +207,7 @@ def test_raw_response_list(self, client: OpenAI) -> None: assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" message = response.parse() - assert_matches_type(SyncCursorPage[ThreadMessage], message, path=["response"]) + assert_matches_type(SyncCursorPage[Message], message, path=["response"]) @parametrize def test_streaming_response_list(self, client: OpenAI) -> None: @@ -218,7 +218,7 @@ def test_streaming_response_list(self, client: OpenAI) -> None: assert response.http_request.headers.get("X-Stainless-Lang") == "python" message = response.parse() - assert_matches_type(SyncCursorPage[ThreadMessage], message, path=["response"]) + assert_matches_type(SyncCursorPage[Message], message, path=["response"]) assert cast(Any, response.is_closed) is True @@ -240,7 +240,7 @@ async def test_method_create(self, async_client: AsyncOpenAI) -> None: content="x", role="user", ) - assert_matches_type(ThreadMessage, message, path=["response"]) + assert_matches_type(Message, message, path=["response"]) @parametrize async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: @@ -251,7 +251,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> file_ids=["string"], metadata={}, ) - assert_matches_type(ThreadMessage, message, path=["response"]) + assert_matches_type(Message, message, path=["response"]) @parametrize async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: @@ -264,7 +264,7 @@ async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" message = response.parse() - assert_matches_type(ThreadMessage, message, path=["response"]) + assert_matches_type(Message, message, path=["response"]) @parametrize async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: @@ -277,7 +277,7 @@ async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> Non assert response.http_request.headers.get("X-Stainless-Lang") == "python" message = await response.parse() - assert_matches_type(ThreadMessage, message, path=["response"]) + assert_matches_type(Message, message, path=["response"]) assert cast(Any, response.is_closed) is True @@ -296,7 +296,7 @@ async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: "string", thread_id="string", ) - assert_matches_type(ThreadMessage, message, path=["response"]) + assert_matches_type(Message, message, path=["response"]) @parametrize async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: @@ -308,7 +308,7 @@ async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" message = response.parse() - assert_matches_type(ThreadMessage, message, path=["response"]) + assert_matches_type(Message, message, path=["response"]) @parametrize async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: @@ -320,7 +320,7 @@ async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> N assert response.http_request.headers.get("X-Stainless-Lang") == "python" message = await response.parse() - assert_matches_type(ThreadMessage, message, path=["response"]) + assert_matches_type(Message, message, path=["response"]) assert cast(Any, response.is_closed) is True @@ -344,7 +344,7 @@ async def test_method_update(self, async_client: AsyncOpenAI) -> None: "string", thread_id="string", ) - assert_matches_type(ThreadMessage, message, path=["response"]) + assert_matches_type(Message, message, path=["response"]) @parametrize async def test_method_update_with_all_params(self, async_client: AsyncOpenAI) -> None: @@ -353,7 +353,7 @@ async def test_method_update_with_all_params(self, async_client: AsyncOpenAI) -> thread_id="string", metadata={}, ) - assert_matches_type(ThreadMessage, message, path=["response"]) + assert_matches_type(Message, message, path=["response"]) @parametrize async def test_raw_response_update(self, async_client: AsyncOpenAI) -> None: @@ -365,7 +365,7 @@ async def test_raw_response_update(self, async_client: AsyncOpenAI) -> None: assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" message = response.parse() - assert_matches_type(ThreadMessage, message, path=["response"]) + assert_matches_type(Message, message, path=["response"]) @parametrize async def test_streaming_response_update(self, async_client: AsyncOpenAI) -> None: @@ -377,7 +377,7 @@ async def test_streaming_response_update(self, async_client: AsyncOpenAI) -> Non assert response.http_request.headers.get("X-Stainless-Lang") == "python" message = await response.parse() - assert_matches_type(ThreadMessage, message, path=["response"]) + assert_matches_type(Message, message, path=["response"]) assert cast(Any, response.is_closed) is True @@ -400,7 +400,7 @@ async def test_method_list(self, async_client: AsyncOpenAI) -> None: message = await async_client.beta.threads.messages.list( "string", ) - assert_matches_type(AsyncCursorPage[ThreadMessage], message, path=["response"]) + assert_matches_type(AsyncCursorPage[Message], message, path=["response"]) @parametrize async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: @@ -411,7 +411,7 @@ async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> N limit=0, order="asc", ) - assert_matches_type(AsyncCursorPage[ThreadMessage], message, path=["response"]) + assert_matches_type(AsyncCursorPage[Message], message, path=["response"]) @parametrize async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: @@ -422,7 +422,7 @@ async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" message = response.parse() - assert_matches_type(AsyncCursorPage[ThreadMessage], message, path=["response"]) + assert_matches_type(AsyncCursorPage[Message], message, path=["response"]) @parametrize async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: @@ -433,7 +433,7 @@ async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: assert response.http_request.headers.get("X-Stainless-Lang") == "python" message = await response.parse() - assert_matches_type(AsyncCursorPage[ThreadMessage], message, path=["response"]) + assert_matches_type(AsyncCursorPage[Message], message, path=["response"]) assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index 9e88d65eaf..de1ad07567 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -21,7 +21,7 @@ class TestRuns: parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize - def test_method_create(self, client: OpenAI) -> None: + def test_method_create_overload_1(self, client: OpenAI) -> None: run = client.beta.threads.runs.create( "string", assistant_id="string", @@ -29,7 +29,7 @@ def test_method_create(self, client: OpenAI) -> None: assert_matches_type(Run, run, path=["response"]) @parametrize - def test_method_create_with_all_params(self, client: OpenAI) -> None: + def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: run = client.beta.threads.runs.create( "string", assistant_id="string", @@ -37,12 +37,13 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: instructions="string", metadata={}, model="string", + stream=False, tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], ) assert_matches_type(Run, run, path=["response"]) @parametrize - def test_raw_response_create(self, client: OpenAI) -> None: + def test_raw_response_create_overload_1(self, client: OpenAI) -> None: response = client.beta.threads.runs.with_raw_response.create( "string", assistant_id="string", @@ -54,7 +55,7 @@ def test_raw_response_create(self, client: OpenAI) -> None: assert_matches_type(Run, run, path=["response"]) @parametrize - def test_streaming_response_create(self, client: OpenAI) -> None: + def test_streaming_response_create_overload_1(self, client: OpenAI) -> None: with client.beta.threads.runs.with_streaming_response.create( "string", assistant_id="string", @@ -68,13 +69,72 @@ def test_streaming_response_create(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - def test_path_params_create(self, client: OpenAI) -> None: + def test_path_params_create_overload_1(self, client: OpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): client.beta.threads.runs.with_raw_response.create( "", assistant_id="string", ) + @parametrize + def test_method_create_overload_2(self, client: OpenAI) -> None: + run_stream = client.beta.threads.runs.create( + "string", + assistant_id="string", + stream=True, + ) + run_stream.response.close() + + @parametrize + def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: + run_stream = client.beta.threads.runs.create( + "string", + assistant_id="string", + stream=True, + additional_instructions="string", + instructions="string", + metadata={}, + model="string", + tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + ) + run_stream.response.close() + + @parametrize + def test_raw_response_create_overload_2(self, client: OpenAI) -> None: + response = client.beta.threads.runs.with_raw_response.create( + "string", + assistant_id="string", + stream=True, + ) + + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + stream = response.parse() + stream.close() + + @parametrize + def test_streaming_response_create_overload_2(self, client: OpenAI) -> None: + with client.beta.threads.runs.with_streaming_response.create( + "string", + assistant_id="string", + stream=True, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + stream = response.parse() + stream.close() + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_create_overload_2(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + client.beta.threads.runs.with_raw_response.create( + "", + assistant_id="string", + stream=True, + ) + @parametrize def test_method_retrieve(self, client: OpenAI) -> None: run = client.beta.threads.runs.retrieve( @@ -278,7 +338,7 @@ def test_path_params_cancel(self, client: OpenAI) -> None: ) @parametrize - def test_method_submit_tool_outputs(self, client: OpenAI) -> None: + def test_method_submit_tool_outputs_overload_1(self, client: OpenAI) -> None: run = client.beta.threads.runs.submit_tool_outputs( "string", thread_id="string", @@ -287,7 +347,30 @@ def test_method_submit_tool_outputs(self, client: OpenAI) -> None: assert_matches_type(Run, run, path=["response"]) @parametrize - def test_raw_response_submit_tool_outputs(self, client: OpenAI) -> None: + def test_method_submit_tool_outputs_with_all_params_overload_1(self, client: OpenAI) -> None: + run = client.beta.threads.runs.submit_tool_outputs( + "string", + thread_id="string", + tool_outputs=[ + { + "tool_call_id": "string", + "output": "string", + }, + { + "tool_call_id": "string", + "output": "string", + }, + { + "tool_call_id": "string", + "output": "string", + }, + ], + stream=False, + ) + assert_matches_type(Run, run, path=["response"]) + + @parametrize + def test_raw_response_submit_tool_outputs_overload_1(self, client: OpenAI) -> None: response = client.beta.threads.runs.with_raw_response.submit_tool_outputs( "string", thread_id="string", @@ -300,7 +383,7 @@ def test_raw_response_submit_tool_outputs(self, client: OpenAI) -> None: assert_matches_type(Run, run, path=["response"]) @parametrize - def test_streaming_response_submit_tool_outputs(self, client: OpenAI) -> None: + def test_streaming_response_submit_tool_outputs_overload_1(self, client: OpenAI) -> None: with client.beta.threads.runs.with_streaming_response.submit_tool_outputs( "string", thread_id="string", @@ -315,11 +398,67 @@ def test_streaming_response_submit_tool_outputs(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True @parametrize - def test_path_params_submit_tool_outputs(self, client: OpenAI) -> None: + def test_path_params_submit_tool_outputs_overload_1(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + client.beta.threads.runs.with_raw_response.submit_tool_outputs( + "string", + thread_id="", + tool_outputs=[{}, {}, {}], + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): + client.beta.threads.runs.with_raw_response.submit_tool_outputs( + "", + thread_id="string", + tool_outputs=[{}, {}, {}], + ) + + @parametrize + def test_method_submit_tool_outputs_overload_2(self, client: OpenAI) -> None: + run_stream = client.beta.threads.runs.submit_tool_outputs( + "string", + thread_id="string", + stream=True, + tool_outputs=[{}, {}, {}], + ) + run_stream.response.close() + + @parametrize + def test_raw_response_submit_tool_outputs_overload_2(self, client: OpenAI) -> None: + response = client.beta.threads.runs.with_raw_response.submit_tool_outputs( + "string", + thread_id="string", + stream=True, + tool_outputs=[{}, {}, {}], + ) + + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + stream = response.parse() + stream.close() + + @parametrize + def test_streaming_response_submit_tool_outputs_overload_2(self, client: OpenAI) -> None: + with client.beta.threads.runs.with_streaming_response.submit_tool_outputs( + "string", + thread_id="string", + stream=True, + tool_outputs=[{}, {}, {}], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + stream = response.parse() + stream.close() + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_submit_tool_outputs_overload_2(self, client: OpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): client.beta.threads.runs.with_raw_response.submit_tool_outputs( "string", thread_id="", + stream=True, tool_outputs=[{}, {}, {}], ) @@ -327,6 +466,7 @@ def test_path_params_submit_tool_outputs(self, client: OpenAI) -> None: client.beta.threads.runs.with_raw_response.submit_tool_outputs( "", thread_id="string", + stream=True, tool_outputs=[{}, {}, {}], ) @@ -335,7 +475,7 @@ class TestAsyncRuns: parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize - async def test_method_create(self, async_client: AsyncOpenAI) -> None: + async def test_method_create_overload_1(self, async_client: AsyncOpenAI) -> None: run = await async_client.beta.threads.runs.create( "string", assistant_id="string", @@ -343,7 +483,7 @@ async def test_method_create(self, async_client: AsyncOpenAI) -> None: assert_matches_type(Run, run, path=["response"]) @parametrize - async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: + async def test_method_create_with_all_params_overload_1(self, async_client: AsyncOpenAI) -> None: run = await async_client.beta.threads.runs.create( "string", assistant_id="string", @@ -351,12 +491,13 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> instructions="string", metadata={}, model="string", + stream=False, tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], ) assert_matches_type(Run, run, path=["response"]) @parametrize - async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: + async def test_raw_response_create_overload_1(self, async_client: AsyncOpenAI) -> None: response = await async_client.beta.threads.runs.with_raw_response.create( "string", assistant_id="string", @@ -368,7 +509,7 @@ async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: assert_matches_type(Run, run, path=["response"]) @parametrize - async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: + async def test_streaming_response_create_overload_1(self, async_client: AsyncOpenAI) -> None: async with async_client.beta.threads.runs.with_streaming_response.create( "string", assistant_id="string", @@ -382,13 +523,72 @@ async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> Non assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_create(self, async_client: AsyncOpenAI) -> None: + async def test_path_params_create_overload_1(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): await async_client.beta.threads.runs.with_raw_response.create( "", assistant_id="string", ) + @parametrize + async def test_method_create_overload_2(self, async_client: AsyncOpenAI) -> None: + run_stream = await async_client.beta.threads.runs.create( + "string", + assistant_id="string", + stream=True, + ) + await run_stream.response.aclose() + + @parametrize + async def test_method_create_with_all_params_overload_2(self, async_client: AsyncOpenAI) -> None: + run_stream = await async_client.beta.threads.runs.create( + "string", + assistant_id="string", + stream=True, + additional_instructions="string", + instructions="string", + metadata={}, + model="string", + tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + ) + await run_stream.response.aclose() + + @parametrize + async def test_raw_response_create_overload_2(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.threads.runs.with_raw_response.create( + "string", + assistant_id="string", + stream=True, + ) + + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + stream = response.parse() + await stream.close() + + @parametrize + async def test_streaming_response_create_overload_2(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.threads.runs.with_streaming_response.create( + "string", + assistant_id="string", + stream=True, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + stream = await response.parse() + await stream.close() + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_create_overload_2(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + await async_client.beta.threads.runs.with_raw_response.create( + "", + assistant_id="string", + stream=True, + ) + @parametrize async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: run = await async_client.beta.threads.runs.retrieve( @@ -592,7 +792,7 @@ async def test_path_params_cancel(self, async_client: AsyncOpenAI) -> None: ) @parametrize - async def test_method_submit_tool_outputs(self, async_client: AsyncOpenAI) -> None: + async def test_method_submit_tool_outputs_overload_1(self, async_client: AsyncOpenAI) -> None: run = await async_client.beta.threads.runs.submit_tool_outputs( "string", thread_id="string", @@ -601,7 +801,30 @@ async def test_method_submit_tool_outputs(self, async_client: AsyncOpenAI) -> No assert_matches_type(Run, run, path=["response"]) @parametrize - async def test_raw_response_submit_tool_outputs(self, async_client: AsyncOpenAI) -> None: + async def test_method_submit_tool_outputs_with_all_params_overload_1(self, async_client: AsyncOpenAI) -> None: + run = await async_client.beta.threads.runs.submit_tool_outputs( + "string", + thread_id="string", + tool_outputs=[ + { + "tool_call_id": "string", + "output": "string", + }, + { + "tool_call_id": "string", + "output": "string", + }, + { + "tool_call_id": "string", + "output": "string", + }, + ], + stream=False, + ) + assert_matches_type(Run, run, path=["response"]) + + @parametrize + async def test_raw_response_submit_tool_outputs_overload_1(self, async_client: AsyncOpenAI) -> None: response = await async_client.beta.threads.runs.with_raw_response.submit_tool_outputs( "string", thread_id="string", @@ -614,7 +837,7 @@ async def test_raw_response_submit_tool_outputs(self, async_client: AsyncOpenAI) assert_matches_type(Run, run, path=["response"]) @parametrize - async def test_streaming_response_submit_tool_outputs(self, async_client: AsyncOpenAI) -> None: + async def test_streaming_response_submit_tool_outputs_overload_1(self, async_client: AsyncOpenAI) -> None: async with async_client.beta.threads.runs.with_streaming_response.submit_tool_outputs( "string", thread_id="string", @@ -629,11 +852,67 @@ async def test_streaming_response_submit_tool_outputs(self, async_client: AsyncO assert cast(Any, response.is_closed) is True @parametrize - async def test_path_params_submit_tool_outputs(self, async_client: AsyncOpenAI) -> None: + async def test_path_params_submit_tool_outputs_overload_1(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + await async_client.beta.threads.runs.with_raw_response.submit_tool_outputs( + "string", + thread_id="", + tool_outputs=[{}, {}, {}], + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): + await async_client.beta.threads.runs.with_raw_response.submit_tool_outputs( + "", + thread_id="string", + tool_outputs=[{}, {}, {}], + ) + + @parametrize + async def test_method_submit_tool_outputs_overload_2(self, async_client: AsyncOpenAI) -> None: + run_stream = await async_client.beta.threads.runs.submit_tool_outputs( + "string", + thread_id="string", + stream=True, + tool_outputs=[{}, {}, {}], + ) + await run_stream.response.aclose() + + @parametrize + async def test_raw_response_submit_tool_outputs_overload_2(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.threads.runs.with_raw_response.submit_tool_outputs( + "string", + thread_id="string", + stream=True, + tool_outputs=[{}, {}, {}], + ) + + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + stream = response.parse() + await stream.close() + + @parametrize + async def test_streaming_response_submit_tool_outputs_overload_2(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.threads.runs.with_streaming_response.submit_tool_outputs( + "string", + thread_id="string", + stream=True, + tool_outputs=[{}, {}, {}], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + stream = await response.parse() + await stream.close() + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_submit_tool_outputs_overload_2(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): await async_client.beta.threads.runs.with_raw_response.submit_tool_outputs( "string", thread_id="", + stream=True, tool_outputs=[{}, {}, {}], ) @@ -641,5 +920,6 @@ async def test_path_params_submit_tool_outputs(self, async_client: AsyncOpenAI) await async_client.beta.threads.runs.with_raw_response.submit_tool_outputs( "", thread_id="string", + stream=True, tool_outputs=[{}, {}, {}], ) From e8e5a0dc7ccf2db19d7f81991ee0987f9c3ae375 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 15 Mar 2024 16:37:44 -0400 Subject: [PATCH 261/816] release: 1.14.1 (#1239) * docs(readme): assistant streaming (#1238) * release: 1.14.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++ helpers.md | 161 ++++++++++++++++++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 5 files changed, 172 insertions(+), 3 deletions(-) create mode 100644 helpers.md diff --git a/.release-please-manifest.json b/.release-please-manifest.json index e72f11310e..a780111df4 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.14.0" + ".": "1.14.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f0fc7556d..f7a80d39a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.14.1 (2024-03-15) + +Full Changelog: [v1.14.0...v1.14.1](https://github.com/openai/openai-python/compare/v1.14.0...v1.14.1) + +### Documentation + +* **readme:** assistant streaming ([#1238](https://github.com/openai/openai-python/issues/1238)) ([0fc30a2](https://github.com/openai/openai-python/commit/0fc30a23030b4ff60f27cd2f472517926ed0f300)) + ## 1.14.0 (2024-03-13) Full Changelog: [v1.13.4...v1.14.0](https://github.com/openai/openai-python/compare/v1.13.4...v1.14.0) diff --git a/helpers.md b/helpers.md new file mode 100644 index 0000000000..03fd5e76b7 --- /dev/null +++ b/helpers.md @@ -0,0 +1,161 @@ +# Streaming Helpers + +OpenAI supports streaming responses when interacting with the [Assistant](#assistant-streaming-api) APIs. + +## Assistant Streaming API + +OpenAI supports streaming responses from Assistants. The SDK provides convenience wrappers around the API +so you can subscribe to the types of events you are interested in as well as receive accumulated responses. + +More information can be found in the documentation: [Assistant Streaming](https://platform.openai.com/docs/assistants/overview?lang=python) + +#### An example of creating a run and subscribing to some events + +You can subscribe to events by creating an event handler class and overloading the relevant event handlers. + +```python +from typing_extensions import override +from openai import AssistantEventHandler + +# First, we create a EventHandler class to define +# how we want to handle the events in the response stream. + +class EventHandler(AssistantEventHandler): + @override + def on_text_created(self, text) -> None: + print(f"\nassistant > ", end="", flush=True) + + @override + def on_text_delta(self, delta, snapshot): + print(delta.value, end="", flush=True) + + def on_tool_call_created(self, tool_call): + print(f"\nassistant > {tool_call.type}\n", flush=True) + + def on_tool_call_delta(self, delta, snapshot): + if delta.type == 'code_interpreter': + if delta.code_interpreter.input: + print(delta.code_interpreter.input, end="", flush=True) + if delta.code_interpreter.outputs: + print(f"\n\noutput >", flush=True) + for output in delta.code_interpreter.outputs: + if output.type == "logs": + print(f"\n{output.logs}", flush=True) + +# Then, we use the `create_and_stream` SDK helper +# with the `EventHandler` class to create the Run +# and stream the response. + +with client.beta.threads.runs.create_and_stream( + thread_id=thread.id, + assistant_id=assistant.id, + instructions="Please address the user as Jane Doe. The user has a premium account.", + event_handler=EventHandler(), +) as stream: + stream.until_done() +``` + +### Assistant Events + +The assistant API provides events you can subscribe to for the following events. + +```python +def on_event(self, event: AssistantStreamEvent) +``` + +This allows you to subscribe to all the possible raw events sent by the OpenAI streaming API. +In many cases it will be more convenient to subscribe to a more specific set of events for your use case. + +More information on the types of events can be found here: [Events](https://platform.openai.com/docs/api-reference/assistants-streaming/events) + +```python +def on_run_step_created(self, run_step: RunStep) +def on_run_step_delta(self, delta: RunStepDelta, snapshot: RunStep) +def on_run_step_done(self, run_step: RunStep) +``` + +These events allow you to subscribe to the creation, delta and completion of a RunStep. + +For more information on how Runs and RunSteps work see the documentation [Runs and RunSteps](https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps) + +```python +def on_message_created(self, message: Message) +def on_message_delta(self, delta: MessageDelta, snapshot: Message) +def on_message_done(self, message: Message) +``` + +This allows you to subscribe to Message creation, delta and completion events. Messages can contain +different types of content that can be sent from a model (and events are available for specific content types). +For convenience, the delta event includes both the incremental update and an accumulated snapshot of the content. + +More information on messages can be found +on in the documentation page [Message](https://platform.openai.com/docs/api-reference/messages/object). + +```python +def on_text_created(self, text: Text) +def on_text_delta(self, delta: TextDelta, snapshot: Text) +def on_text_done(self, text: Text) +``` + +These events allow you to subscribe to the creation, delta and completion of a Text content (a specific type of message). +For convenience, the delta event includes both the incremental update and an accumulated snapshot of the content. + +```python +def on_image_file_done(self, image_file: ImageFile) +``` + +Image files are not sent incrementally so an event is provided for when a image file is available. + +```python +def on_tool_call_created(self, tool_call: ToolCall) +def on_tool_call_delta(self, delta: ToolCallDelta, snapshot: ToolCall) +def on_tool_call_done(self, tool_call: ToolCall) +``` + +These events allow you to subscribe to events for the creation, delta and completion of a ToolCall. + +More information on tools can be found here [Tools](https://platform.openai.com/docs/assistants/tools) + +```python +def on_end(self) +``` + +The last event send when a stream ends. + +```python +def on_timeout(self) +``` + +This event is triggered if the request times out. + +```python +def on_exception(self, exception: Exception) +``` + +This event is triggered if an exception occurs during streaming. + +### Assistant Methods + +The assistant streaming object also provides a few methods for convenience: + +```python +def current_event() +def current_run() +def current_message_snapshot() +def current_run_step_snapshot() +``` + +These methods are provided to allow you to access additional context from within event handlers. In many cases +the handlers should include all the information you need for processing, but if additional context is required it +can be accessed. + +Note: There is not always a relevant context in certain situations (these will be undefined in those cases). + +```python +def get_final_run(self) +def get_final_run_steps(self) +def get_final_messages(self) +``` + +These methods are provided for convenience to collect information at the end of a stream. Calling these events +will trigger consumption of the stream until completion and then return the relevant accumulated objects. diff --git a/pyproject.toml b/pyproject.toml index 0856032512..d562977dbd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.14.0" +version = "1.14.1" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 134799ff42..3f5331b8e0 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.14.0" # x-release-please-version +__version__ = "1.14.1" # x-release-please-version From 5cfb125acce0e8304d12bdd39b405071021db658 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 19 Mar 2024 11:49:15 -0400 Subject: [PATCH 262/816] release: 1.14.2 (#1244) * perf: cache TypeAdapters (#1114) * perf: cache TypeAdapters (#1243) * docs: fix typo in CONTRIBUTING.md (#1245) * chore(internal): update generated pragma comment (#1247) * docs: assistant improvements (#1249) * release: 1.14.2 --------- Co-authored-by: vvanglro <947001731@qq.com> --- .release-please-manifest.json | 2 +- CHANGELOG.md | 20 +++++ CONTRIBUTING.md | 2 +- README.md | 18 ++++ helpers.md | 86 +++++++++++++++---- pyproject.toml | 2 +- src/openai/__init__.py | 2 +- src/openai/_client.py | 2 +- src/openai/_constants.py | 2 +- src/openai/_exceptions.py | 2 +- src/openai/_models.py | 8 +- src/openai/_module_client.py | 2 +- src/openai/_resource.py | 2 +- src/openai/_version.py | 4 +- src/openai/pagination.py | 2 +- src/openai/resources/__init__.py | 2 +- src/openai/resources/audio/__init__.py | 2 +- src/openai/resources/audio/audio.py | 2 +- src/openai/resources/audio/speech.py | 2 +- src/openai/resources/audio/transcriptions.py | 2 +- src/openai/resources/audio/translations.py | 2 +- src/openai/resources/beta/__init__.py | 2 +- .../resources/beta/assistants/__init__.py | 2 +- .../resources/beta/assistants/assistants.py | 2 +- src/openai/resources/beta/assistants/files.py | 2 +- src/openai/resources/beta/beta.py | 2 +- src/openai/resources/beta/threads/__init__.py | 2 +- .../beta/threads/messages/__init__.py | 2 +- .../resources/beta/threads/messages/files.py | 2 +- .../beta/threads/messages/messages.py | 2 +- .../resources/beta/threads/runs/__init__.py | 2 +- .../resources/beta/threads/runs/runs.py | 2 +- .../resources/beta/threads/runs/steps.py | 2 +- src/openai/resources/beta/threads/threads.py | 2 +- src/openai/resources/chat/__init__.py | 2 +- src/openai/resources/chat/chat.py | 2 +- src/openai/resources/chat/completions.py | 2 +- src/openai/resources/completions.py | 2 +- src/openai/resources/embeddings.py | 2 +- src/openai/resources/files.py | 2 +- src/openai/resources/fine_tuning/__init__.py | 2 +- .../resources/fine_tuning/fine_tuning.py | 2 +- src/openai/resources/fine_tuning/jobs.py | 2 +- src/openai/resources/images.py | 2 +- src/openai/resources/models.py | 2 +- src/openai/resources/moderations.py | 2 +- src/openai/types/__init__.py | 2 +- src/openai/types/audio/__init__.py | 2 +- .../types/audio/speech_create_params.py | 2 +- src/openai/types/audio/transcription.py | 2 +- .../audio/transcription_create_params.py | 2 +- src/openai/types/audio/translation.py | 2 +- .../types/audio/translation_create_params.py | 2 +- src/openai/types/beta/__init__.py | 2 +- src/openai/types/beta/assistant.py | 2 +- .../types/beta/assistant_create_params.py | 2 +- src/openai/types/beta/assistant_deleted.py | 2 +- .../types/beta/assistant_list_params.py | 2 +- .../types/beta/assistant_stream_event.py | 2 +- src/openai/types/beta/assistant_tool.py | 2 +- src/openai/types/beta/assistant_tool_param.py | 2 +- .../types/beta/assistant_update_params.py | 2 +- src/openai/types/beta/assistants/__init__.py | 2 +- .../types/beta/assistants/assistant_file.py | 2 +- .../beta/assistants/file_create_params.py | 2 +- .../beta/assistants/file_delete_response.py | 2 +- .../types/beta/assistants/file_list_params.py | 2 +- src/openai/types/beta/chat/__init__.py | 2 +- .../types/beta/code_interpreter_tool.py | 2 +- .../types/beta/code_interpreter_tool_param.py | 2 +- src/openai/types/beta/function_tool.py | 2 +- src/openai/types/beta/function_tool_param.py | 2 +- src/openai/types/beta/retrieval_tool.py | 2 +- src/openai/types/beta/retrieval_tool_param.py | 2 +- src/openai/types/beta/thread.py | 2 +- .../beta/thread_create_and_run_params.py | 2 +- src/openai/types/beta/thread_create_params.py | 2 +- src/openai/types/beta/thread_deleted.py | 2 +- src/openai/types/beta/thread_update_params.py | 2 +- src/openai/types/beta/threads/__init__.py | 2 +- src/openai/types/beta/threads/annotation.py | 2 +- .../types/beta/threads/annotation_delta.py | 2 +- .../beta/threads/file_citation_annotation.py | 2 +- .../threads/file_citation_delta_annotation.py | 2 +- .../beta/threads/file_path_annotation.py | 2 +- .../threads/file_path_delta_annotation.py | 2 +- src/openai/types/beta/threads/image_file.py | 2 +- .../beta/threads/image_file_content_block.py | 2 +- .../types/beta/threads/image_file_delta.py | 2 +- .../beta/threads/image_file_delta_block.py | 2 +- src/openai/types/beta/threads/message.py | 2 +- .../types/beta/threads/message_content.py | 2 +- .../beta/threads/message_content_delta.py | 2 +- .../beta/threads/message_create_params.py | 2 +- .../types/beta/threads/message_delta.py | 2 +- .../types/beta/threads/message_delta_event.py | 2 +- .../types/beta/threads/message_list_params.py | 2 +- .../beta/threads/message_update_params.py | 2 +- .../types/beta/threads/messages/__init__.py | 2 +- .../beta/threads/messages/file_list_params.py | 2 +- .../beta/threads/messages/message_file.py | 2 +- .../required_action_function_tool_call.py | 2 +- src/openai/types/beta/threads/run.py | 2 +- .../types/beta/threads/run_create_params.py | 2 +- .../types/beta/threads/run_list_params.py | 2 +- src/openai/types/beta/threads/run_status.py | 2 +- .../threads/run_submit_tool_outputs_params.py | 2 +- .../types/beta/threads/run_update_params.py | 2 +- .../types/beta/threads/runs/__init__.py | 2 +- .../threads/runs/code_interpreter_logs.py | 2 +- .../runs/code_interpreter_output_image.py | 2 +- .../runs/code_interpreter_tool_call.py | 2 +- .../runs/code_interpreter_tool_call_delta.py | 2 +- .../beta/threads/runs/function_tool_call.py | 2 +- .../threads/runs/function_tool_call_delta.py | 2 +- .../runs/message_creation_step_details.py | 2 +- .../beta/threads/runs/retrieval_tool_call.py | 2 +- .../threads/runs/retrieval_tool_call_delta.py | 2 +- .../types/beta/threads/runs/run_step.py | 2 +- .../types/beta/threads/runs/run_step_delta.py | 2 +- .../beta/threads/runs/run_step_delta_event.py | 2 +- .../runs/run_step_delta_message_delta.py | 2 +- .../beta/threads/runs/step_list_params.py | 2 +- .../types/beta/threads/runs/tool_call.py | 2 +- .../beta/threads/runs/tool_call_delta.py | 2 +- .../threads/runs/tool_call_delta_object.py | 2 +- .../threads/runs/tool_calls_step_details.py | 2 +- src/openai/types/beta/threads/text.py | 2 +- .../types/beta/threads/text_content_block.py | 2 +- src/openai/types/beta/threads/text_delta.py | 2 +- .../types/beta/threads/text_delta_block.py | 2 +- src/openai/types/chat/__init__.py | 2 +- src/openai/types/chat/chat_completion.py | 2 +- ...chat_completion_assistant_message_param.py | 2 +- .../types/chat/chat_completion_chunk.py | 2 +- ...hat_completion_content_part_image_param.py | 2 +- .../chat_completion_content_part_param.py | 2 +- ...chat_completion_content_part_text_param.py | 2 +- ...t_completion_function_call_option_param.py | 2 +- .../chat_completion_function_message_param.py | 2 +- .../types/chat/chat_completion_message.py | 2 +- .../chat/chat_completion_message_param.py | 2 +- .../chat/chat_completion_message_tool_call.py | 2 +- ...chat_completion_message_tool_call_param.py | 2 +- ...chat_completion_named_tool_choice_param.py | 2 +- src/openai/types/chat/chat_completion_role.py | 2 +- .../chat_completion_system_message_param.py | 2 +- .../chat/chat_completion_token_logprob.py | 2 +- ...hat_completion_tool_choice_option_param.py | 2 +- .../chat_completion_tool_message_param.py | 2 +- .../types/chat/chat_completion_tool_param.py | 2 +- .../chat_completion_user_message_param.py | 2 +- .../types/chat/completion_create_params.py | 2 +- src/openai/types/completion.py | 2 +- src/openai/types/completion_choice.py | 2 +- src/openai/types/completion_create_params.py | 2 +- src/openai/types/completion_usage.py | 2 +- src/openai/types/create_embedding_response.py | 2 +- src/openai/types/embedding.py | 2 +- src/openai/types/embedding_create_params.py | 2 +- src/openai/types/file_content.py | 2 +- src/openai/types/file_create_params.py | 2 +- src/openai/types/file_deleted.py | 2 +- src/openai/types/file_list_params.py | 2 +- src/openai/types/file_object.py | 2 +- src/openai/types/fine_tuning/__init__.py | 2 +- .../types/fine_tuning/fine_tuning_job.py | 2 +- .../fine_tuning/fine_tuning_job_event.py | 2 +- .../types/fine_tuning/job_create_params.py | 2 +- .../fine_tuning/job_list_events_params.py | 2 +- .../types/fine_tuning/job_list_params.py | 2 +- src/openai/types/image.py | 2 +- .../types/image_create_variation_params.py | 2 +- src/openai/types/image_edit_params.py | 2 +- src/openai/types/image_generate_params.py | 2 +- src/openai/types/images_response.py | 2 +- src/openai/types/model.py | 2 +- src/openai/types/model_deleted.py | 2 +- src/openai/types/moderation.py | 2 +- src/openai/types/moderation_create_params.py | 2 +- .../types/moderation_create_response.py | 2 +- src/openai/types/shared/__init__.py | 2 +- src/openai/types/shared/error_object.py | 2 +- .../types/shared/function_definition.py | 2 +- .../types/shared/function_parameters.py | 2 +- src/openai/types/shared_params/__init__.py | 2 +- .../shared_params/function_definition.py | 2 +- .../shared_params/function_parameters.py | 2 +- tests/__init__.py | 2 +- tests/api_resources/__init__.py | 2 +- tests/api_resources/audio/__init__.py | 2 +- tests/api_resources/audio/test_speech.py | 2 +- .../audio/test_transcriptions.py | 2 +- .../api_resources/audio/test_translations.py | 2 +- tests/api_resources/beta/__init__.py | 2 +- .../api_resources/beta/assistants/__init__.py | 2 +- .../beta/assistants/test_files.py | 2 +- tests/api_resources/beta/chat/__init__.py | 2 +- tests/api_resources/beta/test_assistants.py | 2 +- tests/api_resources/beta/test_threads.py | 2 +- tests/api_resources/beta/threads/__init__.py | 2 +- .../beta/threads/messages/__init__.py | 2 +- .../beta/threads/messages/test_files.py | 2 +- .../beta/threads/runs/__init__.py | 2 +- .../beta/threads/runs/test_steps.py | 2 +- .../beta/threads/test_messages.py | 2 +- tests/api_resources/beta/threads/test_runs.py | 2 +- tests/api_resources/chat/__init__.py | 2 +- tests/api_resources/chat/test_completions.py | 2 +- tests/api_resources/fine_tuning/__init__.py | 2 +- tests/api_resources/fine_tuning/test_jobs.py | 2 +- tests/api_resources/test_completions.py | 2 +- tests/api_resources/test_embeddings.py | 2 +- tests/api_resources/test_files.py | 2 +- tests/api_resources/test_images.py | 2 +- tests/api_resources/test_models.py | 2 +- tests/api_resources/test_moderations.py | 2 +- tests/test_client.py | 2 +- tests/test_module_client.py | 2 +- 219 files changed, 331 insertions(+), 233 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index a780111df4..19cc6edce7 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.14.1" + ".": "1.14.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index f7a80d39a6..7497d6af56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,25 @@ # Changelog +## 1.14.2 (2024-03-19) + +Full Changelog: [v1.14.1...v1.14.2](https://github.com/openai/openai-python/compare/v1.14.1...v1.14.2) + +### Performance Improvements + +* cache TypeAdapters ([#1114](https://github.com/openai/openai-python/issues/1114)) ([41b6fee](https://github.com/openai/openai-python/commit/41b6feec70d3f203e36ba9a92205389bafce930c)) +* cache TypeAdapters ([#1243](https://github.com/openai/openai-python/issues/1243)) ([2005076](https://github.com/openai/openai-python/commit/2005076f500bef6e0a6cc8f935b9cc9fef65ab5b)) + + +### Chores + +* **internal:** update generated pragma comment ([#1247](https://github.com/openai/openai-python/issues/1247)) ([3eeb9b3](https://github.com/openai/openai-python/commit/3eeb9b3a71e01c2593be443a97a353371466d01a)) + + +### Documentation + +* assistant improvements ([#1249](https://github.com/openai/openai-python/issues/1249)) ([e7a3176](https://github.com/openai/openai-python/commit/e7a3176b7606822bd5ad8f7fece87de6aad1e5b6)) +* fix typo in CONTRIBUTING.md ([#1245](https://github.com/openai/openai-python/issues/1245)) ([adef57a](https://github.com/openai/openai-python/commit/adef57ae5c71734873ba49bccd92fa7f28068d28)) + ## 1.14.1 (2024-03-15) Full Changelog: [v1.14.0...v1.14.1](https://github.com/openai/openai-python/compare/v1.14.0...v1.14.1) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7ab73dbf4c..7473159258 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -86,7 +86,7 @@ Most tests require you to [set up a mock server](https://github.com/stoplightio/ ```bash # you will need npm installed -npx prism path/to/your/openapi.yml +npx prism mock path/to/your/openapi.yml ``` ```bash diff --git a/README.md b/README.md index 7d6c896d50..befe927cea 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,24 @@ we recommend using [python-dotenv](https://pypi.org/project/python-dotenv/) to add `OPENAI_API_KEY="My API Key"` to your `.env` file so that your API Key is not stored in source control. +### Streaming Helpers + +The SDK also includes helpers to process streams and handle the incoming events. + +```python +with client.beta.threads.runs.create_and_stream( + thread_id=thread.id, + assistant_id=assistant.id, + instructions="Please address the user as Jane Doe. The user has a premium account.", +) as stream: + for event in stream: + # Print the text from text delta events + if event.type == "thread.message.delta" and event.data.delta.content: + print(event.data.delta.content[0].text) +``` + +More information on streaming helpers can be found in the dedicated documentation: [helpers.md](helpers.md) + ## Async usage Simply import `AsyncOpenAI` instead of `OpenAI` and use `await` with each API call: diff --git a/helpers.md b/helpers.md index 03fd5e76b7..fed20ee81c 100644 --- a/helpers.md +++ b/helpers.md @@ -15,24 +15,28 @@ You can subscribe to events by creating an event handler class and overloading t ```python from typing_extensions import override -from openai import AssistantEventHandler +from openai import AssistantEventHandler, OpenAI +from openai.types.beta.threads import Text, TextDelta +from openai.types.beta.threads.runs import ToolCall, ToolCallDelta + +client = openai.OpenAI() # First, we create a EventHandler class to define # how we want to handle the events in the response stream. class EventHandler(AssistantEventHandler): @override - def on_text_created(self, text) -> None: + def on_text_created(self, text: Text) -> None: print(f"\nassistant > ", end="", flush=True) @override - def on_text_delta(self, delta, snapshot): + def on_text_delta(self, delta: TextDelta, snapshot: Text): print(delta.value, end="", flush=True) - def on_tool_call_created(self, tool_call): + def on_tool_call_created(self, tool_call: ToolCall): print(f"\nassistant > {tool_call.type}\n", flush=True) - def on_tool_call_delta(self, delta, snapshot): + def on_tool_call_delta(self, delta: ToolCallDelta, snapshot: ToolCall): if delta.type == 'code_interpreter': if delta.code_interpreter.input: print(delta.code_interpreter.input, end="", flush=True) @@ -47,14 +51,64 @@ class EventHandler(AssistantEventHandler): # and stream the response. with client.beta.threads.runs.create_and_stream( - thread_id=thread.id, - assistant_id=assistant.id, - instructions="Please address the user as Jane Doe. The user has a premium account.", + thread_id="thread_id", + assistant_id="assistant_id", event_handler=EventHandler(), ) as stream: stream.until_done() ``` +#### An example of iterating over events + +You can also iterate over all the streamed events. + +```python +with client.beta.threads.runs.create_and_stream( + thread_id=thread.id, + assistant_id=assistant.id +) as stream: + for event in stream: + # Print the text from text delta events + if event.type == "thread.message.delta" and event.data.delta.content: + print(event.data.delta.content[0].text) +``` + +#### An example of iterating over text + +You can also iterate over just the text deltas received + +```python +with client.beta.threads.runs.create_and_stream( + thread_id=thread.id, + assistant_id=assistant.id +) as stream: + for text in stream.text_deltas: + print(text) +``` + +### Creating Streams + +There are three helper methods for creating streams: + +```python +client.beta.threads.runs.create_and_stream() +``` + +This method can be used to start and stream the response to an existing run with an associated thread +that is already populated with messages. + +```python +client.beta.threads.create_and_run_stream() +``` + +This method can be used to add a message to a thread, start a run and then stream the response. + +```python +client.beta.threads.runs.submit_tool_outputs_stream() +``` + +This method can be used to submit a tool output to a run waiting on the output and start a stream. + ### Assistant Events The assistant API provides events you can subscribe to for the following events. @@ -139,22 +193,22 @@ This event is triggered if an exception occurs during streaming. The assistant streaming object also provides a few methods for convenience: ```python -def current_event() -def current_run() -def current_message_snapshot() -def current_run_step_snapshot() +def current_event() -> AssistantStreamEvent | None +def current_run() -> Run | None +def current_message_snapshot() -> Message | None +def current_run_step_snapshot() -> RunStep | None ``` These methods are provided to allow you to access additional context from within event handlers. In many cases the handlers should include all the information you need for processing, but if additional context is required it can be accessed. -Note: There is not always a relevant context in certain situations (these will be undefined in those cases). +Note: There is not always a relevant context in certain situations (these will be `None` in those cases). ```python -def get_final_run(self) -def get_final_run_steps(self) -def get_final_messages(self) +def get_final_run(self) -> Run +def get_final_run_steps(self) -> List[RunStep] +def get_final_messages(self) -> List[Message] ``` These methods are provided for convenience to collect information at the end of a stream. Calling these events diff --git a/pyproject.toml b/pyproject.toml index d562977dbd..de412f3907 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.14.1" +version = "1.14.2" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/__init__.py b/src/openai/__init__.py index 909be95c97..9585fde99b 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/_client.py b/src/openai/_client.py index 5043d60e2a..7fe2c9af79 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/_constants.py b/src/openai/_constants.py index dffb8ecfb6..b2e541f7b1 100644 --- a/src/openai/_constants.py +++ b/src/openai/_constants.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. import httpx diff --git a/src/openai/_exceptions.py b/src/openai/_exceptions.py index d7ded1248f..350fd2584b 100644 --- a/src/openai/_exceptions.py +++ b/src/openai/_exceptions.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/_models.py b/src/openai/_models.py index 88afa40810..166973538f 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -3,6 +3,7 @@ import inspect from typing import TYPE_CHECKING, Any, Type, Union, Generic, TypeVar, Callable, cast from datetime import date, datetime +from functools import lru_cache from typing_extensions import ( Unpack, Literal, @@ -533,7 +534,12 @@ class GenericModel(BaseGenericModel, BaseModel): if PYDANTIC_V2: - from pydantic import TypeAdapter + if TYPE_CHECKING: + from pydantic import TypeAdapter + else: + from pydantic import TypeAdapter as _TypeAdapter + + TypeAdapter = lru_cache(_TypeAdapter) def _validate_non_model_type(*, type_: type[_T], value: object) -> _T: return TypeAdapter(type_).validate_python(value) diff --git a/src/openai/_module_client.py b/src/openai/_module_client.py index d66e137ecd..9227f5e2b4 100644 --- a/src/openai/_module_client.py +++ b/src/openai/_module_client.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import override diff --git a/src/openai/_resource.py b/src/openai/_resource.py index 0b0703bb72..fff9ba19c3 100644 --- a/src/openai/_resource.py +++ b/src/openai/_resource.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/_version.py b/src/openai/_version.py index 3f5331b8e0..b8eb743acc 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.14.1" # x-release-please-version +__version__ = "1.14.2" # x-release-please-version diff --git a/src/openai/pagination.py b/src/openai/pagination.py index f7527753e1..8293638269 100644 --- a/src/openai/pagination.py +++ b/src/openai/pagination.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Any, List, Generic, TypeVar, Optional, cast from typing_extensions import Protocol, override, runtime_checkable diff --git a/src/openai/resources/__init__.py b/src/openai/resources/__init__.py index 1fb4aa62ec..64aa12d260 100644 --- a/src/openai/resources/__init__.py +++ b/src/openai/resources/__init__.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from .beta import ( Beta, diff --git a/src/openai/resources/audio/__init__.py b/src/openai/resources/audio/__init__.py index 63d06494b8..7da1d2dbde 100644 --- a/src/openai/resources/audio/__init__.py +++ b/src/openai/resources/audio/__init__.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from .audio import ( Audio, diff --git a/src/openai/resources/audio/audio.py b/src/openai/resources/audio/audio.py index bafacf4422..537ad573d0 100644 --- a/src/openai/resources/audio/audio.py +++ b/src/openai/resources/audio/audio.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index bf4a0245f6..e26c58051e 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index cfd9aae909..353f28ab05 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index 6063522237..79020a5ece 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/resources/beta/__init__.py b/src/openai/resources/beta/__init__.py index 973c6ba54e..87fea25267 100644 --- a/src/openai/resources/beta/__init__.py +++ b/src/openai/resources/beta/__init__.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from .beta import ( Beta, diff --git a/src/openai/resources/beta/assistants/__init__.py b/src/openai/resources/beta/assistants/__init__.py index ad04a71572..736def9388 100644 --- a/src/openai/resources/beta/assistants/__init__.py +++ b/src/openai/resources/beta/assistants/__init__.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from .files import ( Files, diff --git a/src/openai/resources/beta/assistants/assistants.py b/src/openai/resources/beta/assistants/assistants.py index 4698deec48..232451ab25 100644 --- a/src/openai/resources/beta/assistants/assistants.py +++ b/src/openai/resources/beta/assistants/assistants.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/resources/beta/assistants/files.py b/src/openai/resources/beta/assistants/files.py index 8d5657666c..dc57dfb96c 100644 --- a/src/openai/resources/beta/assistants/files.py +++ b/src/openai/resources/beta/assistants/files.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/resources/beta/beta.py b/src/openai/resources/beta/beta.py index 7081cff305..67baad2716 100644 --- a/src/openai/resources/beta/beta.py +++ b/src/openai/resources/beta/beta.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/resources/beta/threads/__init__.py b/src/openai/resources/beta/threads/__init__.py index 886574b327..a66e445b1f 100644 --- a/src/openai/resources/beta/threads/__init__.py +++ b/src/openai/resources/beta/threads/__init__.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from .runs import ( Runs, diff --git a/src/openai/resources/beta/threads/messages/__init__.py b/src/openai/resources/beta/threads/messages/__init__.py index 0acb0ab201..a3286e6ace 100644 --- a/src/openai/resources/beta/threads/messages/__init__.py +++ b/src/openai/resources/beta/threads/messages/__init__.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from .files import ( Files, diff --git a/src/openai/resources/beta/threads/messages/files.py b/src/openai/resources/beta/threads/messages/files.py index fc8b894d72..349f99725e 100644 --- a/src/openai/resources/beta/threads/messages/files.py +++ b/src/openai/resources/beta/threads/messages/files.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/resources/beta/threads/messages/messages.py b/src/openai/resources/beta/threads/messages/messages.py index 600d9a72ea..21e8bca5b8 100644 --- a/src/openai/resources/beta/threads/messages/messages.py +++ b/src/openai/resources/beta/threads/messages/messages.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/resources/beta/threads/runs/__init__.py b/src/openai/resources/beta/threads/runs/__init__.py index 659c96acfb..50aa9fae60 100644 --- a/src/openai/resources/beta/threads/runs/__init__.py +++ b/src/openai/resources/beta/threads/runs/__init__.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from .runs import ( Runs, diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index c5e9474002..afa447612c 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/resources/beta/threads/runs/steps.py b/src/openai/resources/beta/threads/runs/steps.py index 539745a594..118bd8822a 100644 --- a/src/openai/resources/beta/threads/runs/steps.py +++ b/src/openai/resources/beta/threads/runs/steps.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 17afe285cc..bcb0da8a62 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/resources/chat/__init__.py b/src/openai/resources/chat/__init__.py index a9668053c0..52dfdceacc 100644 --- a/src/openai/resources/chat/__init__.py +++ b/src/openai/resources/chat/__init__.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from .chat import ( Chat, diff --git a/src/openai/resources/chat/chat.py b/src/openai/resources/chat/chat.py index b6effa4e63..d14d055506 100644 --- a/src/openai/resources/chat/chat.py +++ b/src/openai/resources/chat/chat.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index abe466ef77..3000603689 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index 8a2bad5fda..db87c83ca2 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/resources/embeddings.py b/src/openai/resources/embeddings.py index cfef025bc2..a083b6269a 100644 --- a/src/openai/resources/embeddings.py +++ b/src/openai/resources/embeddings.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index 3ea66656b3..33860adad5 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/resources/fine_tuning/__init__.py b/src/openai/resources/fine_tuning/__init__.py index ab0c28ef4b..7765231fee 100644 --- a/src/openai/resources/fine_tuning/__init__.py +++ b/src/openai/resources/fine_tuning/__init__.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from .jobs import ( Jobs, diff --git a/src/openai/resources/fine_tuning/fine_tuning.py b/src/openai/resources/fine_tuning/fine_tuning.py index 33b25baec9..659b3e8501 100644 --- a/src/openai/resources/fine_tuning/fine_tuning.py +++ b/src/openai/resources/fine_tuning/fine_tuning.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/resources/fine_tuning/jobs.py b/src/openai/resources/fine_tuning/jobs.py index 8338de12c4..a0c3e24dac 100644 --- a/src/openai/resources/fine_tuning/jobs.py +++ b/src/openai/resources/fine_tuning/jobs.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py index f5bbdbc338..e12fa51bd9 100644 --- a/src/openai/resources/images.py +++ b/src/openai/resources/images.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/resources/models.py b/src/openai/resources/models.py index 3536f083d2..4e36e20801 100644 --- a/src/openai/resources/models.py +++ b/src/openai/resources/models.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/resources/moderations.py b/src/openai/resources/moderations.py index ac5ca1b64b..385b672f28 100644 --- a/src/openai/resources/moderations.py +++ b/src/openai/resources/moderations.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index e536d0b5a7..0917e22a8f 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/audio/__init__.py b/src/openai/types/audio/__init__.py index ba5f7fd8e0..8d2c44c86a 100644 --- a/src/openai/types/audio/__init__.py +++ b/src/openai/types/audio/__init__.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/audio/speech_create_params.py b/src/openai/types/audio/speech_create_params.py index 0078a9d03a..8d75ec4ccc 100644 --- a/src/openai/types/audio/speech_create_params.py +++ b/src/openai/types/audio/speech_create_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/audio/transcription.py b/src/openai/types/audio/transcription.py index 6532611731..fa512e27f9 100644 --- a/src/openai/types/audio/transcription.py +++ b/src/openai/types/audio/transcription.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from ..._models import BaseModel diff --git a/src/openai/types/audio/transcription_create_params.py b/src/openai/types/audio/transcription_create_params.py index 4164a594cc..6b2d5bae79 100644 --- a/src/openai/types/audio/transcription_create_params.py +++ b/src/openai/types/audio/transcription_create_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/audio/translation.py b/src/openai/types/audio/translation.py index a01d622abc..efc56f7f9b 100644 --- a/src/openai/types/audio/translation.py +++ b/src/openai/types/audio/translation.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from ..._models import BaseModel diff --git a/src/openai/types/audio/translation_create_params.py b/src/openai/types/audio/translation_create_params.py index 1ae312da49..f23a41ed5c 100644 --- a/src/openai/types/audio/translation_create_params.py +++ b/src/openai/types/audio/translation_create_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/__init__.py b/src/openai/types/beta/__init__.py index 714b3e159d..a7de0272b4 100644 --- a/src/openai/types/beta/__init__.py +++ b/src/openai/types/beta/__init__.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/assistant.py b/src/openai/types/beta/assistant.py index 31b847d72c..32561a9aa8 100644 --- a/src/openai/types/beta/assistant.py +++ b/src/openai/types/beta/assistant.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import List, Optional from typing_extensions import Literal diff --git a/src/openai/types/beta/assistant_create_params.py b/src/openai/types/beta/assistant_create_params.py index 0e39619a9c..8bad323640 100644 --- a/src/openai/types/beta/assistant_create_params.py +++ b/src/openai/types/beta/assistant_create_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/assistant_deleted.py b/src/openai/types/beta/assistant_deleted.py index 23802caaf6..3be40cd6b8 100644 --- a/src/openai/types/beta/assistant_deleted.py +++ b/src/openai/types/beta/assistant_deleted.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal diff --git a/src/openai/types/beta/assistant_list_params.py b/src/openai/types/beta/assistant_list_params.py index b2d794a43a..f54f63120b 100644 --- a/src/openai/types/beta/assistant_list_params.py +++ b/src/openai/types/beta/assistant_list_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/assistant_stream_event.py b/src/openai/types/beta/assistant_stream_event.py index ca7f814a8a..90471f7daa 100644 --- a/src/openai/types/beta/assistant_stream_event.py +++ b/src/openai/types/beta/assistant_stream_event.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Union from typing_extensions import Literal, Annotated diff --git a/src/openai/types/beta/assistant_tool.py b/src/openai/types/beta/assistant_tool.py index 9e589eae7a..a4420385e8 100644 --- a/src/openai/types/beta/assistant_tool.py +++ b/src/openai/types/beta/assistant_tool.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Union from typing_extensions import Annotated diff --git a/src/openai/types/beta/assistant_tool_param.py b/src/openai/types/beta/assistant_tool_param.py index 02b56a8c5d..d5758f169e 100644 --- a/src/openai/types/beta/assistant_tool_param.py +++ b/src/openai/types/beta/assistant_tool_param.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/assistant_update_params.py b/src/openai/types/beta/assistant_update_params.py index fbff50f444..7c96aca8c1 100644 --- a/src/openai/types/beta/assistant_update_params.py +++ b/src/openai/types/beta/assistant_update_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/assistants/__init__.py b/src/openai/types/beta/assistants/__init__.py index 9dbb3e2b8b..d4dd2de018 100644 --- a/src/openai/types/beta/assistants/__init__.py +++ b/src/openai/types/beta/assistants/__init__.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/assistants/assistant_file.py b/src/openai/types/beta/assistants/assistant_file.py index 1d1573ac0f..25aec07b49 100644 --- a/src/openai/types/beta/assistants/assistant_file.py +++ b/src/openai/types/beta/assistants/assistant_file.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal diff --git a/src/openai/types/beta/assistants/file_create_params.py b/src/openai/types/beta/assistants/file_create_params.py index f70f96fc1b..55f0e8cda1 100644 --- a/src/openai/types/beta/assistants/file_create_params.py +++ b/src/openai/types/beta/assistants/file_create_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/assistants/file_delete_response.py b/src/openai/types/beta/assistants/file_delete_response.py index 52c138feda..685fb2a75c 100644 --- a/src/openai/types/beta/assistants/file_delete_response.py +++ b/src/openai/types/beta/assistants/file_delete_response.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal diff --git a/src/openai/types/beta/assistants/file_list_params.py b/src/openai/types/beta/assistants/file_list_params.py index 397e35a0d1..53c493b36a 100644 --- a/src/openai/types/beta/assistants/file_list_params.py +++ b/src/openai/types/beta/assistants/file_list_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/chat/__init__.py b/src/openai/types/beta/chat/__init__.py index b2f53e3525..f8ee8b14b1 100644 --- a/src/openai/types/beta/chat/__init__.py +++ b/src/openai/types/beta/chat/__init__.py @@ -1,3 +1,3 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/code_interpreter_tool.py b/src/openai/types/beta/code_interpreter_tool.py index 4964047ba7..17ab3de629 100644 --- a/src/openai/types/beta/code_interpreter_tool.py +++ b/src/openai/types/beta/code_interpreter_tool.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal diff --git a/src/openai/types/beta/code_interpreter_tool_param.py b/src/openai/types/beta/code_interpreter_tool_param.py index 92d6e02dbc..4f6916d756 100644 --- a/src/openai/types/beta/code_interpreter_tool_param.py +++ b/src/openai/types/beta/code_interpreter_tool_param.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/function_tool.py b/src/openai/types/beta/function_tool.py index fa0ab3b83e..5d278e7487 100644 --- a/src/openai/types/beta/function_tool.py +++ b/src/openai/types/beta/function_tool.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal diff --git a/src/openai/types/beta/function_tool_param.py b/src/openai/types/beta/function_tool_param.py index e631d69e20..b44c0d47ef 100644 --- a/src/openai/types/beta/function_tool_param.py +++ b/src/openai/types/beta/function_tool_param.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/retrieval_tool.py b/src/openai/types/beta/retrieval_tool.py index 17d5bea130..b07b785c66 100644 --- a/src/openai/types/beta/retrieval_tool.py +++ b/src/openai/types/beta/retrieval_tool.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal diff --git a/src/openai/types/beta/retrieval_tool_param.py b/src/openai/types/beta/retrieval_tool_param.py index 6f803e4672..d76c0beefc 100644 --- a/src/openai/types/beta/retrieval_tool_param.py +++ b/src/openai/types/beta/retrieval_tool_param.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/thread.py b/src/openai/types/beta/thread.py index a0002a21ef..8fd1423068 100644 --- a/src/openai/types/beta/thread.py +++ b/src/openai/types/beta/thread.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Optional from typing_extensions import Literal diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index 5078639e6a..9c16e1133f 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/thread_create_params.py b/src/openai/types/beta/thread_create_params.py index e78276e839..b3dda503ff 100644 --- a/src/openai/types/beta/thread_create_params.py +++ b/src/openai/types/beta/thread_create_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/thread_deleted.py b/src/openai/types/beta/thread_deleted.py index 410ac1aea0..d385626319 100644 --- a/src/openai/types/beta/thread_deleted.py +++ b/src/openai/types/beta/thread_deleted.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal diff --git a/src/openai/types/beta/thread_update_params.py b/src/openai/types/beta/thread_update_params.py index 6c1d32fc57..94f1b1e22e 100644 --- a/src/openai/types/beta/thread_update_params.py +++ b/src/openai/types/beta/thread_update_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/threads/__init__.py b/src/openai/types/beta/threads/__init__.py index ff45871afe..b57ebccb3a 100644 --- a/src/openai/types/beta/threads/__init__.py +++ b/src/openai/types/beta/threads/__init__.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/threads/annotation.py b/src/openai/types/beta/threads/annotation.py index 86a2115233..31e228c831 100644 --- a/src/openai/types/beta/threads/annotation.py +++ b/src/openai/types/beta/threads/annotation.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Union from typing_extensions import Annotated diff --git a/src/openai/types/beta/threads/annotation_delta.py b/src/openai/types/beta/threads/annotation_delta.py index fdcc67c3ff..912429672f 100644 --- a/src/openai/types/beta/threads/annotation_delta.py +++ b/src/openai/types/beta/threads/annotation_delta.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Union from typing_extensions import Annotated diff --git a/src/openai/types/beta/threads/file_citation_annotation.py b/src/openai/types/beta/threads/file_citation_annotation.py index da63938d93..68571cd477 100644 --- a/src/openai/types/beta/threads/file_citation_annotation.py +++ b/src/openai/types/beta/threads/file_citation_annotation.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal diff --git a/src/openai/types/beta/threads/file_citation_delta_annotation.py b/src/openai/types/beta/threads/file_citation_delta_annotation.py index 3b4c5950d4..b40c0d123e 100644 --- a/src/openai/types/beta/threads/file_citation_delta_annotation.py +++ b/src/openai/types/beta/threads/file_citation_delta_annotation.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Optional from typing_extensions import Literal diff --git a/src/openai/types/beta/threads/file_path_annotation.py b/src/openai/types/beta/threads/file_path_annotation.py index 2d9cf58184..9812737ece 100644 --- a/src/openai/types/beta/threads/file_path_annotation.py +++ b/src/openai/types/beta/threads/file_path_annotation.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal diff --git a/src/openai/types/beta/threads/file_path_delta_annotation.py b/src/openai/types/beta/threads/file_path_delta_annotation.py index 6d89748d2c..0cbb445e48 100644 --- a/src/openai/types/beta/threads/file_path_delta_annotation.py +++ b/src/openai/types/beta/threads/file_path_delta_annotation.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Optional from typing_extensions import Literal diff --git a/src/openai/types/beta/threads/image_file.py b/src/openai/types/beta/threads/image_file.py index 371055627c..db0d6e823a 100644 --- a/src/openai/types/beta/threads/image_file.py +++ b/src/openai/types/beta/threads/image_file.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from ...._models import BaseModel diff --git a/src/openai/types/beta/threads/image_file_content_block.py b/src/openai/types/beta/threads/image_file_content_block.py index 3baf8b884b..a909999065 100644 --- a/src/openai/types/beta/threads/image_file_content_block.py +++ b/src/openai/types/beta/threads/image_file_content_block.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal diff --git a/src/openai/types/beta/threads/image_file_delta.py b/src/openai/types/beta/threads/image_file_delta.py index 2bda05f82b..b0b1d32fa2 100644 --- a/src/openai/types/beta/threads/image_file_delta.py +++ b/src/openai/types/beta/threads/image_file_delta.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Optional diff --git a/src/openai/types/beta/threads/image_file_delta_block.py b/src/openai/types/beta/threads/image_file_delta_block.py index 97cc1c4608..0a5a2e8a5f 100644 --- a/src/openai/types/beta/threads/image_file_delta_block.py +++ b/src/openai/types/beta/threads/image_file_delta_block.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Optional from typing_extensions import Literal diff --git a/src/openai/types/beta/threads/message.py b/src/openai/types/beta/threads/message.py index 4f307928be..027e2bfa15 100644 --- a/src/openai/types/beta/threads/message.py +++ b/src/openai/types/beta/threads/message.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import List, Optional from typing_extensions import Literal diff --git a/src/openai/types/beta/threads/message_content.py b/src/openai/types/beta/threads/message_content.py index 7da6a81fb6..bc79b39fd4 100644 --- a/src/openai/types/beta/threads/message_content.py +++ b/src/openai/types/beta/threads/message_content.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Union from typing_extensions import Annotated diff --git a/src/openai/types/beta/threads/message_content_delta.py b/src/openai/types/beta/threads/message_content_delta.py index 7a8266d02f..3cbc22c94b 100644 --- a/src/openai/types/beta/threads/message_content_delta.py +++ b/src/openai/types/beta/threads/message_content_delta.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Union from typing_extensions import Annotated diff --git a/src/openai/types/beta/threads/message_create_params.py b/src/openai/types/beta/threads/message_create_params.py index 8733f10b8a..b2f27deb3e 100644 --- a/src/openai/types/beta/threads/message_create_params.py +++ b/src/openai/types/beta/threads/message_create_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/threads/message_delta.py b/src/openai/types/beta/threads/message_delta.py index 1113cc27fb..3a55e1442a 100644 --- a/src/openai/types/beta/threads/message_delta.py +++ b/src/openai/types/beta/threads/message_delta.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import List, Optional from typing_extensions import Literal diff --git a/src/openai/types/beta/threads/message_delta_event.py b/src/openai/types/beta/threads/message_delta_event.py index 07a9107a34..3811cef679 100644 --- a/src/openai/types/beta/threads/message_delta_event.py +++ b/src/openai/types/beta/threads/message_delta_event.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal diff --git a/src/openai/types/beta/threads/message_list_params.py b/src/openai/types/beta/threads/message_list_params.py index 31e407bb22..8b139caa93 100644 --- a/src/openai/types/beta/threads/message_list_params.py +++ b/src/openai/types/beta/threads/message_list_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/threads/message_update_params.py b/src/openai/types/beta/threads/message_update_params.py index 2e3e1b4b1a..7000f33122 100644 --- a/src/openai/types/beta/threads/message_update_params.py +++ b/src/openai/types/beta/threads/message_update_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/threads/messages/__init__.py b/src/openai/types/beta/threads/messages/__init__.py index 6046f68204..d129297620 100644 --- a/src/openai/types/beta/threads/messages/__init__.py +++ b/src/openai/types/beta/threads/messages/__init__.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/threads/messages/file_list_params.py b/src/openai/types/beta/threads/messages/file_list_params.py index 3640b8508b..7e2d6136ec 100644 --- a/src/openai/types/beta/threads/messages/file_list_params.py +++ b/src/openai/types/beta/threads/messages/file_list_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/threads/messages/message_file.py b/src/openai/types/beta/threads/messages/message_file.py index 5332dee962..342479ab7b 100644 --- a/src/openai/types/beta/threads/messages/message_file.py +++ b/src/openai/types/beta/threads/messages/message_file.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal diff --git a/src/openai/types/beta/threads/required_action_function_tool_call.py b/src/openai/types/beta/threads/required_action_function_tool_call.py index 0284d0f188..a24dfd068b 100644 --- a/src/openai/types/beta/threads/required_action_function_tool_call.py +++ b/src/openai/types/beta/threads/required_action_function_tool_call.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal diff --git a/src/openai/types/beta/threads/run.py b/src/openai/types/beta/threads/run.py index dd2842c584..d2cac4c279 100644 --- a/src/openai/types/beta/threads/run.py +++ b/src/openai/types/beta/threads/run.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import List, Optional from typing_extensions import Literal diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index c012390f5c..89dff389a9 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/threads/run_list_params.py b/src/openai/types/beta/threads/run_list_params.py index 5f41347718..1e32bca4b4 100644 --- a/src/openai/types/beta/threads/run_list_params.py +++ b/src/openai/types/beta/threads/run_list_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/threads/run_status.py b/src/openai/types/beta/threads/run_status.py index 587e3d7810..bf9b4e7bbf 100644 --- a/src/openai/types/beta/threads/run_status.py +++ b/src/openai/types/beta/threads/run_status.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal diff --git a/src/openai/types/beta/threads/run_submit_tool_outputs_params.py b/src/openai/types/beta/threads/run_submit_tool_outputs_params.py index 49e1ac49ab..ccb5e5e97e 100644 --- a/src/openai/types/beta/threads/run_submit_tool_outputs_params.py +++ b/src/openai/types/beta/threads/run_submit_tool_outputs_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/threads/run_update_params.py b/src/openai/types/beta/threads/run_update_params.py index 09f81aa003..e595eac882 100644 --- a/src/openai/types/beta/threads/run_update_params.py +++ b/src/openai/types/beta/threads/run_update_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/threads/runs/__init__.py b/src/openai/types/beta/threads/runs/__init__.py index 03ae192088..256510dcc7 100644 --- a/src/openai/types/beta/threads/runs/__init__.py +++ b/src/openai/types/beta/threads/runs/__init__.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/threads/runs/code_interpreter_logs.py b/src/openai/types/beta/threads/runs/code_interpreter_logs.py index c91179be22..0bf8c1dac2 100644 --- a/src/openai/types/beta/threads/runs/code_interpreter_logs.py +++ b/src/openai/types/beta/threads/runs/code_interpreter_logs.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Optional from typing_extensions import Literal diff --git a/src/openai/types/beta/threads/runs/code_interpreter_output_image.py b/src/openai/types/beta/threads/runs/code_interpreter_output_image.py index 0d7d26f91f..2257f37e41 100644 --- a/src/openai/types/beta/threads/runs/code_interpreter_output_image.py +++ b/src/openai/types/beta/threads/runs/code_interpreter_output_image.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Optional from typing_extensions import Literal diff --git a/src/openai/types/beta/threads/runs/code_interpreter_tool_call.py b/src/openai/types/beta/threads/runs/code_interpreter_tool_call.py index c537562e91..2f07243684 100644 --- a/src/openai/types/beta/threads/runs/code_interpreter_tool_call.py +++ b/src/openai/types/beta/threads/runs/code_interpreter_tool_call.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import List, Union from typing_extensions import Literal, Annotated diff --git a/src/openai/types/beta/threads/runs/code_interpreter_tool_call_delta.py b/src/openai/types/beta/threads/runs/code_interpreter_tool_call_delta.py index b13105f840..eff76355b3 100644 --- a/src/openai/types/beta/threads/runs/code_interpreter_tool_call_delta.py +++ b/src/openai/types/beta/threads/runs/code_interpreter_tool_call_delta.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import List, Union, Optional from typing_extensions import Literal, Annotated diff --git a/src/openai/types/beta/threads/runs/function_tool_call.py b/src/openai/types/beta/threads/runs/function_tool_call.py index bbd3cb7052..b1d354f894 100644 --- a/src/openai/types/beta/threads/runs/function_tool_call.py +++ b/src/openai/types/beta/threads/runs/function_tool_call.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Optional from typing_extensions import Literal diff --git a/src/openai/types/beta/threads/runs/function_tool_call_delta.py b/src/openai/types/beta/threads/runs/function_tool_call_delta.py index 46c341bc84..faaf026f7f 100644 --- a/src/openai/types/beta/threads/runs/function_tool_call_delta.py +++ b/src/openai/types/beta/threads/runs/function_tool_call_delta.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Optional from typing_extensions import Literal diff --git a/src/openai/types/beta/threads/runs/message_creation_step_details.py b/src/openai/types/beta/threads/runs/message_creation_step_details.py index 13f9398515..73439079d3 100644 --- a/src/openai/types/beta/threads/runs/message_creation_step_details.py +++ b/src/openai/types/beta/threads/runs/message_creation_step_details.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal diff --git a/src/openai/types/beta/threads/runs/retrieval_tool_call.py b/src/openai/types/beta/threads/runs/retrieval_tool_call.py index 6cdbcdd93f..48704ed331 100644 --- a/src/openai/types/beta/threads/runs/retrieval_tool_call.py +++ b/src/openai/types/beta/threads/runs/retrieval_tool_call.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal diff --git a/src/openai/types/beta/threads/runs/retrieval_tool_call_delta.py b/src/openai/types/beta/threads/runs/retrieval_tool_call_delta.py index ac8003d3eb..3310079399 100644 --- a/src/openai/types/beta/threads/runs/retrieval_tool_call_delta.py +++ b/src/openai/types/beta/threads/runs/retrieval_tool_call_delta.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Optional from typing_extensions import Literal diff --git a/src/openai/types/beta/threads/runs/run_step.py b/src/openai/types/beta/threads/runs/run_step.py index 899883ac2d..7c81dcac2b 100644 --- a/src/openai/types/beta/threads/runs/run_step.py +++ b/src/openai/types/beta/threads/runs/run_step.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Union, Optional from typing_extensions import Literal, Annotated diff --git a/src/openai/types/beta/threads/runs/run_step_delta.py b/src/openai/types/beta/threads/runs/run_step_delta.py index fb8b869425..d6b4aefeb9 100644 --- a/src/openai/types/beta/threads/runs/run_step_delta.py +++ b/src/openai/types/beta/threads/runs/run_step_delta.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Union, Optional from typing_extensions import Annotated diff --git a/src/openai/types/beta/threads/runs/run_step_delta_event.py b/src/openai/types/beta/threads/runs/run_step_delta_event.py index ab61dd1f9a..7f3f92aabf 100644 --- a/src/openai/types/beta/threads/runs/run_step_delta_event.py +++ b/src/openai/types/beta/threads/runs/run_step_delta_event.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal diff --git a/src/openai/types/beta/threads/runs/run_step_delta_message_delta.py b/src/openai/types/beta/threads/runs/run_step_delta_message_delta.py index 52ec5d3440..f58ed3d96d 100644 --- a/src/openai/types/beta/threads/runs/run_step_delta_message_delta.py +++ b/src/openai/types/beta/threads/runs/run_step_delta_message_delta.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Optional from typing_extensions import Literal diff --git a/src/openai/types/beta/threads/runs/step_list_params.py b/src/openai/types/beta/threads/runs/step_list_params.py index 9c7b6c64d0..606d444539 100644 --- a/src/openai/types/beta/threads/runs/step_list_params.py +++ b/src/openai/types/beta/threads/runs/step_list_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/beta/threads/runs/tool_call.py b/src/openai/types/beta/threads/runs/tool_call.py index a3abfa77ad..dcca797bf0 100644 --- a/src/openai/types/beta/threads/runs/tool_call.py +++ b/src/openai/types/beta/threads/runs/tool_call.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Union from typing_extensions import Annotated diff --git a/src/openai/types/beta/threads/runs/tool_call_delta.py b/src/openai/types/beta/threads/runs/tool_call_delta.py index a1aa4de6cf..fc98981abf 100644 --- a/src/openai/types/beta/threads/runs/tool_call_delta.py +++ b/src/openai/types/beta/threads/runs/tool_call_delta.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Union from typing_extensions import Annotated diff --git a/src/openai/types/beta/threads/runs/tool_call_delta_object.py b/src/openai/types/beta/threads/runs/tool_call_delta_object.py index 2ce46ab894..9cd59a6e24 100644 --- a/src/openai/types/beta/threads/runs/tool_call_delta_object.py +++ b/src/openai/types/beta/threads/runs/tool_call_delta_object.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import List, Optional from typing_extensions import Literal diff --git a/src/openai/types/beta/threads/runs/tool_calls_step_details.py b/src/openai/types/beta/threads/runs/tool_calls_step_details.py index 6fccfc563a..ca08fabd0e 100644 --- a/src/openai/types/beta/threads/runs/tool_calls_step_details.py +++ b/src/openai/types/beta/threads/runs/tool_calls_step_details.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import List from typing_extensions import Literal diff --git a/src/openai/types/beta/threads/text.py b/src/openai/types/beta/threads/text.py index a5a31c6783..853bec2955 100644 --- a/src/openai/types/beta/threads/text.py +++ b/src/openai/types/beta/threads/text.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import List diff --git a/src/openai/types/beta/threads/text_content_block.py b/src/openai/types/beta/threads/text_content_block.py index 1c9187ea60..3706d6b9d8 100644 --- a/src/openai/types/beta/threads/text_content_block.py +++ b/src/openai/types/beta/threads/text_content_block.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal diff --git a/src/openai/types/beta/threads/text_delta.py b/src/openai/types/beta/threads/text_delta.py index 735846472a..09cd357027 100644 --- a/src/openai/types/beta/threads/text_delta.py +++ b/src/openai/types/beta/threads/text_delta.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import List, Optional diff --git a/src/openai/types/beta/threads/text_delta_block.py b/src/openai/types/beta/threads/text_delta_block.py index 6adbdee479..586116e0d6 100644 --- a/src/openai/types/beta/threads/text_delta_block.py +++ b/src/openai/types/beta/threads/text_delta_block.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Optional from typing_extensions import Literal diff --git a/src/openai/types/chat/__init__.py b/src/openai/types/chat/__init__.py index 39a6335f64..5d122d2020 100644 --- a/src/openai/types/chat/__init__.py +++ b/src/openai/types/chat/__init__.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/chat/chat_completion.py b/src/openai/types/chat/chat_completion.py index dc63d84945..61a94a258e 100644 --- a/src/openai/types/chat/chat_completion.py +++ b/src/openai/types/chat/chat_completion.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import List, Optional from typing_extensions import Literal diff --git a/src/openai/types/chat/chat_completion_assistant_message_param.py b/src/openai/types/chat/chat_completion_assistant_message_param.py index 7377139bf5..e1e399486e 100644 --- a/src/openai/types/chat/chat_completion_assistant_message_param.py +++ b/src/openai/types/chat/chat_completion_assistant_message_param.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/chat/chat_completion_chunk.py b/src/openai/types/chat/chat_completion_chunk.py index 95013e7a4f..c2f18bcb74 100644 --- a/src/openai/types/chat/chat_completion_chunk.py +++ b/src/openai/types/chat/chat_completion_chunk.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import List, Optional from typing_extensions import Literal diff --git a/src/openai/types/chat/chat_completion_content_part_image_param.py b/src/openai/types/chat/chat_completion_content_part_image_param.py index e6732185ef..b1a186aa6d 100644 --- a/src/openai/types/chat/chat_completion_content_part_image_param.py +++ b/src/openai/types/chat/chat_completion_content_part_image_param.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/chat/chat_completion_content_part_param.py b/src/openai/types/chat/chat_completion_content_part_param.py index 8e58239258..f9b5f71e43 100644 --- a/src/openai/types/chat/chat_completion_content_part_param.py +++ b/src/openai/types/chat/chat_completion_content_part_param.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/chat/chat_completion_content_part_text_param.py b/src/openai/types/chat/chat_completion_content_part_text_param.py index 38edcf054e..a270744417 100644 --- a/src/openai/types/chat/chat_completion_content_part_text_param.py +++ b/src/openai/types/chat/chat_completion_content_part_text_param.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/chat/chat_completion_function_call_option_param.py b/src/openai/types/chat/chat_completion_function_call_option_param.py index 72d41d908c..2bc014af7a 100644 --- a/src/openai/types/chat/chat_completion_function_call_option_param.py +++ b/src/openai/types/chat/chat_completion_function_call_option_param.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/chat/chat_completion_function_message_param.py b/src/openai/types/chat/chat_completion_function_message_param.py index 3f9a1a9039..5af12bf94f 100644 --- a/src/openai/types/chat/chat_completion_function_message_param.py +++ b/src/openai/types/chat/chat_completion_function_message_param.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/chat/chat_completion_message.py b/src/openai/types/chat/chat_completion_message.py index da8b2fcd5c..8db7d17d24 100644 --- a/src/openai/types/chat/chat_completion_message.py +++ b/src/openai/types/chat/chat_completion_message.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import List, Optional from typing_extensions import Literal diff --git a/src/openai/types/chat/chat_completion_message_param.py b/src/openai/types/chat/chat_completion_message_param.py index 7ec3d6a7b7..a3644a5310 100644 --- a/src/openai/types/chat/chat_completion_message_param.py +++ b/src/openai/types/chat/chat_completion_message_param.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/chat/chat_completion_message_tool_call.py b/src/openai/types/chat/chat_completion_message_tool_call.py index 63c72fcdca..4fec667096 100644 --- a/src/openai/types/chat/chat_completion_message_tool_call.py +++ b/src/openai/types/chat/chat_completion_message_tool_call.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal diff --git a/src/openai/types/chat/chat_completion_message_tool_call_param.py b/src/openai/types/chat/chat_completion_message_tool_call_param.py index a700f02c4f..f616c363d0 100644 --- a/src/openai/types/chat/chat_completion_message_tool_call_param.py +++ b/src/openai/types/chat/chat_completion_message_tool_call_param.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/chat/chat_completion_named_tool_choice_param.py b/src/openai/types/chat/chat_completion_named_tool_choice_param.py index 0b5ffde37b..369f8b42dd 100644 --- a/src/openai/types/chat/chat_completion_named_tool_choice_param.py +++ b/src/openai/types/chat/chat_completion_named_tool_choice_param.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/chat/chat_completion_role.py b/src/openai/types/chat/chat_completion_role.py index 9fa2acb4bb..1fd83888d3 100644 --- a/src/openai/types/chat/chat_completion_role.py +++ b/src/openai/types/chat/chat_completion_role.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal diff --git a/src/openai/types/chat/chat_completion_system_message_param.py b/src/openai/types/chat/chat_completion_system_message_param.py index 6e862e75c7..94bb3f636c 100644 --- a/src/openai/types/chat/chat_completion_system_message_param.py +++ b/src/openai/types/chat/chat_completion_system_message_param.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/chat/chat_completion_token_logprob.py b/src/openai/types/chat/chat_completion_token_logprob.py index 076ffb680c..c69e258910 100644 --- a/src/openai/types/chat/chat_completion_token_logprob.py +++ b/src/openai/types/chat/chat_completion_token_logprob.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import List, Optional diff --git a/src/openai/types/chat/chat_completion_tool_choice_option_param.py b/src/openai/types/chat/chat_completion_tool_choice_option_param.py index 8104b26acb..9c0ae22528 100644 --- a/src/openai/types/chat/chat_completion_tool_choice_option_param.py +++ b/src/openai/types/chat/chat_completion_tool_choice_option_param.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/chat/chat_completion_tool_message_param.py b/src/openai/types/chat/chat_completion_tool_message_param.py index 373c5b88f4..5c590e033f 100644 --- a/src/openai/types/chat/chat_completion_tool_message_param.py +++ b/src/openai/types/chat/chat_completion_tool_message_param.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/chat/chat_completion_tool_param.py b/src/openai/types/chat/chat_completion_tool_param.py index 54c223955e..0cf6ea7268 100644 --- a/src/openai/types/chat/chat_completion_tool_param.py +++ b/src/openai/types/chat/chat_completion_tool_param.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/chat/chat_completion_user_message_param.py b/src/openai/types/chat/chat_completion_user_message_param.py index cb8ca19bf0..5c15322a22 100644 --- a/src/openai/types/chat/chat_completion_user_message_param.py +++ b/src/openai/types/chat/chat_completion_user_message_param.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index e391c63119..ab6a747021 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/completion.py b/src/openai/types/completion.py index cd80498b16..d3b3102a4a 100644 --- a/src/openai/types/completion.py +++ b/src/openai/types/completion.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import List, Optional from typing_extensions import Literal diff --git a/src/openai/types/completion_choice.py b/src/openai/types/completion_choice.py index 7b08582bfd..d948ebc942 100644 --- a/src/openai/types/completion_choice.py +++ b/src/openai/types/completion_choice.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Dict, List, Optional from typing_extensions import Literal diff --git a/src/openai/types/completion_create_params.py b/src/openai/types/completion_create_params.py index 08ffca760f..36267e9061 100644 --- a/src/openai/types/completion_create_params.py +++ b/src/openai/types/completion_create_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/completion_usage.py b/src/openai/types/completion_usage.py index b825d5529f..e185a5cc38 100644 --- a/src/openai/types/completion_usage.py +++ b/src/openai/types/completion_usage.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from .._models import BaseModel diff --git a/src/openai/types/create_embedding_response.py b/src/openai/types/create_embedding_response.py index bf64037e16..eff247a112 100644 --- a/src/openai/types/create_embedding_response.py +++ b/src/openai/types/create_embedding_response.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import List from typing_extensions import Literal diff --git a/src/openai/types/embedding.py b/src/openai/types/embedding.py index 9c53704d5d..769b1d165f 100644 --- a/src/openai/types/embedding.py +++ b/src/openai/types/embedding.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import List from typing_extensions import Literal diff --git a/src/openai/types/embedding_create_params.py b/src/openai/types/embedding_create_params.py index a549dc94c4..930b3b7914 100644 --- a/src/openai/types/embedding_create_params.py +++ b/src/openai/types/embedding_create_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/file_content.py b/src/openai/types/file_content.py index 92b316b9eb..b4aa08a9a3 100644 --- a/src/openai/types/file_content.py +++ b/src/openai/types/file_content.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __all__ = ["FileContent"] diff --git a/src/openai/types/file_create_params.py b/src/openai/types/file_create_params.py index a59ddb2817..26e2da3372 100644 --- a/src/openai/types/file_create_params.py +++ b/src/openai/types/file_create_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/file_deleted.py b/src/openai/types/file_deleted.py index 3ac8592ff6..f25fa87a8d 100644 --- a/src/openai/types/file_deleted.py +++ b/src/openai/types/file_deleted.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal diff --git a/src/openai/types/file_list_params.py b/src/openai/types/file_list_params.py index a962dd239c..212eca13c0 100644 --- a/src/openai/types/file_list_params.py +++ b/src/openai/types/file_list_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/file_object.py b/src/openai/types/file_object.py index 4ae91b754e..589a1faf38 100644 --- a/src/openai/types/file_object.py +++ b/src/openai/types/file_object.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Optional from typing_extensions import Literal diff --git a/src/openai/types/fine_tuning/__init__.py b/src/openai/types/fine_tuning/__init__.py index d24160c5bd..0bb2b90438 100644 --- a/src/openai/types/fine_tuning/__init__.py +++ b/src/openai/types/fine_tuning/__init__.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/fine_tuning/fine_tuning_job.py b/src/openai/types/fine_tuning/fine_tuning_job.py index 5aa4f07eb1..23fe96d1a0 100644 --- a/src/openai/types/fine_tuning/fine_tuning_job.py +++ b/src/openai/types/fine_tuning/fine_tuning_job.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import List, Union, Optional from typing_extensions import Literal diff --git a/src/openai/types/fine_tuning/fine_tuning_job_event.py b/src/openai/types/fine_tuning/fine_tuning_job_event.py index 62f268868b..2d204bb980 100644 --- a/src/openai/types/fine_tuning/fine_tuning_job_event.py +++ b/src/openai/types/fine_tuning/fine_tuning_job_event.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal diff --git a/src/openai/types/fine_tuning/job_create_params.py b/src/openai/types/fine_tuning/job_create_params.py index da750ffc19..79e0b67e13 100644 --- a/src/openai/types/fine_tuning/job_create_params.py +++ b/src/openai/types/fine_tuning/job_create_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/fine_tuning/job_list_events_params.py b/src/openai/types/fine_tuning/job_list_events_params.py index 7be3d53315..e1c9a64dc8 100644 --- a/src/openai/types/fine_tuning/job_list_events_params.py +++ b/src/openai/types/fine_tuning/job_list_events_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/fine_tuning/job_list_params.py b/src/openai/types/fine_tuning/job_list_params.py index 8160136901..5c075ca33f 100644 --- a/src/openai/types/fine_tuning/job_list_params.py +++ b/src/openai/types/fine_tuning/job_list_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/image.py b/src/openai/types/image.py index a040caf7b6..f48aa2c702 100644 --- a/src/openai/types/image.py +++ b/src/openai/types/image.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Optional diff --git a/src/openai/types/image_create_variation_params.py b/src/openai/types/image_create_variation_params.py index 5714f97fa9..2549307372 100644 --- a/src/openai/types/image_create_variation_params.py +++ b/src/openai/types/image_create_variation_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/image_edit_params.py b/src/openai/types/image_edit_params.py index 751ec4fe7a..073456e349 100644 --- a/src/openai/types/image_edit_params.py +++ b/src/openai/types/image_edit_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/image_generate_params.py b/src/openai/types/image_generate_params.py index 3ff1b979db..18c56f8ed6 100644 --- a/src/openai/types/image_generate_params.py +++ b/src/openai/types/image_generate_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/images_response.py b/src/openai/types/images_response.py index 9d1bc95a42..7cee813184 100644 --- a/src/openai/types/images_response.py +++ b/src/openai/types/images_response.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import List diff --git a/src/openai/types/model.py b/src/openai/types/model.py index 58f3997f70..2631ee8d1a 100644 --- a/src/openai/types/model.py +++ b/src/openai/types/model.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal diff --git a/src/openai/types/model_deleted.py b/src/openai/types/model_deleted.py index 5329da1378..e7601f74e4 100644 --- a/src/openai/types/model_deleted.py +++ b/src/openai/types/model_deleted.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from .._models import BaseModel diff --git a/src/openai/types/moderation.py b/src/openai/types/moderation.py index 1c26ec3367..2a2e5c5d7a 100644 --- a/src/openai/types/moderation.py +++ b/src/openai/types/moderation.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from pydantic import Field as FieldInfo diff --git a/src/openai/types/moderation_create_params.py b/src/openai/types/moderation_create_params.py index 25ed3ce940..d4608def54 100644 --- a/src/openai/types/moderation_create_params.py +++ b/src/openai/types/moderation_create_params.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/moderation_create_response.py b/src/openai/types/moderation_create_response.py index 0962cdbfd9..79684f8a70 100644 --- a/src/openai/types/moderation_create_response.py +++ b/src/openai/types/moderation_create_response.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import List diff --git a/src/openai/types/shared/__init__.py b/src/openai/types/shared/__init__.py index c9ebb1a504..e085744e29 100644 --- a/src/openai/types/shared/__init__.py +++ b/src/openai/types/shared/__init__.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from .error_object import ErrorObject as ErrorObject from .function_definition import FunctionDefinition as FunctionDefinition diff --git a/src/openai/types/shared/error_object.py b/src/openai/types/shared/error_object.py index f18fcc1c33..32d7045e00 100644 --- a/src/openai/types/shared/error_object.py +++ b/src/openai/types/shared/error_object.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Optional diff --git a/src/openai/types/shared/function_definition.py b/src/openai/types/shared/function_definition.py index 32658220fa..a39116d6bd 100644 --- a/src/openai/types/shared/function_definition.py +++ b/src/openai/types/shared/function_definition.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Optional diff --git a/src/openai/types/shared/function_parameters.py b/src/openai/types/shared/function_parameters.py index 405c2d14cc..c9524e4cb8 100644 --- a/src/openai/types/shared/function_parameters.py +++ b/src/openai/types/shared/function_parameters.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Dict diff --git a/src/openai/types/shared_params/__init__.py b/src/openai/types/shared_params/__init__.py index 05bc4ff9ba..ef638cb279 100644 --- a/src/openai/types/shared_params/__init__.py +++ b/src/openai/types/shared_params/__init__.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from .function_definition import FunctionDefinition as FunctionDefinition from .function_parameters import FunctionParameters as FunctionParameters diff --git a/src/openai/types/shared_params/function_definition.py b/src/openai/types/shared_params/function_definition.py index 8e89bd41dd..58d0203b4f 100644 --- a/src/openai/types/shared_params/function_definition.py +++ b/src/openai/types/shared_params/function_definition.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/src/openai/types/shared_params/function_parameters.py b/src/openai/types/shared_params/function_parameters.py index a405f6b2e2..5b40efb78f 100644 --- a/src/openai/types/shared_params/function_parameters.py +++ b/src/openai/types/shared_params/function_parameters.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/tests/__init__.py b/tests/__init__.py index 1016754ef3..fd8019a9a1 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -1 +1 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/__init__.py b/tests/api_resources/__init__.py index 1016754ef3..fd8019a9a1 100644 --- a/tests/api_resources/__init__.py +++ b/tests/api_resources/__init__.py @@ -1 +1 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/audio/__init__.py b/tests/api_resources/audio/__init__.py index 1016754ef3..fd8019a9a1 100644 --- a/tests/api_resources/audio/__init__.py +++ b/tests/api_resources/audio/__init__.py @@ -1 +1 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/audio/test_speech.py b/tests/api_resources/audio/test_speech.py index b1c7f79b1e..781ebeceb9 100644 --- a/tests/api_resources/audio/test_speech.py +++ b/tests/api_resources/audio/test_speech.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/tests/api_resources/audio/test_transcriptions.py b/tests/api_resources/audio/test_transcriptions.py index 80e364b484..ba8e9e4099 100644 --- a/tests/api_resources/audio/test_transcriptions.py +++ b/tests/api_resources/audio/test_transcriptions.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/tests/api_resources/audio/test_translations.py b/tests/api_resources/audio/test_translations.py index 72960c3249..f5c6c68f0b 100644 --- a/tests/api_resources/audio/test_translations.py +++ b/tests/api_resources/audio/test_translations.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/tests/api_resources/beta/__init__.py b/tests/api_resources/beta/__init__.py index 1016754ef3..fd8019a9a1 100644 --- a/tests/api_resources/beta/__init__.py +++ b/tests/api_resources/beta/__init__.py @@ -1 +1 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/beta/assistants/__init__.py b/tests/api_resources/beta/assistants/__init__.py index 1016754ef3..fd8019a9a1 100644 --- a/tests/api_resources/beta/assistants/__init__.py +++ b/tests/api_resources/beta/assistants/__init__.py @@ -1 +1 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/beta/assistants/test_files.py b/tests/api_resources/beta/assistants/test_files.py index 66e3e2efe6..50106234aa 100644 --- a/tests/api_resources/beta/assistants/test_files.py +++ b/tests/api_resources/beta/assistants/test_files.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/tests/api_resources/beta/chat/__init__.py b/tests/api_resources/beta/chat/__init__.py index 1016754ef3..fd8019a9a1 100644 --- a/tests/api_resources/beta/chat/__init__.py +++ b/tests/api_resources/beta/chat/__init__.py @@ -1 +1 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/beta/test_assistants.py b/tests/api_resources/beta/test_assistants.py index 8db40bde93..6edbe4b491 100644 --- a/tests/api_resources/beta/test_assistants.py +++ b/tests/api_resources/beta/test_assistants.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/tests/api_resources/beta/test_threads.py b/tests/api_resources/beta/test_threads.py index 6bb8fc82de..57dda57d16 100644 --- a/tests/api_resources/beta/test_threads.py +++ b/tests/api_resources/beta/test_threads.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/tests/api_resources/beta/threads/__init__.py b/tests/api_resources/beta/threads/__init__.py index 1016754ef3..fd8019a9a1 100644 --- a/tests/api_resources/beta/threads/__init__.py +++ b/tests/api_resources/beta/threads/__init__.py @@ -1 +1 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/beta/threads/messages/__init__.py b/tests/api_resources/beta/threads/messages/__init__.py index 1016754ef3..fd8019a9a1 100644 --- a/tests/api_resources/beta/threads/messages/__init__.py +++ b/tests/api_resources/beta/threads/messages/__init__.py @@ -1 +1 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/beta/threads/messages/test_files.py b/tests/api_resources/beta/threads/messages/test_files.py index 4d0613fd2f..af4eea9377 100644 --- a/tests/api_resources/beta/threads/messages/test_files.py +++ b/tests/api_resources/beta/threads/messages/test_files.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/tests/api_resources/beta/threads/runs/__init__.py b/tests/api_resources/beta/threads/runs/__init__.py index 1016754ef3..fd8019a9a1 100644 --- a/tests/api_resources/beta/threads/runs/__init__.py +++ b/tests/api_resources/beta/threads/runs/__init__.py @@ -1 +1 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/beta/threads/runs/test_steps.py b/tests/api_resources/beta/threads/runs/test_steps.py index c15848cd70..e6108d8dad 100644 --- a/tests/api_resources/beta/threads/runs/test_steps.py +++ b/tests/api_resources/beta/threads/runs/test_steps.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/tests/api_resources/beta/threads/test_messages.py b/tests/api_resources/beta/threads/test_messages.py index c61a9ee109..c708c94068 100644 --- a/tests/api_resources/beta/threads/test_messages.py +++ b/tests/api_resources/beta/threads/test_messages.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index de1ad07567..3a9719b420 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/tests/api_resources/chat/__init__.py b/tests/api_resources/chat/__init__.py index 1016754ef3..fd8019a9a1 100644 --- a/tests/api_resources/chat/__init__.py +++ b/tests/api_resources/chat/__init__.py @@ -1 +1 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index 4fa069ba2e..bb0658f3d9 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/tests/api_resources/fine_tuning/__init__.py b/tests/api_resources/fine_tuning/__init__.py index 1016754ef3..fd8019a9a1 100644 --- a/tests/api_resources/fine_tuning/__init__.py +++ b/tests/api_resources/fine_tuning/__init__.py @@ -1 +1 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/fine_tuning/test_jobs.py b/tests/api_resources/fine_tuning/test_jobs.py index 204cc3b1f5..f4974ebbcd 100644 --- a/tests/api_resources/fine_tuning/test_jobs.py +++ b/tests/api_resources/fine_tuning/test_jobs.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/tests/api_resources/test_completions.py b/tests/api_resources/test_completions.py index 916cdd3cb6..691c4ff77f 100644 --- a/tests/api_resources/test_completions.py +++ b/tests/api_resources/test_completions.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/tests/api_resources/test_embeddings.py b/tests/api_resources/test_embeddings.py index 42599219f3..e75545b4e2 100644 --- a/tests/api_resources/test_embeddings.py +++ b/tests/api_resources/test_embeddings.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/tests/api_resources/test_files.py b/tests/api_resources/test_files.py index d1a17923a6..e5466e9eda 100644 --- a/tests/api_resources/test_files.py +++ b/tests/api_resources/test_files.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/tests/api_resources/test_images.py b/tests/api_resources/test_images.py index b6cb2572ab..2e31f3354a 100644 --- a/tests/api_resources/test_images.py +++ b/tests/api_resources/test_images.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/tests/api_resources/test_models.py b/tests/api_resources/test_models.py index d031d54f6a..71f8e5834b 100644 --- a/tests/api_resources/test_models.py +++ b/tests/api_resources/test_models.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/tests/api_resources/test_moderations.py b/tests/api_resources/test_moderations.py index 285e738c0e..94b9ecd31b 100644 --- a/tests/api_resources/test_moderations.py +++ b/tests/api_resources/test_moderations.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/tests/test_client.py b/tests/test_client.py index a6f936da67..dab1cb0efd 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations diff --git a/tests/test_module_client.py b/tests/test_module_client.py index 40b0bde10b..6de314856b 100644 --- a/tests/test_module_client.py +++ b/tests/test_module_client.py @@ -1,4 +1,4 @@ -# File generated from our OpenAPI spec by Stainless. +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations From 9fe13a7e360743d84566e016589e5b0ee0d80aae Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 20 Mar 2024 10:23:41 -0400 Subject: [PATCH 263/816] chore(internal): loosen input type for util function (#1250) --- src/openai/_models.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/openai/_models.py b/src/openai/_models.py index 166973538f..35a23a95cc 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -290,11 +290,15 @@ def is_basemodel_type(type_: type) -> TypeGuard[type[BaseModel] | type[GenericMo return issubclass(origin, BaseModel) or issubclass(origin, GenericModel) -def construct_type(*, value: object, type_: type) -> object: +def construct_type(*, value: object, type_: object) -> object: """Loose coercion to the expected type with construction of nested values. If the given value does not match the expected type then it is returned as-is. """ + # we allow `object` as the input type because otherwise, passing things like + # `Literal['value']` will be reported as a type error by type checkers + type_ = cast("type[object]", type_) + # unwrap `Annotated[T, ...]` -> `T` if is_annotated_type(type_): meta = get_args(type_)[1:] From 2b23eb538411f9578c5f9357f24fb37f5de8e84a Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 20 Mar 2024 16:02:18 -0400 Subject: [PATCH 264/816] docs(readme): consistent use of sentence case in headings (#1255) --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index befe927cea..80d0a42645 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ asyncio.run(main()) Functionality between the synchronous and asynchronous clients is otherwise identical. -## Streaming Responses +## Streaming responses We provide support for streaming responses using Server Side Events (SSE). @@ -281,7 +281,7 @@ completion = client.chat.completions.create( ) ``` -## File Uploads +## File uploads Request parameters that correspond to file uploads can be passed as `bytes`, a [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike) instance or a tuple of `(filename, contents, media type)`. From 73869eee98818e18fafd0374731116faf7681dc5 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 20 Mar 2024 23:26:40 -0400 Subject: [PATCH 265/816] docs(readme): document how to make undocumented requests (#1256) --- README.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/README.md b/README.md index 80d0a42645..6f446d82e1 100644 --- a/README.md +++ b/README.md @@ -487,6 +487,41 @@ with client.chat.completions.with_streaming_response.create( The context manager is required so that the response will reliably be closed. +### Making custom/undocumented requests + +This library is typed for convenient access the documented API. + +If you need to access undocumented endpoints, params, or response properties, the library can still be used. + +#### Undocumented endpoints + +To make requests to undocumented endpoints, you can make requests using `client.get`, `client.post`, and other +http verbs. Options on the client will be respected (such as retries) will be respected when making this +request. + +```py +import httpx + +response = client.post( + "/foo", + cast_to=httpx.Response, + body={"my_param": True}, +) + +print(response.headers.get("x-foo")) +``` + +#### Undocumented params + +If you want to explicitly send an extra param, you can do so with the `extra_query`, `extra_body`, and `extra_headers` request +options. + +#### Undocumented properties + +To access undocumented response properties, you can access the extra fields like `response.unknown_prop`. You +can also get all the extra fields on the Pydantic model as a dict with +[`response.model_extra`](https://docs.pydantic.dev/latest/api/base_model/#pydantic.BaseModel.model_extra). + ### Configuring the HTTP client You can directly override the [httpx client](https://www.python-httpx.org/api/#client) to customize it for your use case, including: From 046daf6ed4220f652c9fe7dac7a24be144e18864 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 21 Mar 2024 06:36:29 -0400 Subject: [PATCH 266/816] chore(internal): construct error properties instead of using the raw response (#1257) --- src/openai/_exceptions.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/openai/_exceptions.py b/src/openai/_exceptions.py index 350fd2584b..074752c8a1 100644 --- a/src/openai/_exceptions.py +++ b/src/openai/_exceptions.py @@ -8,6 +8,7 @@ import httpx from ._utils import is_dict +from ._models import construct_type __all__ = [ "BadRequestError", @@ -51,9 +52,9 @@ def __init__(self, message: str, request: httpx.Request, *, body: object | None) self.body = body if is_dict(body): - self.code = cast(Any, body.get("code")) - self.param = cast(Any, body.get("param")) - self.type = cast(Any, body.get("type")) + self.code = cast(Any, construct_type(type_=Optional[str], value=body.get("code"))) + self.param = cast(Any, construct_type(type_=Optional[str], value=body.get("param"))) + self.type = cast(Any, construct_type(type_=str, value=body.get("type"))) else: self.code = None self.param = None From bf09f42703161354f64965578c852b9843277e68 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 21 Mar 2024 13:36:22 -0400 Subject: [PATCH 267/816] chore(internal): formatting change (#1258) --- pyproject.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/pyproject.toml b/pyproject.toml index de412f3907..1fb077cc96 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -135,6 +135,7 @@ reportImplicitOverride = true reportImportCycles = false reportPrivateUsage = false + [tool.ruff] line-length = 120 output-format = "grouped" From c9ed0f542756f45127fb668a4f8afa272b018fd9 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 22 Mar 2024 06:31:42 -0400 Subject: [PATCH 268/816] docs(contributing): fix typo (#1264) --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7473159258..354d21b2d2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -121,5 +121,5 @@ You can release to package managers by using [the `Publish PyPI` GitHub action]( ### Publish manually -If you need to manually release a package, you can run the `bin/publish-pypi` script with an `PYPI_TOKEN` set on +If you need to manually release a package, you can run the `bin/publish-pypi` script with a `PYPI_TOKEN` set on the environment. From 93ed942f915c4acfc3e4e117840e946b531dff3b Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 25 Mar 2024 06:33:15 -0400 Subject: [PATCH 269/816] fix: revert regression with 3.7 support (#1269) --- src/openai/_models.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/openai/_models.py b/src/openai/_models.py index 35a23a95cc..77c755b135 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -538,12 +538,14 @@ class GenericModel(BaseGenericModel, BaseModel): if PYDANTIC_V2: + from pydantic import TypeAdapter as _TypeAdapter + + _CachedTypeAdapter = cast("TypeAdapter[object]", lru_cache(maxsize=None)(_TypeAdapter)) + if TYPE_CHECKING: from pydantic import TypeAdapter else: - from pydantic import TypeAdapter as _TypeAdapter - - TypeAdapter = lru_cache(_TypeAdapter) + TypeAdapter = _CachedTypeAdapter def _validate_non_model_type(*, type_: type[_T], value: object) -> _T: return TypeAdapter(type_).validate_python(value) From de7c0e2d9375d042a42e3db6c17e5af9a5701a99 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 25 Mar 2024 06:33:44 -0400 Subject: [PATCH 270/816] release: 1.14.3 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 22 ++++++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 25 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 19cc6edce7..d55a714ec5 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.14.2" + ".": "1.14.3" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 7497d6af56..913dece99e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,27 @@ # Changelog +## 1.14.3 (2024-03-25) + +Full Changelog: [v1.14.2...v1.14.3](https://github.com/openai/openai-python/compare/v1.14.2...v1.14.3) + +### Bug Fixes + +* revert regression with 3.7 support ([#1269](https://github.com/openai/openai-python/issues/1269)) ([37aed56](https://github.com/openai/openai-python/commit/37aed564143dc7281f1eaa6ab64ec5ca334cf25e)) + + +### Chores + +* **internal:** construct error properties instead of using the raw response ([#1257](https://github.com/openai/openai-python/issues/1257)) ([11dce5c](https://github.com/openai/openai-python/commit/11dce5c66395722b245f5d5461ce379ca7b939e4)) +* **internal:** formatting change ([#1258](https://github.com/openai/openai-python/issues/1258)) ([b907dd7](https://github.com/openai/openai-python/commit/b907dd7dcae895e4209559da061d0991a8d640a6)) +* **internal:** loosen input type for util function ([#1250](https://github.com/openai/openai-python/issues/1250)) ([fc8b4c3](https://github.com/openai/openai-python/commit/fc8b4c37dc91dfcc0535c19236092992171784a0)) + + +### Documentation + +* **contributing:** fix typo ([#1264](https://github.com/openai/openai-python/issues/1264)) ([835cb9b](https://github.com/openai/openai-python/commit/835cb9b2f92e2aa3329545b4677865dcd4fd00f0)) +* **readme:** consistent use of sentence case in headings ([#1255](https://github.com/openai/openai-python/issues/1255)) ([519f371](https://github.com/openai/openai-python/commit/519f371af779b5fa353292ff5a2d3332afe0987e)) +* **readme:** document how to make undocumented requests ([#1256](https://github.com/openai/openai-python/issues/1256)) ([5887858](https://github.com/openai/openai-python/commit/5887858a7b649dfde5b733ef01e5cffcf953b2a7)) + ## 1.14.2 (2024-03-19) Full Changelog: [v1.14.1...v1.14.2](https://github.com/openai/openai-python/compare/v1.14.1...v1.14.2) diff --git a/pyproject.toml b/pyproject.toml index 1fb077cc96..8e8ce06881 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.14.2" +version = "1.14.3" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index b8eb743acc..9163853b72 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.14.2" # x-release-please-version +__version__ = "1.14.3" # x-release-please-version From 1ac012d70beae5719c83c191fe2b6d620d6cf8f7 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 28 Mar 2024 11:24:20 +0000 Subject: [PATCH 271/816] chore(internal): bump dependencies (#1273) --- requirements-dev.lock | 4 ++-- requirements.lock | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/requirements-dev.lock b/requirements-dev.lock index 9d79557b3a..4461f65738 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -22,7 +22,7 @@ attrs==23.1.0 azure-core==1.30.1 # via azure-identity azure-identity==1.15.0 -black==24.2.0 +black==24.3.0 # via inline-snapshot certifi==2023.7.22 # via httpcore @@ -67,7 +67,7 @@ importlib-metadata==7.0.0 iniconfig==2.0.0 # via pytest inline-snapshot==0.7.0 -msal==1.27.0 +msal==1.28.0 # via azure-identity # via msal-extensions msal-extensions==1.1.0 diff --git a/requirements.lock b/requirements.lock index f3733bec9a..c933d6c90e 100644 --- a/requirements.lock +++ b/requirements.lock @@ -33,15 +33,15 @@ numpy==1.26.4 # via openai # via pandas # via pandas-stubs -pandas==2.2.0 +pandas==2.2.1 # via openai -pandas-stubs==2.2.0.240218 +pandas-stubs==2.2.1.240316 # via openai pydantic==2.4.2 # via openai pydantic-core==2.10.1 # via pydantic -python-dateutil==2.8.2 +python-dateutil==2.9.0.post0 # via pandas pytz==2024.1 # via pandas From 1e55d60e4aebbe043742025b1211f8f56ef1ba89 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 28 Mar 2024 15:31:53 +0000 Subject: [PATCH 272/816] feat(package): export default constants (#1275) --- src/openai/__init__.py | 4 ++++ src/openai/_base_client.py | 6 +++--- src/openai/_constants.py | 2 +- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/openai/__init__.py b/src/openai/__init__.py index 9585fde99b..cd05a749da 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -12,6 +12,7 @@ from ._models import BaseModel from ._version import __title__, __version__ from ._response import APIResponse as APIResponse, AsyncAPIResponse as AsyncAPIResponse +from ._constants import DEFAULT_TIMEOUT, DEFAULT_MAX_RETRIES, DEFAULT_CONNECTION_LIMITS from ._exceptions import ( APIError, OpenAIError, @@ -63,6 +64,9 @@ "AsyncOpenAI", "file_from_path", "BaseModel", + "DEFAULT_TIMEOUT", + "DEFAULT_MAX_RETRIES", + "DEFAULT_CONNECTION_LIMITS", ] from .lib import azure as _azure diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index f431128eef..7a8595c173 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -71,13 +71,13 @@ extract_response_type, ) from ._constants import ( - DEFAULT_LIMITS, DEFAULT_TIMEOUT, MAX_RETRY_DELAY, DEFAULT_MAX_RETRIES, INITIAL_RETRY_DELAY, RAW_RESPONSE_HEADER, OVERRIDE_CAST_TO_HEADER, + DEFAULT_CONNECTION_LIMITS, ) from ._streaming import Stream, SSEDecoder, AsyncStream, SSEBytesDecoder from ._exceptions import ( @@ -747,7 +747,7 @@ def __init__( if http_client is not None: raise ValueError("The `http_client` argument is mutually exclusive with `connection_pool_limits`") else: - limits = DEFAULT_LIMITS + limits = DEFAULT_CONNECTION_LIMITS if transport is not None: warnings.warn( @@ -1294,7 +1294,7 @@ def __init__( if http_client is not None: raise ValueError("The `http_client` argument is mutually exclusive with `connection_pool_limits`") else: - limits = DEFAULT_LIMITS + limits = DEFAULT_CONNECTION_LIMITS if transport is not None: warnings.warn( diff --git a/src/openai/_constants.py b/src/openai/_constants.py index b2e541f7b1..3f96aea3dd 100644 --- a/src/openai/_constants.py +++ b/src/openai/_constants.py @@ -8,7 +8,7 @@ # default timeout is 10 minutes DEFAULT_TIMEOUT = httpx.Timeout(timeout=600.0, connect=5.0) DEFAULT_MAX_RETRIES = 2 -DEFAULT_LIMITS = httpx.Limits(max_connections=100, max_keepalive_connections=20) +DEFAULT_CONNECTION_LIMITS = httpx.Limits(max_connections=100, max_keepalive_connections=20) INITIAL_RETRY_DELAY = 0.5 MAX_RETRY_DELAY = 8.0 From 31a7e9adbd90fa4ba76ceaa435276b38bdc1aca3 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 29 Mar 2024 14:09:18 +0000 Subject: [PATCH 273/816] fix(project): use absolute github links on PyPi (#1280) --- pyproject.toml | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 8e8ce06881..746896e80d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -2,7 +2,7 @@ name = "openai" version = "1.14.3" description = "The official Python library for the openai API" -readme = "README.md" +dynamic = ["readme"] license = "Apache-2.0" authors = [ { name = "OpenAI", email = "support@openai.com" }, @@ -93,7 +93,7 @@ typecheck = { chain = [ "typecheck:mypy" = "mypy ." [build-system] -requires = ["hatchling"] +requires = ["hatchling", "hatch-fancy-pypi-readme"] build-backend = "hatchling.build" [tool.hatch.build] @@ -104,6 +104,17 @@ include = [ [tool.hatch.build.targets.wheel] packages = ["src/openai"] +[tool.hatch.metadata.hooks.fancy-pypi-readme] +content-type = "text/markdown" + +[[tool.hatch.metadata.hooks.fancy-pypi-readme.fragments]] +path = "README.md" + +[[tool.hatch.metadata.hooks.fancy-pypi-readme.substitutions]] +# replace relative links with absolute links +pattern = '\[(.+?)\]\(((?!https?://)\S+?)\)' +replacement = '[\1](https://github.com/openai/openai-python/tree/main/\g<2>)' + [tool.black] line-length = 120 target-version = ["py37"] From 7828119bc6d17ababeaf28aadb0799e5c492b182 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 29 Mar 2024 17:38:48 +0000 Subject: [PATCH 274/816] feat(client): increase default HTTP max_connections to 1000 and max_keepalive_connections to 100 (#1281) --- src/openai/_constants.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/openai/_constants.py b/src/openai/_constants.py index 3f96aea3dd..3f82bed037 100644 --- a/src/openai/_constants.py +++ b/src/openai/_constants.py @@ -8,7 +8,7 @@ # default timeout is 10 minutes DEFAULT_TIMEOUT = httpx.Timeout(timeout=600.0, connect=5.0) DEFAULT_MAX_RETRIES = 2 -DEFAULT_CONNECTION_LIMITS = httpx.Limits(max_connections=100, max_keepalive_connections=20) +DEFAULT_CONNECTION_LIMITS = httpx.Limits(max_connections=1000, max_keepalive_connections=100) INITIAL_RETRY_DELAY = 0.5 MAX_RETRY_DELAY = 8.0 From 27a4626ab39fb8d8e5b0aa1698e9cadec1b0bc85 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 29 Mar 2024 21:08:28 +0000 Subject: [PATCH 275/816] feat(api): adding temperature parameter (#1282) --- .../beta/threads/messages/messages.py | 22 +++++++--- .../resources/beta/threads/runs/runs.py | 42 +++++++++++++++++++ src/openai/resources/beta/threads/threads.py | 42 +++++++++++++++++++ .../beta/thread_create_and_run_params.py | 16 +++++-- src/openai/types/beta/thread_create_params.py | 9 ++-- src/openai/types/beta/threads/message.py | 6 +-- .../beta/threads/message_create_params.py | 9 ++-- src/openai/types/beta/threads/run.py | 3 ++ .../types/beta/threads/run_create_params.py | 7 ++++ tests/api_resources/beta/test_threads.py | 4 ++ tests/api_resources/beta/threads/test_runs.py | 4 ++ 11 files changed, 146 insertions(+), 18 deletions(-) diff --git a/src/openai/resources/beta/threads/messages/messages.py b/src/openai/resources/beta/threads/messages/messages.py index 21e8bca5b8..1c008a7cc4 100644 --- a/src/openai/resources/beta/threads/messages/messages.py +++ b/src/openai/resources/beta/threads/messages/messages.py @@ -52,7 +52,7 @@ def create( thread_id: str, *, content: str, - role: Literal["user"], + role: Literal["user", "assistant"], file_ids: List[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -68,8 +68,13 @@ def create( Args: content: The content of the message. - role: The role of the entity that is creating the message. Currently only `user` is - supported. + role: + The role of the entity that is creating the message. Allowed values include: + + - `user`: Indicates the message is sent by an actual user and should be used in + most cases to represent user-generated messages. + - `assistant`: Indicates the message is generated by the assistant. Use this + value to insert messages from the assistant into the conversation. file_ids: A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that the message should use. There can be a maximum of 10 files attached to a @@ -276,7 +281,7 @@ async def create( thread_id: str, *, content: str, - role: Literal["user"], + role: Literal["user", "assistant"], file_ids: List[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -292,8 +297,13 @@ async def create( Args: content: The content of the message. - role: The role of the entity that is creating the message. Currently only `user` is - supported. + role: + The role of the entity that is creating the message. Allowed values include: + + - `user`: Indicates the message is sent by an actual user and should be used in + most cases to represent user-generated messages. + - `assistant`: Indicates the message is generated by the assistant. Use this + value to insert messages from the assistant into the conversation. file_ids: A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that the message should use. There can be a maximum of 10 files attached to a diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index afa447612c..ab39a96a8d 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -76,6 +76,7 @@ def create( metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -114,6 +115,10 @@ def create( events, terminating when the Run enters a terminal state with a `data: [DONE]` message. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. @@ -138,6 +143,7 @@ def create( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -176,6 +182,10 @@ def create( model associated with the assistant. If not, the model associated with the assistant will be used. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. @@ -200,6 +210,7 @@ def create( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -238,6 +249,10 @@ def create( model associated with the assistant. If not, the model associated with the assistant will be used. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. @@ -262,6 +277,7 @@ def create( metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -283,6 +299,7 @@ def create( "metadata": metadata, "model": model, "stream": stream, + "temperature": temperature, "tools": tools, }, run_create_params.RunCreateParams, @@ -489,6 +506,7 @@ def create_and_stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, thread_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -510,6 +528,7 @@ def create_and_stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, thread_id: str, event_handler: AssistantEventHandlerT, @@ -531,6 +550,7 @@ def create_and_stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, thread_id: str, event_handler: AssistantEventHandlerT | None = None, @@ -561,6 +581,7 @@ def create_and_stream( "instructions": instructions, "metadata": metadata, "model": model, + "temperature": temperature, "stream": True, "tools": tools, }, @@ -841,6 +862,7 @@ async def create( metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -879,6 +901,10 @@ async def create( events, terminating when the Run enters a terminal state with a `data: [DONE]` message. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. @@ -903,6 +929,7 @@ async def create( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -941,6 +968,10 @@ async def create( model associated with the assistant. If not, the model associated with the assistant will be used. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. @@ -965,6 +996,7 @@ async def create( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -1003,6 +1035,10 @@ async def create( model associated with the assistant. If not, the model associated with the assistant will be used. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. @@ -1027,6 +1063,7 @@ async def create( metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -1048,6 +1085,7 @@ async def create( "metadata": metadata, "model": model, "stream": stream, + "temperature": temperature, "tools": tools, }, run_create_params.RunCreateParams, @@ -1254,6 +1292,7 @@ def create_and_stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, thread_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -1275,6 +1314,7 @@ def create_and_stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, thread_id: str, event_handler: AsyncAssistantEventHandlerT, @@ -1296,6 +1336,7 @@ def create_and_stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, thread_id: str, event_handler: AsyncAssistantEventHandlerT | None = None, @@ -1328,6 +1369,7 @@ def create_and_stream( "instructions": instructions, "metadata": metadata, "model": model, + "temperature": temperature, "stream": True, "tools": tools, }, diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index bcb0da8a62..c2ad6aca5f 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -244,6 +244,7 @@ def create_and_run( metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -278,6 +279,10 @@ def create_and_run( events, terminating when the Run enters a terminal state with a `data: [DONE]` message. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + thread: If no thread is provided, an empty thread will be created. tools: Override the tools the assistant can use for this run. This is useful for @@ -302,6 +307,7 @@ def create_and_run( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -336,6 +342,10 @@ def create_and_run( model associated with the assistant. If not, the model associated with the assistant will be used. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + thread: If no thread is provided, an empty thread will be created. tools: Override the tools the assistant can use for this run. This is useful for @@ -360,6 +370,7 @@ def create_and_run( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -394,6 +405,10 @@ def create_and_run( model associated with the assistant. If not, the model associated with the assistant will be used. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + thread: If no thread is provided, an empty thread will be created. tools: Override the tools the assistant can use for this run. This is useful for @@ -418,6 +433,7 @@ def create_and_run( metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -437,6 +453,7 @@ def create_and_run( "metadata": metadata, "model": model, "stream": stream, + "temperature": temperature, "thread": thread, "tools": tools, }, @@ -458,6 +475,7 @@ def create_and_run_stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -478,6 +496,7 @@ def create_and_run_stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, event_handler: AssistantEventHandlerT, @@ -498,6 +517,7 @@ def create_and_run_stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, event_handler: AssistantEventHandlerT | None = None, @@ -524,6 +544,7 @@ def create_and_run_stream( "instructions": instructions, "metadata": metadata, "model": model, + "temperature": temperature, "stream": True, "thread": thread, "tools": tools, @@ -723,6 +744,7 @@ async def create_and_run( metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -757,6 +779,10 @@ async def create_and_run( events, terminating when the Run enters a terminal state with a `data: [DONE]` message. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + thread: If no thread is provided, an empty thread will be created. tools: Override the tools the assistant can use for this run. This is useful for @@ -781,6 +807,7 @@ async def create_and_run( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -815,6 +842,10 @@ async def create_and_run( model associated with the assistant. If not, the model associated with the assistant will be used. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + thread: If no thread is provided, an empty thread will be created. tools: Override the tools the assistant can use for this run. This is useful for @@ -839,6 +870,7 @@ async def create_and_run( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -873,6 +905,10 @@ async def create_and_run( model associated with the assistant. If not, the model associated with the assistant will be used. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + thread: If no thread is provided, an empty thread will be created. tools: Override the tools the assistant can use for this run. This is useful for @@ -897,6 +933,7 @@ async def create_and_run( metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -916,6 +953,7 @@ async def create_and_run( "metadata": metadata, "model": model, "stream": stream, + "temperature": temperature, "thread": thread, "tools": tools, }, @@ -937,6 +975,7 @@ def create_and_run_stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -957,6 +996,7 @@ def create_and_run_stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, event_handler: AsyncAssistantEventHandlerT, @@ -977,6 +1017,7 @@ def create_and_run_stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, event_handler: AsyncAssistantEventHandlerT | None = None, @@ -1005,6 +1046,7 @@ def create_and_run_stream( "instructions": instructions, "metadata": metadata, "model": model, + "temperature": temperature, "stream": True, "thread": thread, "tools": tools, diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index 9c16e1133f..d4266fc48c 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -49,6 +49,13 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): assistant will be used. """ + temperature: Optional[float] + """What sampling temperature to use, between 0 and 2. + + Higher values like 0.8 will make the output more random, while lower values like + 0.2 will make it more focused and deterministic. + """ + thread: Thread """If no thread is provided, an empty thread will be created.""" @@ -63,10 +70,13 @@ class ThreadMessage(TypedDict, total=False): content: Required[str] """The content of the message.""" - role: Required[Literal["user"]] - """The role of the entity that is creating the message. + role: Required[Literal["user", "assistant"]] + """The role of the entity that is creating the message. Allowed values include: - Currently only `user` is supported. + - `user`: Indicates the message is sent by an actual user and should be used in + most cases to represent user-generated messages. + - `assistant`: Indicates the message is generated by the assistant. Use this + value to insert messages from the assistant into the conversation. """ file_ids: List[str] diff --git a/src/openai/types/beta/thread_create_params.py b/src/openai/types/beta/thread_create_params.py index b3dda503ff..1b382186aa 100644 --- a/src/openai/types/beta/thread_create_params.py +++ b/src/openai/types/beta/thread_create_params.py @@ -28,10 +28,13 @@ class Message(TypedDict, total=False): content: Required[str] """The content of the message.""" - role: Required[Literal["user"]] - """The role of the entity that is creating the message. + role: Required[Literal["user", "assistant"]] + """The role of the entity that is creating the message. Allowed values include: - Currently only `user` is supported. + - `user`: Indicates the message is sent by an actual user and should be used in + most cases to represent user-generated messages. + - `assistant`: Indicates the message is generated by the assistant. Use this + value to insert messages from the assistant into the conversation. """ file_ids: List[str] diff --git a/src/openai/types/beta/threads/message.py b/src/openai/types/beta/threads/message.py index 027e2bfa15..bde0263975 100644 --- a/src/openai/types/beta/threads/message.py +++ b/src/openai/types/beta/threads/message.py @@ -63,9 +63,9 @@ class Message(BaseModel): run_id: Optional[str] = None """ - If applicable, the ID of the - [run](https://platform.openai.com/docs/api-reference/runs) associated with the - authoring of this message. + The ID of the [run](https://platform.openai.com/docs/api-reference/runs) + associated with the creation of this message. Value is `null` when messages are + created manually using the create message or create thread endpoints. """ status: Literal["in_progress", "incomplete", "completed"] diff --git a/src/openai/types/beta/threads/message_create_params.py b/src/openai/types/beta/threads/message_create_params.py index b2f27deb3e..9b9467ef4d 100644 --- a/src/openai/types/beta/threads/message_create_params.py +++ b/src/openai/types/beta/threads/message_create_params.py @@ -12,10 +12,13 @@ class MessageCreateParams(TypedDict, total=False): content: Required[str] """The content of the message.""" - role: Required[Literal["user"]] - """The role of the entity that is creating the message. + role: Required[Literal["user", "assistant"]] + """The role of the entity that is creating the message. Allowed values include: - Currently only `user` is supported. + - `user`: Indicates the message is sent by an actual user and should be used in + most cases to represent user-generated messages. + - `assistant`: Indicates the message is generated by the assistant. Use this + value to insert messages from the assistant into the conversation. """ file_ids: List[str] diff --git a/src/openai/types/beta/threads/run.py b/src/openai/types/beta/threads/run.py index d2cac4c279..3ab276245f 100644 --- a/src/openai/types/beta/threads/run.py +++ b/src/openai/types/beta/threads/run.py @@ -139,3 +139,6 @@ class Run(BaseModel): This value will be `null` if the run is not in a terminal state (i.e. `in_progress`, `queued`, etc.). """ + + temperature: Optional[float] = None + """The sampling temperature used for this run. If not set, defaults to 1.""" diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index 89dff389a9..ac185973a5 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -48,6 +48,13 @@ class RunCreateParamsBase(TypedDict, total=False): assistant will be used. """ + temperature: Optional[float] + """What sampling temperature to use, between 0 and 2. + + Higher values like 0.8 will make the output more random, while lower values like + 0.2 will make it more focused and deterministic. + """ + tools: Optional[Iterable[AssistantToolParam]] """Override the tools the assistant can use for this run. diff --git a/tests/api_resources/beta/test_threads.py b/tests/api_resources/beta/test_threads.py index 57dda57d16..fd3f7c5102 100644 --- a/tests/api_resources/beta/test_threads.py +++ b/tests/api_resources/beta/test_threads.py @@ -210,6 +210,7 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) metadata={}, model="string", stream=False, + temperature=1, thread={ "messages": [ { @@ -277,6 +278,7 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) instructions="string", metadata={}, model="string", + temperature=1, thread={ "messages": [ { @@ -522,6 +524,7 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie metadata={}, model="string", stream=False, + temperature=1, thread={ "messages": [ { @@ -589,6 +592,7 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie instructions="string", metadata={}, model="string", + temperature=1, thread={ "messages": [ { diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index 3a9719b420..aabe2c7fc9 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -38,6 +38,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: metadata={}, model="string", stream=False, + temperature=1, tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], ) assert_matches_type(Run, run, path=["response"]) @@ -95,6 +96,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: instructions="string", metadata={}, model="string", + temperature=1, tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], ) run_stream.response.close() @@ -492,6 +494,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn metadata={}, model="string", stream=False, + temperature=1, tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], ) assert_matches_type(Run, run, path=["response"]) @@ -549,6 +552,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn instructions="string", metadata={}, model="string", + temperature=1, tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], ) await run_stream.response.aclose() From 802819c864102e009221b2ef9089a70db0d8f57c Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Sat, 30 Mar 2024 20:44:48 +0000 Subject: [PATCH 276/816] docs(readme): change undocumented params wording (#1284) --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6f446d82e1..7f053e5429 100644 --- a/README.md +++ b/README.md @@ -511,12 +511,12 @@ response = client.post( print(response.headers.get("x-foo")) ``` -#### Undocumented params +#### Undocumented request params If you want to explicitly send an extra param, you can do so with the `extra_query`, `extra_body`, and `extra_headers` request options. -#### Undocumented properties +#### Undocumented response properties To access undocumented response properties, you can access the extra fields like `response.unknown_prop`. You can also get all the extra fields on the Pydantic model as a dict with From 0470d1baa8ef1f64d0116f3f47683d5bf622cbef Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Sun, 31 Mar 2024 06:04:07 +0100 Subject: [PATCH 277/816] release: 1.15.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 25 +++++++++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 28 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index d55a714ec5..7ccfe12c9e 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.14.3" + ".": "1.15.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 913dece99e..180bbf2a28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,30 @@ # Changelog +## 1.15.0 (2024-03-31) + +Full Changelog: [v1.14.3...v1.15.0](https://github.com/openai/openai-python/compare/v1.14.3...v1.15.0) + +### Features + +* **api:** adding temperature parameter ([#1282](https://github.com/openai/openai-python/issues/1282)) ([0e68fd3](https://github.com/openai/openai-python/commit/0e68fd3690155785d1fb0ee9a8604f51e6701b1d)) +* **client:** increase default HTTP max_connections to 1000 and max_keepalive_connections to 100 ([#1281](https://github.com/openai/openai-python/issues/1281)) ([340d139](https://github.com/openai/openai-python/commit/340d1391e3071a265ed12c0a8d70d4d73a860bd8)) +* **package:** export default constants ([#1275](https://github.com/openai/openai-python/issues/1275)) ([fdc126e](https://github.com/openai/openai-python/commit/fdc126e428320f1bed5eabd3eed229f08ab9effa)) + + +### Bug Fixes + +* **project:** use absolute github links on PyPi ([#1280](https://github.com/openai/openai-python/issues/1280)) ([94cd528](https://github.com/openai/openai-python/commit/94cd52837650e5b7e115119d69e6b1c7ba1f6bf1)) + + +### Chores + +* **internal:** bump dependencies ([#1273](https://github.com/openai/openai-python/issues/1273)) ([18dcd65](https://github.com/openai/openai-python/commit/18dcd654d9f54628b5fe21a499d1fef500e15f7f)) + + +### Documentation + +* **readme:** change undocumented params wording ([#1284](https://github.com/openai/openai-python/issues/1284)) ([7498ef1](https://github.com/openai/openai-python/commit/7498ef1e9568200086ba3efb99ea100feb05e3f0)) + ## 1.14.3 (2024-03-25) Full Changelog: [v1.14.2...v1.14.3](https://github.com/openai/openai-python/compare/v1.14.2...v1.14.3) diff --git a/pyproject.toml b/pyproject.toml index 746896e80d..beb31f24a1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.14.3" +version = "1.15.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 9163853b72..6865a9f7bd 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.14.3" # x-release-please-version +__version__ = "1.15.0" # x-release-please-version From 07079085ca769cb679033a7c91cc0d160a624a58 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 1 Apr 2024 10:47:23 +0100 Subject: [PATCH 278/816] chore(client): validate that max_retries is not None (#1286) --- src/openai/_base_client.py | 5 +++++ tests/test_client.py | 10 ++++++++++ 2 files changed, 15 insertions(+) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 7a8595c173..502ed7c7ae 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -361,6 +361,11 @@ def __init__( self._strict_response_validation = _strict_response_validation self._idempotency_header = None + if max_retries is None: # pyright: ignore[reportUnnecessaryComparison] + raise TypeError( + "max_retries cannot be None. If you want to disable retries, pass `0`; if you want unlimited retries, pass `math.inf` or a very high number; if you want the default behavior, pass `openai.DEFAULT_MAX_RETRIES`" + ) + def _enforce_trailing_slash(self, url: URL) -> URL: if url.raw_path.endswith(b"/"): return url diff --git a/tests/test_client.py b/tests/test_client.py index dab1cb0efd..ba85fd9d5f 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -646,6 +646,10 @@ class Model(BaseModel): assert isinstance(exc.value.__cause__, ValidationError) + def test_client_max_retries_validation(self) -> None: + with pytest.raises(TypeError, match=r"max_retries cannot be None"): + OpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True, max_retries=cast(Any, None)) + @pytest.mark.respx(base_url=base_url) def test_default_stream_cls(self, respx_mock: MockRouter) -> None: class Model(BaseModel): @@ -1368,6 +1372,12 @@ class Model(BaseModel): assert isinstance(exc.value.__cause__, ValidationError) + async def test_client_max_retries_validation(self) -> None: + with pytest.raises(TypeError, match=r"max_retries cannot be None"): + AsyncOpenAI( + base_url=base_url, api_key=api_key, _strict_response_validation=True, max_retries=cast(Any, None) + ) + @pytest.mark.respx(base_url=base_url) @pytest.mark.asyncio async def test_default_stream_cls(self, respx_mock: MockRouter) -> None: From 8efca3a34a0d0527523bb9f50ab7b5bd8d7c9d0c Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 1 Apr 2024 22:52:54 +0200 Subject: [PATCH 279/816] feat(api): add support for filtering messages by run_id (#1288) --- src/openai/resources/beta/threads/messages/messages.py | 8 ++++++++ src/openai/types/beta/threads/message_list_params.py | 3 +++ tests/api_resources/beta/threads/test_messages.py | 2 ++ 3 files changed, 13 insertions(+) diff --git a/src/openai/resources/beta/threads/messages/messages.py b/src/openai/resources/beta/threads/messages/messages.py index 1c008a7cc4..bbce3e99e4 100644 --- a/src/openai/resources/beta/threads/messages/messages.py +++ b/src/openai/resources/beta/threads/messages/messages.py @@ -203,6 +203,7 @@ def list( before: str | NotGiven = NOT_GIVEN, limit: int | NotGiven = NOT_GIVEN, order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + run_id: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -230,6 +231,8 @@ def list( order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. + run_id: Filter messages by the run ID that generated them. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -255,6 +258,7 @@ def list( "before": before, "limit": limit, "order": order, + "run_id": run_id, }, message_list_params.MessageListParams, ), @@ -432,6 +436,7 @@ def list( before: str | NotGiven = NOT_GIVEN, limit: int | NotGiven = NOT_GIVEN, order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + run_id: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -459,6 +464,8 @@ def list( order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. + run_id: Filter messages by the run ID that generated them. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -484,6 +491,7 @@ def list( "before": before, "limit": limit, "order": order, + "run_id": run_id, }, message_list_params.MessageListParams, ), diff --git a/src/openai/types/beta/threads/message_list_params.py b/src/openai/types/beta/threads/message_list_params.py index 8b139caa93..18c2442fb5 100644 --- a/src/openai/types/beta/threads/message_list_params.py +++ b/src/openai/types/beta/threads/message_list_params.py @@ -37,3 +37,6 @@ class MessageListParams(TypedDict, total=False): `asc` for ascending order and `desc` for descending order. """ + + run_id: str + """Filter messages by the run ID that generated them.""" diff --git a/tests/api_resources/beta/threads/test_messages.py b/tests/api_resources/beta/threads/test_messages.py index c708c94068..22198ccbc5 100644 --- a/tests/api_resources/beta/threads/test_messages.py +++ b/tests/api_resources/beta/threads/test_messages.py @@ -195,6 +195,7 @@ def test_method_list_with_all_params(self, client: OpenAI) -> None: before="string", limit=0, order="asc", + run_id="string", ) assert_matches_type(SyncCursorPage[Message], message, path=["response"]) @@ -410,6 +411,7 @@ async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> N before="string", limit=0, order="asc", + run_id="string", ) assert_matches_type(AsyncCursorPage[Message], message, path=["response"]) From 595f3b366a83138564ed19596bc84b50a59a72a8 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 2 Apr 2024 00:39:26 +0200 Subject: [PATCH 280/816] feat(api): run polling helpers (#1289) refactor: rename createAndStream to stream --- README.md | 20 +- api.md | 5 + examples/assistant.py | 27 +- examples/assistant_stream_helpers.py | 2 +- helpers.md | 10 +- .../resources/beta/threads/runs/runs.py | 495 +++++++++++++++++- src/openai/resources/beta/threads/threads.py | 80 +++ tests/api_resources/beta/threads/test_runs.py | 2 + 8 files changed, 610 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 7f053e5429..5264026dc9 100644 --- a/README.md +++ b/README.md @@ -51,12 +51,30 @@ we recommend using [python-dotenv](https://pypi.org/project/python-dotenv/) to add `OPENAI_API_KEY="My API Key"` to your `.env` file so that your API Key is not stored in source control. +### Polling Helpers + +When interacting with the API some actions such as starting a Run may take time to complete. The SDK includes +helper functions which will poll the status until it reaches a terminal state and then return the resulting object. +If an API method results in an action which could benefit from polling there will be a corresponding version of the +method ending in '\_and_poll'. + +For instance to create a Run and poll until it reaches a terminal state you can run: + +```python +run = client.beta.threads.runs.create_and_poll( + thread_id=thread.id, + assistant_id=assistant.id, +) +``` + +More information on the lifecycle of a Run can be found in the [Run Lifecycle Documentation](https://platform.openai.com/docs/assistants/how-it-works/run-lifecycle) + ### Streaming Helpers The SDK also includes helpers to process streams and handle the incoming events. ```python -with client.beta.threads.runs.create_and_stream( +with client.beta.threads.runs.stream( thread_id=thread.id, assistant_id=assistant.id, instructions="Please address the user as Jane Doe. The user has a premium account.", diff --git a/api.md b/api.md index 29392cff13..dbc95cd0b4 100644 --- a/api.md +++ b/api.md @@ -230,6 +230,7 @@ Methods: - client.beta.threads.update(thread_id, \*\*params) -> Thread - client.beta.threads.delete(thread_id) -> ThreadDeleted - client.beta.threads.create_and_run(\*\*params) -> Run +- client.beta.threads.create_and_run_poll(\*args) -> Run - client.beta.threads.create_and_run_stream(\*args) -> AssistantStreamManager[AssistantEventHandler] | AssistantStreamManager[AssistantEventHandlerT] ### Runs @@ -248,7 +249,11 @@ Methods: - client.beta.threads.runs.list(thread_id, \*\*params) -> SyncCursorPage[Run] - client.beta.threads.runs.cancel(run_id, \*, thread_id) -> Run - client.beta.threads.runs.submit_tool_outputs(run_id, \*, thread_id, \*\*params) -> Run +- client.beta.threads.runs.create_and_poll(\*args) -> Run - client.beta.threads.runs.create_and_stream(\*args) -> AssistantStreamManager[AssistantEventHandler] | AssistantStreamManager[AssistantEventHandlerT] +- client.beta.threads.runs.poll(\*args) -> Run +- client.beta.threads.runs.stream(\*args) -> AssistantStreamManager[AssistantEventHandler] | AssistantStreamManager[AssistantEventHandlerT] +- client.beta.threads.runs.submit_tool_outputs_and_poll(\*args) -> Run - client.beta.threads.runs.submit_tool_outputs_stream(\*args) -> AssistantStreamManager[AssistantEventHandler] | AssistantStreamManager[AssistantEventHandlerT] #### Steps diff --git a/examples/assistant.py b/examples/assistant.py index c5fbb82a3a..0631494ecc 100644 --- a/examples/assistant.py +++ b/examples/assistant.py @@ -1,4 +1,3 @@ -import time import openai @@ -20,28 +19,20 @@ content="I need to solve the equation `3x + 11 = 14`. Can you help me?", ) -run = client.beta.threads.runs.create( +run = client.beta.threads.runs.create_and_poll( thread_id=thread.id, assistant_id=assistant.id, instructions="Please address the user as Jane Doe. The user has a premium account.", ) -print("checking assistant status. ") -while True: - run = client.beta.threads.runs.retrieve(thread_id=thread.id, run_id=run.id) +print("Run completed with status: " + run.status) - if run.status == "completed": - print("done!") - messages = client.beta.threads.messages.list(thread_id=thread.id) +if run.status == "completed": + messages = client.beta.threads.messages.list(thread_id=thread.id) - print("messages: ") - for message in messages: - assert message.content[0].type == "text" - print({"role": message.role, "message": message.content[0].text.value}) + print("messages: ") + for message in messages: + assert message.content[0].type == "text" + print({"role": message.role, "message": message.content[0].text.value}) - client.beta.assistants.delete(assistant.id) - - break - else: - print("in progress...") - time.sleep(5) + client.beta.assistants.delete(assistant.id) diff --git a/examples/assistant_stream_helpers.py b/examples/assistant_stream_helpers.py index 6c2aae0b46..7baec77c72 100644 --- a/examples/assistant_stream_helpers.py +++ b/examples/assistant_stream_helpers.py @@ -63,7 +63,7 @@ def main() -> None: ) print(f"Question: {question}\n") - with client.beta.threads.runs.create_and_stream( + with client.beta.threads.runs.stream( thread_id=thread.id, assistant_id=assistant.id, instructions="Please address the user as Jane Doe. The user has a premium account.", diff --git a/helpers.md b/helpers.md index fed20ee81c..4271cd9ede 100644 --- a/helpers.md +++ b/helpers.md @@ -46,11 +46,11 @@ class EventHandler(AssistantEventHandler): if output.type == "logs": print(f"\n{output.logs}", flush=True) -# Then, we use the `create_and_stream` SDK helper +# Then, we use the `stream` SDK helper # with the `EventHandler` class to create the Run # and stream the response. -with client.beta.threads.runs.create_and_stream( +with client.beta.threads.runs.stream( thread_id="thread_id", assistant_id="assistant_id", event_handler=EventHandler(), @@ -63,7 +63,7 @@ with client.beta.threads.runs.create_and_stream( You can also iterate over all the streamed events. ```python -with client.beta.threads.runs.create_and_stream( +with client.beta.threads.runs.stream( thread_id=thread.id, assistant_id=assistant.id ) as stream: @@ -78,7 +78,7 @@ with client.beta.threads.runs.create_and_stream( You can also iterate over just the text deltas received ```python -with client.beta.threads.runs.create_and_stream( +with client.beta.threads.runs.stream( thread_id=thread.id, assistant_id=assistant.id ) as stream: @@ -91,7 +91,7 @@ with client.beta.threads.runs.create_and_stream( There are three helper methods for creating streams: ```python -client.beta.threads.runs.create_and_stream() +client.beta.threads.runs.stream() ``` This method can be used to start and stream the response to an existing run with an associated thread diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index ab39a96a8d..4529c65025 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -2,6 +2,8 @@ from __future__ import annotations +import time +import typing_extensions from typing import Iterable, Optional, overload from functools import partial from typing_extensions import Literal @@ -19,6 +21,7 @@ ) from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import ( + is_given, required_args, maybe_transform, async_maybe_transform, @@ -497,7 +500,58 @@ def cancel( cast_to=Run, ) + def create_and_poll( + self, + *, + assistant_id: str, + additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + poll_interval_ms: int | NotGiven = NOT_GIVEN, + thread_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Run: + """ + A helper to create a run an poll for a terminal state. More information on Run + lifecycles can be found here: + https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + """ + run = self.create( + thread_id=thread_id, + assistant_id=assistant_id, + additional_instructions=additional_instructions, + instructions=instructions, + metadata=metadata, + model=model, + temperature=temperature, + # We assume we are not streaming when polling + stream=False, + tools=tools, + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + ) + return self.poll( + run.id, + thread_id=thread_id, + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + poll_interval_ms=poll_interval_ms, + timeout=timeout, + ) + @overload + @typing_extensions.deprecated("use `stream` instead") def create_and_stream( self, *, @@ -520,6 +574,7 @@ def create_and_stream( ... @overload + @typing_extensions.deprecated("use `stream` instead") def create_and_stream( self, *, @@ -542,6 +597,7 @@ def create_and_stream( """Create a Run stream""" ... + @typing_extensions.deprecated("use `stream` instead") def create_and_stream( self, *, @@ -596,6 +652,150 @@ def create_and_stream( ) return AssistantStreamManager(make_request, event_handler=event_handler or AssistantEventHandler()) + def poll( + self, + run_id: str, + thread_id: str, + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + poll_interval_ms: int | NotGiven = NOT_GIVEN, + ) -> Run: + """ + A helper to poll a run status until it reaches a terminal state. More + information on Run lifecycles can be found here: + https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + """ + extra_headers = {"X-Stainless-Poll-Helper": "true", **(extra_headers or {})} + + if is_given(poll_interval_ms): + extra_headers["X-Stainless-Custom-Poll-Interval"] = str(poll_interval_ms) + + terminal_states = {"requires_action", "cancelled", "completed", "failed", "expired"} + while True: + response = self.with_raw_response.retrieve( + thread_id=thread_id, + run_id=run_id, + extra_headers=extra_headers, + extra_body=extra_body, + extra_query=extra_query, + timeout=timeout, + ) + + run = response.parse() + # Return if we reached a terminal state + if run.status in terminal_states: + return run + + if not is_given(poll_interval_ms): + from_header = response.headers.get("openai-poll-after-ms") + if from_header is not None: + poll_interval_ms = int(from_header) + else: + poll_interval_ms = 1000 + + time.sleep(poll_interval_ms / 1000) + + @overload + def stream( + self, + *, + assistant_id: str, + additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + thread_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AssistantStreamManager[AssistantEventHandler]: + """Create a Run stream""" + ... + + @overload + def stream( + self, + *, + assistant_id: str, + additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + thread_id: str, + event_handler: AssistantEventHandlerT, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AssistantStreamManager[AssistantEventHandlerT]: + """Create a Run stream""" + ... + + def stream( + self, + *, + assistant_id: str, + additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + thread_id: str, + event_handler: AssistantEventHandlerT | None = None, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AssistantStreamManager[AssistantEventHandler] | AssistantStreamManager[AssistantEventHandlerT]: + """Create a Run stream""" + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + + extra_headers = { + "OpenAI-Beta": "assistants=v1", + "X-Stainless-Stream-Helper": "threads.runs.create_and_stream", + "X-Stainless-Custom-Event-Handler": "true" if event_handler else "false", + **(extra_headers or {}), + } + make_request = partial( + self._post, + f"/threads/{thread_id}/runs", + body=maybe_transform( + { + "assistant_id": assistant_id, + "additional_instructions": additional_instructions, + "instructions": instructions, + "metadata": metadata, + "model": model, + "temperature": temperature, + "stream": True, + "tools": tools, + }, + run_create_params.RunCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Run, + stream=True, + stream_cls=Stream[AssistantStreamEvent], + ) + return AssistantStreamManager(make_request, event_handler=event_handler or AssistantEventHandler()) + @overload def submit_tool_outputs( self, @@ -747,6 +947,45 @@ def submit_tool_outputs( stream_cls=Stream[AssistantStreamEvent], ) + def submit_tool_outputs_and_poll( + self, + *, + tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], + run_id: str, + thread_id: str, + poll_interval_ms: int | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Run: + """ + A helper to submit a tool output to a run and poll for a terminal run state. + More information on Run lifecycles can be found here: + https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + """ + run = self.submit_tool_outputs( + run_id=run_id, + thread_id=thread_id, + tool_outputs=tool_outputs, + stream=False, + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + ) + return self.poll( + run_id=run.id, + thread_id=thread_id, + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + poll_interval_ms=poll_interval_ms, + ) + @overload def submit_tool_outputs_stream( self, @@ -763,7 +1002,8 @@ def submit_tool_outputs_stream( ) -> AssistantStreamManager[AssistantEventHandler]: """ Submit the tool outputs from a previous run and stream the run to a terminal - state. + state. More information on Run lifecycles can be found here: + https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps """ ... @@ -784,7 +1024,8 @@ def submit_tool_outputs_stream( ) -> AssistantStreamManager[AssistantEventHandlerT]: """ Submit the tool outputs from a previous run and stream the run to a terminal - state. + state. More information on Run lifecycles can be found here: + https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps """ ... @@ -804,7 +1045,8 @@ def submit_tool_outputs_stream( ) -> AssistantStreamManager[AssistantEventHandler] | AssistantStreamManager[AssistantEventHandlerT]: """ Submit the tool outputs from a previous run and stream the run to a terminal - state. + state. More information on Run lifecycles can be found here: + https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps """ if not run_id: raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") @@ -1283,7 +1525,58 @@ async def cancel( cast_to=Run, ) + async def create_and_poll( + self, + *, + assistant_id: str, + additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + poll_interval_ms: int | NotGiven = NOT_GIVEN, + thread_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Run: + """ + A helper to create a run an poll for a terminal state. More information on Run + lifecycles can be found here: + https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + """ + run = await self.create( + thread_id=thread_id, + assistant_id=assistant_id, + additional_instructions=additional_instructions, + instructions=instructions, + metadata=metadata, + model=model, + temperature=temperature, + # We assume we are not streaming when polling + stream=False, + tools=tools, + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + ) + return await self.poll( + run.id, + thread_id=thread_id, + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + poll_interval_ms=poll_interval_ms, + timeout=timeout, + ) + @overload + @typing_extensions.deprecated("use `stream` instead") def create_and_stream( self, *, @@ -1306,6 +1599,7 @@ def create_and_stream( ... @overload + @typing_extensions.deprecated("use `stream` instead") def create_and_stream( self, *, @@ -1328,6 +1622,7 @@ def create_and_stream( """Create a Run stream""" ... + @typing_extensions.deprecated("use `stream` instead") def create_and_stream( self, *, @@ -1384,6 +1679,152 @@ def create_and_stream( ) return AsyncAssistantStreamManager(request, event_handler=event_handler or AsyncAssistantEventHandler()) + async def poll( + self, + run_id: str, + thread_id: str, + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + poll_interval_ms: int | NotGiven = NOT_GIVEN, + ) -> Run: + """ + A helper to poll a run status until it reaches a terminal state. More + information on Run lifecycles can be found here: + https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + """ + extra_headers = {"X-Stainless-Poll-Helper": "true", **(extra_headers or {})} + + if is_given(poll_interval_ms): + extra_headers["X-Stainless-Custom-Poll-Interval"] = str(poll_interval_ms) + + terminal_states = {"requires_action", "cancelled", "completed", "failed", "expired"} + while True: + response = await self.with_raw_response.retrieve( + thread_id=thread_id, + run_id=run_id, + extra_headers=extra_headers, + extra_body=extra_body, + extra_query=extra_query, + timeout=timeout, + ) + + run = response.parse() + # Return if we reached a terminal state + if run.status in terminal_states: + return run + + if not is_given(poll_interval_ms): + from_header = response.headers.get("openai-poll-after-ms") + if from_header is not None: + poll_interval_ms = int(from_header) + else: + poll_interval_ms = 1000 + + time.sleep(poll_interval_ms / 1000) + + @overload + def stream( + self, + *, + assistant_id: str, + additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + thread_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncAssistantStreamManager[AsyncAssistantEventHandler]: + """Create a Run stream""" + ... + + @overload + def stream( + self, + *, + assistant_id: str, + additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + thread_id: str, + event_handler: AsyncAssistantEventHandlerT, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncAssistantStreamManager[AsyncAssistantEventHandlerT]: + """Create a Run stream""" + ... + + def stream( + self, + *, + assistant_id: str, + additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + thread_id: str, + event_handler: AsyncAssistantEventHandlerT | None = None, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> ( + AsyncAssistantStreamManager[AsyncAssistantEventHandler] + | AsyncAssistantStreamManager[AsyncAssistantEventHandlerT] + ): + """Create a Run stream""" + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + + extra_headers = { + "OpenAI-Beta": "assistants=v1", + "X-Stainless-Stream-Helper": "threads.runs.create_and_stream", + "X-Stainless-Custom-Event-Handler": "true" if event_handler else "false", + **(extra_headers or {}), + } + request = self._post( + f"/threads/{thread_id}/runs", + body=maybe_transform( + { + "assistant_id": assistant_id, + "additional_instructions": additional_instructions, + "instructions": instructions, + "metadata": metadata, + "model": model, + "temperature": temperature, + "stream": True, + "tools": tools, + }, + run_create_params.RunCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Run, + stream=True, + stream_cls=AsyncStream[AssistantStreamEvent], + ) + return AsyncAssistantStreamManager(request, event_handler=event_handler or AsyncAssistantEventHandler()) + @overload async def submit_tool_outputs( self, @@ -1535,6 +1976,45 @@ async def submit_tool_outputs( stream_cls=AsyncStream[AssistantStreamEvent], ) + async def submit_tool_outputs_and_poll( + self, + *, + tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], + run_id: str, + thread_id: str, + poll_interval_ms: int | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Run: + """ + A helper to submit a tool output to a run and poll for a terminal run state. + More information on Run lifecycles can be found here: + https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + """ + run = await self.submit_tool_outputs( + run_id=run_id, + thread_id=thread_id, + tool_outputs=tool_outputs, + stream=False, + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + ) + return await self.poll( + run_id=run.id, + thread_id=thread_id, + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + poll_interval_ms=poll_interval_ms, + ) + @overload def submit_tool_outputs_stream( self, @@ -1551,7 +2031,8 @@ def submit_tool_outputs_stream( ) -> AsyncAssistantStreamManager[AsyncAssistantEventHandler]: """ Submit the tool outputs from a previous run and stream the run to a terminal - state. + state. More information on Run lifecycles can be found here: + https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps """ ... @@ -1572,7 +2053,8 @@ def submit_tool_outputs_stream( ) -> AsyncAssistantStreamManager[AsyncAssistantEventHandlerT]: """ Submit the tool outputs from a previous run and stream the run to a terminal - state. + state. More information on Run lifecycles can be found here: + https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps """ ... @@ -1595,7 +2077,8 @@ def submit_tool_outputs_stream( ): """ Submit the tool outputs from a previous run and stream the run to a terminal - state. + state. More information on Run lifecycles can be found here: + https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps """ if not run_id: raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index c2ad6aca5f..3509267d4f 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -467,6 +467,45 @@ def create_and_run( stream_cls=Stream[AssistantStreamEvent], ) + def create_and_run_poll( + self, + *, + assistant_id: str, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + poll_interval_ms: int | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Run: + """ + A helper to create a thread, start a run and then poll for a terminal state. + More information on Run lifecycles can be found here: + https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + """ + run = self.create_and_run( + assistant_id=assistant_id, + instructions=instructions, + metadata=metadata, + model=model, + temperature=temperature, + stream=False, + thread=thread, + tools=tools, + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + ) + return self.runs.poll(run.id, run.thread_id, extra_headers, extra_query, extra_body, timeout, poll_interval_ms) + @overload def create_and_run_stream( self, @@ -967,6 +1006,47 @@ async def create_and_run( stream_cls=AsyncStream[AssistantStreamEvent], ) + async def create_and_run_poll( + self, + *, + assistant_id: str, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + model: Optional[str] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + poll_interval_ms: int | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Run: + """ + A helper to create a thread, start a run and then poll for a terminal state. + More information on Run lifecycles can be found here: + https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + """ + run = await self.create_and_run( + assistant_id=assistant_id, + instructions=instructions, + metadata=metadata, + model=model, + temperature=temperature, + stream=False, + thread=thread, + tools=tools, + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + ) + return await self.runs.poll( + run.id, run.thread_id, extra_headers, extra_query, extra_body, timeout, poll_interval_ms + ) + @overload def create_and_run_stream( self, diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index aabe2c7fc9..b9f392dc87 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -14,6 +14,8 @@ Run, ) +# pyright: reportDeprecated=false + base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") From 632cd6feef405076abfa48a898e6bdfc57691996 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 2 Apr 2024 00:39:54 +0200 Subject: [PATCH 281/816] release: 1.16.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 19 +++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 22 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 7ccfe12c9e..bc845f32af 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.15.0" + ".": "1.16.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 180bbf2a28..ce046a623d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,24 @@ # Changelog +## 1.16.0 (2024-04-01) + +Full Changelog: [v1.15.0...v1.16.0](https://github.com/openai/openai-python/compare/v1.15.0...v1.16.0) + +### Features + +* **api:** add support for filtering messages by run_id ([#1288](https://github.com/openai/openai-python/issues/1288)) ([58d6b77](https://github.com/openai/openai-python/commit/58d6b773218ef1dd8dc6208124a16078e4ac11c1)) +* **api:** run polling helpers ([#1289](https://github.com/openai/openai-python/issues/1289)) ([6b427f3](https://github.com/openai/openai-python/commit/6b427f38610847bce3ce5334177f07917bd7c187)) + + +### Chores + +* **client:** validate that max_retries is not None ([#1286](https://github.com/openai/openai-python/issues/1286)) ([aa5920a](https://github.com/openai/openai-python/commit/aa5920af6131c49a44352524154ee4a1684e76b2)) + + +### Refactors + +* rename createAndStream to stream ([6b427f3](https://github.com/openai/openai-python/commit/6b427f38610847bce3ce5334177f07917bd7c187)) + ## 1.15.0 (2024-03-31) Full Changelog: [v1.14.3...v1.15.0](https://github.com/openai/openai-python/compare/v1.14.3...v1.15.0) diff --git a/pyproject.toml b/pyproject.toml index beb31f24a1..437a5e9cc8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.15.0" +version = "1.16.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 6865a9f7bd..fe724b63af 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.15.0" # x-release-please-version +__version__ = "1.16.0" # x-release-please-version From f0bdef04611a24ed150d19c4d180aacab3052704 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 2 Apr 2024 17:11:51 +0200 Subject: [PATCH 282/816] release: 1.16.1 (#1292) * chore(internal): defer model build for import latency (#1291) * release: 1.16.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_models.py | 6 +++++- src/openai/_version.py | 2 +- 5 files changed, 16 insertions(+), 4 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index bc845f32af..1937985906 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.16.0" + ".": "1.16.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index ce046a623d..d0fe2d628e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.16.1 (2024-04-02) + +Full Changelog: [v1.16.0...v1.16.1](https://github.com/openai/openai-python/compare/v1.16.0...v1.16.1) + +### Chores + +* **internal:** defer model build for import latency ([#1291](https://github.com/openai/openai-python/issues/1291)) ([bc6866e](https://github.com/openai/openai-python/commit/bc6866eb2335d01532190d0906cad7bf9af28621)) + ## 1.16.0 (2024-04-01) Full Changelog: [v1.15.0...v1.16.0](https://github.com/openai/openai-python/compare/v1.15.0...v1.16.0) diff --git a/pyproject.toml b/pyproject.toml index 437a5e9cc8..efaa42595e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.16.0" +version = "1.16.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_models.py b/src/openai/_models.py index 77c755b135..0f001150f5 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -1,5 +1,6 @@ from __future__ import annotations +import os import inspect from typing import TYPE_CHECKING, Any, Type, Union, Generic, TypeVar, Callable, cast from datetime import date, datetime @@ -38,6 +39,7 @@ is_given, is_mapping, parse_date, + coerce_boolean, parse_datetime, strip_not_given, extract_type_arg, @@ -74,7 +76,9 @@ class _ConfigProtocol(Protocol): class BaseModel(pydantic.BaseModel): if PYDANTIC_V2: - model_config: ClassVar[ConfigDict] = ConfigDict(extra="allow") + model_config: ClassVar[ConfigDict] = ConfigDict( + extra="allow", defer_build=coerce_boolean(os.environ.get("DEFER_PYDANTIC_BUILD", "true")) + ) else: @property diff --git a/src/openai/_version.py b/src/openai/_version.py index fe724b63af..9d3ac751cd 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.16.0" # x-release-please-version +__version__ = "1.16.1" # x-release-please-version From 7e1e4572f46bb2ee495dc49017e589aca132c28c Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 3 Apr 2024 09:36:41 -0400 Subject: [PATCH 283/816] fix(client): correct logic for line decoding in streaming (#1293) --- src/openai/_streaming.py | 73 +++++++---- tests/test_streaming.py | 268 ++++++++++++++++++++++++++++++--------- 2 files changed, 253 insertions(+), 88 deletions(-) diff --git a/src/openai/_streaming.py b/src/openai/_streaming.py index 9c7cc6a573..0fda992cff 100644 --- a/src/openai/_streaming.py +++ b/src/openai/_streaming.py @@ -24,7 +24,7 @@ class Stream(Generic[_T]): response: httpx.Response - _decoder: SSEDecoder | SSEBytesDecoder + _decoder: SSEBytesDecoder def __init__( self, @@ -47,10 +47,7 @@ def __iter__(self) -> Iterator[_T]: yield item def _iter_events(self) -> Iterator[ServerSentEvent]: - if isinstance(self._decoder, SSEBytesDecoder): - yield from self._decoder.iter_bytes(self.response.iter_bytes()) - else: - yield from self._decoder.iter(self.response.iter_lines()) + yield from self._decoder.iter_bytes(self.response.iter_bytes()) def __stream__(self) -> Iterator[_T]: cast_to = cast(Any, self._cast_to) @@ -151,12 +148,8 @@ async def __aiter__(self) -> AsyncIterator[_T]: yield item async def _iter_events(self) -> AsyncIterator[ServerSentEvent]: - if isinstance(self._decoder, SSEBytesDecoder): - async for sse in self._decoder.aiter_bytes(self.response.aiter_bytes()): - yield sse - else: - async for sse in self._decoder.aiter(self.response.aiter_lines()): - yield sse + async for sse in self._decoder.aiter_bytes(self.response.aiter_bytes()): + yield sse async def __stream__(self) -> AsyncIterator[_T]: cast_to = cast(Any, self._cast_to) @@ -282,21 +275,49 @@ def __init__(self) -> None: self._last_event_id = None self._retry = None - def iter(self, iterator: Iterator[str]) -> Iterator[ServerSentEvent]: - """Given an iterator that yields lines, iterate over it & yield every event encountered""" - for line in iterator: - line = line.rstrip("\n") - sse = self.decode(line) - if sse is not None: - yield sse - - async def aiter(self, iterator: AsyncIterator[str]) -> AsyncIterator[ServerSentEvent]: - """Given an async iterator that yields lines, iterate over it & yield every event encountered""" - async for line in iterator: - line = line.rstrip("\n") - sse = self.decode(line) - if sse is not None: - yield sse + def iter_bytes(self, iterator: Iterator[bytes]) -> Iterator[ServerSentEvent]: + """Given an iterator that yields raw binary data, iterate over it & yield every event encountered""" + for chunk in self._iter_chunks(iterator): + # Split before decoding so splitlines() only uses \r and \n + for raw_line in chunk.splitlines(): + line = raw_line.decode("utf-8") + sse = self.decode(line) + if sse: + yield sse + + def _iter_chunks(self, iterator: Iterator[bytes]) -> Iterator[bytes]: + """Given an iterator that yields raw binary data, iterate over it and yield individual SSE chunks""" + data = b"" + for chunk in iterator: + for line in chunk.splitlines(keepends=True): + data += line + if data.endswith((b"\r\r", b"\n\n", b"\r\n\r\n")): + yield data + data = b"" + if data: + yield data + + async def aiter_bytes(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[ServerSentEvent]: + """Given an iterator that yields raw binary data, iterate over it & yield every event encountered""" + async for chunk in self._aiter_chunks(iterator): + # Split before decoding so splitlines() only uses \r and \n + for raw_line in chunk.splitlines(): + line = raw_line.decode("utf-8") + sse = self.decode(line) + if sse: + yield sse + + async def _aiter_chunks(self, iterator: AsyncIterator[bytes]) -> AsyncIterator[bytes]: + """Given an iterator that yields raw binary data, iterate over it and yield individual SSE chunks""" + data = b"" + async for chunk in iterator: + for line in chunk.splitlines(keepends=True): + data += line + if data.endswith((b"\r\r", b"\n\n", b"\r\n\r\n")): + yield data + data = b"" + if data: + yield data def decode(self, line: str) -> ServerSentEvent | None: # See: https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation # noqa: E501 diff --git a/tests/test_streaming.py b/tests/test_streaming.py index 75e4ca2699..04f8e51abd 100644 --- a/tests/test_streaming.py +++ b/tests/test_streaming.py @@ -1,104 +1,248 @@ +from __future__ import annotations + from typing import Iterator, AsyncIterator +import httpx import pytest -from openai._streaming import SSEDecoder +from openai import OpenAI, AsyncOpenAI +from openai._streaming import Stream, AsyncStream, ServerSentEvent @pytest.mark.asyncio -async def test_basic_async() -> None: - async def body() -> AsyncIterator[str]: - yield "event: completion" - yield 'data: {"foo":true}' - yield "" - - async for sse in SSEDecoder().aiter(body()): - assert sse.event == "completion" - assert sse.json() == {"foo": True} +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +async def test_basic(sync: bool, client: OpenAI, async_client: AsyncOpenAI) -> None: + def body() -> Iterator[bytes]: + yield b"event: completion\n" + yield b'data: {"foo":true}\n' + yield b"\n" + iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client) -def test_basic() -> None: - def body() -> Iterator[str]: - yield "event: completion" - yield 'data: {"foo":true}' - yield "" - - it = SSEDecoder().iter(body()) - sse = next(it) + sse = await iter_next(iterator) assert sse.event == "completion" assert sse.json() == {"foo": True} - with pytest.raises(StopIteration): - next(it) + await assert_empty_iter(iterator) -def test_data_missing_event() -> None: - def body() -> Iterator[str]: - yield 'data: {"foo":true}' - yield "" +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +async def test_data_missing_event(sync: bool, client: OpenAI, async_client: AsyncOpenAI) -> None: + def body() -> Iterator[bytes]: + yield b'data: {"foo":true}\n' + yield b"\n" - it = SSEDecoder().iter(body()) - sse = next(it) + iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client) + + sse = await iter_next(iterator) assert sse.event is None assert sse.json() == {"foo": True} - with pytest.raises(StopIteration): - next(it) + await assert_empty_iter(iterator) + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +async def test_event_missing_data(sync: bool, client: OpenAI, async_client: AsyncOpenAI) -> None: + def body() -> Iterator[bytes]: + yield b"event: ping\n" + yield b"\n" -def test_event_missing_data() -> None: - def body() -> Iterator[str]: - yield "event: ping" - yield "" + iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client) - it = SSEDecoder().iter(body()) - sse = next(it) + sse = await iter_next(iterator) assert sse.event == "ping" assert sse.data == "" - with pytest.raises(StopIteration): - next(it) + await assert_empty_iter(iterator) -def test_multiple_events() -> None: - def body() -> Iterator[str]: - yield "event: ping" - yield "" - yield "event: completion" - yield "" +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +async def test_multiple_events(sync: bool, client: OpenAI, async_client: AsyncOpenAI) -> None: + def body() -> Iterator[bytes]: + yield b"event: ping\n" + yield b"\n" + yield b"event: completion\n" + yield b"\n" - it = SSEDecoder().iter(body()) + iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client) - sse = next(it) + sse = await iter_next(iterator) assert sse.event == "ping" assert sse.data == "" - sse = next(it) + sse = await iter_next(iterator) assert sse.event == "completion" assert sse.data == "" - with pytest.raises(StopIteration): - next(it) - - -def test_multiple_events_with_data() -> None: - def body() -> Iterator[str]: - yield "event: ping" - yield 'data: {"foo":true}' - yield "" - yield "event: completion" - yield 'data: {"bar":false}' - yield "" + await assert_empty_iter(iterator) - it = SSEDecoder().iter(body()) - sse = next(it) +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +async def test_multiple_events_with_data(sync: bool, client: OpenAI, async_client: AsyncOpenAI) -> None: + def body() -> Iterator[bytes]: + yield b"event: ping\n" + yield b'data: {"foo":true}\n' + yield b"\n" + yield b"event: completion\n" + yield b'data: {"bar":false}\n' + yield b"\n" + + iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client) + + sse = await iter_next(iterator) assert sse.event == "ping" assert sse.json() == {"foo": True} - sse = next(it) + sse = await iter_next(iterator) assert sse.event == "completion" assert sse.json() == {"bar": False} - with pytest.raises(StopIteration): - next(it) + await assert_empty_iter(iterator) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +async def test_multiple_data_lines_with_empty_line(sync: bool, client: OpenAI, async_client: AsyncOpenAI) -> None: + def body() -> Iterator[bytes]: + yield b"event: ping\n" + yield b"data: {\n" + yield b'data: "foo":\n' + yield b"data: \n" + yield b"data:\n" + yield b"data: true}\n" + yield b"\n\n" + + iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client) + + sse = await iter_next(iterator) + assert sse.event == "ping" + assert sse.json() == {"foo": True} + assert sse.data == '{\n"foo":\n\n\ntrue}' + + await assert_empty_iter(iterator) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +async def test_data_json_escaped_double_new_line(sync: bool, client: OpenAI, async_client: AsyncOpenAI) -> None: + def body() -> Iterator[bytes]: + yield b"event: ping\n" + yield b'data: {"foo": "my long\\n\\ncontent"}' + yield b"\n\n" + + iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client) + + sse = await iter_next(iterator) + assert sse.event == "ping" + assert sse.json() == {"foo": "my long\n\ncontent"} + + await assert_empty_iter(iterator) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +async def test_multiple_data_lines(sync: bool, client: OpenAI, async_client: AsyncOpenAI) -> None: + def body() -> Iterator[bytes]: + yield b"event: ping\n" + yield b"data: {\n" + yield b'data: "foo":\n' + yield b"data: true}\n" + yield b"\n\n" + + iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client) + + sse = await iter_next(iterator) + assert sse.event == "ping" + assert sse.json() == {"foo": True} + + await assert_empty_iter(iterator) + + +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +async def test_special_new_line_character( + sync: bool, + client: OpenAI, + async_client: AsyncOpenAI, +) -> None: + def body() -> Iterator[bytes]: + yield b'data: {"content":" culpa"}\n' + yield b"\n" + yield b'data: {"content":" \xe2\x80\xa8"}\n' + yield b"\n" + yield b'data: {"content":"foo"}\n' + yield b"\n" + + iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client) + + sse = await iter_next(iterator) + assert sse.event is None + assert sse.json() == {"content": " culpa"} + + sse = await iter_next(iterator) + assert sse.event is None + assert sse.json() == {"content": " 
"} + + sse = await iter_next(iterator) + assert sse.event is None + assert sse.json() == {"content": "foo"} + + await assert_empty_iter(iterator) + + +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +async def test_multi_byte_character_multiple_chunks( + sync: bool, + client: OpenAI, + async_client: AsyncOpenAI, +) -> None: + def body() -> Iterator[bytes]: + yield b'data: {"content":"' + # bytes taken from the string 'известни' and arbitrarily split + # so that some multi-byte characters span multiple chunks + yield b"\xd0" + yield b"\xb8\xd0\xb7\xd0" + yield b"\xb2\xd0\xb5\xd1\x81\xd1\x82\xd0\xbd\xd0\xb8" + yield b'"}\n' + yield b"\n" + + iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client) + + sse = await iter_next(iterator) + assert sse.event is None + assert sse.json() == {"content": "известни"} + + +async def to_aiter(iter: Iterator[bytes]) -> AsyncIterator[bytes]: + for chunk in iter: + yield chunk + + +async def iter_next(iter: Iterator[ServerSentEvent] | AsyncIterator[ServerSentEvent]) -> ServerSentEvent: + if isinstance(iter, AsyncIterator): + return await iter.__anext__() + + return next(iter) + + +async def assert_empty_iter(iter: Iterator[ServerSentEvent] | AsyncIterator[ServerSentEvent]) -> None: + with pytest.raises((StopAsyncIteration, RuntimeError)): + await iter_next(iter) + + +def make_event_iterator( + content: Iterator[bytes], + *, + sync: bool, + client: OpenAI, + async_client: AsyncOpenAI, +) -> Iterator[ServerSentEvent] | AsyncIterator[ServerSentEvent]: + if sync: + return Stream(cast_to=object, client=client, response=httpx.Response(200, content=content))._iter_events() + + return AsyncStream( + cast_to=object, client=async_client, response=httpx.Response(200, content=to_aiter(content)) + )._iter_events() From 0bdc3772a159f433a5c6c9bb18bfa3ea807599b4 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 4 Apr 2024 01:03:43 -0400 Subject: [PATCH 284/816] release: 1.16.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 1937985906..fb1bd8f489 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.16.1" + ".": "1.16.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index d0fe2d628e..3b22f06aae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.16.2 (2024-04-04) + +Full Changelog: [v1.16.1...v1.16.2](https://github.com/openai/openai-python/compare/v1.16.1...v1.16.2) + +### Bug Fixes + +* **client:** correct logic for line decoding in streaming ([#1293](https://github.com/openai/openai-python/issues/1293)) ([687caef](https://github.com/openai/openai-python/commit/687caefa4acf615bf404f16817bfd9a6f285ee5c)) + ## 1.16.1 (2024-04-02) Full Changelog: [v1.16.0...v1.16.1](https://github.com/openai/openai-python/compare/v1.16.0...v1.16.1) diff --git a/pyproject.toml b/pyproject.toml index efaa42595e..67006726fb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.16.1" +version = "1.16.2" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 9d3ac751cd..85803a60a6 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.16.1" # x-release-please-version +__version__ = "1.16.2" # x-release-please-version From e2d65bf77aa6e2bca043f70f5e0a38d8bd08b5e8 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 5 Apr 2024 08:36:56 -0400 Subject: [PATCH 285/816] feat(api): add additional messages when creating thread run (#1298) --- .../resources/beta/threads/runs/runs.py | 42 ++++++++++ .../types/beta/threads/run_create_params.py | 37 ++++++++- tests/api_resources/beta/threads/test_runs.py | 80 +++++++++++++++++++ 3 files changed, 157 insertions(+), 2 deletions(-) diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 4529c65025..8576a5c09a 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -75,6 +75,7 @@ def create( *, assistant_id: str, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, @@ -100,6 +101,8 @@ def create( is useful for modifying the behavior on a per-run basis without overriding other instructions. + additional_messages: Adds additional messages to the thread before creating the run. + instructions: Overrides the [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis. @@ -143,6 +146,7 @@ def create( assistant_id: str, stream: Literal[True], additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, @@ -171,6 +175,8 @@ def create( is useful for modifying the behavior on a per-run basis without overriding other instructions. + additional_messages: Adds additional messages to the thread before creating the run. + instructions: Overrides the [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis. @@ -210,6 +216,7 @@ def create( assistant_id: str, stream: bool, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, @@ -238,6 +245,8 @@ def create( is useful for modifying the behavior on a per-run basis without overriding other instructions. + additional_messages: Adds additional messages to the thread before creating the run. + instructions: Overrides the [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis. @@ -276,6 +285,7 @@ def create( *, assistant_id: str, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, @@ -298,6 +308,7 @@ def create( { "assistant_id": assistant_id, "additional_instructions": additional_instructions, + "additional_messages": additional_messages, "instructions": instructions, "metadata": metadata, "model": model, @@ -505,6 +516,7 @@ def create_and_poll( *, assistant_id: str, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, @@ -528,6 +540,7 @@ def create_and_poll( thread_id=thread_id, assistant_id=assistant_id, additional_instructions=additional_instructions, + additional_messages=additional_messages, instructions=instructions, metadata=metadata, model=model, @@ -557,6 +570,7 @@ def create_and_stream( *, assistant_id: str, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, @@ -580,6 +594,7 @@ def create_and_stream( *, assistant_id: str, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, @@ -603,6 +618,7 @@ def create_and_stream( *, assistant_id: str, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, @@ -634,6 +650,7 @@ def create_and_stream( { "assistant_id": assistant_id, "additional_instructions": additional_instructions, + "additional_messages": additional_messages, "instructions": instructions, "metadata": metadata, "model": model, @@ -703,6 +720,7 @@ def stream( *, assistant_id: str, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, @@ -725,6 +743,7 @@ def stream( *, assistant_id: str, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, @@ -747,6 +766,7 @@ def stream( *, assistant_id: str, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, @@ -778,6 +798,7 @@ def stream( { "assistant_id": assistant_id, "additional_instructions": additional_instructions, + "additional_messages": additional_messages, "instructions": instructions, "metadata": metadata, "model": model, @@ -1100,6 +1121,7 @@ async def create( *, assistant_id: str, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, @@ -1125,6 +1147,8 @@ async def create( is useful for modifying the behavior on a per-run basis without overriding other instructions. + additional_messages: Adds additional messages to the thread before creating the run. + instructions: Overrides the [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis. @@ -1168,6 +1192,7 @@ async def create( assistant_id: str, stream: Literal[True], additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, @@ -1196,6 +1221,8 @@ async def create( is useful for modifying the behavior on a per-run basis without overriding other instructions. + additional_messages: Adds additional messages to the thread before creating the run. + instructions: Overrides the [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis. @@ -1235,6 +1262,7 @@ async def create( assistant_id: str, stream: bool, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, @@ -1263,6 +1291,8 @@ async def create( is useful for modifying the behavior on a per-run basis without overriding other instructions. + additional_messages: Adds additional messages to the thread before creating the run. + instructions: Overrides the [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis. @@ -1301,6 +1331,7 @@ async def create( *, assistant_id: str, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, @@ -1323,6 +1354,7 @@ async def create( { "assistant_id": assistant_id, "additional_instructions": additional_instructions, + "additional_messages": additional_messages, "instructions": instructions, "metadata": metadata, "model": model, @@ -1530,6 +1562,7 @@ async def create_and_poll( *, assistant_id: str, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, @@ -1553,6 +1586,7 @@ async def create_and_poll( thread_id=thread_id, assistant_id=assistant_id, additional_instructions=additional_instructions, + additional_messages=additional_messages, instructions=instructions, metadata=metadata, model=model, @@ -1582,6 +1616,7 @@ def create_and_stream( *, assistant_id: str, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, @@ -1605,6 +1640,7 @@ def create_and_stream( *, assistant_id: str, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, @@ -1628,6 +1664,7 @@ def create_and_stream( *, assistant_id: str, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, @@ -1661,6 +1698,7 @@ def create_and_stream( { "assistant_id": assistant_id, "additional_instructions": additional_instructions, + "additional_messages": additional_messages, "instructions": instructions, "metadata": metadata, "model": model, @@ -1730,6 +1768,7 @@ def stream( *, assistant_id: str, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, @@ -1752,6 +1791,7 @@ def stream( *, assistant_id: str, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, @@ -1774,6 +1814,7 @@ def stream( *, assistant_id: str, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, + additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Optional[str] | NotGiven = NOT_GIVEN, @@ -1807,6 +1848,7 @@ def stream( { "assistant_id": assistant_id, "additional_instructions": additional_instructions, + "additional_messages": additional_messages, "instructions": instructions, "metadata": metadata, "model": model, diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index ac185973a5..e9bc19d980 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -2,12 +2,12 @@ from __future__ import annotations -from typing import Union, Iterable, Optional +from typing import List, Union, Iterable, Optional from typing_extensions import Literal, Required, TypedDict from ..assistant_tool_param import AssistantToolParam -__all__ = ["RunCreateParamsBase", "RunCreateParamsNonStreaming", "RunCreateParamsStreaming"] +__all__ = ["RunCreateParamsBase", "AdditionalMessage", "RunCreateParamsNonStreaming", "RunCreateParamsStreaming"] class RunCreateParamsBase(TypedDict, total=False): @@ -25,6 +25,9 @@ class RunCreateParamsBase(TypedDict, total=False): other instructions. """ + additional_messages: Optional[Iterable[AdditionalMessage]] + """Adds additional messages to the thread before creating the run.""" + instructions: Optional[str] """ Overrides the @@ -62,6 +65,36 @@ class RunCreateParamsBase(TypedDict, total=False): """ +class AdditionalMessage(TypedDict, total=False): + content: Required[str] + """The content of the message.""" + + role: Required[Literal["user", "assistant"]] + """The role of the entity that is creating the message. Allowed values include: + + - `user`: Indicates the message is sent by an actual user and should be used in + most cases to represent user-generated messages. + - `assistant`: Indicates the message is generated by the assistant. Use this + value to insert messages from the assistant into the conversation. + """ + + file_ids: List[str] + """ + A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + the message should use. There can be a maximum of 10 files attached to a + message. Useful for tools like `retrieval` and `code_interpreter` that can + access and use files. + """ + + metadata: Optional[object] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format. Keys can be a maximum of 64 characters long and values can be + a maxium of 512 characters long. + """ + + class RunCreateParamsNonStreaming(RunCreateParamsBase): stream: Optional[Literal[False]] """ diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index b9f392dc87..271bcccdd3 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -36,6 +36,26 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: "string", assistant_id="string", additional_instructions="string", + additional_messages=[ + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + ], instructions="string", metadata={}, model="string", @@ -95,6 +115,26 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: assistant_id="string", stream=True, additional_instructions="string", + additional_messages=[ + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + ], instructions="string", metadata={}, model="string", @@ -492,6 +532,26 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn "string", assistant_id="string", additional_instructions="string", + additional_messages=[ + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + ], instructions="string", metadata={}, model="string", @@ -551,6 +611,26 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn assistant_id="string", stream=True, additional_instructions="string", + additional_messages=[ + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + { + "role": "user", + "content": "x", + "file_ids": ["string"], + "metadata": {}, + }, + ], instructions="string", metadata={}, model="string", From 347363ed67a6a1611346427bb9ebe4becce53f7e Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 8 Apr 2024 12:50:01 +0200 Subject: [PATCH 286/816] feat(client): add DefaultHttpxClient and DefaultAsyncHttpxClient (#1302) --- README.md | 5 ++--- src/openai/__init__.py | 3 +++ src/openai/_base_client.py | 44 ++++++++++++++++++++++++++++++++++++-- src/openai/_client.py | 8 +++++-- 4 files changed, 53 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 5264026dc9..f007d9187b 100644 --- a/README.md +++ b/README.md @@ -549,13 +549,12 @@ You can directly override the [httpx client](https://www.python-httpx.org/api/#c - Additional [advanced](https://www.python-httpx.org/advanced/#client-instances) functionality ```python -import httpx -from openai import OpenAI +from openai import OpenAI, DefaultHttpxClient client = OpenAI( # Or use the `OPENAI_BASE_URL` env var base_url="http://my.test.server.example.com:8083/", - http_client=httpx.Client( + http_client=DefaultHttpxClient( proxies="http://my.test.proxy.example.com/", transport=httpx.HTTPTransport(local_address="0.0.0.0"), ), diff --git a/src/openai/__init__.py b/src/openai/__init__.py index cd05a749da..1daa26f7b7 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -29,6 +29,7 @@ UnprocessableEntityError, APIResponseValidationError, ) +from ._base_client import DefaultHttpxClient, DefaultAsyncHttpxClient from ._utils._logs import setup_logging as _setup_logging __all__ = [ @@ -67,6 +68,8 @@ "DEFAULT_TIMEOUT", "DEFAULT_MAX_RETRIES", "DEFAULT_CONNECTION_LIMITS", + "DefaultHttpxClient", + "DefaultAsyncHttpxClient", ] from .lib import azure as _azure diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 502ed7c7ae..0bb284a211 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -716,7 +716,27 @@ def _idempotency_key(self) -> str: return f"stainless-python-retry-{uuid.uuid4()}" -class SyncHttpxClientWrapper(httpx.Client): +class _DefaultHttpxClient(httpx.Client): + def __init__(self, **kwargs: Any) -> None: + kwargs.setdefault("timeout", DEFAULT_TIMEOUT) + kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS) + kwargs.setdefault("follow_redirects", True) + super().__init__(**kwargs) + + +if TYPE_CHECKING: + DefaultHttpxClient = httpx.Client + """An alias to `httpx.Client` that provides the same defaults that this SDK + uses internally. + + This is useful because overriding the `http_client` with your own instance of + `httpx.Client` will result in httpx's defaults being used, not ours. + """ +else: + DefaultHttpxClient = _DefaultHttpxClient + + +class SyncHttpxClientWrapper(DefaultHttpxClient): def __del__(self) -> None: try: self.close() @@ -1262,7 +1282,27 @@ def get_api_list( return self._request_api_list(model, page, opts) -class AsyncHttpxClientWrapper(httpx.AsyncClient): +class _DefaultAsyncHttpxClient(httpx.AsyncClient): + def __init__(self, **kwargs: Any) -> None: + kwargs.setdefault("timeout", DEFAULT_TIMEOUT) + kwargs.setdefault("limits", DEFAULT_CONNECTION_LIMITS) + kwargs.setdefault("follow_redirects", True) + super().__init__(**kwargs) + + +if TYPE_CHECKING: + DefaultAsyncHttpxClient = httpx.AsyncClient + """An alias to `httpx.AsyncClient` that provides the same defaults that this SDK + uses internally. + + This is useful because overriding the `http_client` with your own instance of + `httpx.AsyncClient` will result in httpx's defaults being used, not ours. + """ +else: + DefaultAsyncHttpxClient = _DefaultAsyncHttpxClient + + +class AsyncHttpxClientWrapper(DefaultAsyncHttpxClient): def __del__(self) -> None: try: # TODO(someday): support non asyncio runtimes here diff --git a/src/openai/_client.py b/src/openai/_client.py index 7fe2c9af79..e9169df72a 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -74,7 +74,9 @@ def __init__( max_retries: int = DEFAULT_MAX_RETRIES, default_headers: Mapping[str, str] | None = None, default_query: Mapping[str, object] | None = None, - # Configure a custom httpx client. See the [httpx documentation](https://www.python-httpx.org/api/#client) for more details. + # Configure a custom httpx client. + # We provide a `DefaultHttpxClient` class that you can pass to retain the default values we use for `limits`, `timeout` & `follow_redirects`. + # See the [httpx documentation](https://www.python-httpx.org/api/#client) for more details. http_client: httpx.Client | None = None, # Enable or disable schema validation for data returned by the API. # When enabled an error APIResponseValidationError is raised @@ -272,7 +274,9 @@ def __init__( max_retries: int = DEFAULT_MAX_RETRIES, default_headers: Mapping[str, str] | None = None, default_query: Mapping[str, object] | None = None, - # Configure a custom httpx client. See the [httpx documentation](https://www.python-httpx.org/api/#asyncclient) for more details. + # Configure a custom httpx client. + # We provide a `DefaultAsyncHttpxClient` class that you can pass to retain the default values we use for `limits`, `timeout` & `follow_redirects`. + # See the [httpx documentation](https://www.python-httpx.org/api/#asyncclient) for more details. http_client: httpx.AsyncClient | None = None, # Enable or disable schema validation for data returned by the API. # When enabled an error APIResponseValidationError is raised From 47656567e016a1ddf09497f180a19265b28ec93c Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 9 Apr 2024 08:20:45 -0400 Subject: [PATCH 287/816] feat(models): add to_dict & to_json helper methods (#1305) --- README.md | 8 ++-- examples/azure.py | 4 +- examples/azure_ad.py | 2 +- examples/streaming.py | 8 ++-- src/openai/_models.py | 73 +++++++++++++++++++++++++++++++++++ src/openai/lib/_validators.py | 10 +++-- tests/test_models.py | 64 ++++++++++++++++++++++++++++++ 7 files changed, 155 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index f007d9187b..3bdd6c4a43 100644 --- a/README.md +++ b/README.md @@ -200,10 +200,10 @@ We recommend that you always instantiate a client (e.g., with `client = OpenAI() ## Using types -Nested request parameters are [TypedDicts](https://docs.python.org/3/library/typing.html#typing.TypedDict). Responses are [Pydantic models](https://docs.pydantic.dev), which provide helper methods for things like: +Nested request parameters are [TypedDicts](https://docs.python.org/3/library/typing.html#typing.TypedDict). Responses are [Pydantic models](https://docs.pydantic.dev) which also provide helper methods for things like: -- Serializing back into JSON, `model.model_dump_json(indent=2, exclude_unset=True)` -- Converting to a dictionary, `model.model_dump(exclude_unset=True)` +- Serializing back into JSON, `model.to_json()` +- Converting to a dictionary, `model.to_dict()` Typed requests and responses provide autocomplete and documentation within your editor. If you would like to see type errors in VS Code to help catch bugs earlier, set `python.analysis.typeCheckingMode` to `basic`. @@ -594,7 +594,7 @@ completion = client.chat.completions.create( }, ], ) -print(completion.model_dump_json(indent=2)) +print(completion.to_json()) ``` In addition to the options provided in the base `OpenAI` client, the following options are provided: diff --git a/examples/azure.py b/examples/azure.py index a28b8cc433..6936c4cb0e 100755 --- a/examples/azure.py +++ b/examples/azure.py @@ -20,7 +20,7 @@ }, ], ) -print(completion.model_dump_json(indent=2)) +print(completion.to_json()) deployment_client = AzureOpenAI( @@ -40,4 +40,4 @@ }, ], ) -print(completion.model_dump_json(indent=2)) +print(completion.to_json()) diff --git a/examples/azure_ad.py b/examples/azure_ad.py index f13079dd04..1b0d81863d 100755 --- a/examples/azure_ad.py +++ b/examples/azure_ad.py @@ -27,4 +27,4 @@ }, ], ) -print(completion.model_dump_json(indent=2)) +print(completion.to_json()) diff --git a/examples/streaming.py b/examples/streaming.py index 368fa5f911..9a84891a83 100755 --- a/examples/streaming.py +++ b/examples/streaming.py @@ -22,12 +22,12 @@ def sync_main() -> None: # You can manually control iteration over the response first = next(response) - print(f"got response data: {first.model_dump_json(indent=2)}") + print(f"got response data: {first.to_json()}") # Or you could automatically iterate through all of data. # Note that the for loop will not exit until *all* of the data has been processed. for data in response: - print(data.model_dump_json()) + print(data.to_json()) async def async_main() -> None: @@ -43,12 +43,12 @@ async def async_main() -> None: # You can manually control iteration over the response. # In Python 3.10+ you can also use the `await anext(response)` builtin instead first = await response.__anext__() - print(f"got response data: {first.model_dump_json(indent=2)}") + print(f"got response data: {first.to_json()}") # Or you could automatically iterate through all of data. # Note that the for loop will not exit until *all* of the data has been processed. async for data in response: - print(data.model_dump_json()) + print(data.to_json()) sync_main() diff --git a/src/openai/_models.py b/src/openai/_models.py index 0f001150f5..80ab51256f 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -90,6 +90,79 @@ def model_fields_set(self) -> set[str]: class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated] extra: Any = pydantic.Extra.allow # type: ignore + def to_dict( + self, + *, + mode: Literal["json", "python"] = "python", + use_api_names: bool = True, + exclude_unset: bool = True, + exclude_defaults: bool = False, + exclude_none: bool = False, + warnings: bool = True, + ) -> dict[str, object]: + """Recursively generate a dictionary representation of the model, optionally specifying which fields to include or exclude. + + By default, fields that were not set by the API will not be included, + and keys will match the API response, *not* the property names from the model. + + For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property, + the output will use the `"fooBar"` key (unless `use_api_names=False` is passed). + + Args: + mode: + If mode is 'json', the dictionary will only contain JSON serializable types. e.g. `datetime` will be turned into a string, `"2024-3-22T18:11:19.117000Z"`. + If mode is 'python', the dictionary may contain any Python objects. e.g. `datetime(2024, 3, 22)` + + use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`. + exclude_unset: Whether to exclude fields that have not been explicitly set. + exclude_defaults: Whether to exclude fields that are set to their default value from the output. + exclude_none: Whether to exclude fields that have a value of `None` from the output. + warnings: Whether to log warnings when invalid fields are encountered. This is only supported in Pydantic v2. + """ + return self.model_dump( + mode=mode, + by_alias=use_api_names, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + warnings=warnings, + ) + + def to_json( + self, + *, + indent: int | None = 2, + use_api_names: bool = True, + exclude_unset: bool = True, + exclude_defaults: bool = False, + exclude_none: bool = False, + warnings: bool = True, + ) -> str: + """Generates a JSON string representing this model as it would be received from or sent to the API (but with indentation). + + By default, fields that were not set by the API will not be included, + and keys will match the API response, *not* the property names from the model. + + For example, if the API responds with `"fooBar": true` but we've defined a `foo_bar: bool` property, + the output will use the `"fooBar"` key (unless `use_api_names=False` is passed). + + Args: + indent: Indentation to use in the JSON output. If `None` is passed, the output will be compact. Defaults to `2` + use_api_names: Whether to use the key that the API responded with or the property name. Defaults to `True`. + exclude_unset: Whether to exclude fields that have not been explicitly set. + exclude_defaults: Whether to exclude fields that have the default value. + exclude_none: Whether to exclude fields that have a value of `None`. + warnings: Whether to show any warnings that occurred during serialization. This is only supported in Pydantic v2. + """ + return self.model_dump_json( + indent=indent, + by_alias=use_api_names, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + warnings=warnings, + ) + @override def __str__(self) -> str: # mypy complains about an invalid self arg diff --git a/src/openai/lib/_validators.py b/src/openai/lib/_validators.py index e36f0e95fb..cf24cd2294 100644 --- a/src/openai/lib/_validators.py +++ b/src/openai/lib/_validators.py @@ -678,9 +678,11 @@ def write_out_file(df: pd.DataFrame, fname: str, any_remediations: bool, auto_ac df_train = df.sample(n=n_train, random_state=42) df_valid = df.drop(df_train.index) df_train[["prompt", "completion"]].to_json( # type: ignore - fnames[0], lines=True, orient="records", force_ascii=False + fnames[0], lines=True, orient="records", force_ascii=False, indent=None + ) + df_valid[["prompt", "completion"]].to_json( + fnames[1], lines=True, orient="records", force_ascii=False, indent=None ) - df_valid[["prompt", "completion"]].to_json(fnames[1], lines=True, orient="records", force_ascii=False) n_classes, pos_class = get_classification_hyperparams(df) additional_params += " --compute_classification_metrics" @@ -690,7 +692,9 @@ def write_out_file(df: pd.DataFrame, fname: str, any_remediations: bool, auto_ac additional_params += f" --classification_n_classes {n_classes}" else: assert len(fnames) == 1 - df[["prompt", "completion"]].to_json(fnames[0], lines=True, orient="records", force_ascii=False) + df[["prompt", "completion"]].to_json( + fnames[0], lines=True, orient="records", force_ascii=False, indent=None + ) # Add -v VALID_FILE if we split the file into train / valid files_string = ("s" if split else "") + " to `" + ("` and `".join(fnames)) diff --git a/tests/test_models.py b/tests/test_models.py index d003d32181..969e4eb315 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -501,6 +501,42 @@ class Model(BaseModel): assert "resource_id" in m.model_fields_set +def test_to_dict() -> None: + class Model(BaseModel): + foo: Optional[str] = Field(alias="FOO", default=None) + + m = Model(FOO="hello") + assert m.to_dict() == {"FOO": "hello"} + assert m.to_dict(use_api_names=False) == {"foo": "hello"} + + m2 = Model() + assert m2.to_dict() == {} + assert m2.to_dict(exclude_unset=False) == {"FOO": None} + assert m2.to_dict(exclude_unset=False, exclude_none=True) == {} + assert m2.to_dict(exclude_unset=False, exclude_defaults=True) == {} + + m3 = Model(FOO=None) + assert m3.to_dict() == {"FOO": None} + assert m3.to_dict(exclude_none=True) == {} + assert m3.to_dict(exclude_defaults=True) == {} + + if PYDANTIC_V2: + + class Model2(BaseModel): + created_at: datetime + + time_str = "2024-03-21T11:39:01.275859" + m4 = Model2.construct(created_at=time_str) + assert m4.to_dict(mode="python") == {"created_at": datetime.fromisoformat(time_str)} + assert m4.to_dict(mode="json") == {"created_at": time_str} + else: + with pytest.raises(ValueError, match="mode is only supported in Pydantic v2"): + m.to_dict(mode="json") + + with pytest.raises(ValueError, match="warnings is only supported in Pydantic v2"): + m.to_dict(warnings=False) + + def test_forwards_compat_model_dump_method() -> None: class Model(BaseModel): foo: Optional[str] = Field(alias="FOO", default=None) @@ -532,6 +568,34 @@ class Model(BaseModel): m.model_dump(warnings=False) +def test_to_json() -> None: + class Model(BaseModel): + foo: Optional[str] = Field(alias="FOO", default=None) + + m = Model(FOO="hello") + assert json.loads(m.to_json()) == {"FOO": "hello"} + assert json.loads(m.to_json(use_api_names=False)) == {"foo": "hello"} + + if PYDANTIC_V2: + assert m.to_json(indent=None) == '{"FOO":"hello"}' + else: + assert m.to_json(indent=None) == '{"FOO": "hello"}' + + m2 = Model() + assert json.loads(m2.to_json()) == {} + assert json.loads(m2.to_json(exclude_unset=False)) == {"FOO": None} + assert json.loads(m2.to_json(exclude_unset=False, exclude_none=True)) == {} + assert json.loads(m2.to_json(exclude_unset=False, exclude_defaults=True)) == {} + + m3 = Model(FOO=None) + assert json.loads(m3.to_json()) == {"FOO": None} + assert json.loads(m3.to_json(exclude_none=True)) == {} + + if not PYDANTIC_V2: + with pytest.raises(ValueError, match="warnings is only supported in Pydantic v2"): + m.to_json(warnings=False) + + def test_forwards_compat_model_dump_json_method() -> None: class Model(BaseModel): foo: Optional[str] = Field(alias="FOO", default=None) From 0cbce3f6777fd8f137ed7445e9bc2f2aa5c9f5b4 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 10 Apr 2024 01:03:43 -0400 Subject: [PATCH 288/816] release: 1.17.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 10 ++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 13 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index fb1bd8f489..6a197bef5a 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.16.2" + ".": "1.17.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b22f06aae..0da030b337 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## 1.17.0 (2024-04-10) + +Full Changelog: [v1.16.2...v1.17.0](https://github.com/openai/openai-python/compare/v1.16.2...v1.17.0) + +### Features + +* **api:** add additional messages when creating thread run ([#1298](https://github.com/openai/openai-python/issues/1298)) ([70eb081](https://github.com/openai/openai-python/commit/70eb081804b14cc8c151ebd85458545a50a074fd)) +* **client:** add DefaultHttpxClient and DefaultAsyncHttpxClient ([#1302](https://github.com/openai/openai-python/issues/1302)) ([69cdfc3](https://github.com/openai/openai-python/commit/69cdfc319fff7ebf28cdd13cc6c1761b7d97811d)) +* **models:** add to_dict & to_json helper methods ([#1305](https://github.com/openai/openai-python/issues/1305)) ([40a881d](https://github.com/openai/openai-python/commit/40a881d10442af8b445ce030f8ab338710e1c4c8)) + ## 1.16.2 (2024-04-04) Full Changelog: [v1.16.1...v1.16.2](https://github.com/openai/openai-python/compare/v1.16.1...v1.16.2) diff --git a/pyproject.toml b/pyproject.toml index 67006726fb..b3043bc0cd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.16.2" +version = "1.17.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 85803a60a6..0c55423216 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.16.2" # x-release-please-version +__version__ = "1.17.0" # x-release-please-version From 35afd5039e230152cc4486729f4e856ed5a76616 Mon Sep 17 00:00:00 2001 From: Zeeland Date: Wed, 10 Apr 2024 18:25:42 +0800 Subject: [PATCH 289/816] chore: fix typo (#1304) --- src/openai/_utils/_proxy.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/openai/_utils/_proxy.py b/src/openai/_utils/_proxy.py index b9c12dc3f4..c46a62a698 100644 --- a/src/openai/_utils/_proxy.py +++ b/src/openai/_utils/_proxy.py @@ -10,7 +10,7 @@ class LazyProxy(Generic[T], ABC): """Implements data methods to pretend that an instance is another instance. - This includes forwarding attribute access and othe methods. + This includes forwarding attribute access and other methods. """ # Note: we have to special case proxies that themselves return proxies From b36b8d869a4e79ee8549476d979cd3322c3695c5 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 12 Apr 2024 12:52:41 -0400 Subject: [PATCH 290/816] chore(internal): formatting (#1311) --- .github/workflows/ci.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ec10edfe36..c44028d96c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,7 +22,7 @@ jobs: echo "$HOME/.rye/shims" >> $GITHUB_PATH env: RYE_VERSION: 0.24.0 - RYE_INSTALL_OPTION: "--yes" + RYE_INSTALL_OPTION: '--yes' - name: Install dependencies run: | @@ -39,3 +39,5 @@ jobs: - name: Ensure importable run: | rye run python -c 'import openai' + + From 595e6b834fe26e08e9ac5415ab15bc19b8661f2c Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 12 Apr 2024 12:53:12 -0400 Subject: [PATCH 291/816] release: 1.17.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 9 +++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 6a197bef5a..3741b313a5 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.17.0" + ".": "1.17.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 0da030b337..7e18ab5f54 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 1.17.1 (2024-04-12) + +Full Changelog: [v1.17.0...v1.17.1](https://github.com/openai/openai-python/compare/v1.17.0...v1.17.1) + +### Chores + +* fix typo ([#1304](https://github.com/openai/openai-python/issues/1304)) ([1129082](https://github.com/openai/openai-python/commit/1129082955f98d76c0927781ef9e7d0beeda2ec4)) +* **internal:** formatting ([#1311](https://github.com/openai/openai-python/issues/1311)) ([8fd411b](https://github.com/openai/openai-python/commit/8fd411b48b6b1eafaab2dac26201525c1ee0b942)) + ## 1.17.0 (2024-04-10) Full Changelog: [v1.16.2...v1.17.0](https://github.com/openai/openai-python/compare/v1.16.2...v1.17.0) diff --git a/pyproject.toml b/pyproject.toml index b3043bc0cd..9eb6330616 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.17.0" +version = "1.17.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 0c55423216..a4ffbb2c35 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.17.0" # x-release-please-version +__version__ = "1.17.1" # x-release-please-version From f5247e30eed8a1ad843c473c7a50f7bb81ffd7b5 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 15 Apr 2024 15:05:04 -0400 Subject: [PATCH 292/816] feat(api): updates (#1314) --- .stats.yml | 2 +- api.md | 40 +- .../resources/beta/assistants/assistants.py | 58 +- .../resources/beta/threads/runs/runs.py | 935 +++++++++++++++++- src/openai/resources/beta/threads/threads.py | 734 +++++++++++++- src/openai/resources/chat/completions.py | 34 +- .../resources/fine_tuning/fine_tuning.py | 1 + .../resources/fine_tuning/jobs/__init__.py | 33 + .../resources/fine_tuning/jobs/checkpoints.py | 176 ++++ .../resources/fine_tuning/{ => jobs}/jobs.py | 72 +- src/openai/types/beta/__init__.py | 12 + src/openai/types/beta/assistant.py | 2 +- .../types/beta/assistant_create_params.py | 32 +- .../types/beta/assistant_response_format.py | 13 + .../beta/assistant_response_format_option.py | 10 + .../assistant_response_format_option_param.py | 12 + .../beta/assistant_response_format_param.py | 12 + .../types/beta/assistant_tool_choice.py | 16 + .../beta/assistant_tool_choice_function.py | 10 + .../assistant_tool_choice_function_param.py | 12 + .../beta/assistant_tool_choice_option.py | 10 + .../assistant_tool_choice_option_param.py | 12 + .../types/beta/assistant_tool_choice_param.py | 16 + .../types/beta/assistant_update_params.py | 2 +- .../beta/thread_create_and_run_params.py | 94 +- src/openai/types/beta/threads/run.py | 87 +- .../types/beta/threads/run_create_params.py | 101 +- .../types/chat/completion_create_params.py | 5 +- src/openai/types/fine_tuning/__init__.py | 5 + .../types/fine_tuning/fine_tuning_job.py | 7 + .../fine_tuning_job_integration.py | 7 + .../fine_tuning_job_wandb_integration.py | 33 + ...ine_tuning_job_wandb_integration_object.py | 21 + .../types/fine_tuning/job_create_params.py | 57 +- src/openai/types/fine_tuning/jobs/__init__.py | 6 + .../jobs/checkpoint_list_params.py | 15 + .../jobs/fine_tuning_job_checkpoint.py | 47 + tests/api_resources/beta/test_assistants.py | 16 +- tests/api_resources/beta/test_threads.py | 40 +- tests/api_resources/beta/threads/test_runs.py | 40 +- tests/api_resources/chat/test_completions.py | 32 +- .../fine_tuning/jobs/__init__.py | 1 + .../fine_tuning/jobs/test_checkpoints.py | 117 +++ tests/api_resources/fine_tuning/test_jobs.py | 60 ++ 44 files changed, 2923 insertions(+), 124 deletions(-) create mode 100644 src/openai/resources/fine_tuning/jobs/__init__.py create mode 100644 src/openai/resources/fine_tuning/jobs/checkpoints.py rename src/openai/resources/fine_tuning/{ => jobs}/jobs.py (89%) create mode 100644 src/openai/types/beta/assistant_response_format.py create mode 100644 src/openai/types/beta/assistant_response_format_option.py create mode 100644 src/openai/types/beta/assistant_response_format_option_param.py create mode 100644 src/openai/types/beta/assistant_response_format_param.py create mode 100644 src/openai/types/beta/assistant_tool_choice.py create mode 100644 src/openai/types/beta/assistant_tool_choice_function.py create mode 100644 src/openai/types/beta/assistant_tool_choice_function_param.py create mode 100644 src/openai/types/beta/assistant_tool_choice_option.py create mode 100644 src/openai/types/beta/assistant_tool_choice_option_param.py create mode 100644 src/openai/types/beta/assistant_tool_choice_param.py create mode 100644 src/openai/types/fine_tuning/fine_tuning_job_integration.py create mode 100644 src/openai/types/fine_tuning/fine_tuning_job_wandb_integration.py create mode 100644 src/openai/types/fine_tuning/fine_tuning_job_wandb_integration_object.py create mode 100644 src/openai/types/fine_tuning/jobs/__init__.py create mode 100644 src/openai/types/fine_tuning/jobs/checkpoint_list_params.py create mode 100644 src/openai/types/fine_tuning/jobs/fine_tuning_job_checkpoint.py create mode 100644 tests/api_resources/fine_tuning/jobs/__init__.py create mode 100644 tests/api_resources/fine_tuning/jobs/test_checkpoints.py diff --git a/.stats.yml b/.stats.yml index c550abf3c6..284caebf44 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1 +1 @@ -configured_endpoints: 51 +configured_endpoints: 52 diff --git a/api.md b/api.md index dbc95cd0b4..cc3c91a8d5 100644 --- a/api.md +++ b/api.md @@ -159,16 +159,34 @@ Methods: Types: ```python -from openai.types.fine_tuning import FineTuningJob, FineTuningJobEvent +from openai.types.fine_tuning import ( + FineTuningJob, + FineTuningJobEvent, + FineTuningJobIntegration, + FineTuningJobWandbIntegration, + FineTuningJobWandbIntegrationObject, +) +``` + +Methods: + +- client.fine_tuning.jobs.create(\*\*params) -> FineTuningJob +- client.fine_tuning.jobs.retrieve(fine_tuning_job_id) -> FineTuningJob +- client.fine_tuning.jobs.list(\*\*params) -> SyncCursorPage[FineTuningJob] +- client.fine_tuning.jobs.cancel(fine_tuning_job_id) -> FineTuningJob +- client.fine_tuning.jobs.list_events(fine_tuning_job_id, \*\*params) -> SyncCursorPage[FineTuningJobEvent] + +### Checkpoints + +Types: + +```python +from openai.types.fine_tuning.jobs import FineTuningJobCheckpoint ``` Methods: -- client.fine_tuning.jobs.create(\*\*params) -> FineTuningJob -- client.fine_tuning.jobs.retrieve(fine_tuning_job_id) -> FineTuningJob -- client.fine_tuning.jobs.list(\*\*params) -> SyncCursorPage[FineTuningJob] -- client.fine_tuning.jobs.cancel(fine_tuning_job_id) -> FineTuningJob -- client.fine_tuning.jobs.list_events(fine_tuning_job_id, \*\*params) -> SyncCursorPage[FineTuningJobEvent] +- client.fine_tuning.jobs.checkpoints.list(fine_tuning_job_id, \*\*params) -> SyncCursorPage[FineTuningJobCheckpoint] # Beta @@ -220,7 +238,15 @@ Methods: Types: ```python -from openai.types.beta import Thread, ThreadDeleted +from openai.types.beta import ( + AssistantResponseFormat, + AssistantResponseFormatOption, + AssistantToolChoice, + AssistantToolChoiceFunction, + AssistantToolChoiceOption, + Thread, + ThreadDeleted, +) ``` Methods: diff --git a/src/openai/resources/beta/assistants/assistants.py b/src/openai/resources/beta/assistants/assistants.py index 232451ab25..9e88794ebc 100644 --- a/src/openai/resources/beta/assistants/assistants.py +++ b/src/openai/resources/beta/assistants/assistants.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import List, Iterable, Optional +from typing import List, Union, Iterable, Optional from typing_extensions import Literal import httpx @@ -57,7 +57,29 @@ def with_streaming_response(self) -> AssistantsWithStreamingResponse: def create( self, *, - model: str, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + ], description: Optional[str] | NotGiven = NOT_GIVEN, file_ids: List[str] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, @@ -87,7 +109,7 @@ def create( attached to this assistant. There can be a maximum of 20 files attached to the assistant. Files are ordered by their creation date in ascending order. - instructions: The system instructions that the assistant uses. The maximum length is 32768 + instructions: The system instructions that the assistant uses. The maximum length is 256,000 characters. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful @@ -194,7 +216,7 @@ def update( file was previously attached to the list but does not show up in the list, it will be deleted from the assistant. - instructions: The system instructions that the assistant uses. The maximum length is 32768 + instructions: The system instructions that the assistant uses. The maximum length is 256,000 characters. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful @@ -360,7 +382,29 @@ def with_streaming_response(self) -> AsyncAssistantsWithStreamingResponse: async def create( self, *, - model: str, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + ], description: Optional[str] | NotGiven = NOT_GIVEN, file_ids: List[str] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, @@ -390,7 +434,7 @@ async def create( attached to this assistant. There can be a maximum of 20 files attached to the assistant. Files are ordered by their creation date in ascending order. - instructions: The system instructions that the assistant uses. The maximum length is 32768 + instructions: The system instructions that the assistant uses. The maximum length is 256,000 characters. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful @@ -497,7 +541,7 @@ async def update( file was previously attached to the list but does not show up in the list, it will be deleted from the assistant. - instructions: The system instructions that the assistant uses. The maximum length is 32768 + instructions: The system instructions that the assistant uses. The maximum length is 256,000 characters. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 8576a5c09a..9fa7239c0b 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -4,7 +4,7 @@ import time import typing_extensions -from typing import Iterable, Optional, overload +from typing import Union, Iterable, Optional, overload from functools import partial from typing_extensions import Literal @@ -31,7 +31,12 @@ from ....._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ....._streaming import Stream, AsyncStream from .....pagination import SyncCursorPage, AsyncCursorPage -from .....types.beta import AssistantToolParam, AssistantStreamEvent +from .....types.beta import ( + AssistantToolParam, + AssistantStreamEvent, + AssistantToolChoiceOptionParam, + AssistantResponseFormatOptionParam, +) from ....._base_client import ( AsyncPaginator, make_request_options, @@ -77,11 +82,40 @@ def create( additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -107,6 +141,18 @@ def create( [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis. + max_completion_tokens: The maximum number of completion tokens that may be used over the course of the + run. The run will make a best effort to use only the number of completion tokens + specified, across multiple turns of the run. If the run exceeds the number of + completion tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + + max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. + The run will make a best effort to use only the number of prompt tokens + specified, across multiple turns of the run. If the run exceeds the number of + prompt tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 @@ -117,6 +163,21 @@ def create( model associated with the assistant. If not, the model associated with the assistant will be used. + response_format: Specifies the format that the model must output. Compatible with + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. + stream: If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. @@ -125,6 +186,13 @@ def create( make the output more random, while lower values like 0.2 will make it more focused and deterministic. + tool_choice: Controls which (if any) tool is called by the model. `none` means the model will + not call any tools and instead generates a message. `auto` is the default value + and means the model can pick between generating a message or calling a tool. + Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + `{"type": "function", "function": {"name": "my_function"}}` forces the model to + call that tool. + tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. @@ -148,10 +216,39 @@ def create( additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -181,6 +278,18 @@ def create( [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis. + max_completion_tokens: The maximum number of completion tokens that may be used over the course of the + run. The run will make a best effort to use only the number of completion tokens + specified, across multiple turns of the run. If the run exceeds the number of + completion tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + + max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. + The run will make a best effort to use only the number of prompt tokens + specified, across multiple turns of the run. If the run exceeds the number of + prompt tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 @@ -191,10 +300,32 @@ def create( model associated with the assistant. If not, the model associated with the assistant will be used. + response_format: Specifies the format that the model must output. Compatible with + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. + tool_choice: Controls which (if any) tool is called by the model. `none` means the model will + not call any tools and instead generates a message. `auto` is the default value + and means the model can pick between generating a message or calling a tool. + Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + `{"type": "function", "function": {"name": "my_function"}}` forces the model to + call that tool. + tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. @@ -218,10 +349,39 @@ def create( additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -251,6 +411,18 @@ def create( [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis. + max_completion_tokens: The maximum number of completion tokens that may be used over the course of the + run. The run will make a best effort to use only the number of completion tokens + specified, across multiple turns of the run. If the run exceeds the number of + completion tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + + max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. + The run will make a best effort to use only the number of prompt tokens + specified, across multiple turns of the run. If the run exceeds the number of + prompt tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 @@ -261,10 +433,32 @@ def create( model associated with the assistant. If not, the model associated with the assistant will be used. + response_format: Specifies the format that the model must output. Compatible with + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. + tool_choice: Controls which (if any) tool is called by the model. `none` means the model will + not call any tools and instead generates a message. `auto` is the default value + and means the model can pick between generating a message or calling a tool. + Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + `{"type": "function", "function": {"name": "my_function"}}` forces the model to + call that tool. + tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. @@ -287,11 +481,40 @@ def create( additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -310,11 +533,16 @@ def create( "additional_instructions": additional_instructions, "additional_messages": additional_messages, "instructions": instructions, + "max_completion_tokens": max_completion_tokens, + "max_prompt_tokens": max_prompt_tokens, "metadata": metadata, "model": model, + "response_format": response_format, "stream": stream, "temperature": temperature, + "tool_choice": tool_choice, "tools": tools, + "truncation_strategy": truncation_strategy, }, run_create_params.RunCreateParams, ), @@ -518,10 +746,39 @@ def create_and_poll( additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, poll_interval_ms: int | NotGiven = NOT_GIVEN, thread_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -542,12 +799,17 @@ def create_and_poll( additional_instructions=additional_instructions, additional_messages=additional_messages, instructions=instructions, + max_completion_tokens=max_completion_tokens, + max_prompt_tokens=max_prompt_tokens, metadata=metadata, model=model, + response_format=response_format, temperature=temperature, + tool_choice=tool_choice, # We assume we are not streaming when polling stream=False, tools=tools, + truncation_strategy=truncation_strategy, extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, @@ -572,10 +834,39 @@ def create_and_stream( additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, thread_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -596,10 +887,39 @@ def create_and_stream( additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, thread_id: str, event_handler: AssistantEventHandlerT, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -620,10 +940,39 @@ def create_and_stream( additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, thread_id: str, event_handler: AssistantEventHandlerT | None = None, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -652,11 +1001,16 @@ def create_and_stream( "additional_instructions": additional_instructions, "additional_messages": additional_messages, "instructions": instructions, + "max_completion_tokens": max_completion_tokens, + "max_prompt_tokens": max_prompt_tokens, "metadata": metadata, "model": model, + "response_format": response_format, "temperature": temperature, + "tool_choice": tool_choice, "stream": True, "tools": tools, + "truncation_strategy": truncation_strategy, }, run_create_params.RunCreateParams, ), @@ -722,10 +1076,39 @@ def stream( additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, thread_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -745,10 +1128,39 @@ def stream( additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, thread_id: str, event_handler: AssistantEventHandlerT, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -768,10 +1180,39 @@ def stream( additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, thread_id: str, event_handler: AssistantEventHandlerT | None = None, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -800,11 +1241,16 @@ def stream( "additional_instructions": additional_instructions, "additional_messages": additional_messages, "instructions": instructions, + "max_completion_tokens": max_completion_tokens, + "max_prompt_tokens": max_prompt_tokens, "metadata": metadata, "model": model, + "response_format": response_format, "temperature": temperature, + "tool_choice": tool_choice, "stream": True, "tools": tools, + "truncation_strategy": truncation_strategy, }, run_create_params.RunCreateParams, ), @@ -1123,11 +1569,40 @@ async def create( additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -1153,6 +1628,18 @@ async def create( [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis. + max_completion_tokens: The maximum number of completion tokens that may be used over the course of the + run. The run will make a best effort to use only the number of completion tokens + specified, across multiple turns of the run. If the run exceeds the number of + completion tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + + max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. + The run will make a best effort to use only the number of prompt tokens + specified, across multiple turns of the run. If the run exceeds the number of + prompt tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 @@ -1163,6 +1650,21 @@ async def create( model associated with the assistant. If not, the model associated with the assistant will be used. + response_format: Specifies the format that the model must output. Compatible with + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. + stream: If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. @@ -1171,6 +1673,13 @@ async def create( make the output more random, while lower values like 0.2 will make it more focused and deterministic. + tool_choice: Controls which (if any) tool is called by the model. `none` means the model will + not call any tools and instead generates a message. `auto` is the default value + and means the model can pick between generating a message or calling a tool. + Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + `{"type": "function", "function": {"name": "my_function"}}` forces the model to + call that tool. + tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. @@ -1194,10 +1703,39 @@ async def create( additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -1227,6 +1765,18 @@ async def create( [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis. + max_completion_tokens: The maximum number of completion tokens that may be used over the course of the + run. The run will make a best effort to use only the number of completion tokens + specified, across multiple turns of the run. If the run exceeds the number of + completion tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + + max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. + The run will make a best effort to use only the number of prompt tokens + specified, across multiple turns of the run. If the run exceeds the number of + prompt tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 @@ -1237,10 +1787,32 @@ async def create( model associated with the assistant. If not, the model associated with the assistant will be used. + response_format: Specifies the format that the model must output. Compatible with + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. + tool_choice: Controls which (if any) tool is called by the model. `none` means the model will + not call any tools and instead generates a message. `auto` is the default value + and means the model can pick between generating a message or calling a tool. + Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + `{"type": "function", "function": {"name": "my_function"}}` forces the model to + call that tool. + tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. @@ -1264,10 +1836,39 @@ async def create( additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -1297,6 +1898,18 @@ async def create( [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis. + max_completion_tokens: The maximum number of completion tokens that may be used over the course of the + run. The run will make a best effort to use only the number of completion tokens + specified, across multiple turns of the run. If the run exceeds the number of + completion tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + + max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. + The run will make a best effort to use only the number of prompt tokens + specified, across multiple turns of the run. If the run exceeds the number of + prompt tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 @@ -1307,10 +1920,32 @@ async def create( model associated with the assistant. If not, the model associated with the assistant will be used. + response_format: Specifies the format that the model must output. Compatible with + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. + tool_choice: Controls which (if any) tool is called by the model. `none` means the model will + not call any tools and instead generates a message. `auto` is the default value + and means the model can pick between generating a message or calling a tool. + Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + `{"type": "function", "function": {"name": "my_function"}}` forces the model to + call that tool. + tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. @@ -1333,11 +1968,40 @@ async def create( additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -1356,11 +2020,16 @@ async def create( "additional_instructions": additional_instructions, "additional_messages": additional_messages, "instructions": instructions, + "max_completion_tokens": max_completion_tokens, + "max_prompt_tokens": max_prompt_tokens, "metadata": metadata, "model": model, + "response_format": response_format, "stream": stream, "temperature": temperature, + "tool_choice": tool_choice, "tools": tools, + "truncation_strategy": truncation_strategy, }, run_create_params.RunCreateParams, ), @@ -1564,10 +2233,39 @@ async def create_and_poll( additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, poll_interval_ms: int | NotGiven = NOT_GIVEN, thread_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -1588,12 +2286,17 @@ async def create_and_poll( additional_instructions=additional_instructions, additional_messages=additional_messages, instructions=instructions, + max_completion_tokens=max_completion_tokens, + max_prompt_tokens=max_prompt_tokens, metadata=metadata, model=model, + response_format=response_format, temperature=temperature, + tool_choice=tool_choice, # We assume we are not streaming when polling stream=False, tools=tools, + truncation_strategy=truncation_strategy, extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, @@ -1618,10 +2321,39 @@ def create_and_stream( additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, thread_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -1642,10 +2374,39 @@ def create_and_stream( additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, thread_id: str, event_handler: AsyncAssistantEventHandlerT, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -1666,10 +2427,39 @@ def create_and_stream( additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, thread_id: str, event_handler: AsyncAssistantEventHandlerT | None = None, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -1700,11 +2490,16 @@ def create_and_stream( "additional_instructions": additional_instructions, "additional_messages": additional_messages, "instructions": instructions, + "max_completion_tokens": max_completion_tokens, + "max_prompt_tokens": max_prompt_tokens, "metadata": metadata, "model": model, + "response_format": response_format, "temperature": temperature, + "tool_choice": tool_choice, "stream": True, "tools": tools, + "truncation_strategy": truncation_strategy, }, run_create_params.RunCreateParams, ), @@ -1770,10 +2565,39 @@ def stream( additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, thread_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -1793,10 +2617,39 @@ def stream( additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, thread_id: str, event_handler: AsyncAssistantEventHandlerT, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -1816,10 +2669,39 @@ def stream( additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, thread_id: str, event_handler: AsyncAssistantEventHandlerT | None = None, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -1850,11 +2732,16 @@ def stream( "additional_instructions": additional_instructions, "additional_messages": additional_messages, "instructions": instructions, + "max_completion_tokens": max_completion_tokens, + "max_prompt_tokens": max_prompt_tokens, "metadata": metadata, "model": model, + "response_format": response_format, "temperature": temperature, + "tool_choice": tool_choice, "stream": True, "tools": tools, + "truncation_strategy": truncation_strategy, }, run_create_params.RunCreateParams, ), diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 3509267d4f..9c2e2f0043 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Iterable, Optional, overload +from typing import Union, Iterable, Optional, overload from functools import partial from typing_extensions import Literal @@ -40,6 +40,8 @@ Thread, ThreadDeleted, AssistantStreamEvent, + AssistantToolChoiceOptionParam, + AssistantResponseFormatOptionParam, thread_create_params, thread_update_params, thread_create_and_run_params, @@ -241,12 +243,41 @@ def create_and_run( *, assistant_id: str, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -265,6 +296,18 @@ def create_and_run( instructions: Override the default system message of the assistant. This is useful for modifying the behavior on a per-run basis. + max_completion_tokens: The maximum number of completion tokens that may be used over the course of the + run. The run will make a best effort to use only the number of completion tokens + specified, across multiple turns of the run. If the run exceeds the number of + completion tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + + max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. + The run will make a best effort to use only the number of prompt tokens + specified, across multiple turns of the run. If the run exceeds the number of + prompt tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 @@ -275,6 +318,21 @@ def create_and_run( model associated with the assistant. If not, the model associated with the assistant will be used. + response_format: Specifies the format that the model must output. Compatible with + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. + stream: If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. @@ -285,6 +343,13 @@ def create_and_run( thread: If no thread is provided, an empty thread will be created. + tool_choice: Controls which (if any) tool is called by the model. `none` means the model will + not call any tools and instead generates a message. `auto` is the default value + and means the model can pick between generating a message or calling a tool. + Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + `{"type": "function", "function": {"name": "my_function"}}` forces the model to + call that tool. + tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. @@ -305,11 +370,40 @@ def create_and_run( assistant_id: str, stream: Literal[True], instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -332,6 +426,18 @@ def create_and_run( instructions: Override the default system message of the assistant. This is useful for modifying the behavior on a per-run basis. + max_completion_tokens: The maximum number of completion tokens that may be used over the course of the + run. The run will make a best effort to use only the number of completion tokens + specified, across multiple turns of the run. If the run exceeds the number of + completion tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + + max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. + The run will make a best effort to use only the number of prompt tokens + specified, across multiple turns of the run. If the run exceeds the number of + prompt tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 @@ -342,12 +448,34 @@ def create_and_run( model associated with the assistant. If not, the model associated with the assistant will be used. + response_format: Specifies the format that the model must output. Compatible with + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. thread: If no thread is provided, an empty thread will be created. + tool_choice: Controls which (if any) tool is called by the model. `none` means the model will + not call any tools and instead generates a message. `auto` is the default value + and means the model can pick between generating a message or calling a tool. + Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + `{"type": "function", "function": {"name": "my_function"}}` forces the model to + call that tool. + tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. @@ -368,11 +496,40 @@ def create_and_run( assistant_id: str, stream: bool, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -395,6 +552,18 @@ def create_and_run( instructions: Override the default system message of the assistant. This is useful for modifying the behavior on a per-run basis. + max_completion_tokens: The maximum number of completion tokens that may be used over the course of the + run. The run will make a best effort to use only the number of completion tokens + specified, across multiple turns of the run. If the run exceeds the number of + completion tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + + max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. + The run will make a best effort to use only the number of prompt tokens + specified, across multiple turns of the run. If the run exceeds the number of + prompt tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 @@ -405,12 +574,34 @@ def create_and_run( model associated with the assistant. If not, the model associated with the assistant will be used. + response_format: Specifies the format that the model must output. Compatible with + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. thread: If no thread is provided, an empty thread will be created. + tool_choice: Controls which (if any) tool is called by the model. `none` means the model will + not call any tools and instead generates a message. `auto` is the default value + and means the model can pick between generating a message or calling a tool. + Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + `{"type": "function", "function": {"name": "my_function"}}` forces the model to + call that tool. + tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. @@ -430,12 +621,41 @@ def create_and_run( *, assistant_id: str, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -450,12 +670,17 @@ def create_and_run( { "assistant_id": assistant_id, "instructions": instructions, + "max_completion_tokens": max_completion_tokens, + "max_prompt_tokens": max_prompt_tokens, "metadata": metadata, "model": model, + "response_format": response_format, "stream": stream, "temperature": temperature, "thread": thread, + "tool_choice": tool_choice, "tools": tools, + "truncation_strategy": truncation_strategy, }, thread_create_and_run_params.ThreadCreateAndRunParams, ), @@ -472,11 +697,40 @@ def create_and_run_poll( *, assistant_id: str, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, poll_interval_ms: int | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -493,11 +747,16 @@ def create_and_run_poll( run = self.create_and_run( assistant_id=assistant_id, instructions=instructions, + max_completion_tokens=max_completion_tokens, + max_prompt_tokens=max_prompt_tokens, metadata=metadata, model=model, + response_format=response_format, temperature=temperature, stream=False, thread=thread, + tool_choice=tool_choice, + truncation_strategy=truncation_strategy, tools=tools, extra_headers=extra_headers, extra_query=extra_query, @@ -512,11 +771,40 @@ def create_and_run_stream( *, assistant_id: str, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -533,11 +821,40 @@ def create_and_run_stream( *, assistant_id: str, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, event_handler: AssistantEventHandlerT, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -554,11 +871,40 @@ def create_and_run_stream( *, assistant_id: str, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, event_handler: AssistantEventHandlerT | None = None, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -581,12 +927,17 @@ def create_and_run_stream( { "assistant_id": assistant_id, "instructions": instructions, + "max_completion_tokens": max_completion_tokens, + "max_prompt_tokens": max_prompt_tokens, "metadata": metadata, "model": model, + "response_format": response_format, "temperature": temperature, + "tool_choice": tool_choice, "stream": True, "thread": thread, "tools": tools, + "truncation_strategy": truncation_strategy, }, thread_create_and_run_params.ThreadCreateAndRunParams, ), @@ -780,12 +1131,41 @@ async def create_and_run( *, assistant_id: str, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -804,6 +1184,18 @@ async def create_and_run( instructions: Override the default system message of the assistant. This is useful for modifying the behavior on a per-run basis. + max_completion_tokens: The maximum number of completion tokens that may be used over the course of the + run. The run will make a best effort to use only the number of completion tokens + specified, across multiple turns of the run. If the run exceeds the number of + completion tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + + max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. + The run will make a best effort to use only the number of prompt tokens + specified, across multiple turns of the run. If the run exceeds the number of + prompt tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 @@ -814,6 +1206,21 @@ async def create_and_run( model associated with the assistant. If not, the model associated with the assistant will be used. + response_format: Specifies the format that the model must output. Compatible with + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. + stream: If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. @@ -824,6 +1231,13 @@ async def create_and_run( thread: If no thread is provided, an empty thread will be created. + tool_choice: Controls which (if any) tool is called by the model. `none` means the model will + not call any tools and instead generates a message. `auto` is the default value + and means the model can pick between generating a message or calling a tool. + Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + `{"type": "function", "function": {"name": "my_function"}}` forces the model to + call that tool. + tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. @@ -844,11 +1258,40 @@ async def create_and_run( assistant_id: str, stream: Literal[True], instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -871,6 +1314,18 @@ async def create_and_run( instructions: Override the default system message of the assistant. This is useful for modifying the behavior on a per-run basis. + max_completion_tokens: The maximum number of completion tokens that may be used over the course of the + run. The run will make a best effort to use only the number of completion tokens + specified, across multiple turns of the run. If the run exceeds the number of + completion tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + + max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. + The run will make a best effort to use only the number of prompt tokens + specified, across multiple turns of the run. If the run exceeds the number of + prompt tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 @@ -881,12 +1336,34 @@ async def create_and_run( model associated with the assistant. If not, the model associated with the assistant will be used. + response_format: Specifies the format that the model must output. Compatible with + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. thread: If no thread is provided, an empty thread will be created. + tool_choice: Controls which (if any) tool is called by the model. `none` means the model will + not call any tools and instead generates a message. `auto` is the default value + and means the model can pick between generating a message or calling a tool. + Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + `{"type": "function", "function": {"name": "my_function"}}` forces the model to + call that tool. + tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. @@ -907,11 +1384,40 @@ async def create_and_run( assistant_id: str, stream: bool, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -934,6 +1440,18 @@ async def create_and_run( instructions: Override the default system message of the assistant. This is useful for modifying the behavior on a per-run basis. + max_completion_tokens: The maximum number of completion tokens that may be used over the course of the + run. The run will make a best effort to use only the number of completion tokens + specified, across multiple turns of the run. If the run exceeds the number of + completion tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + + max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. + The run will make a best effort to use only the number of prompt tokens + specified, across multiple turns of the run. If the run exceeds the number of + prompt tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 @@ -944,12 +1462,34 @@ async def create_and_run( model associated with the assistant. If not, the model associated with the assistant will be used. + response_format: Specifies the format that the model must output. Compatible with + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. thread: If no thread is provided, an empty thread will be created. + tool_choice: Controls which (if any) tool is called by the model. `none` means the model will + not call any tools and instead generates a message. `auto` is the default value + and means the model can pick between generating a message or calling a tool. + Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + `{"type": "function", "function": {"name": "my_function"}}` forces the model to + call that tool. + tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. @@ -969,12 +1509,41 @@ async def create_and_run( *, assistant_id: str, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -989,12 +1558,17 @@ async def create_and_run( { "assistant_id": assistant_id, "instructions": instructions, + "max_completion_tokens": max_completion_tokens, + "max_prompt_tokens": max_prompt_tokens, "metadata": metadata, "model": model, + "response_format": response_format, "stream": stream, "temperature": temperature, "thread": thread, + "tool_choice": tool_choice, "tools": tools, + "truncation_strategy": truncation_strategy, }, thread_create_and_run_params.ThreadCreateAndRunParams, ), @@ -1011,11 +1585,40 @@ async def create_and_run_poll( *, assistant_id: str, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, poll_interval_ms: int | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -1032,11 +1635,16 @@ async def create_and_run_poll( run = await self.create_and_run( assistant_id=assistant_id, instructions=instructions, + max_completion_tokens=max_completion_tokens, + max_prompt_tokens=max_prompt_tokens, metadata=metadata, model=model, + response_format=response_format, temperature=temperature, stream=False, thread=thread, + tool_choice=tool_choice, + truncation_strategy=truncation_strategy, tools=tools, extra_headers=extra_headers, extra_query=extra_query, @@ -1053,11 +1661,40 @@ def create_and_run_stream( *, assistant_id: str, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -1074,11 +1711,40 @@ def create_and_run_stream( *, assistant_id: str, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, event_handler: AsyncAssistantEventHandlerT, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -1095,11 +1761,40 @@ def create_and_run_stream( *, assistant_id: str, instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, + max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Optional[str] | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] + | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, + tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, event_handler: AsyncAssistantEventHandlerT | None = None, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -1124,12 +1819,17 @@ def create_and_run_stream( { "assistant_id": assistant_id, "instructions": instructions, + "max_completion_tokens": max_completion_tokens, + "max_prompt_tokens": max_prompt_tokens, "metadata": metadata, "model": model, + "response_format": response_format, "temperature": temperature, + "tool_choice": tool_choice, "stream": True, "thread": thread, "tools": tools, + "truncation_strategy": truncation_strategy, }, thread_create_and_run_params.ThreadCreateAndRunParams, ), diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index 3000603689..1a23e7876e 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -50,6 +50,8 @@ def create( model: Union[ str, Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", "gpt-4-turbo-preview", "gpt-4-1106-preview", @@ -137,8 +139,7 @@ def create( logprobs: Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the `content` of - `message`. This option is currently not available on the `gpt-4-vision-preview` - model. + `message`. max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the chat completion. @@ -240,6 +241,8 @@ def create( model: Union[ str, Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", "gpt-4-turbo-preview", "gpt-4-1106-preview", @@ -334,8 +337,7 @@ def create( logprobs: Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the `content` of - `message`. This option is currently not available on the `gpt-4-vision-preview` - model. + `message`. max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the chat completion. @@ -430,6 +432,8 @@ def create( model: Union[ str, Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", "gpt-4-turbo-preview", "gpt-4-1106-preview", @@ -524,8 +528,7 @@ def create( logprobs: Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the `content` of - `message`. This option is currently not available on the `gpt-4-vision-preview` - model. + `message`. max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the chat completion. @@ -620,6 +623,8 @@ def create( model: Union[ str, Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", "gpt-4-turbo-preview", "gpt-4-1106-preview", @@ -717,6 +722,8 @@ async def create( model: Union[ str, Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", "gpt-4-turbo-preview", "gpt-4-1106-preview", @@ -804,8 +811,7 @@ async def create( logprobs: Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the `content` of - `message`. This option is currently not available on the `gpt-4-vision-preview` - model. + `message`. max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the chat completion. @@ -907,6 +913,8 @@ async def create( model: Union[ str, Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", "gpt-4-turbo-preview", "gpt-4-1106-preview", @@ -1001,8 +1009,7 @@ async def create( logprobs: Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the `content` of - `message`. This option is currently not available on the `gpt-4-vision-preview` - model. + `message`. max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the chat completion. @@ -1097,6 +1104,8 @@ async def create( model: Union[ str, Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", "gpt-4-turbo-preview", "gpt-4-1106-preview", @@ -1191,8 +1200,7 @@ async def create( logprobs: Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the `content` of - `message`. This option is currently not available on the `gpt-4-vision-preview` - model. + `message`. max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the chat completion. @@ -1287,6 +1295,8 @@ async def create( model: Union[ str, Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", "gpt-4-turbo-preview", "gpt-4-1106-preview", diff --git a/src/openai/resources/fine_tuning/fine_tuning.py b/src/openai/resources/fine_tuning/fine_tuning.py index 659b3e8501..0404fed6ec 100644 --- a/src/openai/resources/fine_tuning/fine_tuning.py +++ b/src/openai/resources/fine_tuning/fine_tuning.py @@ -11,6 +11,7 @@ AsyncJobsWithStreamingResponse, ) from ..._compat import cached_property +from .jobs.jobs import Jobs, AsyncJobs from ..._resource import SyncAPIResource, AsyncAPIResource __all__ = ["FineTuning", "AsyncFineTuning"] diff --git a/src/openai/resources/fine_tuning/jobs/__init__.py b/src/openai/resources/fine_tuning/jobs/__init__.py new file mode 100644 index 0000000000..94cd1fb7e7 --- /dev/null +++ b/src/openai/resources/fine_tuning/jobs/__init__.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .jobs import ( + Jobs, + AsyncJobs, + JobsWithRawResponse, + AsyncJobsWithRawResponse, + JobsWithStreamingResponse, + AsyncJobsWithStreamingResponse, +) +from .checkpoints import ( + Checkpoints, + AsyncCheckpoints, + CheckpointsWithRawResponse, + AsyncCheckpointsWithRawResponse, + CheckpointsWithStreamingResponse, + AsyncCheckpointsWithStreamingResponse, +) + +__all__ = [ + "Checkpoints", + "AsyncCheckpoints", + "CheckpointsWithRawResponse", + "AsyncCheckpointsWithRawResponse", + "CheckpointsWithStreamingResponse", + "AsyncCheckpointsWithStreamingResponse", + "Jobs", + "AsyncJobs", + "JobsWithRawResponse", + "AsyncJobsWithRawResponse", + "JobsWithStreamingResponse", + "AsyncJobsWithStreamingResponse", +] diff --git a/src/openai/resources/fine_tuning/jobs/checkpoints.py b/src/openai/resources/fine_tuning/jobs/checkpoints.py new file mode 100644 index 0000000000..e9ea6aad9a --- /dev/null +++ b/src/openai/resources/fine_tuning/jobs/checkpoints.py @@ -0,0 +1,176 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import httpx + +from .... import _legacy_response +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ...._utils import maybe_transform +from ...._compat import cached_property +from ...._resource import SyncAPIResource, AsyncAPIResource +from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ....pagination import SyncCursorPage, AsyncCursorPage +from ...._base_client import ( + AsyncPaginator, + make_request_options, +) +from ....types.fine_tuning.jobs import FineTuningJobCheckpoint, checkpoint_list_params + +__all__ = ["Checkpoints", "AsyncCheckpoints"] + + +class Checkpoints(SyncAPIResource): + @cached_property + def with_raw_response(self) -> CheckpointsWithRawResponse: + return CheckpointsWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> CheckpointsWithStreamingResponse: + return CheckpointsWithStreamingResponse(self) + + def list( + self, + fine_tuning_job_id: str, + *, + after: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> SyncCursorPage[FineTuningJobCheckpoint]: + """ + List checkpoints for a fine-tuning job. + + Args: + after: Identifier for the last checkpoint ID from the previous pagination request. + + limit: Number of checkpoints to retrieve. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not fine_tuning_job_id: + raise ValueError(f"Expected a non-empty value for `fine_tuning_job_id` but received {fine_tuning_job_id!r}") + return self._get_api_list( + f"/fine_tuning/jobs/{fine_tuning_job_id}/checkpoints", + page=SyncCursorPage[FineTuningJobCheckpoint], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "limit": limit, + }, + checkpoint_list_params.CheckpointListParams, + ), + ), + model=FineTuningJobCheckpoint, + ) + + +class AsyncCheckpoints(AsyncAPIResource): + @cached_property + def with_raw_response(self) -> AsyncCheckpointsWithRawResponse: + return AsyncCheckpointsWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncCheckpointsWithStreamingResponse: + return AsyncCheckpointsWithStreamingResponse(self) + + def list( + self, + fine_tuning_job_id: str, + *, + after: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncPaginator[FineTuningJobCheckpoint, AsyncCursorPage[FineTuningJobCheckpoint]]: + """ + List checkpoints for a fine-tuning job. + + Args: + after: Identifier for the last checkpoint ID from the previous pagination request. + + limit: Number of checkpoints to retrieve. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not fine_tuning_job_id: + raise ValueError(f"Expected a non-empty value for `fine_tuning_job_id` but received {fine_tuning_job_id!r}") + return self._get_api_list( + f"/fine_tuning/jobs/{fine_tuning_job_id}/checkpoints", + page=AsyncCursorPage[FineTuningJobCheckpoint], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "limit": limit, + }, + checkpoint_list_params.CheckpointListParams, + ), + ), + model=FineTuningJobCheckpoint, + ) + + +class CheckpointsWithRawResponse: + def __init__(self, checkpoints: Checkpoints) -> None: + self._checkpoints = checkpoints + + self.list = _legacy_response.to_raw_response_wrapper( + checkpoints.list, + ) + + +class AsyncCheckpointsWithRawResponse: + def __init__(self, checkpoints: AsyncCheckpoints) -> None: + self._checkpoints = checkpoints + + self.list = _legacy_response.async_to_raw_response_wrapper( + checkpoints.list, + ) + + +class CheckpointsWithStreamingResponse: + def __init__(self, checkpoints: Checkpoints) -> None: + self._checkpoints = checkpoints + + self.list = to_streamed_response_wrapper( + checkpoints.list, + ) + + +class AsyncCheckpointsWithStreamingResponse: + def __init__(self, checkpoints: AsyncCheckpoints) -> None: + self._checkpoints = checkpoints + + self.list = async_to_streamed_response_wrapper( + checkpoints.list, + ) diff --git a/src/openai/resources/fine_tuning/jobs.py b/src/openai/resources/fine_tuning/jobs/jobs.py similarity index 89% rename from src/openai/resources/fine_tuning/jobs.py rename to src/openai/resources/fine_tuning/jobs/jobs.py index a0c3e24dac..229f716c48 100644 --- a/src/openai/resources/fine_tuning/jobs.py +++ b/src/openai/resources/fine_tuning/jobs/jobs.py @@ -2,26 +2,34 @@ from __future__ import annotations -from typing import Union, Optional +from typing import Union, Iterable, Optional from typing_extensions import Literal import httpx -from ... import _legacy_response -from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ..._utils import ( +from .... import _legacy_response +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ...._utils import ( maybe_transform, async_maybe_transform, ) -from ..._compat import cached_property -from ..._resource import SyncAPIResource, AsyncAPIResource -from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper -from ...pagination import SyncCursorPage, AsyncCursorPage -from ..._base_client import ( +from ...._compat import cached_property +from .checkpoints import ( + Checkpoints, + AsyncCheckpoints, + CheckpointsWithRawResponse, + AsyncCheckpointsWithRawResponse, + CheckpointsWithStreamingResponse, + AsyncCheckpointsWithStreamingResponse, +) +from ...._resource import SyncAPIResource, AsyncAPIResource +from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ....pagination import SyncCursorPage, AsyncCursorPage +from ...._base_client import ( AsyncPaginator, make_request_options, ) -from ...types.fine_tuning import ( +from ....types.fine_tuning import ( FineTuningJob, FineTuningJobEvent, job_list_params, @@ -33,6 +41,10 @@ class Jobs(SyncAPIResource): + @cached_property + def checkpoints(self) -> Checkpoints: + return Checkpoints(self._client) + @cached_property def with_raw_response(self) -> JobsWithRawResponse: return JobsWithRawResponse(self) @@ -47,6 +59,8 @@ def create( model: Union[str, Literal["babbage-002", "davinci-002", "gpt-3.5-turbo"]], training_file: str, hyperparameters: job_create_params.Hyperparameters | NotGiven = NOT_GIVEN, + integrations: Optional[Iterable[job_create_params.Integration]] | NotGiven = NOT_GIVEN, + seed: Optional[int] | NotGiven = NOT_GIVEN, suffix: Optional[str] | NotGiven = NOT_GIVEN, validation_file: Optional[str] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -82,6 +96,12 @@ def create( hyperparameters: The hyperparameters used for the fine-tuning job. + integrations: A list of integrations to enable for your fine-tuning job. + + seed: The seed controls the reproducibility of the job. Passing in the same seed and + job parameters should produce the same results, but may differ in rare cases. If + a seed is not specified, one will be generated for you. + suffix: A string of up to 18 characters that will be added to your fine-tuned model name. @@ -116,6 +136,8 @@ def create( "model": model, "training_file": training_file, "hyperparameters": hyperparameters, + "integrations": integrations, + "seed": seed, "suffix": suffix, "validation_file": validation_file, }, @@ -294,6 +316,10 @@ def list_events( class AsyncJobs(AsyncAPIResource): + @cached_property + def checkpoints(self) -> AsyncCheckpoints: + return AsyncCheckpoints(self._client) + @cached_property def with_raw_response(self) -> AsyncJobsWithRawResponse: return AsyncJobsWithRawResponse(self) @@ -308,6 +334,8 @@ async def create( model: Union[str, Literal["babbage-002", "davinci-002", "gpt-3.5-turbo"]], training_file: str, hyperparameters: job_create_params.Hyperparameters | NotGiven = NOT_GIVEN, + integrations: Optional[Iterable[job_create_params.Integration]] | NotGiven = NOT_GIVEN, + seed: Optional[int] | NotGiven = NOT_GIVEN, suffix: Optional[str] | NotGiven = NOT_GIVEN, validation_file: Optional[str] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -343,6 +371,12 @@ async def create( hyperparameters: The hyperparameters used for the fine-tuning job. + integrations: A list of integrations to enable for your fine-tuning job. + + seed: The seed controls the reproducibility of the job. Passing in the same seed and + job parameters should produce the same results, but may differ in rare cases. If + a seed is not specified, one will be generated for you. + suffix: A string of up to 18 characters that will be added to your fine-tuned model name. @@ -377,6 +411,8 @@ async def create( "model": model, "training_file": training_file, "hyperparameters": hyperparameters, + "integrations": integrations, + "seed": seed, "suffix": suffix, "validation_file": validation_file, }, @@ -574,6 +610,10 @@ def __init__(self, jobs: Jobs) -> None: jobs.list_events, ) + @cached_property + def checkpoints(self) -> CheckpointsWithRawResponse: + return CheckpointsWithRawResponse(self._jobs.checkpoints) + class AsyncJobsWithRawResponse: def __init__(self, jobs: AsyncJobs) -> None: @@ -595,6 +635,10 @@ def __init__(self, jobs: AsyncJobs) -> None: jobs.list_events, ) + @cached_property + def checkpoints(self) -> AsyncCheckpointsWithRawResponse: + return AsyncCheckpointsWithRawResponse(self._jobs.checkpoints) + class JobsWithStreamingResponse: def __init__(self, jobs: Jobs) -> None: @@ -616,6 +660,10 @@ def __init__(self, jobs: Jobs) -> None: jobs.list_events, ) + @cached_property + def checkpoints(self) -> CheckpointsWithStreamingResponse: + return CheckpointsWithStreamingResponse(self._jobs.checkpoints) + class AsyncJobsWithStreamingResponse: def __init__(self, jobs: AsyncJobs) -> None: @@ -636,3 +684,7 @@ def __init__(self, jobs: AsyncJobs) -> None: self.list_events = async_to_streamed_response_wrapper( jobs.list_events, ) + + @cached_property + def checkpoints(self) -> AsyncCheckpointsWithStreamingResponse: + return AsyncCheckpointsWithStreamingResponse(self._jobs.checkpoints) diff --git a/src/openai/types/beta/__init__.py b/src/openai/types/beta/__init__.py index a7de0272b4..0171694587 100644 --- a/src/openai/types/beta/__init__.py +++ b/src/openai/types/beta/__init__.py @@ -15,9 +15,21 @@ from .thread_create_params import ThreadCreateParams as ThreadCreateParams from .thread_update_params import ThreadUpdateParams as ThreadUpdateParams from .assistant_list_params import AssistantListParams as AssistantListParams +from .assistant_tool_choice import AssistantToolChoice as AssistantToolChoice from .code_interpreter_tool import CodeInterpreterTool as CodeInterpreterTool from .assistant_stream_event import AssistantStreamEvent as AssistantStreamEvent from .assistant_create_params import AssistantCreateParams as AssistantCreateParams from .assistant_update_params import AssistantUpdateParams as AssistantUpdateParams +from .assistant_response_format import AssistantResponseFormat as AssistantResponseFormat +from .assistant_tool_choice_param import AssistantToolChoiceParam as AssistantToolChoiceParam from .code_interpreter_tool_param import CodeInterpreterToolParam as CodeInterpreterToolParam +from .assistant_tool_choice_option import AssistantToolChoiceOption as AssistantToolChoiceOption from .thread_create_and_run_params import ThreadCreateAndRunParams as ThreadCreateAndRunParams +from .assistant_tool_choice_function import AssistantToolChoiceFunction as AssistantToolChoiceFunction +from .assistant_response_format_param import AssistantResponseFormatParam as AssistantResponseFormatParam +from .assistant_response_format_option import AssistantResponseFormatOption as AssistantResponseFormatOption +from .assistant_tool_choice_option_param import AssistantToolChoiceOptionParam as AssistantToolChoiceOptionParam +from .assistant_tool_choice_function_param import AssistantToolChoiceFunctionParam as AssistantToolChoiceFunctionParam +from .assistant_response_format_option_param import ( + AssistantResponseFormatOptionParam as AssistantResponseFormatOptionParam, +) diff --git a/src/openai/types/beta/assistant.py b/src/openai/types/beta/assistant.py index 32561a9aa8..0a0d28ed01 100644 --- a/src/openai/types/beta/assistant.py +++ b/src/openai/types/beta/assistant.py @@ -29,7 +29,7 @@ class Assistant(BaseModel): instructions: Optional[str] = None """The system instructions that the assistant uses. - The maximum length is 32768 characters. + The maximum length is 256,000 characters. """ metadata: Optional[object] = None diff --git a/src/openai/types/beta/assistant_create_params.py b/src/openai/types/beta/assistant_create_params.py index 8bad323640..011121485f 100644 --- a/src/openai/types/beta/assistant_create_params.py +++ b/src/openai/types/beta/assistant_create_params.py @@ -2,8 +2,8 @@ from __future__ import annotations -from typing import List, Iterable, Optional -from typing_extensions import Required, TypedDict +from typing import List, Union, Iterable, Optional +from typing_extensions import Literal, Required, TypedDict from .assistant_tool_param import AssistantToolParam @@ -11,7 +11,31 @@ class AssistantCreateParams(TypedDict, total=False): - model: Required[str] + model: Required[ + Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + ] + ] """ID of the model to use. You can use the @@ -34,7 +58,7 @@ class AssistantCreateParams(TypedDict, total=False): instructions: Optional[str] """The system instructions that the assistant uses. - The maximum length is 32768 characters. + The maximum length is 256,000 characters. """ metadata: Optional[object] diff --git a/src/openai/types/beta/assistant_response_format.py b/src/openai/types/beta/assistant_response_format.py new file mode 100644 index 0000000000..f53bdaf62a --- /dev/null +++ b/src/openai/types/beta/assistant_response_format.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["AssistantResponseFormat"] + + +class AssistantResponseFormat(BaseModel): + type: Optional[Literal["text", "json_object"]] = None + """Must be one of `text` or `json_object`.""" diff --git a/src/openai/types/beta/assistant_response_format_option.py b/src/openai/types/beta/assistant_response_format_option.py new file mode 100644 index 0000000000..d4e05e0ea9 --- /dev/null +++ b/src/openai/types/beta/assistant_response_format_option.py @@ -0,0 +1,10 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Literal + +from .assistant_response_format import AssistantResponseFormat + +__all__ = ["AssistantResponseFormatOption"] + +AssistantResponseFormatOption = Union[Literal["none", "auto"], AssistantResponseFormat] diff --git a/src/openai/types/beta/assistant_response_format_option_param.py b/src/openai/types/beta/assistant_response_format_option_param.py new file mode 100644 index 0000000000..46e04125d1 --- /dev/null +++ b/src/openai/types/beta/assistant_response_format_option_param.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal + +from .assistant_response_format_param import AssistantResponseFormatParam + +__all__ = ["AssistantResponseFormatOptionParam"] + +AssistantResponseFormatOptionParam = Union[Literal["none", "auto"], AssistantResponseFormatParam] diff --git a/src/openai/types/beta/assistant_response_format_param.py b/src/openai/types/beta/assistant_response_format_param.py new file mode 100644 index 0000000000..96e1d02115 --- /dev/null +++ b/src/openai/types/beta/assistant_response_format_param.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, TypedDict + +__all__ = ["AssistantResponseFormatParam"] + + +class AssistantResponseFormatParam(TypedDict, total=False): + type: Literal["text", "json_object"] + """Must be one of `text` or `json_object`.""" diff --git a/src/openai/types/beta/assistant_tool_choice.py b/src/openai/types/beta/assistant_tool_choice.py new file mode 100644 index 0000000000..4314d4b41e --- /dev/null +++ b/src/openai/types/beta/assistant_tool_choice.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel +from .assistant_tool_choice_function import AssistantToolChoiceFunction + +__all__ = ["AssistantToolChoice"] + + +class AssistantToolChoice(BaseModel): + type: Literal["function", "code_interpreter", "retrieval"] + """The type of the tool. If type is `function`, the function name must be set""" + + function: Optional[AssistantToolChoiceFunction] = None diff --git a/src/openai/types/beta/assistant_tool_choice_function.py b/src/openai/types/beta/assistant_tool_choice_function.py new file mode 100644 index 0000000000..87f38310ca --- /dev/null +++ b/src/openai/types/beta/assistant_tool_choice_function.py @@ -0,0 +1,10 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from ..._models import BaseModel + +__all__ = ["AssistantToolChoiceFunction"] + + +class AssistantToolChoiceFunction(BaseModel): + name: str + """The name of the function to call.""" diff --git a/src/openai/types/beta/assistant_tool_choice_function_param.py b/src/openai/types/beta/assistant_tool_choice_function_param.py new file mode 100644 index 0000000000..428857de91 --- /dev/null +++ b/src/openai/types/beta/assistant_tool_choice_function_param.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +__all__ = ["AssistantToolChoiceFunctionParam"] + + +class AssistantToolChoiceFunctionParam(TypedDict, total=False): + name: Required[str] + """The name of the function to call.""" diff --git a/src/openai/types/beta/assistant_tool_choice_option.py b/src/openai/types/beta/assistant_tool_choice_option.py new file mode 100644 index 0000000000..0045a5986e --- /dev/null +++ b/src/openai/types/beta/assistant_tool_choice_option.py @@ -0,0 +1,10 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Literal + +from .assistant_tool_choice import AssistantToolChoice + +__all__ = ["AssistantToolChoiceOption"] + +AssistantToolChoiceOption = Union[Literal["none", "auto"], AssistantToolChoice] diff --git a/src/openai/types/beta/assistant_tool_choice_option_param.py b/src/openai/types/beta/assistant_tool_choice_option_param.py new file mode 100644 index 0000000000..618e7bff98 --- /dev/null +++ b/src/openai/types/beta/assistant_tool_choice_option_param.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal + +from .assistant_tool_choice_param import AssistantToolChoiceParam + +__all__ = ["AssistantToolChoiceOptionParam"] + +AssistantToolChoiceOptionParam = Union[Literal["none", "auto"], AssistantToolChoiceParam] diff --git a/src/openai/types/beta/assistant_tool_choice_param.py b/src/openai/types/beta/assistant_tool_choice_param.py new file mode 100644 index 0000000000..5cf6ea27be --- /dev/null +++ b/src/openai/types/beta/assistant_tool_choice_param.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +from .assistant_tool_choice_function_param import AssistantToolChoiceFunctionParam + +__all__ = ["AssistantToolChoiceParam"] + + +class AssistantToolChoiceParam(TypedDict, total=False): + type: Required[Literal["function", "code_interpreter", "retrieval"]] + """The type of the tool. If type is `function`, the function name must be set""" + + function: AssistantToolChoiceFunctionParam diff --git a/src/openai/types/beta/assistant_update_params.py b/src/openai/types/beta/assistant_update_params.py index 7c96aca8c1..6e9d9ed5db 100644 --- a/src/openai/types/beta/assistant_update_params.py +++ b/src/openai/types/beta/assistant_update_params.py @@ -26,7 +26,7 @@ class AssistantUpdateParams(TypedDict, total=False): instructions: Optional[str] """The system instructions that the assistant uses. - The maximum length is 32768 characters. + The maximum length is 256,000 characters. """ metadata: Optional[object] diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index d4266fc48c..50f947a40a 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -8,12 +8,15 @@ from .function_tool_param import FunctionToolParam from .retrieval_tool_param import RetrievalToolParam from .code_interpreter_tool_param import CodeInterpreterToolParam +from .assistant_tool_choice_option_param import AssistantToolChoiceOptionParam +from .assistant_response_format_option_param import AssistantResponseFormatOptionParam __all__ = [ "ThreadCreateAndRunParamsBase", "Thread", "ThreadMessage", "Tool", + "TruncationStrategy", "ThreadCreateAndRunParamsNonStreaming", "ThreadCreateAndRunParamsStreaming", ] @@ -33,6 +36,24 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): This is useful for modifying the behavior on a per-run basis. """ + max_completion_tokens: Optional[int] + """ + The maximum number of completion tokens that may be used over the course of the + run. The run will make a best effort to use only the number of completion tokens + specified, across multiple turns of the run. If the run exceeds the number of + completion tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + """ + + max_prompt_tokens: Optional[int] + """The maximum number of prompt tokens that may be used over the course of the run. + + The run will make a best effort to use only the number of prompt tokens + specified, across multiple turns of the run. If the run exceeds the number of + prompt tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + """ + metadata: Optional[object] """Set of 16 key-value pairs that can be attached to an object. @@ -41,7 +62,30 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): a maxium of 512 characters long. """ - model: Optional[str] + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] """ The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the @@ -49,6 +93,25 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): assistant will be used. """ + response_format: Optional[AssistantResponseFormatOptionParam] + """Specifies the format that the model must output. + + Compatible with + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. + """ + temperature: Optional[float] """What sampling temperature to use, between 0 and 2. @@ -59,12 +122,24 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): thread: Thread """If no thread is provided, an empty thread will be created.""" + tool_choice: Optional[AssistantToolChoiceOptionParam] + """ + Controls which (if any) tool is called by the model. `none` means the model will + not call any tools and instead generates a message. `auto` is the default value + and means the model can pick between generating a message or calling a tool. + Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + `{"type": "function", "function": {"name": "my_function"}}` forces the model to + call that tool. + """ + tools: Optional[Iterable[Tool]] """Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. """ + truncation_strategy: Optional[TruncationStrategy] + class ThreadMessage(TypedDict, total=False): content: Required[str] @@ -115,6 +190,23 @@ class Thread(TypedDict, total=False): Tool = Union[CodeInterpreterToolParam, RetrievalToolParam, FunctionToolParam] +class TruncationStrategy(TypedDict, total=False): + type: Required[Literal["auto", "last_messages"]] + """The truncation strategy to use for the thread. + + The default is `auto`. If set to `last_messages`, the thread will be truncated + to the n most recent messages in the thread. When set to `auto`, messages in the + middle of the thread will be dropped to fit the context length of the model, + `max_prompt_tokens`. + """ + + last_messages: Optional[int] + """ + The number of most recent messages from the thread when constructing the context + for the run. + """ + + class ThreadCreateAndRunParamsNonStreaming(ThreadCreateAndRunParamsBase): stream: Optional[Literal[False]] """ diff --git a/src/openai/types/beta/threads/run.py b/src/openai/types/beta/threads/run.py index 3ab276245f..2efc3c77fa 100644 --- a/src/openai/types/beta/threads/run.py +++ b/src/openai/types/beta/threads/run.py @@ -6,9 +6,28 @@ from ...._models import BaseModel from .run_status import RunStatus from ..assistant_tool import AssistantTool +from ..assistant_tool_choice_option import AssistantToolChoiceOption +from ..assistant_response_format_option import AssistantResponseFormatOption from .required_action_function_tool_call import RequiredActionFunctionToolCall -__all__ = ["Run", "LastError", "RequiredAction", "RequiredActionSubmitToolOutputs", "Usage"] +__all__ = [ + "Run", + "IncompleteDetails", + "LastError", + "RequiredAction", + "RequiredActionSubmitToolOutputs", + "TruncationStrategy", + "Usage", +] + + +class IncompleteDetails(BaseModel): + reason: Optional[Literal["max_completion_tokens", "max_prompt_tokens"]] = None + """The reason why the run is incomplete. + + This will point to which specific token limit was reached over the course of the + run. + """ class LastError(BaseModel): @@ -32,6 +51,23 @@ class RequiredAction(BaseModel): """For now, this is always `submit_tool_outputs`.""" +class TruncationStrategy(BaseModel): + type: Literal["auto", "last_messages"] + """The truncation strategy to use for the thread. + + The default is `auto`. If set to `last_messages`, the thread will be truncated + to the n most recent messages in the thread. When set to `auto`, messages in the + middle of the thread will be dropped to fit the context length of the model, + `max_prompt_tokens`. + """ + + last_messages: Optional[int] = None + """ + The number of most recent messages from the thread when constructing the context + for the run. + """ + + class Usage(BaseModel): completion_tokens: int """Number of completion tokens used over the course of the run.""" @@ -76,6 +112,12 @@ class Run(BaseModel): this run. """ + incomplete_details: Optional[IncompleteDetails] = None + """Details on why the run is incomplete. + + Will be `null` if the run is not incomplete. + """ + instructions: str """ The instructions that the @@ -86,6 +128,18 @@ class Run(BaseModel): last_error: Optional[LastError] = None """The last error associated with this run. Will be `null` if there are no errors.""" + max_completion_tokens: Optional[int] = None + """ + The maximum number of completion tokens specified to have been used over the + course of the run. + """ + + max_prompt_tokens: Optional[int] = None + """ + The maximum number of prompt tokens specified to have been used over the course + of the run. + """ + metadata: Optional[object] = None """Set of 16 key-value pairs that can be attached to an object. @@ -110,6 +164,25 @@ class Run(BaseModel): Will be `null` if no action is required. """ + response_format: Optional[AssistantResponseFormatOption] = None + """Specifies the format that the model must output. + + Compatible with + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. + """ + started_at: Optional[int] = None """The Unix timestamp (in seconds) for when the run was started.""" @@ -126,6 +199,16 @@ class Run(BaseModel): that was executed on as a part of this run. """ + tool_choice: Optional[AssistantToolChoiceOption] = None + """ + Controls which (if any) tool is called by the model. `none` means the model will + not call any tools and instead generates a message. `auto` is the default value + and means the model can pick between generating a message or calling a tool. + Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + `{"type": "function", "function": {"name": "my_function"}}` forces the model to + call that tool. + """ + tools: List[AssistantTool] """ The list of tools that the @@ -133,6 +216,8 @@ class Run(BaseModel): this run. """ + truncation_strategy: Optional[TruncationStrategy] = None + usage: Optional[Usage] = None """Usage statistics related to the run. diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index e9bc19d980..9f2d4ba18b 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -6,8 +6,16 @@ from typing_extensions import Literal, Required, TypedDict from ..assistant_tool_param import AssistantToolParam +from ..assistant_tool_choice_option_param import AssistantToolChoiceOptionParam +from ..assistant_response_format_option_param import AssistantResponseFormatOptionParam -__all__ = ["RunCreateParamsBase", "AdditionalMessage", "RunCreateParamsNonStreaming", "RunCreateParamsStreaming"] +__all__ = [ + "RunCreateParamsBase", + "AdditionalMessage", + "TruncationStrategy", + "RunCreateParamsNonStreaming", + "RunCreateParamsStreaming", +] class RunCreateParamsBase(TypedDict, total=False): @@ -35,6 +43,24 @@ class RunCreateParamsBase(TypedDict, total=False): of the assistant. This is useful for modifying the behavior on a per-run basis. """ + max_completion_tokens: Optional[int] + """ + The maximum number of completion tokens that may be used over the course of the + run. The run will make a best effort to use only the number of completion tokens + specified, across multiple turns of the run. If the run exceeds the number of + completion tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + """ + + max_prompt_tokens: Optional[int] + """The maximum number of prompt tokens that may be used over the course of the run. + + The run will make a best effort to use only the number of prompt tokens + specified, across multiple turns of the run. If the run exceeds the number of + prompt tokens specified, the run will end with status `complete`. See + `incomplete_details` for more info. + """ + metadata: Optional[object] """Set of 16 key-value pairs that can be attached to an object. @@ -43,7 +69,30 @@ class RunCreateParamsBase(TypedDict, total=False): a maxium of 512 characters long. """ - model: Optional[str] + model: Union[ + str, + Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + None, + ] """ The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the @@ -51,6 +100,25 @@ class RunCreateParamsBase(TypedDict, total=False): assistant will be used. """ + response_format: Optional[AssistantResponseFormatOptionParam] + """Specifies the format that the model must output. + + Compatible with + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. + """ + temperature: Optional[float] """What sampling temperature to use, between 0 and 2. @@ -58,12 +126,24 @@ class RunCreateParamsBase(TypedDict, total=False): 0.2 will make it more focused and deterministic. """ + tool_choice: Optional[AssistantToolChoiceOptionParam] + """ + Controls which (if any) tool is called by the model. `none` means the model will + not call any tools and instead generates a message. `auto` is the default value + and means the model can pick between generating a message or calling a tool. + Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + `{"type": "function", "function": {"name": "my_function"}}` forces the model to + call that tool. + """ + tools: Optional[Iterable[AssistantToolParam]] """Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. """ + truncation_strategy: Optional[TruncationStrategy] + class AdditionalMessage(TypedDict, total=False): content: Required[str] @@ -95,6 +175,23 @@ class AdditionalMessage(TypedDict, total=False): """ +class TruncationStrategy(TypedDict, total=False): + type: Required[Literal["auto", "last_messages"]] + """The truncation strategy to use for the thread. + + The default is `auto`. If set to `last_messages`, the thread will be truncated + to the n most recent messages in the thread. When set to `auto`, messages in the + middle of the thread will be dropped to fit the context length of the model, + `max_prompt_tokens`. + """ + + last_messages: Optional[int] + """ + The number of most recent messages from the thread when constructing the context + for the run. + """ + + class RunCreateParamsNonStreaming(RunCreateParamsBase): stream: Optional[Literal[False]] """ diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index ab6a747021..1e0f7f8195 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -32,6 +32,8 @@ class CompletionCreateParamsBase(TypedDict, total=False): Union[ str, Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", "gpt-4-turbo-preview", "gpt-4-1106-preview", @@ -102,8 +104,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): """Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the - `content` of `message`. This option is currently not available on the - `gpt-4-vision-preview` model. + `content` of `message`. """ max_tokens: Optional[int] diff --git a/src/openai/types/fine_tuning/__init__.py b/src/openai/types/fine_tuning/__init__.py index 0bb2b90438..92b81329b1 100644 --- a/src/openai/types/fine_tuning/__init__.py +++ b/src/openai/types/fine_tuning/__init__.py @@ -7,3 +7,8 @@ from .job_create_params import JobCreateParams as JobCreateParams from .fine_tuning_job_event import FineTuningJobEvent as FineTuningJobEvent from .job_list_events_params import JobListEventsParams as JobListEventsParams +from .fine_tuning_job_integration import FineTuningJobIntegration as FineTuningJobIntegration +from .fine_tuning_job_wandb_integration import FineTuningJobWandbIntegration as FineTuningJobWandbIntegration +from .fine_tuning_job_wandb_integration_object import ( + FineTuningJobWandbIntegrationObject as FineTuningJobWandbIntegrationObject, +) diff --git a/src/openai/types/fine_tuning/fine_tuning_job.py b/src/openai/types/fine_tuning/fine_tuning_job.py index 23fe96d1a0..1593bf50c7 100644 --- a/src/openai/types/fine_tuning/fine_tuning_job.py +++ b/src/openai/types/fine_tuning/fine_tuning_job.py @@ -4,6 +4,7 @@ from typing_extensions import Literal from ..._models import BaseModel +from .fine_tuning_job_wandb_integration_object import FineTuningJobWandbIntegrationObject __all__ = ["FineTuningJob", "Error", "Hyperparameters"] @@ -80,6 +81,9 @@ class FineTuningJob(BaseModel): [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). """ + seed: int + """The seed used for the fine-tuning job.""" + status: Literal["validating_files", "queued", "running", "succeeded", "failed", "cancelled"] """ The current status of the fine-tuning job, which can be either @@ -105,3 +109,6 @@ class FineTuningJob(BaseModel): You can retrieve the validation results with the [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). """ + + integrations: Optional[List[FineTuningJobWandbIntegrationObject]] = None + """A list of integrations to enable for this fine-tuning job.""" diff --git a/src/openai/types/fine_tuning/fine_tuning_job_integration.py b/src/openai/types/fine_tuning/fine_tuning_job_integration.py new file mode 100644 index 0000000000..8076313cae --- /dev/null +++ b/src/openai/types/fine_tuning/fine_tuning_job_integration.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +from .fine_tuning_job_wandb_integration_object import FineTuningJobWandbIntegrationObject + +FineTuningJobIntegration = FineTuningJobWandbIntegrationObject diff --git a/src/openai/types/fine_tuning/fine_tuning_job_wandb_integration.py b/src/openai/types/fine_tuning/fine_tuning_job_wandb_integration.py new file mode 100644 index 0000000000..4ac282eb54 --- /dev/null +++ b/src/openai/types/fine_tuning/fine_tuning_job_wandb_integration.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from ..._models import BaseModel + +__all__ = ["FineTuningJobWandbIntegration"] + + +class FineTuningJobWandbIntegration(BaseModel): + project: str + """The name of the project that the new run will be created under.""" + + entity: Optional[str] = None + """The entity to use for the run. + + This allows you to set the team or username of the WandB user that you would + like associated with the run. If not set, the default entity for the registered + WandB API key is used. + """ + + name: Optional[str] = None + """A display name to set for the run. + + If not set, we will use the Job ID as the name. + """ + + tags: Optional[List[str]] = None + """A list of tags to be attached to the newly created run. + + These tags are passed through directly to WandB. Some default tags are generated + by OpenAI: "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". + """ diff --git a/src/openai/types/fine_tuning/fine_tuning_job_wandb_integration_object.py b/src/openai/types/fine_tuning/fine_tuning_job_wandb_integration_object.py new file mode 100644 index 0000000000..5b94354d50 --- /dev/null +++ b/src/openai/types/fine_tuning/fine_tuning_job_wandb_integration_object.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel +from .fine_tuning_job_wandb_integration import FineTuningJobWandbIntegration + +__all__ = ["FineTuningJobWandbIntegrationObject"] + + +class FineTuningJobWandbIntegrationObject(BaseModel): + type: Literal["wandb"] + """The type of the integration being enabled for the fine-tuning job""" + + wandb: FineTuningJobWandbIntegration + """The settings for your integration with Weights and Biases. + + This payload specifies the project that metrics will be sent to. Optionally, you + can set an explicit display name for your run, add tags to your run, and set a + default entity (team, username, etc) to be associated with your run. + """ diff --git a/src/openai/types/fine_tuning/job_create_params.py b/src/openai/types/fine_tuning/job_create_params.py index 79e0b67e13..892c737fa3 100644 --- a/src/openai/types/fine_tuning/job_create_params.py +++ b/src/openai/types/fine_tuning/job_create_params.py @@ -2,10 +2,10 @@ from __future__ import annotations -from typing import Union, Optional +from typing import List, Union, Iterable, Optional from typing_extensions import Literal, Required, TypedDict -__all__ = ["JobCreateParams", "Hyperparameters"] +__all__ = ["JobCreateParams", "Hyperparameters", "Integration", "IntegrationWandb"] class JobCreateParams(TypedDict, total=False): @@ -32,6 +32,17 @@ class JobCreateParams(TypedDict, total=False): hyperparameters: Hyperparameters """The hyperparameters used for the fine-tuning job.""" + integrations: Optional[Iterable[Integration]] + """A list of integrations to enable for your fine-tuning job.""" + + seed: Optional[int] + """The seed controls the reproducibility of the job. + + Passing in the same seed and job parameters should produce the same results, but + may differ in rare cases. If a seed is not specified, one will be generated for + you. + """ + suffix: Optional[str] """ A string of up to 18 characters that will be added to your fine-tuned model @@ -76,3 +87,45 @@ class Hyperparameters(TypedDict, total=False): An epoch refers to one full cycle through the training dataset. """ + + +class IntegrationWandb(TypedDict, total=False): + project: Required[str] + """The name of the project that the new run will be created under.""" + + entity: Optional[str] + """The entity to use for the run. + + This allows you to set the team or username of the WandB user that you would + like associated with the run. If not set, the default entity for the registered + WandB API key is used. + """ + + name: Optional[str] + """A display name to set for the run. + + If not set, we will use the Job ID as the name. + """ + + tags: List[str] + """A list of tags to be attached to the newly created run. + + These tags are passed through directly to WandB. Some default tags are generated + by OpenAI: "openai/finetune", "openai/{base-model}", "openai/{ftjob-abcdef}". + """ + + +class Integration(TypedDict, total=False): + type: Required[Literal["wandb"]] + """The type of integration to enable. + + Currently, only "wandb" (Weights and Biases) is supported. + """ + + wandb: Required[IntegrationWandb] + """The settings for your integration with Weights and Biases. + + This payload specifies the project that metrics will be sent to. Optionally, you + can set an explicit display name for your run, add tags to your run, and set a + default entity (team, username, etc) to be associated with your run. + """ diff --git a/src/openai/types/fine_tuning/jobs/__init__.py b/src/openai/types/fine_tuning/jobs/__init__.py new file mode 100644 index 0000000000..6c93da1b69 --- /dev/null +++ b/src/openai/types/fine_tuning/jobs/__init__.py @@ -0,0 +1,6 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .checkpoint_list_params import CheckpointListParams as CheckpointListParams +from .fine_tuning_job_checkpoint import FineTuningJobCheckpoint as FineTuningJobCheckpoint diff --git a/src/openai/types/fine_tuning/jobs/checkpoint_list_params.py b/src/openai/types/fine_tuning/jobs/checkpoint_list_params.py new file mode 100644 index 0000000000..adceb3b218 --- /dev/null +++ b/src/openai/types/fine_tuning/jobs/checkpoint_list_params.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["CheckpointListParams"] + + +class CheckpointListParams(TypedDict, total=False): + after: str + """Identifier for the last checkpoint ID from the previous pagination request.""" + + limit: int + """Number of checkpoints to retrieve.""" diff --git a/src/openai/types/fine_tuning/jobs/fine_tuning_job_checkpoint.py b/src/openai/types/fine_tuning/jobs/fine_tuning_job_checkpoint.py new file mode 100644 index 0000000000..bd07317a3e --- /dev/null +++ b/src/openai/types/fine_tuning/jobs/fine_tuning_job_checkpoint.py @@ -0,0 +1,47 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["FineTuningJobCheckpoint", "Metrics"] + + +class Metrics(BaseModel): + full_valid_loss: Optional[float] = None + + full_valid_mean_token_accuracy: Optional[float] = None + + step: Optional[float] = None + + train_loss: Optional[float] = None + + train_mean_token_accuracy: Optional[float] = None + + valid_loss: Optional[float] = None + + valid_mean_token_accuracy: Optional[float] = None + + +class FineTuningJobCheckpoint(BaseModel): + id: str + """The checkpoint identifier, which can be referenced in the API endpoints.""" + + created_at: int + """The Unix timestamp (in seconds) for when the checkpoint was created.""" + + fine_tuned_model_checkpoint: str + """The name of the fine-tuned checkpoint model that is created.""" + + fine_tuning_job_id: str + """The name of the fine-tuning job that this checkpoint was created from.""" + + metrics: Metrics + """Metrics at the step number during the fine-tuning job.""" + + object: Literal["fine_tuning.job.checkpoint"] + """The object type, which is always "fine_tuning.job.checkpoint".""" + + step_number: int + """The step number that the checkpoint was created at.""" diff --git a/tests/api_resources/beta/test_assistants.py b/tests/api_resources/beta/test_assistants.py index 6edbe4b491..a509627b8e 100644 --- a/tests/api_resources/beta/test_assistants.py +++ b/tests/api_resources/beta/test_assistants.py @@ -24,14 +24,14 @@ class TestAssistants: @parametrize def test_method_create(self, client: OpenAI) -> None: assistant = client.beta.assistants.create( - model="string", + model="gpt-4-turbo", ) assert_matches_type(Assistant, assistant, path=["response"]) @parametrize def test_method_create_with_all_params(self, client: OpenAI) -> None: assistant = client.beta.assistants.create( - model="string", + model="gpt-4-turbo", description="string", file_ids=["string", "string", "string"], instructions="string", @@ -44,7 +44,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: @parametrize def test_raw_response_create(self, client: OpenAI) -> None: response = client.beta.assistants.with_raw_response.create( - model="string", + model="gpt-4-turbo", ) assert response.is_closed is True @@ -55,7 +55,7 @@ def test_raw_response_create(self, client: OpenAI) -> None: @parametrize def test_streaming_response_create(self, client: OpenAI) -> None: with client.beta.assistants.with_streaming_response.create( - model="string", + model="gpt-4-turbo", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -235,14 +235,14 @@ class TestAsyncAssistants: @parametrize async def test_method_create(self, async_client: AsyncOpenAI) -> None: assistant = await async_client.beta.assistants.create( - model="string", + model="gpt-4-turbo", ) assert_matches_type(Assistant, assistant, path=["response"]) @parametrize async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: assistant = await async_client.beta.assistants.create( - model="string", + model="gpt-4-turbo", description="string", file_ids=["string", "string", "string"], instructions="string", @@ -255,7 +255,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> @parametrize async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: response = await async_client.beta.assistants.with_raw_response.create( - model="string", + model="gpt-4-turbo", ) assert response.is_closed is True @@ -266,7 +266,7 @@ async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: async with async_client.beta.assistants.with_streaming_response.create( - model="string", + model="gpt-4-turbo", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" diff --git a/tests/api_resources/beta/test_threads.py b/tests/api_resources/beta/test_threads.py index fd3f7c5102..7c07251433 100644 --- a/tests/api_resources/beta/test_threads.py +++ b/tests/api_resources/beta/test_threads.py @@ -207,8 +207,11 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) thread = client.beta.threads.create_and_run( assistant_id="string", instructions="string", + max_completion_tokens=256, + max_prompt_tokens=256, metadata={}, - model="string", + model="gpt-4-turbo", + response_format="none", stream=False, temperature=1, thread={ @@ -234,7 +237,12 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) ], "metadata": {}, }, + tool_choice="none", tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + truncation_strategy={ + "type": "auto", + "last_messages": 1, + }, ) assert_matches_type(Run, thread, path=["response"]) @@ -276,8 +284,11 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) assistant_id="string", stream=True, instructions="string", + max_completion_tokens=256, + max_prompt_tokens=256, metadata={}, - model="string", + model="gpt-4-turbo", + response_format="none", temperature=1, thread={ "messages": [ @@ -302,7 +313,12 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) ], "metadata": {}, }, + tool_choice="none", tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + truncation_strategy={ + "type": "auto", + "last_messages": 1, + }, ) thread_stream.response.close() @@ -521,8 +537,11 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie thread = await async_client.beta.threads.create_and_run( assistant_id="string", instructions="string", + max_completion_tokens=256, + max_prompt_tokens=256, metadata={}, - model="string", + model="gpt-4-turbo", + response_format="none", stream=False, temperature=1, thread={ @@ -548,7 +567,12 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie ], "metadata": {}, }, + tool_choice="none", tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + truncation_strategy={ + "type": "auto", + "last_messages": 1, + }, ) assert_matches_type(Run, thread, path=["response"]) @@ -590,8 +614,11 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie assistant_id="string", stream=True, instructions="string", + max_completion_tokens=256, + max_prompt_tokens=256, metadata={}, - model="string", + model="gpt-4-turbo", + response_format="none", temperature=1, thread={ "messages": [ @@ -616,7 +643,12 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie ], "metadata": {}, }, + tool_choice="none", tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + truncation_strategy={ + "type": "auto", + "last_messages": 1, + }, ) await thread_stream.response.aclose() diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index 271bcccdd3..cf5b2998b9 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -57,11 +57,19 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: }, ], instructions="string", + max_completion_tokens=256, + max_prompt_tokens=256, metadata={}, - model="string", + model="gpt-4-turbo", + response_format="none", stream=False, temperature=1, + tool_choice="none", tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + truncation_strategy={ + "type": "auto", + "last_messages": 1, + }, ) assert_matches_type(Run, run, path=["response"]) @@ -136,10 +144,18 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: }, ], instructions="string", + max_completion_tokens=256, + max_prompt_tokens=256, metadata={}, - model="string", + model="gpt-4-turbo", + response_format="none", temperature=1, + tool_choice="none", tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + truncation_strategy={ + "type": "auto", + "last_messages": 1, + }, ) run_stream.response.close() @@ -553,11 +569,19 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn }, ], instructions="string", + max_completion_tokens=256, + max_prompt_tokens=256, metadata={}, - model="string", + model="gpt-4-turbo", + response_format="none", stream=False, temperature=1, + tool_choice="none", tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + truncation_strategy={ + "type": "auto", + "last_messages": 1, + }, ) assert_matches_type(Run, run, path=["response"]) @@ -632,10 +656,18 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn }, ], instructions="string", + max_completion_tokens=256, + max_prompt_tokens=256, metadata={}, - model="string", + model="gpt-4-turbo", + response_format="none", temperature=1, + tool_choice="none", tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + truncation_strategy={ + "type": "auto", + "last_messages": 1, + }, ) await run_stream.response.aclose() diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index bb0658f3d9..c54b56a37d 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -26,7 +26,7 @@ def test_method_create_overload_1(self, client: OpenAI) -> None: "role": "system", } ], - model="gpt-3.5-turbo", + model="gpt-4-turbo", ) assert_matches_type(ChatCompletion, completion, path=["response"]) @@ -40,7 +40,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: "name": "string", } ], - model="gpt-3.5-turbo", + model="gpt-4-turbo", frequency_penalty=-2, function_call="none", functions=[ @@ -102,7 +102,7 @@ def test_raw_response_create_overload_1(self, client: OpenAI) -> None: "role": "system", } ], - model="gpt-3.5-turbo", + model="gpt-4-turbo", ) assert response.is_closed is True @@ -119,7 +119,7 @@ def test_streaming_response_create_overload_1(self, client: OpenAI) -> None: "role": "system", } ], - model="gpt-3.5-turbo", + model="gpt-4-turbo", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -138,7 +138,7 @@ def test_method_create_overload_2(self, client: OpenAI) -> None: "role": "system", } ], - model="gpt-3.5-turbo", + model="gpt-4-turbo", stream=True, ) completion_stream.response.close() @@ -153,7 +153,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: "name": "string", } ], - model="gpt-3.5-turbo", + model="gpt-4-turbo", stream=True, frequency_penalty=-2, function_call="none", @@ -215,7 +215,7 @@ def test_raw_response_create_overload_2(self, client: OpenAI) -> None: "role": "system", } ], - model="gpt-3.5-turbo", + model="gpt-4-turbo", stream=True, ) @@ -232,7 +232,7 @@ def test_streaming_response_create_overload_2(self, client: OpenAI) -> None: "role": "system", } ], - model="gpt-3.5-turbo", + model="gpt-4-turbo", stream=True, ) as response: assert not response.is_closed @@ -256,7 +256,7 @@ async def test_method_create_overload_1(self, async_client: AsyncOpenAI) -> None "role": "system", } ], - model="gpt-3.5-turbo", + model="gpt-4-turbo", ) assert_matches_type(ChatCompletion, completion, path=["response"]) @@ -270,7 +270,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn "name": "string", } ], - model="gpt-3.5-turbo", + model="gpt-4-turbo", frequency_penalty=-2, function_call="none", functions=[ @@ -332,7 +332,7 @@ async def test_raw_response_create_overload_1(self, async_client: AsyncOpenAI) - "role": "system", } ], - model="gpt-3.5-turbo", + model="gpt-4-turbo", ) assert response.is_closed is True @@ -349,7 +349,7 @@ async def test_streaming_response_create_overload_1(self, async_client: AsyncOpe "role": "system", } ], - model="gpt-3.5-turbo", + model="gpt-4-turbo", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -368,7 +368,7 @@ async def test_method_create_overload_2(self, async_client: AsyncOpenAI) -> None "role": "system", } ], - model="gpt-3.5-turbo", + model="gpt-4-turbo", stream=True, ) await completion_stream.response.aclose() @@ -383,7 +383,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn "name": "string", } ], - model="gpt-3.5-turbo", + model="gpt-4-turbo", stream=True, frequency_penalty=-2, function_call="none", @@ -445,7 +445,7 @@ async def test_raw_response_create_overload_2(self, async_client: AsyncOpenAI) - "role": "system", } ], - model="gpt-3.5-turbo", + model="gpt-4-turbo", stream=True, ) @@ -462,7 +462,7 @@ async def test_streaming_response_create_overload_2(self, async_client: AsyncOpe "role": "system", } ], - model="gpt-3.5-turbo", + model="gpt-4-turbo", stream=True, ) as response: assert not response.is_closed diff --git a/tests/api_resources/fine_tuning/jobs/__init__.py b/tests/api_resources/fine_tuning/jobs/__init__.py new file mode 100644 index 0000000000..fd8019a9a1 --- /dev/null +++ b/tests/api_resources/fine_tuning/jobs/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/fine_tuning/jobs/test_checkpoints.py b/tests/api_resources/fine_tuning/jobs/test_checkpoints.py new file mode 100644 index 0000000000..915d5c6f63 --- /dev/null +++ b/tests/api_resources/fine_tuning/jobs/test_checkpoints.py @@ -0,0 +1,117 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai.pagination import SyncCursorPage, AsyncCursorPage +from openai.types.fine_tuning.jobs import FineTuningJobCheckpoint + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") + + +class TestCheckpoints: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + def test_method_list(self, client: OpenAI) -> None: + checkpoint = client.fine_tuning.jobs.checkpoints.list( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert_matches_type(SyncCursorPage[FineTuningJobCheckpoint], checkpoint, path=["response"]) + + @parametrize + def test_method_list_with_all_params(self, client: OpenAI) -> None: + checkpoint = client.fine_tuning.jobs.checkpoints.list( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + after="string", + limit=0, + ) + assert_matches_type(SyncCursorPage[FineTuningJobCheckpoint], checkpoint, path=["response"]) + + @parametrize + def test_raw_response_list(self, client: OpenAI) -> None: + response = client.fine_tuning.jobs.checkpoints.with_raw_response.list( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + checkpoint = response.parse() + assert_matches_type(SyncCursorPage[FineTuningJobCheckpoint], checkpoint, path=["response"]) + + @parametrize + def test_streaming_response_list(self, client: OpenAI) -> None: + with client.fine_tuning.jobs.checkpoints.with_streaming_response.list( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + checkpoint = response.parse() + assert_matches_type(SyncCursorPage[FineTuningJobCheckpoint], checkpoint, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_list(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `fine_tuning_job_id` but received ''"): + client.fine_tuning.jobs.checkpoints.with_raw_response.list( + "", + ) + + +class TestAsyncCheckpoints: + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + async def test_method_list(self, async_client: AsyncOpenAI) -> None: + checkpoint = await async_client.fine_tuning.jobs.checkpoints.list( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert_matches_type(AsyncCursorPage[FineTuningJobCheckpoint], checkpoint, path=["response"]) + + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: + checkpoint = await async_client.fine_tuning.jobs.checkpoints.list( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + after="string", + limit=0, + ) + assert_matches_type(AsyncCursorPage[FineTuningJobCheckpoint], checkpoint, path=["response"]) + + @parametrize + async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: + response = await async_client.fine_tuning.jobs.checkpoints.with_raw_response.list( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + checkpoint = response.parse() + assert_matches_type(AsyncCursorPage[FineTuningJobCheckpoint], checkpoint, path=["response"]) + + @parametrize + async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: + async with async_client.fine_tuning.jobs.checkpoints.with_streaming_response.list( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + checkpoint = await response.parse() + assert_matches_type(AsyncCursorPage[FineTuningJobCheckpoint], checkpoint, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_list(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `fine_tuning_job_id` but received ''"): + await async_client.fine_tuning.jobs.checkpoints.with_raw_response.list( + "", + ) diff --git a/tests/api_resources/fine_tuning/test_jobs.py b/tests/api_resources/fine_tuning/test_jobs.py index f4974ebbcd..1ff6d63b31 100644 --- a/tests/api_resources/fine_tuning/test_jobs.py +++ b/tests/api_resources/fine_tuning/test_jobs.py @@ -39,6 +39,36 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "learning_rate_multiplier": "auto", "n_epochs": "auto", }, + integrations=[ + { + "type": "wandb", + "wandb": { + "project": "my-wandb-project", + "name": "string", + "entity": "string", + "tags": ["custom-tag", "custom-tag", "custom-tag"], + }, + }, + { + "type": "wandb", + "wandb": { + "project": "my-wandb-project", + "name": "string", + "entity": "string", + "tags": ["custom-tag", "custom-tag", "custom-tag"], + }, + }, + { + "type": "wandb", + "wandb": { + "project": "my-wandb-project", + "name": "string", + "entity": "string", + "tags": ["custom-tag", "custom-tag", "custom-tag"], + }, + }, + ], + seed=42, suffix="x", validation_file="file-abc123", ) @@ -248,6 +278,36 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "learning_rate_multiplier": "auto", "n_epochs": "auto", }, + integrations=[ + { + "type": "wandb", + "wandb": { + "project": "my-wandb-project", + "name": "string", + "entity": "string", + "tags": ["custom-tag", "custom-tag", "custom-tag"], + }, + }, + { + "type": "wandb", + "wandb": { + "project": "my-wandb-project", + "name": "string", + "entity": "string", + "tags": ["custom-tag", "custom-tag", "custom-tag"], + }, + }, + { + "type": "wandb", + "wandb": { + "project": "my-wandb-project", + "name": "string", + "entity": "string", + "tags": ["custom-tag", "custom-tag", "custom-tag"], + }, + }, + ], + seed=42, suffix="x", validation_file="file-abc123", ) From db069cdacaf7ff8d7c1308db9f2465d38252ea1e Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 15 Apr 2024 16:10:17 -0400 Subject: [PATCH 293/816] feat(api): add batch API (#1316) https://platform.openai.com/docs/api-reference/batch/create --- .stats.yml | 2 +- api.md | 14 + src/openai/__init__.py | 1 + src/openai/_client.py | 8 + src/openai/_module_client.py | 7 + src/openai/resources/__init__.py | 14 + src/openai/resources/batches.py | 354 +++++++++++++++++++++++ src/openai/types/__init__.py | 4 + src/openai/types/batch.py | 85 ++++++ src/openai/types/batch_create_params.py | 35 +++ src/openai/types/batch_error.py | 21 ++ src/openai/types/batch_request_counts.py | 16 + tests/api_resources/test_batches.py | 268 +++++++++++++++++ 13 files changed, 828 insertions(+), 1 deletion(-) create mode 100644 src/openai/resources/batches.py create mode 100644 src/openai/types/batch.py create mode 100644 src/openai/types/batch_create_params.py create mode 100644 src/openai/types/batch_error.py create mode 100644 src/openai/types/batch_request_counts.py create mode 100644 tests/api_resources/test_batches.py diff --git a/.stats.yml b/.stats.yml index 284caebf44..47c2bce1cc 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1 +1 @@ -configured_endpoints: 52 +configured_endpoints: 55 diff --git a/api.md b/api.md index cc3c91a8d5..38f77592e8 100644 --- a/api.md +++ b/api.md @@ -361,3 +361,17 @@ Methods: - client.beta.threads.messages.files.retrieve(file_id, \*, thread_id, message_id) -> MessageFile - client.beta.threads.messages.files.list(message_id, \*, thread_id, \*\*params) -> SyncCursorPage[MessageFile] + +# Batches + +Types: + +```python +from openai.types import Batch, BatchError, BatchRequestCounts +``` + +Methods: + +- client.batches.create(\*\*params) -> Batch +- client.batches.retrieve(batch_id) -> Batch +- client.batches.cancel(batch_id) -> Batch diff --git a/src/openai/__init__.py b/src/openai/__init__.py index 1daa26f7b7..490ba017f0 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -335,6 +335,7 @@ def _reset_client() -> None: # type: ignore[reportUnusedFunction] files as files, images as images, models as models, + batches as batches, embeddings as embeddings, completions as completions, fine_tuning as fine_tuning, diff --git a/src/openai/_client.py b/src/openai/_client.py index e9169df72a..5a6852e571 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -57,6 +57,7 @@ class OpenAI(SyncAPIClient): models: resources.Models fine_tuning: resources.FineTuning beta: resources.Beta + batches: resources.Batches with_raw_response: OpenAIWithRawResponse with_streaming_response: OpenAIWithStreamedResponse @@ -134,6 +135,7 @@ def __init__( self.models = resources.Models(self) self.fine_tuning = resources.FineTuning(self) self.beta = resources.Beta(self) + self.batches = resources.Batches(self) self.with_raw_response = OpenAIWithRawResponse(self) self.with_streaming_response = OpenAIWithStreamedResponse(self) @@ -257,6 +259,7 @@ class AsyncOpenAI(AsyncAPIClient): models: resources.AsyncModels fine_tuning: resources.AsyncFineTuning beta: resources.AsyncBeta + batches: resources.AsyncBatches with_raw_response: AsyncOpenAIWithRawResponse with_streaming_response: AsyncOpenAIWithStreamedResponse @@ -334,6 +337,7 @@ def __init__( self.models = resources.AsyncModels(self) self.fine_tuning = resources.AsyncFineTuning(self) self.beta = resources.AsyncBeta(self) + self.batches = resources.AsyncBatches(self) self.with_raw_response = AsyncOpenAIWithRawResponse(self) self.with_streaming_response = AsyncOpenAIWithStreamedResponse(self) @@ -458,6 +462,7 @@ def __init__(self, client: OpenAI) -> None: self.models = resources.ModelsWithRawResponse(client.models) self.fine_tuning = resources.FineTuningWithRawResponse(client.fine_tuning) self.beta = resources.BetaWithRawResponse(client.beta) + self.batches = resources.BatchesWithRawResponse(client.batches) class AsyncOpenAIWithRawResponse: @@ -472,6 +477,7 @@ def __init__(self, client: AsyncOpenAI) -> None: self.models = resources.AsyncModelsWithRawResponse(client.models) self.fine_tuning = resources.AsyncFineTuningWithRawResponse(client.fine_tuning) self.beta = resources.AsyncBetaWithRawResponse(client.beta) + self.batches = resources.AsyncBatchesWithRawResponse(client.batches) class OpenAIWithStreamedResponse: @@ -486,6 +492,7 @@ def __init__(self, client: OpenAI) -> None: self.models = resources.ModelsWithStreamingResponse(client.models) self.fine_tuning = resources.FineTuningWithStreamingResponse(client.fine_tuning) self.beta = resources.BetaWithStreamingResponse(client.beta) + self.batches = resources.BatchesWithStreamingResponse(client.batches) class AsyncOpenAIWithStreamedResponse: @@ -500,6 +507,7 @@ def __init__(self, client: AsyncOpenAI) -> None: self.models = resources.AsyncModelsWithStreamingResponse(client.models) self.fine_tuning = resources.AsyncFineTuningWithStreamingResponse(client.fine_tuning) self.beta = resources.AsyncBetaWithStreamingResponse(client.beta) + self.batches = resources.AsyncBatchesWithStreamingResponse(client.batches) Client = OpenAI diff --git a/src/openai/_module_client.py b/src/openai/_module_client.py index 9227f5e2b4..6f7356eb3c 100644 --- a/src/openai/_module_client.py +++ b/src/openai/_module_client.py @@ -42,6 +42,12 @@ def __load__(self) -> resources.Models: return _load_client().models +class BatchesProxy(LazyProxy[resources.Batches]): + @override + def __load__(self) -> resources.Batches: + return _load_client().batches + + class EmbeddingsProxy(LazyProxy[resources.Embeddings]): @override def __load__(self) -> resources.Embeddings: @@ -72,6 +78,7 @@ def __load__(self) -> resources.FineTuning: audio: resources.Audio = AudioProxy().__as_proxied__() images: resources.Images = ImagesProxy().__as_proxied__() models: resources.Models = ModelsProxy().__as_proxied__() +batches: resources.Batches = BatchesProxy().__as_proxied__() embeddings: resources.Embeddings = EmbeddingsProxy().__as_proxied__() completions: resources.Completions = CompletionsProxy().__as_proxied__() moderations: resources.Moderations = ModerationsProxy().__as_proxied__() diff --git a/src/openai/resources/__init__.py b/src/openai/resources/__init__.py index 64aa12d260..ecae4243fc 100644 --- a/src/openai/resources/__init__.py +++ b/src/openai/resources/__init__.py @@ -48,6 +48,14 @@ ModelsWithStreamingResponse, AsyncModelsWithStreamingResponse, ) +from .batches import ( + Batches, + AsyncBatches, + BatchesWithRawResponse, + AsyncBatchesWithRawResponse, + BatchesWithStreamingResponse, + AsyncBatchesWithStreamingResponse, +) from .embeddings import ( Embeddings, AsyncEmbeddings, @@ -142,4 +150,10 @@ "AsyncBetaWithRawResponse", "BetaWithStreamingResponse", "AsyncBetaWithStreamingResponse", + "Batches", + "AsyncBatches", + "BatchesWithRawResponse", + "AsyncBatchesWithRawResponse", + "BatchesWithStreamingResponse", + "AsyncBatchesWithStreamingResponse", ] diff --git a/src/openai/resources/batches.py b/src/openai/resources/batches.py new file mode 100644 index 0000000000..0921ccb194 --- /dev/null +++ b/src/openai/resources/batches.py @@ -0,0 +1,354 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Optional +from typing_extensions import Literal + +import httpx + +from .. import _legacy_response +from ..types import Batch, batch_create_params +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._utils import ( + maybe_transform, + async_maybe_transform, +) +from .._compat import cached_property +from .._resource import SyncAPIResource, AsyncAPIResource +from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from .._base_client import ( + make_request_options, +) + +__all__ = ["Batches", "AsyncBatches"] + + +class Batches(SyncAPIResource): + @cached_property + def with_raw_response(self) -> BatchesWithRawResponse: + return BatchesWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> BatchesWithStreamingResponse: + return BatchesWithStreamingResponse(self) + + def create( + self, + *, + completion_window: Literal["24h"], + endpoint: Literal["/v1/chat/completions"], + input_file_id: str, + metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Batch: + """ + Creates and executes a batch from an uploaded file of requests + + Args: + completion_window: The time frame within which the batch should be processed. Currently only `24h` + is supported. + + endpoint: The endpoint to be used for all requests in the batch. Currently only + `/v1/chat/completions` is supported. + + input_file_id: The ID of an uploaded file that contains requests for the new batch. + + See [upload file](https://platform.openai.com/docs/api-reference/files/create) + for how to upload a file. + + Your input file must be formatted as a JSONL file, and must be uploaded with the + purpose `batch`. + + metadata: Optional custom metadata for the batch. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._post( + "/batches", + body=maybe_transform( + { + "completion_window": completion_window, + "endpoint": endpoint, + "input_file_id": input_file_id, + "metadata": metadata, + }, + batch_create_params.BatchCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Batch, + ) + + def retrieve( + self, + batch_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Batch: + """ + Retrieves a batch. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not batch_id: + raise ValueError(f"Expected a non-empty value for `batch_id` but received {batch_id!r}") + return self._get( + f"/batches/{batch_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Batch, + ) + + def cancel( + self, + batch_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Batch: + """ + Cancels an in-progress batch. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not batch_id: + raise ValueError(f"Expected a non-empty value for `batch_id` but received {batch_id!r}") + return self._post( + f"/batches/{batch_id}/cancel", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Batch, + ) + + +class AsyncBatches(AsyncAPIResource): + @cached_property + def with_raw_response(self) -> AsyncBatchesWithRawResponse: + return AsyncBatchesWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncBatchesWithStreamingResponse: + return AsyncBatchesWithStreamingResponse(self) + + async def create( + self, + *, + completion_window: Literal["24h"], + endpoint: Literal["/v1/chat/completions"], + input_file_id: str, + metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Batch: + """ + Creates and executes a batch from an uploaded file of requests + + Args: + completion_window: The time frame within which the batch should be processed. Currently only `24h` + is supported. + + endpoint: The endpoint to be used for all requests in the batch. Currently only + `/v1/chat/completions` is supported. + + input_file_id: The ID of an uploaded file that contains requests for the new batch. + + See [upload file](https://platform.openai.com/docs/api-reference/files/create) + for how to upload a file. + + Your input file must be formatted as a JSONL file, and must be uploaded with the + purpose `batch`. + + metadata: Optional custom metadata for the batch. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._post( + "/batches", + body=await async_maybe_transform( + { + "completion_window": completion_window, + "endpoint": endpoint, + "input_file_id": input_file_id, + "metadata": metadata, + }, + batch_create_params.BatchCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Batch, + ) + + async def retrieve( + self, + batch_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Batch: + """ + Retrieves a batch. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not batch_id: + raise ValueError(f"Expected a non-empty value for `batch_id` but received {batch_id!r}") + return await self._get( + f"/batches/{batch_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Batch, + ) + + async def cancel( + self, + batch_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Batch: + """ + Cancels an in-progress batch. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not batch_id: + raise ValueError(f"Expected a non-empty value for `batch_id` but received {batch_id!r}") + return await self._post( + f"/batches/{batch_id}/cancel", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Batch, + ) + + +class BatchesWithRawResponse: + def __init__(self, batches: Batches) -> None: + self._batches = batches + + self.create = _legacy_response.to_raw_response_wrapper( + batches.create, + ) + self.retrieve = _legacy_response.to_raw_response_wrapper( + batches.retrieve, + ) + self.cancel = _legacy_response.to_raw_response_wrapper( + batches.cancel, + ) + + +class AsyncBatchesWithRawResponse: + def __init__(self, batches: AsyncBatches) -> None: + self._batches = batches + + self.create = _legacy_response.async_to_raw_response_wrapper( + batches.create, + ) + self.retrieve = _legacy_response.async_to_raw_response_wrapper( + batches.retrieve, + ) + self.cancel = _legacy_response.async_to_raw_response_wrapper( + batches.cancel, + ) + + +class BatchesWithStreamingResponse: + def __init__(self, batches: Batches) -> None: + self._batches = batches + + self.create = to_streamed_response_wrapper( + batches.create, + ) + self.retrieve = to_streamed_response_wrapper( + batches.retrieve, + ) + self.cancel = to_streamed_response_wrapper( + batches.cancel, + ) + + +class AsyncBatchesWithStreamingResponse: + def __init__(self, batches: AsyncBatches) -> None: + self._batches = batches + + self.create = async_to_streamed_response_wrapper( + batches.create, + ) + self.retrieve = async_to_streamed_response_wrapper( + batches.retrieve, + ) + self.cancel = async_to_streamed_response_wrapper( + batches.cancel, + ) diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index 0917e22a8f..4bbcdddc2a 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -2,6 +2,7 @@ from __future__ import annotations +from .batch import Batch as Batch from .image import Image as Image from .model import Model as Model from .shared import ( @@ -12,6 +13,7 @@ from .embedding import Embedding as Embedding from .completion import Completion as Completion from .moderation import Moderation as Moderation +from .batch_error import BatchError as BatchError from .file_object import FileObject as FileObject from .file_content import FileContent as FileContent from .file_deleted import FileDeleted as FileDeleted @@ -22,6 +24,8 @@ from .completion_choice import CompletionChoice as CompletionChoice from .image_edit_params import ImageEditParams as ImageEditParams from .file_create_params import FileCreateParams as FileCreateParams +from .batch_create_params import BatchCreateParams as BatchCreateParams +from .batch_request_counts import BatchRequestCounts as BatchRequestCounts from .image_generate_params import ImageGenerateParams as ImageGenerateParams from .embedding_create_params import EmbeddingCreateParams as EmbeddingCreateParams from .completion_create_params import CompletionCreateParams as CompletionCreateParams diff --git a/src/openai/types/batch.py b/src/openai/types/batch.py new file mode 100644 index 0000000000..bde04d1a24 --- /dev/null +++ b/src/openai/types/batch.py @@ -0,0 +1,85 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import builtins +from typing import List, Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .batch_error import BatchError +from .batch_request_counts import BatchRequestCounts + +__all__ = ["Batch", "Errors"] + + +class Errors(BaseModel): + data: Optional[List[BatchError]] = None + + object: Optional[str] = None + """The object type, which is always `list`.""" + + +class Batch(BaseModel): + id: str + + completion_window: str + """The time frame within which the batch should be processed.""" + + created_at: str + """The Unix timestamp (in seconds) for when the batch was created.""" + + endpoint: str + """The OpenAI API endpoint used by the batch.""" + + input_file_id: str + """The ID of the input file for the batch.""" + + object: Literal["batch"] + """The object type, which is always `batch`.""" + + status: Literal[ + "validating", "failed", "in_progress", "finalizing", "completed", "expired", "cancelling", "cancelled" + ] + """The current status of the batch.""" + + cancelled_at: Optional[str] = None + """The Unix timestamp (in seconds) for when the batch was cancelled.""" + + cancelling_at: Optional[str] = None + """The Unix timestamp (in seconds) for when the batch started cancelling.""" + + completed_at: Optional[str] = None + """The Unix timestamp (in seconds) for when the batch was completed.""" + + error_file_id: Optional[str] = None + """The ID of the file containing the outputs of requests with errors.""" + + errors: Optional[Errors] = None + + expired_at: Optional[str] = None + """The Unix timestamp (in seconds) for when the batch expired.""" + + expires_at: Optional[str] = None + """The Unix timestamp (in seconds) for when the batch will expire.""" + + failed_at: Optional[str] = None + """The Unix timestamp (in seconds) for when the batch failed.""" + + finalizing_at: Optional[str] = None + """The Unix timestamp (in seconds) for when the batch started finalizing.""" + + in_progress_at: Optional[str] = None + """The Unix timestamp (in seconds) for when the batch started processing.""" + + metadata: Optional[builtins.object] = None + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format. Keys can be a maximum of 64 characters long and values can be + a maxium of 512 characters long. + """ + + output_file_id: Optional[str] = None + """The ID of the file containing the outputs of successfully executed requests.""" + + request_counts: Optional[BatchRequestCounts] = None + """The request counts for different statuses within the batch.""" diff --git a/src/openai/types/batch_create_params.py b/src/openai/types/batch_create_params.py new file mode 100644 index 0000000000..6a22be8626 --- /dev/null +++ b/src/openai/types/batch_create_params.py @@ -0,0 +1,35 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["BatchCreateParams"] + + +class BatchCreateParams(TypedDict, total=False): + completion_window: Required[Literal["24h"]] + """The time frame within which the batch should be processed. + + Currently only `24h` is supported. + """ + + endpoint: Required[Literal["/v1/chat/completions"]] + """The endpoint to be used for all requests in the batch. + + Currently only `/v1/chat/completions` is supported. + """ + + input_file_id: Required[str] + """The ID of an uploaded file that contains requests for the new batch. + + See [upload file](https://platform.openai.com/docs/api-reference/files/create) + for how to upload a file. + + Your input file must be formatted as a JSONL file, and must be uploaded with the + purpose `batch`. + """ + + metadata: Optional[Dict[str, str]] + """Optional custom metadata for the batch.""" diff --git a/src/openai/types/batch_error.py b/src/openai/types/batch_error.py new file mode 100644 index 0000000000..1cdd808dbd --- /dev/null +++ b/src/openai/types/batch_error.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from .._models import BaseModel + +__all__ = ["BatchError"] + + +class BatchError(BaseModel): + code: Optional[str] = None + """An error code identifying the error type.""" + + line: Optional[int] = None + """The line number of the input file where the error occurred, if applicable.""" + + message: Optional[str] = None + """A human-readable message providing more details about the error.""" + + param: Optional[str] = None + """The name of the parameter that caused the error, if applicable.""" diff --git a/src/openai/types/batch_request_counts.py b/src/openai/types/batch_request_counts.py new file mode 100644 index 0000000000..068b071af1 --- /dev/null +++ b/src/openai/types/batch_request_counts.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .._models import BaseModel + +__all__ = ["BatchRequestCounts"] + + +class BatchRequestCounts(BaseModel): + completed: int + """Number of requests that have been completed successfully.""" + + failed: int + """Number of requests that have failed.""" + + total: int + """Total number of requests in the batch.""" diff --git a/tests/api_resources/test_batches.py b/tests/api_resources/test_batches.py new file mode 100644 index 0000000000..aafeff8116 --- /dev/null +++ b/tests/api_resources/test_batches.py @@ -0,0 +1,268 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai.types import Batch + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") + + +class TestBatches: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + def test_method_create(self, client: OpenAI) -> None: + batch = client.batches.create( + completion_window="24h", + endpoint="/v1/chat/completions", + input_file_id="string", + ) + assert_matches_type(Batch, batch, path=["response"]) + + @parametrize + def test_method_create_with_all_params(self, client: OpenAI) -> None: + batch = client.batches.create( + completion_window="24h", + endpoint="/v1/chat/completions", + input_file_id="string", + metadata={"foo": "string"}, + ) + assert_matches_type(Batch, batch, path=["response"]) + + @parametrize + def test_raw_response_create(self, client: OpenAI) -> None: + response = client.batches.with_raw_response.create( + completion_window="24h", + endpoint="/v1/chat/completions", + input_file_id="string", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + batch = response.parse() + assert_matches_type(Batch, batch, path=["response"]) + + @parametrize + def test_streaming_response_create(self, client: OpenAI) -> None: + with client.batches.with_streaming_response.create( + completion_window="24h", + endpoint="/v1/chat/completions", + input_file_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + batch = response.parse() + assert_matches_type(Batch, batch, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_method_retrieve(self, client: OpenAI) -> None: + batch = client.batches.retrieve( + "string", + ) + assert_matches_type(Batch, batch, path=["response"]) + + @parametrize + def test_raw_response_retrieve(self, client: OpenAI) -> None: + response = client.batches.with_raw_response.retrieve( + "string", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + batch = response.parse() + assert_matches_type(Batch, batch, path=["response"]) + + @parametrize + def test_streaming_response_retrieve(self, client: OpenAI) -> None: + with client.batches.with_streaming_response.retrieve( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + batch = response.parse() + assert_matches_type(Batch, batch, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_retrieve(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `batch_id` but received ''"): + client.batches.with_raw_response.retrieve( + "", + ) + + @parametrize + def test_method_cancel(self, client: OpenAI) -> None: + batch = client.batches.cancel( + "string", + ) + assert_matches_type(Batch, batch, path=["response"]) + + @parametrize + def test_raw_response_cancel(self, client: OpenAI) -> None: + response = client.batches.with_raw_response.cancel( + "string", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + batch = response.parse() + assert_matches_type(Batch, batch, path=["response"]) + + @parametrize + def test_streaming_response_cancel(self, client: OpenAI) -> None: + with client.batches.with_streaming_response.cancel( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + batch = response.parse() + assert_matches_type(Batch, batch, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_cancel(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `batch_id` but received ''"): + client.batches.with_raw_response.cancel( + "", + ) + + +class TestAsyncBatches: + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + async def test_method_create(self, async_client: AsyncOpenAI) -> None: + batch = await async_client.batches.create( + completion_window="24h", + endpoint="/v1/chat/completions", + input_file_id="string", + ) + assert_matches_type(Batch, batch, path=["response"]) + + @parametrize + async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: + batch = await async_client.batches.create( + completion_window="24h", + endpoint="/v1/chat/completions", + input_file_id="string", + metadata={"foo": "string"}, + ) + assert_matches_type(Batch, batch, path=["response"]) + + @parametrize + async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: + response = await async_client.batches.with_raw_response.create( + completion_window="24h", + endpoint="/v1/chat/completions", + input_file_id="string", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + batch = response.parse() + assert_matches_type(Batch, batch, path=["response"]) + + @parametrize + async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: + async with async_client.batches.with_streaming_response.create( + completion_window="24h", + endpoint="/v1/chat/completions", + input_file_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + batch = await response.parse() + assert_matches_type(Batch, batch, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: + batch = await async_client.batches.retrieve( + "string", + ) + assert_matches_type(Batch, batch, path=["response"]) + + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: + response = await async_client.batches.with_raw_response.retrieve( + "string", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + batch = response.parse() + assert_matches_type(Batch, batch, path=["response"]) + + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: + async with async_client.batches.with_streaming_response.retrieve( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + batch = await response.parse() + assert_matches_type(Batch, batch, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `batch_id` but received ''"): + await async_client.batches.with_raw_response.retrieve( + "", + ) + + @parametrize + async def test_method_cancel(self, async_client: AsyncOpenAI) -> None: + batch = await async_client.batches.cancel( + "string", + ) + assert_matches_type(Batch, batch, path=["response"]) + + @parametrize + async def test_raw_response_cancel(self, async_client: AsyncOpenAI) -> None: + response = await async_client.batches.with_raw_response.cancel( + "string", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + batch = response.parse() + assert_matches_type(Batch, batch, path=["response"]) + + @parametrize + async def test_streaming_response_cancel(self, async_client: AsyncOpenAI) -> None: + async with async_client.batches.with_streaming_response.cancel( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + batch = await response.parse() + assert_matches_type(Batch, batch, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_cancel(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `batch_id` but received ''"): + await async_client.batches.with_raw_response.cancel( + "", + ) From 2f759aabf346548fbb09d54ae0c279ce8ce9e148 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 15 Apr 2024 16:10:45 -0400 Subject: [PATCH 294/816] release: 1.18.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 9 +++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 3741b313a5..4ce109ae13 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.17.1" + ".": "1.18.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e18ab5f54..03285021ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 1.18.0 (2024-04-15) + +Full Changelog: [v1.17.1...v1.18.0](https://github.com/openai/openai-python/compare/v1.17.1...v1.18.0) + +### Features + +* **api:** add batch API ([#1316](https://github.com/openai/openai-python/issues/1316)) ([3e6f19e](https://github.com/openai/openai-python/commit/3e6f19e6e7489bf1c94944a5f8f9b1d4535cdc43)) +* **api:** updates ([#1314](https://github.com/openai/openai-python/issues/1314)) ([8281dc9](https://github.com/openai/openai-python/commit/8281dc956178f5de345645660081f7d0c15a57a6)) + ## 1.17.1 (2024-04-12) Full Changelog: [v1.17.0...v1.17.1](https://github.com/openai/openai-python/compare/v1.17.0...v1.17.1) diff --git a/pyproject.toml b/pyproject.toml index 9eb6330616..505f1a3e7a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.17.1" +version = "1.18.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index a4ffbb2c35..2957462e3d 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.17.1" # x-release-please-version +__version__ = "1.18.0" # x-release-please-version From 3cb47431c9143e9b5f0085938b6d01c818e7c941 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 15 Apr 2024 17:34:22 -0400 Subject: [PATCH 295/816] feat(errors): add request_id property (#1317) --- src/openai/_exceptions.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/openai/_exceptions.py b/src/openai/_exceptions.py index 074752c8a1..f6731cfac5 100644 --- a/src/openai/_exceptions.py +++ b/src/openai/_exceptions.py @@ -76,11 +76,13 @@ class APIStatusError(APIError): response: httpx.Response status_code: int + request_id: str | None def __init__(self, message: str, *, response: httpx.Response, body: object | None) -> None: super().__init__(message, response.request, body=body) self.response = response self.status_code = response.status_code + self.request_id = response.headers.get("x-request-id") class APIConnectionError(APIError): From 1a83130d7aff056d83c6760e20246a26a400c0d4 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 15 Apr 2024 17:34:48 -0400 Subject: [PATCH 296/816] release: 1.19.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 4ce109ae13..de44c40d86 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.18.0" + ".": "1.19.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 03285021ee..bd42e74a05 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.19.0 (2024-04-15) + +Full Changelog: [v1.18.0...v1.19.0](https://github.com/openai/openai-python/compare/v1.18.0...v1.19.0) + +### Features + +* **errors:** add request_id property ([#1317](https://github.com/openai/openai-python/issues/1317)) ([f9eb77d](https://github.com/openai/openai-python/commit/f9eb77dca422b9456f4e3b31c7474046235eec1d)) + ## 1.18.0 (2024-04-15) Full Changelog: [v1.17.1...v1.18.0](https://github.com/openai/openai-python/compare/v1.17.1...v1.18.0) diff --git a/pyproject.toml b/pyproject.toml index 505f1a3e7a..66049e22d2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.18.0" +version = "1.19.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 2957462e3d..b652844d7a 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.18.0" # x-release-please-version +__version__ = "1.19.0" # x-release-please-version From 3408b5d24287f435df8020a6d3f96076c39f6920 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 16 Apr 2024 09:18:14 -0400 Subject: [PATCH 297/816] feat(client): add header OpenAI-Project (#1320) --- src/openai/__init__.py | 14 ++++++++++++++ src/openai/_client.py | 20 ++++++++++++++++++++ src/openai/lib/azure.py | 13 +++++++++++++ tests/test_module_client.py | 1 + 4 files changed, 48 insertions(+) diff --git a/src/openai/__init__.py b/src/openai/__init__.py index 490ba017f0..0e87ae9259 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -108,6 +108,8 @@ organization: str | None = None +project: str | None = None + base_url: str | _httpx.URL | None = None timeout: float | Timeout | None = DEFAULT_TIMEOUT @@ -159,6 +161,17 @@ def organization(self, value: str | None) -> None: # type: ignore organization = value + @property # type: ignore + @override + def project(self) -> str | None: + return project + + @project.setter # type: ignore + def project(self, value: str | None) -> None: # type: ignore + global project + + project = value + @property @override def base_url(http://github.com/self) -> _httpx.URL: @@ -310,6 +323,7 @@ def _load_client() -> OpenAI: # type: ignore[reportUnusedFunction] _client = _ModuleClient( api_key=api_key, organization=organization, + project=project, base_url=base_url, timeout=timeout, max_retries=max_retries, diff --git a/src/openai/_client.py b/src/openai/_client.py index 5a6852e571..8f3060c6f6 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -64,12 +64,14 @@ class OpenAI(SyncAPIClient): # client options api_key: str organization: str | None + project: str | None def __init__( self, *, api_key: str | None = None, organization: str | None = None, + project: str | None = None, base_url: str | httpx.URL | None = None, timeout: Union[float, Timeout, None, NotGiven] = NOT_GIVEN, max_retries: int = DEFAULT_MAX_RETRIES, @@ -94,6 +96,7 @@ def __init__( This automatically infers the following arguments from their corresponding environment variables if they are not provided: - `api_key` from `OPENAI_API_KEY` - `organization` from `OPENAI_ORG_ID` + - `project` from `OPENAI_PROJECT_ID` """ if api_key is None: api_key = os.environ.get("OPENAI_API_KEY") @@ -107,6 +110,10 @@ def __init__( organization = os.environ.get("OPENAI_ORG_ID") self.organization = organization + if project is None: + project = os.environ.get("OPENAI_PROJECT_ID") + self.project = project + if base_url is None: base_url = os.environ.get("OPENAI_BASE_URL") if base_url is None: @@ -157,6 +164,7 @@ def default_headers(self) -> dict[str, str | Omit]: **super().default_headers, "X-Stainless-Async": "false", "OpenAI-Organization": self.organization if self.organization is not None else Omit(), + "OpenAI-Project": self.project if self.project is not None else Omit(), **self._custom_headers, } @@ -165,6 +173,7 @@ def copy( *, api_key: str | None = None, organization: str | None = None, + project: str | None = None, base_url: str | httpx.URL | None = None, timeout: float | Timeout | None | NotGiven = NOT_GIVEN, http_client: httpx.Client | None = None, @@ -200,6 +209,7 @@ def copy( return self.__class__( api_key=api_key or self.api_key, organization=organization or self.organization, + project=project or self.project, base_url=base_url or self.base_url, timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, http_client=http_client, @@ -266,12 +276,14 @@ class AsyncOpenAI(AsyncAPIClient): # client options api_key: str organization: str | None + project: str | None def __init__( self, *, api_key: str | None = None, organization: str | None = None, + project: str | None = None, base_url: str | httpx.URL | None = None, timeout: Union[float, Timeout, None, NotGiven] = NOT_GIVEN, max_retries: int = DEFAULT_MAX_RETRIES, @@ -296,6 +308,7 @@ def __init__( This automatically infers the following arguments from their corresponding environment variables if they are not provided: - `api_key` from `OPENAI_API_KEY` - `organization` from `OPENAI_ORG_ID` + - `project` from `OPENAI_PROJECT_ID` """ if api_key is None: api_key = os.environ.get("OPENAI_API_KEY") @@ -309,6 +322,10 @@ def __init__( organization = os.environ.get("OPENAI_ORG_ID") self.organization = organization + if project is None: + project = os.environ.get("OPENAI_PROJECT_ID") + self.project = project + if base_url is None: base_url = os.environ.get("OPENAI_BASE_URL") if base_url is None: @@ -359,6 +376,7 @@ def default_headers(self) -> dict[str, str | Omit]: **super().default_headers, "X-Stainless-Async": f"async:{get_async_library()}", "OpenAI-Organization": self.organization if self.organization is not None else Omit(), + "OpenAI-Project": self.project if self.project is not None else Omit(), **self._custom_headers, } @@ -367,6 +385,7 @@ def copy( *, api_key: str | None = None, organization: str | None = None, + project: str | None = None, base_url: str | httpx.URL | None = None, timeout: float | Timeout | None | NotGiven = NOT_GIVEN, http_client: httpx.AsyncClient | None = None, @@ -402,6 +421,7 @@ def copy( return self.__class__( api_key=api_key or self.api_key, organization=organization or self.organization, + project=project or self.project, base_url=base_url or self.base_url, timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, http_client=http_client, diff --git a/src/openai/lib/azure.py b/src/openai/lib/azure.py index b3b94de80e..b76b83c61c 100644 --- a/src/openai/lib/azure.py +++ b/src/openai/lib/azure.py @@ -130,6 +130,7 @@ def __init__( azure_ad_token: str | None = None, azure_ad_token_provider: AzureADTokenProvider | None = None, organization: str | None = None, + project: str | None = None, base_url: str | None = None, timeout: float | Timeout | None | NotGiven = NOT_GIVEN, max_retries: int = DEFAULT_MAX_RETRIES, @@ -143,6 +144,7 @@ def __init__( This automatically infers the following arguments from their corresponding environment variables if they are not provided: - `api_key` from `AZURE_OPENAI_API_KEY` - `organization` from `OPENAI_ORG_ID` + - `project` from `OPENAI_PROJECT_ID` - `azure_ad_token` from `AZURE_OPENAI_AD_TOKEN` - `api_version` from `OPENAI_API_VERSION` - `azure_endpoint` from `AZURE_OPENAI_ENDPOINT` @@ -205,6 +207,7 @@ def __init__( super().__init__( api_key=api_key, organization=organization, + project=project, base_url=base_url, timeout=timeout, max_retries=max_retries, @@ -223,6 +226,7 @@ def copy( *, api_key: str | None = None, organization: str | None = None, + project: str | None = None, api_version: str | None = None, azure_ad_token: str | None = None, azure_ad_token_provider: AzureADTokenProvider | None = None, @@ -242,6 +246,7 @@ def copy( return super().copy( api_key=api_key, organization=organization, + project=project, base_url=base_url, timeout=timeout, http_client=http_client, @@ -306,6 +311,7 @@ def __init__( azure_ad_token: str | None = None, azure_ad_token_provider: AsyncAzureADTokenProvider | None = None, organization: str | None = None, + project: str | None = None, timeout: float | Timeout | None | NotGiven = NOT_GIVEN, max_retries: int = DEFAULT_MAX_RETRIES, default_headers: Mapping[str, str] | None = None, @@ -325,6 +331,7 @@ def __init__( azure_ad_token: str | None = None, azure_ad_token_provider: AsyncAzureADTokenProvider | None = None, organization: str | None = None, + project: str | None = None, timeout: float | Timeout | None | NotGiven = NOT_GIVEN, max_retries: int = DEFAULT_MAX_RETRIES, default_headers: Mapping[str, str] | None = None, @@ -344,6 +351,7 @@ def __init__( azure_ad_token: str | None = None, azure_ad_token_provider: AsyncAzureADTokenProvider | None = None, organization: str | None = None, + project: str | None = None, timeout: float | Timeout | None | NotGiven = NOT_GIVEN, max_retries: int = DEFAULT_MAX_RETRIES, default_headers: Mapping[str, str] | None = None, @@ -363,6 +371,7 @@ def __init__( azure_ad_token: str | None = None, azure_ad_token_provider: AsyncAzureADTokenProvider | None = None, organization: str | None = None, + project: str | None = None, base_url: str | None = None, timeout: float | Timeout | None | NotGiven = NOT_GIVEN, max_retries: int = DEFAULT_MAX_RETRIES, @@ -376,6 +385,7 @@ def __init__( This automatically infers the following arguments from their corresponding environment variables if they are not provided: - `api_key` from `AZURE_OPENAI_API_KEY` - `organization` from `OPENAI_ORG_ID` + - `project` from `OPENAI_PROJECT_ID` - `azure_ad_token` from `AZURE_OPENAI_AD_TOKEN` - `api_version` from `OPENAI_API_VERSION` - `azure_endpoint` from `AZURE_OPENAI_ENDPOINT` @@ -438,6 +448,7 @@ def __init__( super().__init__( api_key=api_key, organization=organization, + project=project, base_url=base_url, timeout=timeout, max_retries=max_retries, @@ -456,6 +467,7 @@ def copy( *, api_key: str | None = None, organization: str | None = None, + project: str | None = None, api_version: str | None = None, azure_ad_token: str | None = None, azure_ad_token_provider: AsyncAzureADTokenProvider | None = None, @@ -475,6 +487,7 @@ def copy( return super().copy( api_key=api_key, organization=organization, + project=project, base_url=base_url, timeout=timeout, http_client=http_client, diff --git a/tests/test_module_client.py b/tests/test_module_client.py index 6de314856b..05b5f81111 100644 --- a/tests/test_module_client.py +++ b/tests/test_module_client.py @@ -16,6 +16,7 @@ def reset_state() -> None: openai._reset_client() openai.api_key = None or "My API Key" openai.organization = None + openai.project = None openai.base_url = None openai.timeout = DEFAULT_TIMEOUT openai.max_retries = DEFAULT_MAX_RETRIES From 1dc93403acbfa0405649244520416b263c66edaa Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 16 Apr 2024 12:54:34 -0400 Subject: [PATCH 298/816] feat: extract chat models to a named enum (#1322) --- api.md | 6 + src/openai/resources/chat/completions.py | 201 +----------------- src/openai/types/__init__.py | 1 + .../types/chat/completion_create_params.py | 28 +-- src/openai/types/chat_model.py | 27 +++ 5 files changed, 45 insertions(+), 218 deletions(-) create mode 100644 src/openai/types/chat_model.py diff --git a/api.md b/api.md index 38f77592e8..c772fb7c7b 100644 --- a/api.md +++ b/api.md @@ -18,6 +18,12 @@ Methods: # Chat +Types: + +```python +from openai.types import ChatModel +``` + ## Completions Types: diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index 1a23e7876e..3b070b716e 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -8,6 +8,7 @@ import httpx from ... import _legacy_response +from ...types import ChatModel from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ..._utils import ( required_args, @@ -47,30 +48,7 @@ def create( self, *, messages: Iterable[ChatCompletionMessageParam], - model: Union[ - str, - Literal[ - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0301", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - ], + model: Union[str, ChatModel], frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, @@ -238,30 +216,7 @@ def create( self, *, messages: Iterable[ChatCompletionMessageParam], - model: Union[ - str, - Literal[ - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0301", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - ], + model: Union[str, ChatModel], stream: Literal[True], frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, @@ -429,30 +384,7 @@ def create( self, *, messages: Iterable[ChatCompletionMessageParam], - model: Union[ - str, - Literal[ - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0301", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - ], + model: Union[str, ChatModel], stream: bool, frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, @@ -620,30 +552,7 @@ def create( self, *, messages: Iterable[ChatCompletionMessageParam], - model: Union[ - str, - Literal[ - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0301", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - ], + model: Union[str, ChatModel], frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, @@ -719,30 +628,7 @@ async def create( self, *, messages: Iterable[ChatCompletionMessageParam], - model: Union[ - str, - Literal[ - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0301", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - ], + model: Union[str, ChatModel], frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, @@ -910,30 +796,7 @@ async def create( self, *, messages: Iterable[ChatCompletionMessageParam], - model: Union[ - str, - Literal[ - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0301", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - ], + model: Union[str, ChatModel], stream: Literal[True], frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, @@ -1101,30 +964,7 @@ async def create( self, *, messages: Iterable[ChatCompletionMessageParam], - model: Union[ - str, - Literal[ - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0301", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - ], + model: Union[str, ChatModel], stream: bool, frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, @@ -1292,30 +1132,7 @@ async def create( self, *, messages: Iterable[ChatCompletionMessageParam], - model: Union[ - str, - Literal[ - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0301", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - ], + model: Union[str, ChatModel], frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index 4bbcdddc2a..b6f35cfecf 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -11,6 +11,7 @@ FunctionParameters as FunctionParameters, ) from .embedding import Embedding as Embedding +from .chat_model import ChatModel as ChatModel from .completion import Completion as Completion from .moderation import Moderation as Moderation from .batch_error import BatchError as BatchError diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 1e0f7f8195..964b246c41 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -6,6 +6,7 @@ from typing_extensions import Literal, Required, TypedDict from ...types import shared_params +from ..chat_model import ChatModel from .chat_completion_tool_param import ChatCompletionToolParam from .chat_completion_message_param import ChatCompletionMessageParam from .chat_completion_tool_choice_option_param import ChatCompletionToolChoiceOptionParam @@ -28,32 +29,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models). """ - model: Required[ - Union[ - str, - Literal[ - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0301", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - ] - ] + model: Required[Union[str, ChatModel]] """ID of the model to use. See the diff --git a/src/openai/types/chat_model.py b/src/openai/types/chat_model.py new file mode 100644 index 0000000000..219dab5138 --- /dev/null +++ b/src/openai/types/chat_model.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +__all__ = ["ChatModel"] + +ChatModel = Literal[ + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0301", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", +] From 15e7ac157dcc80d952107f596bb9c38cfa06685d Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 16 Apr 2024 12:55:02 -0400 Subject: [PATCH 299/816] release: 1.20.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 9 +++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index de44c40d86..69eb19a7b0 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.19.0" + ".": "1.20.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index bd42e74a05..a39d5faa30 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 1.20.0 (2024-04-16) + +Full Changelog: [v1.19.0...v1.20.0](https://github.com/openai/openai-python/compare/v1.19.0...v1.20.0) + +### Features + +* **client:** add header OpenAI-Project ([#1320](https://github.com/openai/openai-python/issues/1320)) ([0c489f1](https://github.com/openai/openai-python/commit/0c489f16a7d9e5ac753da87273b223893edefa69)) +* extract chat models to a named enum ([#1322](https://github.com/openai/openai-python/issues/1322)) ([1ccd9b6](https://github.com/openai/openai-python/commit/1ccd9b67322736a4714e58c953d59585322c527d)) + ## 1.19.0 (2024-04-15) Full Changelog: [v1.18.0...v1.19.0](https://github.com/openai/openai-python/compare/v1.18.0...v1.19.0) diff --git a/pyproject.toml b/pyproject.toml index 66049e22d2..11ab55cbe9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.19.0" +version = "1.20.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index b652844d7a..32723952ed 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.19.0" # x-release-please-version +__version__ = "1.20.0" # x-release-please-version From 5b20698dc3d023028a7bd447098b949c5bfc3b19 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 17 Apr 2024 12:35:22 -0400 Subject: [PATCH 300/816] feat(api): add vector stores (#1325) --- .stats.yml | 2 +- README.md | 16 +- api.md | 105 ++- helpers.md | 21 + pyproject.toml | 3 +- requirements-dev.lock | 10 + src/openai/resources/beta/__init__.py | 14 + .../beta/{assistants => }/assistants.py | 265 +++++-- .../resources/beta/assistants/__init__.py | 33 - src/openai/resources/beta/beta.py | 34 +- .../beta/threads/{messages => }/messages.py | 86 +- .../beta/threads/messages/__init__.py | 33 - .../resources/beta/threads/messages/files.py | 312 -------- .../resources/beta/threads/runs/runs.py | 90 ++- .../resources/beta/threads/runs/steps.py | 8 +- src/openai/resources/beta/threads/threads.py | 189 ++++- .../resources/beta/vector_stores/__init__.py | 47 ++ .../beta/vector_stores/file_batches.py | 739 ++++++++++++++++++ .../{assistants => vector_stores}/files.py | 352 +++++++-- .../beta/vector_stores/vector_stores.py | 688 ++++++++++++++++ src/openai/resources/fine_tuning/jobs/jobs.py | 4 +- src/openai/types/beta/__init__.py | 9 +- src/openai/types/beta/assistant.py | 44 +- .../types/beta/assistant_create_params.py | 111 ++- src/openai/types/beta/assistant_tool.py | 4 +- .../types/beta/assistant_tool_choice.py | 2 +- .../types/beta/assistant_tool_choice_param.py | 2 +- src/openai/types/beta/assistant_tool_param.py | 4 +- .../types/beta/assistant_update_params.py | 83 +- src/openai/types/beta/assistants/__init__.py | 8 - .../types/beta/assistants/assistant_file.py | 21 - src/openai/types/beta/file_search_tool.py | 12 + ...ool_param.py => file_search_tool_param.py} | 8 +- src/openai/types/beta/thread.py | 37 +- .../beta/thread_create_and_run_params.py | 130 ++- src/openai/types/beta/thread_create_params.py | 84 +- src/openai/types/beta/thread_update_params.py | 37 +- src/openai/types/beta/threads/message.py | 19 +- .../beta/threads/message_create_params.py | 20 +- .../types/beta/threads/message_delta.py | 7 - .../types/beta/threads/messages/__init__.py | 6 - .../beta/threads/messages/message_file.py | 25 - src/openai/types/beta/threads/run.py | 10 +- .../types/beta/threads/run_create_params.py | 24 +- .../types/beta/threads/runs/__init__.py | 4 +- ..._tool_call.py => file_search_tool_call.py} | 10 +- ...elta.py => file_search_tool_call_delta.py} | 14 +- .../types/beta/threads/runs/tool_call.py | 4 +- .../beta/threads/runs/tool_call_delta.py | 4 +- .../threads/runs/tool_call_delta_object.py | 2 +- .../threads/runs/tool_calls_step_details.py | 2 +- src/openai/types/beta/vector_store.py | 79 ++ .../types/beta/vector_store_create_params.py | 42 + ...rieval_tool.py => vector_store_deleted.py} | 11 +- ..._params.py => vector_store_list_params.py} | 4 +- .../types/beta/vector_store_update_params.py | 35 + .../types/beta/vector_stores/__init__.py | 11 + .../vector_stores/file_batch_create_params.py | 17 + .../file_batch_list_files_params.py | 47 ++ .../file_create_params.py | 6 +- .../file_list_params.py | 10 +- .../beta/vector_stores/vector_store_file.py | 48 ++ .../vector_stores/vector_store_file_batch.py | 54 ++ .../vector_store_file_deleted.py} | 6 +- .../types/fine_tuning/job_create_params.py | 2 +- tests/api_resources/beta/test_assistants.py | 48 +- tests/api_resources/beta/test_threads.py | 370 ++++++++- .../api_resources/beta/test_vector_stores.py | 426 ++++++++++ .../beta/threads/messages/__init__.py | 1 - .../beta/threads/messages/test_files.py | 263 ------- .../beta/threads/test_messages.py | 30 +- tests/api_resources/beta/threads/test_runs.py | 184 ++++- .../{assistants => vector_stores}/__init__.py | 0 .../beta/vector_stores/test_file_batches.py | 424 ++++++++++ .../test_files.py | 219 +++--- 75 files changed, 4830 insertions(+), 1305 deletions(-) rename src/openai/resources/beta/{assistants => }/assistants.py (71%) delete mode 100644 src/openai/resources/beta/assistants/__init__.py rename src/openai/resources/beta/threads/{messages => }/messages.py (88%) delete mode 100644 src/openai/resources/beta/threads/messages/__init__.py delete mode 100644 src/openai/resources/beta/threads/messages/files.py create mode 100644 src/openai/resources/beta/vector_stores/__init__.py create mode 100644 src/openai/resources/beta/vector_stores/file_batches.py rename src/openai/resources/beta/{assistants => vector_stores}/files.py (57%) create mode 100644 src/openai/resources/beta/vector_stores/vector_stores.py delete mode 100644 src/openai/types/beta/assistants/__init__.py delete mode 100644 src/openai/types/beta/assistants/assistant_file.py create mode 100644 src/openai/types/beta/file_search_tool.py rename src/openai/types/beta/{retrieval_tool_param.py => file_search_tool_param.py} (50%) delete mode 100644 src/openai/types/beta/threads/messages/__init__.py delete mode 100644 src/openai/types/beta/threads/messages/message_file.py rename src/openai/types/beta/threads/runs/{retrieval_tool_call.py => file_search_tool_call.py} (61%) rename src/openai/types/beta/threads/runs/{retrieval_tool_call_delta.py => file_search_tool_call_delta.py} (67%) create mode 100644 src/openai/types/beta/vector_store.py create mode 100644 src/openai/types/beta/vector_store_create_params.py rename src/openai/types/beta/{retrieval_tool.py => vector_store_deleted.py} (52%) rename src/openai/types/beta/{assistants/file_list_params.py => vector_store_list_params.py} (92%) create mode 100644 src/openai/types/beta/vector_store_update_params.py create mode 100644 src/openai/types/beta/vector_stores/__init__.py create mode 100644 src/openai/types/beta/vector_stores/file_batch_create_params.py create mode 100644 src/openai/types/beta/vector_stores/file_batch_list_files_params.py rename src/openai/types/beta/{assistants => vector_stores}/file_create_params.py (70%) rename src/openai/types/beta/{threads/messages => vector_stores}/file_list_params.py (84%) create mode 100644 src/openai/types/beta/vector_stores/vector_store_file.py create mode 100644 src/openai/types/beta/vector_stores/vector_store_file_batch.py rename src/openai/types/beta/{assistants/file_delete_response.py => vector_stores/vector_store_file_deleted.py} (60%) create mode 100644 tests/api_resources/beta/test_vector_stores.py delete mode 100644 tests/api_resources/beta/threads/messages/__init__.py delete mode 100644 tests/api_resources/beta/threads/messages/test_files.py rename tests/api_resources/beta/{assistants => vector_stores}/__init__.py (100%) create mode 100644 tests/api_resources/beta/vector_stores/test_file_batches.py rename tests/api_resources/beta/{assistants => vector_stores}/test_files.py (59%) diff --git a/.stats.yml b/.stats.yml index 47c2bce1cc..2814bb7778 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1 +1 @@ -configured_endpoints: 55 +configured_endpoints: 62 diff --git a/README.md b/README.md index 3bdd6c4a43..84d9017e45 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ so that your API Key is not stored in source control. ### Polling Helpers -When interacting with the API some actions such as starting a Run may take time to complete. The SDK includes +When interacting with the API some actions such as starting a Run and adding files to vector stores are asynchronous and take time to complete. The SDK includes helper functions which will poll the status until it reaches a terminal state and then return the resulting object. If an API method results in an action which could benefit from polling there will be a corresponding version of the method ending in '\_and_poll'. @@ -69,6 +69,20 @@ run = client.beta.threads.runs.create_and_poll( More information on the lifecycle of a Run can be found in the [Run Lifecycle Documentation](https://platform.openai.com/docs/assistants/how-it-works/run-lifecycle) +### Bulk Upload Helpers + +When creating an interacting with vector stores, you can use the polling helpers to monitor the status of operations. +For convenience, we also provide a bulk upload helper to allow you to simultaneously upload several files at once. + +```python +sample_files = [Path("sample-paper.pdf"), ...] + +batch = await client.vector_stores.file_batches.upload_and_poll( + store.id, + files=sample_files, +) +``` + ### Streaming Helpers The SDK also includes helpers to process streams and handle the incoming events. diff --git a/api.md b/api.md index c772fb7c7b..962ed7b7c5 100644 --- a/api.md +++ b/api.md @@ -196,6 +196,59 @@ Methods: # Beta +## VectorStores + +Types: + +```python +from openai.types.beta import VectorStore, VectorStoreDeleted +``` + +Methods: + +- client.beta.vector_stores.create(\*\*params) -> VectorStore +- client.beta.vector_stores.retrieve(vector_store_id) -> VectorStore +- client.beta.vector_stores.update(vector_store_id, \*\*params) -> VectorStore +- client.beta.vector_stores.list(\*\*params) -> SyncCursorPage[VectorStore] +- client.beta.vector_stores.delete(vector_store_id) -> VectorStoreDeleted + +### Files + +Types: + +```python +from openai.types.beta.vector_stores import VectorStoreFile, VectorStoreFileDeleted +``` + +Methods: + +- client.beta.vector_stores.files.create(vector_store_id, \*\*params) -> VectorStoreFile +- client.beta.vector_stores.files.retrieve(file_id, \*, vector_store_id) -> VectorStoreFile +- client.beta.vector_stores.files.list(vector_store_id, \*\*params) -> SyncCursorPage[VectorStoreFile] +- client.beta.vector_stores.files.delete(file_id, \*, vector_store_id) -> VectorStoreFileDeleted +- client.beta.vector_stores.files.create_and_poll(\*args) -> VectorStoreFile +- client.beta.vector_stores.files.poll(\*args) -> VectorStoreFile +- client.beta.vector_stores.files.upload(\*args) -> VectorStoreFile +- client.beta.vector_stores.files.upload_and_poll(\*args) -> VectorStoreFile + +### FileBatches + +Types: + +```python +from openai.types.beta.vector_stores import VectorStoreFileBatch +``` + +Methods: + +- client.beta.vector_stores.file_batches.create(vector_store_id, \*\*params) -> VectorStoreFileBatch +- client.beta.vector_stores.file_batches.retrieve(batch_id, \*, vector_store_id) -> VectorStoreFileBatch +- client.beta.vector_stores.file_batches.cancel(batch_id, \*, vector_store_id) -> VectorStoreFileBatch +- client.beta.vector_stores.file_batches.list_files(batch_id, \*, vector_store_id, \*\*params) -> SyncCursorPage[VectorStoreFile] +- client.beta.vector_stores.file_batches.create_and_poll(\*args) -> VectorStoreFileBatch +- client.beta.vector_stores.file_batches.poll(\*args) -> VectorStoreFileBatch +- client.beta.vector_stores.file_batches.upload_and_poll(\*args) -> VectorStoreFileBatch + ## Assistants Types: @@ -207,9 +260,9 @@ from openai.types.beta import ( AssistantStreamEvent, AssistantTool, CodeInterpreterTool, + FileSearchTool, FunctionTool, MessageStreamEvent, - RetrievalTool, RunStepStreamEvent, RunStreamEvent, ThreadStreamEvent, @@ -218,26 +271,11 @@ from openai.types.beta import ( Methods: -- client.beta.assistants.create(\*\*params) -> Assistant -- client.beta.assistants.retrieve(assistant_id) -> Assistant -- client.beta.assistants.update(assistant_id, \*\*params) -> Assistant -- client.beta.assistants.list(\*\*params) -> SyncCursorPage[Assistant] -- client.beta.assistants.delete(assistant_id) -> AssistantDeleted - -### Files - -Types: - -```python -from openai.types.beta.assistants import AssistantFile, FileDeleteResponse -``` - -Methods: - -- client.beta.assistants.files.create(assistant_id, \*\*params) -> AssistantFile -- client.beta.assistants.files.retrieve(file_id, \*, assistant_id) -> AssistantFile -- client.beta.assistants.files.list(assistant_id, \*\*params) -> SyncCursorPage[AssistantFile] -- client.beta.assistants.files.delete(file_id, \*, assistant_id) -> FileDeleteResponse +- client.beta.assistants.create(\*\*params) -> Assistant +- client.beta.assistants.retrieve(assistant_id) -> Assistant +- client.beta.assistants.update(assistant_id, \*\*params) -> Assistant +- client.beta.assistants.list(\*\*params) -> SyncCursorPage[Assistant] +- client.beta.assistants.delete(assistant_id) -> AssistantDeleted ## Threads @@ -298,11 +336,11 @@ from openai.types.beta.threads.runs import ( CodeInterpreterOutputImage, CodeInterpreterToolCall, CodeInterpreterToolCallDelta, + FileSearchToolCall, + FileSearchToolCallDelta, FunctionToolCall, FunctionToolCallDelta, MessageCreationStepDetails, - RetrievalToolCall, - RetrievalToolCallDelta, RunStep, RunStepDelta, RunStepDeltaEvent, @@ -350,23 +388,10 @@ from openai.types.beta.threads import ( Methods: -- client.beta.threads.messages.create(thread_id, \*\*params) -> Message -- client.beta.threads.messages.retrieve(message_id, \*, thread_id) -> Message -- client.beta.threads.messages.update(message_id, \*, thread_id, \*\*params) -> Message -- client.beta.threads.messages.list(thread_id, \*\*params) -> SyncCursorPage[Message] - -#### Files - -Types: - -```python -from openai.types.beta.threads.messages import MessageFile -``` - -Methods: - -- client.beta.threads.messages.files.retrieve(file_id, \*, thread_id, message_id) -> MessageFile -- client.beta.threads.messages.files.list(message_id, \*, thread_id, \*\*params) -> SyncCursorPage[MessageFile] +- client.beta.threads.messages.create(thread_id, \*\*params) -> Message +- client.beta.threads.messages.retrieve(message_id, \*, thread_id) -> Message +- client.beta.threads.messages.update(message_id, \*, thread_id, \*\*params) -> Message +- client.beta.threads.messages.list(thread_id, \*\*params) -> SyncCursorPage[Message] # Batches diff --git a/helpers.md b/helpers.md index 4271cd9ede..cf738f3f16 100644 --- a/helpers.md +++ b/helpers.md @@ -213,3 +213,24 @@ def get_final_messages(self) -> List[Message] These methods are provided for convenience to collect information at the end of a stream. Calling these events will trigger consumption of the stream until completion and then return the relevant accumulated objects. + +# Polling Helpers + +When interacting with the API some actions such as starting a Run and adding files to vector stores are asynchronous and take time to complete. +The SDK includes helper functions which will poll the status until it reaches a terminal state and then return the resulting object. +If an API method results in an action which could benefit from polling there will be a corresponding version of the +method ending in `_and_poll`. + +All methods also allow you to set the polling frequency, how often the API is checked for an update, via a function argument (`poll_interval_ms`). + +The polling methods are: + +```python +client.beta.threads.create_and_run_poll(...) +client.beta.threads.runs.create_and_poll(...) +client.beta.threads.runs.submit_tool_ouptputs_and_poll(...) +client.beta.vector_stores.files.upload_and_poll(...) +client.beta.vector_stores.files.create_and_poll(...) +client.beta.vector_stores.file_batches.create_and_poll(...) +client.beta.vector_stores.file_batches.upload_and_poll(...) +``` diff --git a/pyproject.toml b/pyproject.toml index 11ab55cbe9..6c3ae2b592 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -63,7 +63,8 @@ dev-dependencies = [ "inline-snapshot >=0.7.0", "azure-identity >=1.14.1", "types-tqdm > 4", - "types-pyaudio > 0" + "types-pyaudio > 0", + "trio >=0.22.2" ] [tool.rye.scripts] diff --git a/requirements-dev.lock b/requirements-dev.lock index 4461f65738..657e6cb810 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -18,7 +18,9 @@ argcomplete==3.1.2 asttokens==2.4.1 # via inline-snapshot attrs==23.1.0 + # via outcome # via pytest + # via trio azure-core==1.30.1 # via azure-identity azure-identity==1.15.0 @@ -48,6 +50,7 @@ distro==1.8.0 # via openai exceptiongroup==1.1.3 # via anyio + # via trio executing==2.0.1 # via inline-snapshot filelock==3.12.4 @@ -63,6 +66,7 @@ idna==3.4 # via anyio # via httpx # via requests + # via trio importlib-metadata==7.0.0 iniconfig==2.0.0 # via pytest @@ -83,6 +87,8 @@ numpy==1.26.3 # via openai # via pandas # via pandas-stubs +outcome==1.3.0.post0 + # via trio packaging==23.2 # via black # via msal-extensions @@ -136,6 +142,9 @@ sniffio==1.3.0 # via anyio # via httpx # via openai + # via trio +sortedcontainers==2.4.0 + # via trio time-machine==2.9.0 toml==0.10.2 # via inline-snapshot @@ -145,6 +154,7 @@ tomli==2.0.1 # via pytest tqdm==4.66.1 # via openai +trio==0.22.2 types-pyaudio==0.2.16.20240106 types-pytz==2024.1.0.20240203 # via pandas-stubs diff --git a/src/openai/resources/beta/__init__.py b/src/openai/resources/beta/__init__.py index 87fea25267..01f5338757 100644 --- a/src/openai/resources/beta/__init__.py +++ b/src/openai/resources/beta/__init__.py @@ -24,8 +24,22 @@ AssistantsWithStreamingResponse, AsyncAssistantsWithStreamingResponse, ) +from .vector_stores import ( + VectorStores, + AsyncVectorStores, + VectorStoresWithRawResponse, + AsyncVectorStoresWithRawResponse, + VectorStoresWithStreamingResponse, + AsyncVectorStoresWithStreamingResponse, +) __all__ = [ + "VectorStores", + "AsyncVectorStores", + "VectorStoresWithRawResponse", + "AsyncVectorStoresWithRawResponse", + "VectorStoresWithStreamingResponse", + "AsyncVectorStoresWithStreamingResponse", "Assistants", "AsyncAssistants", "AssistantsWithRawResponse", diff --git a/src/openai/resources/beta/assistants/assistants.py b/src/openai/resources/beta/assistants.py similarity index 71% rename from src/openai/resources/beta/assistants/assistants.py rename to src/openai/resources/beta/assistants.py index 9e88794ebc..8695a949ca 100644 --- a/src/openai/resources/beta/assistants/assistants.py +++ b/src/openai/resources/beta/assistants.py @@ -2,38 +2,31 @@ from __future__ import annotations -from typing import List, Union, Iterable, Optional +from typing import Union, Iterable, Optional from typing_extensions import Literal import httpx -from .... import _legacy_response -from .files import ( - Files, - AsyncFiles, - FilesWithRawResponse, - AsyncFilesWithRawResponse, - FilesWithStreamingResponse, - AsyncFilesWithStreamingResponse, -) -from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ...._utils import ( +from ... import _legacy_response +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ..._utils import ( maybe_transform, async_maybe_transform, ) -from ...._compat import cached_property -from ...._resource import SyncAPIResource, AsyncAPIResource -from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper -from ....pagination import SyncCursorPage, AsyncCursorPage -from ....types.beta import ( +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ...pagination import SyncCursorPage, AsyncCursorPage +from ...types.beta import ( Assistant, AssistantDeleted, AssistantToolParam, + AssistantResponseFormatOptionParam, assistant_list_params, assistant_create_params, assistant_update_params, ) -from ...._base_client import ( +from ..._base_client import ( AsyncPaginator, make_request_options, ) @@ -42,10 +35,6 @@ class Assistants(SyncAPIResource): - @cached_property - def files(self) -> Files: - return Files(self._client) - @cached_property def with_raw_response(self) -> AssistantsWithRawResponse: return AssistantsWithRawResponse(self) @@ -81,11 +70,14 @@ def create( ], ], description: Optional[str] | NotGiven = NOT_GIVEN, - file_ids: List[str] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_resources: Optional[assistant_create_params.ToolResources] | NotGiven = NOT_GIVEN, tools: Iterable[AssistantToolParam] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -105,10 +97,6 @@ def create( description: The description of the assistant. The maximum length is 512 characters. - file_ids: A list of [file](https://platform.openai.com/docs/api-reference/files) IDs - attached to this assistant. There can be a maximum of 20 files attached to the - assistant. Files are ordered by their creation date in ascending order. - instructions: The system instructions that the assistant uses. The maximum length is 256,000 characters. @@ -119,8 +107,39 @@ def create( name: The name of the assistant. The maximum length is 256 characters. + response_format: Specifies the format that the model must output. Compatible with + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + + tool_resources: A set of resources that are used by the assistant's tools. The resources are + specific to the type of tool. For example, the `code_interpreter` tool requires + a list of file IDs, while the `file_search` tool requires a list of vector store + IDs. + tools: A list of tool enabled on the assistant. There can be a maximum of 128 tools per - assistant. Tools can be of types `code_interpreter`, `retrieval`, or `function`. + assistant. Tools can be of types `code_interpreter`, `file_search`, or + `function`. + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or temperature but not both. extra_headers: Send extra headers @@ -130,18 +149,21 @@ def create( timeout: Override the client-level default timeout for this request, in seconds """ - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._post( "/assistants", body=maybe_transform( { "model": model, "description": description, - "file_ids": file_ids, "instructions": instructions, "metadata": metadata, "name": name, + "response_format": response_format, + "temperature": temperature, + "tool_resources": tool_resources, "tools": tools, + "top_p": top_p, }, assistant_create_params.AssistantCreateParams, ), @@ -176,7 +198,7 @@ def retrieve( """ if not assistant_id: raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._get( f"/assistants/{assistant_id}", options=make_request_options( @@ -190,12 +212,15 @@ def update( assistant_id: str, *, description: Optional[str] | NotGiven = NOT_GIVEN, - file_ids: List[str] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: str | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_resources: Optional[assistant_update_params.ToolResources] | NotGiven = NOT_GIVEN, tools: Iterable[AssistantToolParam] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -210,12 +235,6 @@ def update( The maximum length is 512 characters. - file_ids: A list of [File](https://platform.openai.com/docs/api-reference/files) IDs - attached to this assistant. There can be a maximum of 20 files attached to the - assistant. Files are ordered by their creation date in ascending order. If a - file was previously attached to the list but does not show up in the list, it - will be deleted from the assistant. - instructions: The system instructions that the assistant uses. The maximum length is 256,000 characters. @@ -232,8 +251,39 @@ def update( name: The name of the assistant. The maximum length is 256 characters. + response_format: Specifies the format that the model must output. Compatible with + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + + tool_resources: A set of resources that are used by the assistant's tools. The resources are + specific to the type of tool. For example, the `code_interpreter` tool requires + a list of file IDs, while the `file_search` tool requires a list of vector store + IDs. + tools: A list of tool enabled on the assistant. There can be a maximum of 128 tools per - assistant. Tools can be of types `code_interpreter`, `retrieval`, or `function`. + assistant. Tools can be of types `code_interpreter`, `file_search`, or + `function`. + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or temperature but not both. extra_headers: Send extra headers @@ -245,18 +295,21 @@ def update( """ if not assistant_id: raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._post( f"/assistants/{assistant_id}", body=maybe_transform( { "description": description, - "file_ids": file_ids, "instructions": instructions, "metadata": metadata, "model": model, "name": name, + "response_format": response_format, + "temperature": temperature, + "tool_resources": tool_resources, "tools": tools, + "top_p": top_p, }, assistant_update_params.AssistantUpdateParams, ), @@ -309,7 +362,7 @@ def list( timeout: Override the client-level default timeout for this request, in seconds """ - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._get_api_list( "/assistants", page=SyncCursorPage[Assistant], @@ -356,7 +409,7 @@ def delete( """ if not assistant_id: raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._delete( f"/assistants/{assistant_id}", options=make_request_options( @@ -367,10 +420,6 @@ def delete( class AsyncAssistants(AsyncAPIResource): - @cached_property - def files(self) -> AsyncFiles: - return AsyncFiles(self._client) - @cached_property def with_raw_response(self) -> AsyncAssistantsWithRawResponse: return AsyncAssistantsWithRawResponse(self) @@ -406,11 +455,14 @@ async def create( ], ], description: Optional[str] | NotGiven = NOT_GIVEN, - file_ids: List[str] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_resources: Optional[assistant_create_params.ToolResources] | NotGiven = NOT_GIVEN, tools: Iterable[AssistantToolParam] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -430,10 +482,6 @@ async def create( description: The description of the assistant. The maximum length is 512 characters. - file_ids: A list of [file](https://platform.openai.com/docs/api-reference/files) IDs - attached to this assistant. There can be a maximum of 20 files attached to the - assistant. Files are ordered by their creation date in ascending order. - instructions: The system instructions that the assistant uses. The maximum length is 256,000 characters. @@ -444,8 +492,39 @@ async def create( name: The name of the assistant. The maximum length is 256 characters. + response_format: Specifies the format that the model must output. Compatible with + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + + tool_resources: A set of resources that are used by the assistant's tools. The resources are + specific to the type of tool. For example, the `code_interpreter` tool requires + a list of file IDs, while the `file_search` tool requires a list of vector store + IDs. + tools: A list of tool enabled on the assistant. There can be a maximum of 128 tools per - assistant. Tools can be of types `code_interpreter`, `retrieval`, or `function`. + assistant. Tools can be of types `code_interpreter`, `file_search`, or + `function`. + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or temperature but not both. extra_headers: Send extra headers @@ -455,18 +534,21 @@ async def create( timeout: Override the client-level default timeout for this request, in seconds """ - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._post( "/assistants", body=await async_maybe_transform( { "model": model, "description": description, - "file_ids": file_ids, "instructions": instructions, "metadata": metadata, "name": name, + "response_format": response_format, + "temperature": temperature, + "tool_resources": tool_resources, "tools": tools, + "top_p": top_p, }, assistant_create_params.AssistantCreateParams, ), @@ -501,7 +583,7 @@ async def retrieve( """ if not assistant_id: raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._get( f"/assistants/{assistant_id}", options=make_request_options( @@ -515,12 +597,15 @@ async def update( assistant_id: str, *, description: Optional[str] | NotGiven = NOT_GIVEN, - file_ids: List[str] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: str | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, + response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_resources: Optional[assistant_update_params.ToolResources] | NotGiven = NOT_GIVEN, tools: Iterable[AssistantToolParam] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -535,12 +620,6 @@ async def update( The maximum length is 512 characters. - file_ids: A list of [File](https://platform.openai.com/docs/api-reference/files) IDs - attached to this assistant. There can be a maximum of 20 files attached to the - assistant. Files are ordered by their creation date in ascending order. If a - file was previously attached to the list but does not show up in the list, it - will be deleted from the assistant. - instructions: The system instructions that the assistant uses. The maximum length is 256,000 characters. @@ -557,8 +636,39 @@ async def update( name: The name of the assistant. The maximum length is 256 characters. + response_format: Specifies the format that the model must output. Compatible with + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. + + tool_resources: A set of resources that are used by the assistant's tools. The resources are + specific to the type of tool. For example, the `code_interpreter` tool requires + a list of file IDs, while the `file_search` tool requires a list of vector store + IDs. + tools: A list of tool enabled on the assistant. There can be a maximum of 128 tools per - assistant. Tools can be of types `code_interpreter`, `retrieval`, or `function`. + assistant. Tools can be of types `code_interpreter`, `file_search`, or + `function`. + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or temperature but not both. extra_headers: Send extra headers @@ -570,18 +680,21 @@ async def update( """ if not assistant_id: raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._post( f"/assistants/{assistant_id}", body=await async_maybe_transform( { "description": description, - "file_ids": file_ids, "instructions": instructions, "metadata": metadata, "model": model, "name": name, + "response_format": response_format, + "temperature": temperature, + "tool_resources": tool_resources, "tools": tools, + "top_p": top_p, }, assistant_update_params.AssistantUpdateParams, ), @@ -634,7 +747,7 @@ def list( timeout: Override the client-level default timeout for this request, in seconds """ - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._get_api_list( "/assistants", page=AsyncCursorPage[Assistant], @@ -681,7 +794,7 @@ async def delete( """ if not assistant_id: raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._delete( f"/assistants/{assistant_id}", options=make_request_options( @@ -711,10 +824,6 @@ def __init__(self, assistants: Assistants) -> None: assistants.delete, ) - @cached_property - def files(self) -> FilesWithRawResponse: - return FilesWithRawResponse(self._assistants.files) - class AsyncAssistantsWithRawResponse: def __init__(self, assistants: AsyncAssistants) -> None: @@ -736,10 +845,6 @@ def __init__(self, assistants: AsyncAssistants) -> None: assistants.delete, ) - @cached_property - def files(self) -> AsyncFilesWithRawResponse: - return AsyncFilesWithRawResponse(self._assistants.files) - class AssistantsWithStreamingResponse: def __init__(self, assistants: Assistants) -> None: @@ -761,10 +866,6 @@ def __init__(self, assistants: Assistants) -> None: assistants.delete, ) - @cached_property - def files(self) -> FilesWithStreamingResponse: - return FilesWithStreamingResponse(self._assistants.files) - class AsyncAssistantsWithStreamingResponse: def __init__(self, assistants: AsyncAssistants) -> None: @@ -785,7 +886,3 @@ def __init__(self, assistants: AsyncAssistants) -> None: self.delete = async_to_streamed_response_wrapper( assistants.delete, ) - - @cached_property - def files(self) -> AsyncFilesWithStreamingResponse: - return AsyncFilesWithStreamingResponse(self._assistants.files) diff --git a/src/openai/resources/beta/assistants/__init__.py b/src/openai/resources/beta/assistants/__init__.py deleted file mode 100644 index 736def9388..0000000000 --- a/src/openai/resources/beta/assistants/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -from .files import ( - Files, - AsyncFiles, - FilesWithRawResponse, - AsyncFilesWithRawResponse, - FilesWithStreamingResponse, - AsyncFilesWithStreamingResponse, -) -from .assistants import ( - Assistants, - AsyncAssistants, - AssistantsWithRawResponse, - AsyncAssistantsWithRawResponse, - AssistantsWithStreamingResponse, - AsyncAssistantsWithStreamingResponse, -) - -__all__ = [ - "Files", - "AsyncFiles", - "FilesWithRawResponse", - "AsyncFilesWithRawResponse", - "FilesWithStreamingResponse", - "AsyncFilesWithStreamingResponse", - "Assistants", - "AsyncAssistants", - "AssistantsWithRawResponse", - "AsyncAssistantsWithRawResponse", - "AssistantsWithStreamingResponse", - "AsyncAssistantsWithStreamingResponse", -] diff --git a/src/openai/resources/beta/beta.py b/src/openai/resources/beta/beta.py index 67baad2716..0d9806678f 100644 --- a/src/openai/resources/beta/beta.py +++ b/src/openai/resources/beta/beta.py @@ -20,13 +20,25 @@ AsyncAssistantsWithStreamingResponse, ) from ..._resource import SyncAPIResource, AsyncAPIResource +from .vector_stores import ( + VectorStores, + AsyncVectorStores, + VectorStoresWithRawResponse, + AsyncVectorStoresWithRawResponse, + VectorStoresWithStreamingResponse, + AsyncVectorStoresWithStreamingResponse, +) from .threads.threads import Threads, AsyncThreads -from .assistants.assistants import Assistants, AsyncAssistants +from .vector_stores.vector_stores import VectorStores, AsyncVectorStores __all__ = ["Beta", "AsyncBeta"] class Beta(SyncAPIResource): + @cached_property + def vector_stores(self) -> VectorStores: + return VectorStores(self._client) + @cached_property def assistants(self) -> Assistants: return Assistants(self._client) @@ -45,6 +57,10 @@ def with_streaming_response(self) -> BetaWithStreamingResponse: class AsyncBeta(AsyncAPIResource): + @cached_property + def vector_stores(self) -> AsyncVectorStores: + return AsyncVectorStores(self._client) + @cached_property def assistants(self) -> AsyncAssistants: return AsyncAssistants(self._client) @@ -66,6 +82,10 @@ class BetaWithRawResponse: def __init__(self, beta: Beta) -> None: self._beta = beta + @cached_property + def vector_stores(self) -> VectorStoresWithRawResponse: + return VectorStoresWithRawResponse(self._beta.vector_stores) + @cached_property def assistants(self) -> AssistantsWithRawResponse: return AssistantsWithRawResponse(self._beta.assistants) @@ -79,6 +99,10 @@ class AsyncBetaWithRawResponse: def __init__(self, beta: AsyncBeta) -> None: self._beta = beta + @cached_property + def vector_stores(self) -> AsyncVectorStoresWithRawResponse: + return AsyncVectorStoresWithRawResponse(self._beta.vector_stores) + @cached_property def assistants(self) -> AsyncAssistantsWithRawResponse: return AsyncAssistantsWithRawResponse(self._beta.assistants) @@ -92,6 +116,10 @@ class BetaWithStreamingResponse: def __init__(self, beta: Beta) -> None: self._beta = beta + @cached_property + def vector_stores(self) -> VectorStoresWithStreamingResponse: + return VectorStoresWithStreamingResponse(self._beta.vector_stores) + @cached_property def assistants(self) -> AssistantsWithStreamingResponse: return AssistantsWithStreamingResponse(self._beta.assistants) @@ -105,6 +133,10 @@ class AsyncBetaWithStreamingResponse: def __init__(self, beta: AsyncBeta) -> None: self._beta = beta + @cached_property + def vector_stores(self) -> AsyncVectorStoresWithStreamingResponse: + return AsyncVectorStoresWithStreamingResponse(self._beta.vector_stores) + @cached_property def assistants(self) -> AsyncAssistantsWithStreamingResponse: return AsyncAssistantsWithStreamingResponse(self._beta.assistants) diff --git a/src/openai/resources/beta/threads/messages/messages.py b/src/openai/resources/beta/threads/messages.py similarity index 88% rename from src/openai/resources/beta/threads/messages/messages.py rename to src/openai/resources/beta/threads/messages.py index bbce3e99e4..7a24b80dea 100644 --- a/src/openai/resources/beta/threads/messages/messages.py +++ b/src/openai/resources/beta/threads/messages.py @@ -2,43 +2,31 @@ from __future__ import annotations -from typing import List, Optional +from typing import Iterable, Optional from typing_extensions import Literal import httpx -from ..... import _legacy_response -from .files import ( - Files, - AsyncFiles, - FilesWithRawResponse, - AsyncFilesWithRawResponse, - FilesWithStreamingResponse, - AsyncFilesWithStreamingResponse, -) -from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ....._utils import ( +from .... import _legacy_response +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ...._utils import ( maybe_transform, async_maybe_transform, ) -from ....._compat import cached_property -from ....._resource import SyncAPIResource, AsyncAPIResource -from ....._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper -from .....pagination import SyncCursorPage, AsyncCursorPage -from ....._base_client import ( +from ...._compat import cached_property +from ...._resource import SyncAPIResource, AsyncAPIResource +from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ....pagination import SyncCursorPage, AsyncCursorPage +from ...._base_client import ( AsyncPaginator, make_request_options, ) -from .....types.beta.threads import Message, message_list_params, message_create_params, message_update_params +from ....types.beta.threads import Message, message_list_params, message_create_params, message_update_params __all__ = ["Messages", "AsyncMessages"] class Messages(SyncAPIResource): - @cached_property - def files(self) -> Files: - return Files(self._client) - @cached_property def with_raw_response(self) -> MessagesWithRawResponse: return MessagesWithRawResponse(self) @@ -53,7 +41,7 @@ def create( *, content: str, role: Literal["user", "assistant"], - file_ids: List[str] | NotGiven = NOT_GIVEN, + attachments: Optional[Iterable[message_create_params.Attachment]] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -76,10 +64,7 @@ def create( - `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into the conversation. - file_ids: A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that - the message should use. There can be a maximum of 10 files attached to a - message. Useful for tools like `retrieval` and `code_interpreter` that can - access and use files. + attachments: A list of files attached to the message, and the tools they should be added to. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys @@ -96,14 +81,14 @@ def create( """ if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._post( f"/threads/{thread_id}/messages", body=maybe_transform( { "content": content, "role": role, - "file_ids": file_ids, + "attachments": attachments, "metadata": metadata, }, message_create_params.MessageCreateParams, @@ -142,7 +127,7 @@ def retrieve( raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") if not message_id: raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._get( f"/threads/{thread_id}/messages/{message_id}", options=make_request_options( @@ -185,7 +170,7 @@ def update( raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") if not message_id: raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._post( f"/threads/{thread_id}/messages/{message_id}", body=maybe_transform({"metadata": metadata}, message_update_params.MessageUpdateParams), @@ -243,7 +228,7 @@ def list( """ if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._get_api_list( f"/threads/{thread_id}/messages", page=SyncCursorPage[Message], @@ -268,10 +253,6 @@ def list( class AsyncMessages(AsyncAPIResource): - @cached_property - def files(self) -> AsyncFiles: - return AsyncFiles(self._client) - @cached_property def with_raw_response(self) -> AsyncMessagesWithRawResponse: return AsyncMessagesWithRawResponse(self) @@ -286,7 +267,7 @@ async def create( *, content: str, role: Literal["user", "assistant"], - file_ids: List[str] | NotGiven = NOT_GIVEN, + attachments: Optional[Iterable[message_create_params.Attachment]] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -309,10 +290,7 @@ async def create( - `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into the conversation. - file_ids: A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that - the message should use. There can be a maximum of 10 files attached to a - message. Useful for tools like `retrieval` and `code_interpreter` that can - access and use files. + attachments: A list of files attached to the message, and the tools they should be added to. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys @@ -329,14 +307,14 @@ async def create( """ if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._post( f"/threads/{thread_id}/messages", body=await async_maybe_transform( { "content": content, "role": role, - "file_ids": file_ids, + "attachments": attachments, "metadata": metadata, }, message_create_params.MessageCreateParams, @@ -375,7 +353,7 @@ async def retrieve( raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") if not message_id: raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._get( f"/threads/{thread_id}/messages/{message_id}", options=make_request_options( @@ -418,7 +396,7 @@ async def update( raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") if not message_id: raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._post( f"/threads/{thread_id}/messages/{message_id}", body=await async_maybe_transform({"metadata": metadata}, message_update_params.MessageUpdateParams), @@ -476,7 +454,7 @@ def list( """ if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._get_api_list( f"/threads/{thread_id}/messages", page=AsyncCursorPage[Message], @@ -517,10 +495,6 @@ def __init__(self, messages: Messages) -> None: messages.list, ) - @cached_property - def files(self) -> FilesWithRawResponse: - return FilesWithRawResponse(self._messages.files) - class AsyncMessagesWithRawResponse: def __init__(self, messages: AsyncMessages) -> None: @@ -539,10 +513,6 @@ def __init__(self, messages: AsyncMessages) -> None: messages.list, ) - @cached_property - def files(self) -> AsyncFilesWithRawResponse: - return AsyncFilesWithRawResponse(self._messages.files) - class MessagesWithStreamingResponse: def __init__(self, messages: Messages) -> None: @@ -561,10 +531,6 @@ def __init__(self, messages: Messages) -> None: messages.list, ) - @cached_property - def files(self) -> FilesWithStreamingResponse: - return FilesWithStreamingResponse(self._messages.files) - class AsyncMessagesWithStreamingResponse: def __init__(self, messages: AsyncMessages) -> None: @@ -582,7 +548,3 @@ def __init__(self, messages: AsyncMessages) -> None: self.list = async_to_streamed_response_wrapper( messages.list, ) - - @cached_property - def files(self) -> AsyncFilesWithStreamingResponse: - return AsyncFilesWithStreamingResponse(self._messages.files) diff --git a/src/openai/resources/beta/threads/messages/__init__.py b/src/openai/resources/beta/threads/messages/__init__.py deleted file mode 100644 index a3286e6ace..0000000000 --- a/src/openai/resources/beta/threads/messages/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -from .files import ( - Files, - AsyncFiles, - FilesWithRawResponse, - AsyncFilesWithRawResponse, - FilesWithStreamingResponse, - AsyncFilesWithStreamingResponse, -) -from .messages import ( - Messages, - AsyncMessages, - MessagesWithRawResponse, - AsyncMessagesWithRawResponse, - MessagesWithStreamingResponse, - AsyncMessagesWithStreamingResponse, -) - -__all__ = [ - "Files", - "AsyncFiles", - "FilesWithRawResponse", - "AsyncFilesWithRawResponse", - "FilesWithStreamingResponse", - "AsyncFilesWithStreamingResponse", - "Messages", - "AsyncMessages", - "MessagesWithRawResponse", - "AsyncMessagesWithRawResponse", - "MessagesWithStreamingResponse", - "AsyncMessagesWithStreamingResponse", -] diff --git a/src/openai/resources/beta/threads/messages/files.py b/src/openai/resources/beta/threads/messages/files.py deleted file mode 100644 index 349f99725e..0000000000 --- a/src/openai/resources/beta/threads/messages/files.py +++ /dev/null @@ -1,312 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -from __future__ import annotations - -from typing_extensions import Literal - -import httpx - -from ..... import _legacy_response -from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ....._utils import maybe_transform -from ....._compat import cached_property -from ....._resource import SyncAPIResource, AsyncAPIResource -from ....._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper -from .....pagination import SyncCursorPage, AsyncCursorPage -from ....._base_client import ( - AsyncPaginator, - make_request_options, -) -from .....types.beta.threads.messages import MessageFile, file_list_params - -__all__ = ["Files", "AsyncFiles"] - - -class Files(SyncAPIResource): - @cached_property - def with_raw_response(self) -> FilesWithRawResponse: - return FilesWithRawResponse(self) - - @cached_property - def with_streaming_response(self) -> FilesWithStreamingResponse: - return FilesWithStreamingResponse(self) - - def retrieve( - self, - file_id: str, - *, - thread_id: str, - message_id: str, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> MessageFile: - """ - Retrieves a message file. - - Args: - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - if not thread_id: - raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") - if not message_id: - raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") - if not file_id: - raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} - return self._get( - f"/threads/{thread_id}/messages/{message_id}/files/{file_id}", - options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout - ), - cast_to=MessageFile, - ) - - def list( - self, - message_id: str, - *, - thread_id: str, - after: str | NotGiven = NOT_GIVEN, - before: str | NotGiven = NOT_GIVEN, - limit: int | NotGiven = NOT_GIVEN, - order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> SyncCursorPage[MessageFile]: - """Returns a list of message files. - - Args: - after: A cursor for use in pagination. - - `after` is an object ID that defines your place - in the list. For instance, if you make a list request and receive 100 objects, - ending with obj_foo, your subsequent call can include after=obj_foo in order to - fetch the next page of the list. - - before: A cursor for use in pagination. `before` is an object ID that defines your place - in the list. For instance, if you make a list request and receive 100 objects, - ending with obj_foo, your subsequent call can include before=obj_foo in order to - fetch the previous page of the list. - - limit: A limit on the number of objects to be returned. Limit can range between 1 and - 100, and the default is 20. - - order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending - order and `desc` for descending order. - - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - if not thread_id: - raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") - if not message_id: - raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} - return self._get_api_list( - f"/threads/{thread_id}/messages/{message_id}/files", - page=SyncCursorPage[MessageFile], - options=make_request_options( - extra_headers=extra_headers, - extra_query=extra_query, - extra_body=extra_body, - timeout=timeout, - query=maybe_transform( - { - "after": after, - "before": before, - "limit": limit, - "order": order, - }, - file_list_params.FileListParams, - ), - ), - model=MessageFile, - ) - - -class AsyncFiles(AsyncAPIResource): - @cached_property - def with_raw_response(self) -> AsyncFilesWithRawResponse: - return AsyncFilesWithRawResponse(self) - - @cached_property - def with_streaming_response(self) -> AsyncFilesWithStreamingResponse: - return AsyncFilesWithStreamingResponse(self) - - async def retrieve( - self, - file_id: str, - *, - thread_id: str, - message_id: str, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> MessageFile: - """ - Retrieves a message file. - - Args: - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - if not thread_id: - raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") - if not message_id: - raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") - if not file_id: - raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} - return await self._get( - f"/threads/{thread_id}/messages/{message_id}/files/{file_id}", - options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout - ), - cast_to=MessageFile, - ) - - def list( - self, - message_id: str, - *, - thread_id: str, - after: str | NotGiven = NOT_GIVEN, - before: str | NotGiven = NOT_GIVEN, - limit: int | NotGiven = NOT_GIVEN, - order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> AsyncPaginator[MessageFile, AsyncCursorPage[MessageFile]]: - """Returns a list of message files. - - Args: - after: A cursor for use in pagination. - - `after` is an object ID that defines your place - in the list. For instance, if you make a list request and receive 100 objects, - ending with obj_foo, your subsequent call can include after=obj_foo in order to - fetch the next page of the list. - - before: A cursor for use in pagination. `before` is an object ID that defines your place - in the list. For instance, if you make a list request and receive 100 objects, - ending with obj_foo, your subsequent call can include before=obj_foo in order to - fetch the previous page of the list. - - limit: A limit on the number of objects to be returned. Limit can range between 1 and - 100, and the default is 20. - - order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending - order and `desc` for descending order. - - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - if not thread_id: - raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") - if not message_id: - raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} - return self._get_api_list( - f"/threads/{thread_id}/messages/{message_id}/files", - page=AsyncCursorPage[MessageFile], - options=make_request_options( - extra_headers=extra_headers, - extra_query=extra_query, - extra_body=extra_body, - timeout=timeout, - query=maybe_transform( - { - "after": after, - "before": before, - "limit": limit, - "order": order, - }, - file_list_params.FileListParams, - ), - ), - model=MessageFile, - ) - - -class FilesWithRawResponse: - def __init__(self, files: Files) -> None: - self._files = files - - self.retrieve = _legacy_response.to_raw_response_wrapper( - files.retrieve, - ) - self.list = _legacy_response.to_raw_response_wrapper( - files.list, - ) - - -class AsyncFilesWithRawResponse: - def __init__(self, files: AsyncFiles) -> None: - self._files = files - - self.retrieve = _legacy_response.async_to_raw_response_wrapper( - files.retrieve, - ) - self.list = _legacy_response.async_to_raw_response_wrapper( - files.list, - ) - - -class FilesWithStreamingResponse: - def __init__(self, files: Files) -> None: - self._files = files - - self.retrieve = to_streamed_response_wrapper( - files.retrieve, - ) - self.list = to_streamed_response_wrapper( - files.list, - ) - - -class AsyncFilesWithStreamingResponse: - def __init__(self, files: AsyncFiles) -> None: - self._files = files - - self.retrieve = async_to_streamed_response_wrapper( - files.retrieve, - ) - self.list = async_to_streamed_response_wrapper( - files.list, - ) diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 9fa7239c0b..7aab17a30d 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -115,6 +115,7 @@ def create( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -196,6 +197,10 @@ def create( tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -248,6 +253,7 @@ def create( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -329,6 +335,10 @@ def create( tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -381,6 +391,7 @@ def create( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -462,6 +473,10 @@ def create( tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -514,6 +529,7 @@ def create( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -524,7 +540,7 @@ def create( ) -> Run | Stream[AssistantStreamEvent]: if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._post( f"/threads/{thread_id}/runs", body=maybe_transform( @@ -542,6 +558,7 @@ def create( "temperature": temperature, "tool_choice": tool_choice, "tools": tools, + "top_p": top_p, "truncation_strategy": truncation_strategy, }, run_create_params.RunCreateParams, @@ -582,7 +599,7 @@ def retrieve( raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") if not run_id: raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._get( f"/threads/{thread_id}/runs/{run_id}", options=make_request_options( @@ -625,7 +642,7 @@ def update( raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") if not run_id: raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._post( f"/threads/{thread_id}/runs/{run_id}", body=maybe_transform({"metadata": metadata}, run_update_params.RunUpdateParams), @@ -680,7 +697,7 @@ def list( """ if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._get_api_list( f"/threads/{thread_id}/runs", page=SyncCursorPage[Run], @@ -730,7 +747,7 @@ def cancel( raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") if not run_id: raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._post( f"/threads/{thread_id}/runs/{run_id}/cancel", options=make_request_options( @@ -778,6 +795,7 @@ def create_and_poll( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, poll_interval_ms: int | NotGiven = NOT_GIVEN, thread_id: str, @@ -810,6 +828,7 @@ def create_and_poll( stream=False, tools=tools, truncation_strategy=truncation_strategy, + top_p=top_p, extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, @@ -866,6 +885,7 @@ def create_and_stream( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, thread_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -919,6 +939,7 @@ def create_and_stream( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, thread_id: str, event_handler: AssistantEventHandlerT, @@ -972,6 +993,7 @@ def create_and_stream( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, thread_id: str, event_handler: AssistantEventHandlerT | None = None, @@ -987,7 +1009,7 @@ def create_and_stream( raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = { - "OpenAI-Beta": "assistants=v1", + "OpenAI-Beta": "assistants=v2", "X-Stainless-Stream-Helper": "threads.runs.create_and_stream", "X-Stainless-Custom-Event-Handler": "true" if event_handler else "false", **(extra_headers or {}), @@ -1011,6 +1033,7 @@ def create_and_stream( "stream": True, "tools": tools, "truncation_strategy": truncation_strategy, + "top_p": top_p, }, run_create_params.RunCreateParams, ), @@ -1108,6 +1131,7 @@ def stream( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, thread_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -1160,6 +1184,7 @@ def stream( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, thread_id: str, event_handler: AssistantEventHandlerT, @@ -1212,6 +1237,7 @@ def stream( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, thread_id: str, event_handler: AssistantEventHandlerT | None = None, @@ -1227,7 +1253,7 @@ def stream( raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = { - "OpenAI-Beta": "assistants=v1", + "OpenAI-Beta": "assistants=v2", "X-Stainless-Stream-Helper": "threads.runs.create_and_stream", "X-Stainless-Custom-Event-Handler": "true" if event_handler else "false", **(extra_headers or {}), @@ -1251,6 +1277,7 @@ def stream( "stream": True, "tools": tools, "truncation_strategy": truncation_strategy, + "top_p": top_p, }, run_create_params.RunCreateParams, ), @@ -1396,7 +1423,7 @@ def submit_tool_outputs( raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") if not run_id: raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._post( f"/threads/{thread_id}/runs/{run_id}/submit_tool_outputs", body=maybe_transform( @@ -1522,7 +1549,7 @@ def submit_tool_outputs_stream( raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = { - "OpenAI-Beta": "assistants=v1", + "OpenAI-Beta": "assistants=v2", "X-Stainless-Stream-Helper": "threads.runs.submit_tool_outputs_stream", "X-Stainless-Custom-Event-Handler": "true" if event_handler else "false", **(extra_headers or {}), @@ -1602,6 +1629,7 @@ async def create( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -1683,6 +1711,10 @@ async def create( tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -1735,6 +1767,7 @@ async def create( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -1816,6 +1849,10 @@ async def create( tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -1868,6 +1905,7 @@ async def create( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -1949,6 +1987,10 @@ async def create( tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -2001,6 +2043,7 @@ async def create( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -2011,7 +2054,7 @@ async def create( ) -> Run | AsyncStream[AssistantStreamEvent]: if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._post( f"/threads/{thread_id}/runs", body=await async_maybe_transform( @@ -2029,6 +2072,7 @@ async def create( "temperature": temperature, "tool_choice": tool_choice, "tools": tools, + "top_p": top_p, "truncation_strategy": truncation_strategy, }, run_create_params.RunCreateParams, @@ -2069,7 +2113,7 @@ async def retrieve( raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") if not run_id: raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._get( f"/threads/{thread_id}/runs/{run_id}", options=make_request_options( @@ -2112,7 +2156,7 @@ async def update( raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") if not run_id: raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._post( f"/threads/{thread_id}/runs/{run_id}", body=await async_maybe_transform({"metadata": metadata}, run_update_params.RunUpdateParams), @@ -2167,7 +2211,7 @@ def list( """ if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._get_api_list( f"/threads/{thread_id}/runs", page=AsyncCursorPage[Run], @@ -2217,7 +2261,7 @@ async def cancel( raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") if not run_id: raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._post( f"/threads/{thread_id}/runs/{run_id}/cancel", options=make_request_options( @@ -2265,6 +2309,7 @@ async def create_and_poll( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, poll_interval_ms: int | NotGiven = NOT_GIVEN, thread_id: str, @@ -2297,6 +2342,7 @@ async def create_and_poll( stream=False, tools=tools, truncation_strategy=truncation_strategy, + top_p=top_p, extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, @@ -2353,6 +2399,7 @@ def create_and_stream( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, thread_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -2406,6 +2453,7 @@ def create_and_stream( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, thread_id: str, event_handler: AsyncAssistantEventHandlerT, @@ -2459,6 +2507,7 @@ def create_and_stream( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, thread_id: str, event_handler: AsyncAssistantEventHandlerT | None = None, @@ -2477,7 +2526,7 @@ def create_and_stream( raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = { - "OpenAI-Beta": "assistants=v1", + "OpenAI-Beta": "assistants=v2", "X-Stainless-Stream-Helper": "threads.runs.create_and_stream", "X-Stainless-Custom-Event-Handler": "true" if event_handler else "false", **(extra_headers or {}), @@ -2500,6 +2549,7 @@ def create_and_stream( "stream": True, "tools": tools, "truncation_strategy": truncation_strategy, + "top_p": top_p, }, run_create_params.RunCreateParams, ), @@ -2597,6 +2647,7 @@ def stream( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, thread_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -2649,6 +2700,7 @@ def stream( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, thread_id: str, event_handler: AsyncAssistantEventHandlerT, @@ -2701,6 +2753,7 @@ def stream( temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[run_create_params.TruncationStrategy] | NotGiven = NOT_GIVEN, thread_id: str, event_handler: AsyncAssistantEventHandlerT | None = None, @@ -2719,7 +2772,7 @@ def stream( raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = { - "OpenAI-Beta": "assistants=v1", + "OpenAI-Beta": "assistants=v2", "X-Stainless-Stream-Helper": "threads.runs.create_and_stream", "X-Stainless-Custom-Event-Handler": "true" if event_handler else "false", **(extra_headers or {}), @@ -2742,6 +2795,7 @@ def stream( "stream": True, "tools": tools, "truncation_strategy": truncation_strategy, + "top_p": top_p, }, run_create_params.RunCreateParams, ), @@ -2887,7 +2941,7 @@ async def submit_tool_outputs( raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") if not run_id: raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._post( f"/threads/{thread_id}/runs/{run_id}/submit_tool_outputs", body=await async_maybe_transform( @@ -3016,7 +3070,7 @@ def submit_tool_outputs_stream( raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = { - "OpenAI-Beta": "assistants=v1", + "OpenAI-Beta": "assistants=v2", "X-Stainless-Stream-Helper": "threads.runs.submit_tool_outputs_stream", "X-Stainless-Custom-Event-Handler": "true" if event_handler else "false", **(extra_headers or {}), diff --git a/src/openai/resources/beta/threads/runs/steps.py b/src/openai/resources/beta/threads/runs/steps.py index 118bd8822a..986ef2997a 100644 --- a/src/openai/resources/beta/threads/runs/steps.py +++ b/src/openai/resources/beta/threads/runs/steps.py @@ -62,7 +62,7 @@ def retrieve( raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") if not step_id: raise ValueError(f"Expected a non-empty value for `step_id` but received {step_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._get( f"/threads/{thread_id}/runs/{run_id}/steps/{step_id}", options=make_request_options( @@ -119,7 +119,7 @@ def list( raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") if not run_id: raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._get_api_list( f"/threads/{thread_id}/runs/{run_id}/steps", page=SyncCursorPage[RunStep], @@ -182,7 +182,7 @@ async def retrieve( raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") if not step_id: raise ValueError(f"Expected a non-empty value for `step_id` but received {step_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._get( f"/threads/{thread_id}/runs/{run_id}/steps/{step_id}", options=make_request_options( @@ -239,7 +239,7 @@ def list( raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") if not run_id: raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._get_api_list( f"/threads/{thread_id}/runs/{run_id}/steps", page=AsyncCursorPage[RunStep], diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 9c2e2f0043..678c621a10 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -57,7 +57,6 @@ AsyncAssistantEventHandlerT, AsyncAssistantStreamManager, ) -from .messages.messages import Messages, AsyncMessages from ....types.beta.threads import Run __all__ = ["Threads", "AsyncThreads"] @@ -85,6 +84,7 @@ def create( *, messages: Iterable[thread_create_params.Message] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, + tool_resources: Optional[thread_create_params.ToolResources] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -104,6 +104,11 @@ def create( can be a maximum of 64 characters long and values can be a maxium of 512 characters long. + tool_resources: A set of resources that are made available to the assistant's tools in this + thread. The resources are specific to the type of tool. For example, the + `code_interpreter` tool requires a list of file IDs, while the `file_search` + tool requires a list of vector store IDs. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -112,13 +117,14 @@ def create( timeout: Override the client-level default timeout for this request, in seconds """ - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._post( "/threads", body=maybe_transform( { "messages": messages, "metadata": metadata, + "tool_resources": tool_resources, }, thread_create_params.ThreadCreateParams, ), @@ -153,7 +159,7 @@ def retrieve( """ if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._get( f"/threads/{thread_id}", options=make_request_options( @@ -167,6 +173,7 @@ def update( thread_id: str, *, metadata: Optional[object] | NotGiven = NOT_GIVEN, + tool_resources: Optional[thread_update_params.ToolResources] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -183,6 +190,11 @@ def update( can be a maximum of 64 characters long and values can be a maxium of 512 characters long. + tool_resources: A set of resources that are made available to the assistant's tools in this + thread. The resources are specific to the type of tool. For example, the + `code_interpreter` tool requires a list of file IDs, while the `file_search` + tool requires a list of vector store IDs. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -193,10 +205,16 @@ def update( """ if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._post( f"/threads/{thread_id}", - body=maybe_transform({"metadata": metadata}, thread_update_params.ThreadUpdateParams), + body=maybe_transform( + { + "metadata": metadata, + "tool_resources": tool_resources, + }, + thread_update_params.ThreadUpdateParams, + ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), @@ -228,7 +246,7 @@ def delete( """ if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._delete( f"/threads/{thread_id}", options=make_request_options( @@ -276,7 +294,9 @@ def create_and_run( temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, + tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -299,13 +319,13 @@ def create_and_run( max_completion_tokens: The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of - completion tokens specified, the run will end with status `complete`. See + completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of - prompt tokens specified, the run will end with status `complete`. See + prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful @@ -350,9 +370,18 @@ def create_and_run( `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. + tool_resources: A set of resources that are used by the assistant's tools. The resources are + specific to the type of tool. For example, the `code_interpreter` tool requires + a list of file IDs, while the `file_search` tool requires a list of vector store + IDs. + tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -402,7 +431,9 @@ def create_and_run( temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, + tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -429,13 +460,13 @@ def create_and_run( max_completion_tokens: The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of - completion tokens specified, the run will end with status `complete`. See + completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of - prompt tokens specified, the run will end with status `complete`. See + prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful @@ -476,9 +507,18 @@ def create_and_run( `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. + tool_resources: A set of resources that are used by the assistant's tools. The resources are + specific to the type of tool. For example, the `code_interpreter` tool requires + a list of file IDs, while the `file_search` tool requires a list of vector store + IDs. + tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -528,7 +568,9 @@ def create_and_run( temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, + tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -555,13 +597,13 @@ def create_and_run( max_completion_tokens: The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of - completion tokens specified, the run will end with status `complete`. See + completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of - prompt tokens specified, the run will end with status `complete`. See + prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful @@ -602,9 +644,18 @@ def create_and_run( `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. + tool_resources: A set of resources that are used by the assistant's tools. The resources are + specific to the type of tool. For example, the `code_interpreter` tool requires + a list of file IDs, while the `file_search` tool requires a list of vector store + IDs. + tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -654,7 +705,9 @@ def create_and_run( temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, + tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -663,7 +716,7 @@ def create_and_run( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Run | Stream[AssistantStreamEvent]: - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._post( "/threads/runs", body=maybe_transform( @@ -679,7 +732,9 @@ def create_and_run( "temperature": temperature, "thread": thread, "tool_choice": tool_choice, + "tool_resources": tool_resources, "tools": tools, + "top_p": top_p, "truncation_strategy": truncation_strategy, }, thread_create_and_run_params.ThreadCreateAndRunParams, @@ -729,7 +784,9 @@ def create_and_run_poll( temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, + tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, poll_interval_ms: int | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -755,8 +812,10 @@ def create_and_run_poll( temperature=temperature, stream=False, thread=thread, + tool_resources=tool_resources, tool_choice=tool_choice, truncation_strategy=truncation_strategy, + top_p=top_p, tools=tools, extra_headers=extra_headers, extra_query=extra_query, @@ -803,7 +862,9 @@ def create_and_run_stream( temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, + tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -853,7 +914,9 @@ def create_and_run_stream( temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, + tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, event_handler: AssistantEventHandlerT, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -903,7 +966,9 @@ def create_and_run_stream( temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, + tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, event_handler: AssistantEventHandlerT | None = None, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -915,7 +980,7 @@ def create_and_run_stream( ) -> AssistantStreamManager[AssistantEventHandler] | AssistantStreamManager[AssistantEventHandlerT]: """Create a thread and stream the run back""" extra_headers = { - "OpenAI-Beta": "assistants=v1", + "OpenAI-Beta": "assistants=v2", "X-Stainless-Stream-Helper": "threads.create_and_run_stream", "X-Stainless-Custom-Event-Handler": "true" if event_handler else "false", **(extra_headers or {}), @@ -937,7 +1002,9 @@ def create_and_run_stream( "stream": True, "thread": thread, "tools": tools, + "tool": tool_resources, "truncation_strategy": truncation_strategy, + "top_p": top_p, }, thread_create_and_run_params.ThreadCreateAndRunParams, ), @@ -973,6 +1040,7 @@ async def create( *, messages: Iterable[thread_create_params.Message] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, + tool_resources: Optional[thread_create_params.ToolResources] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -992,6 +1060,11 @@ async def create( can be a maximum of 64 characters long and values can be a maxium of 512 characters long. + tool_resources: A set of resources that are made available to the assistant's tools in this + thread. The resources are specific to the type of tool. For example, the + `code_interpreter` tool requires a list of file IDs, while the `file_search` + tool requires a list of vector store IDs. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -1000,13 +1073,14 @@ async def create( timeout: Override the client-level default timeout for this request, in seconds """ - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._post( "/threads", body=await async_maybe_transform( { "messages": messages, "metadata": metadata, + "tool_resources": tool_resources, }, thread_create_params.ThreadCreateParams, ), @@ -1041,7 +1115,7 @@ async def retrieve( """ if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._get( f"/threads/{thread_id}", options=make_request_options( @@ -1055,6 +1129,7 @@ async def update( thread_id: str, *, metadata: Optional[object] | NotGiven = NOT_GIVEN, + tool_resources: Optional[thread_update_params.ToolResources] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -1071,6 +1146,11 @@ async def update( can be a maximum of 64 characters long and values can be a maxium of 512 characters long. + tool_resources: A set of resources that are made available to the assistant's tools in this + thread. The resources are specific to the type of tool. For example, the + `code_interpreter` tool requires a list of file IDs, while the `file_search` + tool requires a list of vector store IDs. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -1081,10 +1161,16 @@ async def update( """ if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._post( f"/threads/{thread_id}", - body=await async_maybe_transform({"metadata": metadata}, thread_update_params.ThreadUpdateParams), + body=await async_maybe_transform( + { + "metadata": metadata, + "tool_resources": tool_resources, + }, + thread_update_params.ThreadUpdateParams, + ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), @@ -1116,7 +1202,7 @@ async def delete( """ if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._delete( f"/threads/{thread_id}", options=make_request_options( @@ -1164,7 +1250,9 @@ async def create_and_run( temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, + tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -1187,13 +1275,13 @@ async def create_and_run( max_completion_tokens: The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of - completion tokens specified, the run will end with status `complete`. See + completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of - prompt tokens specified, the run will end with status `complete`. See + prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful @@ -1238,9 +1326,18 @@ async def create_and_run( `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. + tool_resources: A set of resources that are used by the assistant's tools. The resources are + specific to the type of tool. For example, the `code_interpreter` tool requires + a list of file IDs, while the `file_search` tool requires a list of vector store + IDs. + tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -1290,7 +1387,9 @@ async def create_and_run( temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, + tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -1317,13 +1416,13 @@ async def create_and_run( max_completion_tokens: The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of - completion tokens specified, the run will end with status `complete`. See + completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of - prompt tokens specified, the run will end with status `complete`. See + prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful @@ -1364,9 +1463,18 @@ async def create_and_run( `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. + tool_resources: A set of resources that are used by the assistant's tools. The resources are + specific to the type of tool. For example, the `code_interpreter` tool requires + a list of file IDs, while the `file_search` tool requires a list of vector store + IDs. + tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -1416,7 +1524,9 @@ async def create_and_run( temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, + tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -1443,13 +1553,13 @@ async def create_and_run( max_completion_tokens: The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of - completion tokens specified, the run will end with status `complete`. See + completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of - prompt tokens specified, the run will end with status `complete`. See + prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful @@ -1490,9 +1600,18 @@ async def create_and_run( `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. + tool_resources: A set of resources that are used by the assistant's tools. The resources are + specific to the type of tool. For example, the `code_interpreter` tool requires + a list of file IDs, while the `file_search` tool requires a list of vector store + IDs. + tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -1542,7 +1661,9 @@ async def create_and_run( temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, + tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -1551,7 +1672,7 @@ async def create_and_run( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Run | AsyncStream[AssistantStreamEvent]: - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._post( "/threads/runs", body=await async_maybe_transform( @@ -1567,7 +1688,9 @@ async def create_and_run( "temperature": temperature, "thread": thread, "tool_choice": tool_choice, + "tool_resources": tool_resources, "tools": tools, + "top_p": top_p, "truncation_strategy": truncation_strategy, }, thread_create_and_run_params.ThreadCreateAndRunParams, @@ -1617,7 +1740,9 @@ async def create_and_run_poll( temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, + tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, poll_interval_ms: int | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -1643,8 +1768,10 @@ async def create_and_run_poll( temperature=temperature, stream=False, thread=thread, + tool_resources=tool_resources, tool_choice=tool_choice, truncation_strategy=truncation_strategy, + top_p=top_p, tools=tools, extra_headers=extra_headers, extra_query=extra_query, @@ -1693,7 +1820,9 @@ def create_and_run_stream( temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, + tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -1743,7 +1872,9 @@ def create_and_run_stream( temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, + tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, event_handler: AsyncAssistantEventHandlerT, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -1793,7 +1924,9 @@ def create_and_run_stream( temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, + tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, event_handler: AsyncAssistantEventHandlerT | None = None, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -1808,7 +1941,7 @@ def create_and_run_stream( ): """Create a thread and stream the run back""" extra_headers = { - "OpenAI-Beta": "assistants=v1", + "OpenAI-Beta": "assistants=v2", "X-Stainless-Stream-Helper": "threads.create_and_run_stream", "X-Stainless-Custom-Event-Handler": "true" if event_handler else "false", **(extra_headers or {}), @@ -1829,7 +1962,9 @@ def create_and_run_stream( "stream": True, "thread": thread, "tools": tools, + "tool": tool_resources, "truncation_strategy": truncation_strategy, + "top_p": top_p, }, thread_create_and_run_params.ThreadCreateAndRunParams, ), diff --git a/src/openai/resources/beta/vector_stores/__init__.py b/src/openai/resources/beta/vector_stores/__init__.py new file mode 100644 index 0000000000..96ae16c302 --- /dev/null +++ b/src/openai/resources/beta/vector_stores/__init__.py @@ -0,0 +1,47 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .files import ( + Files, + AsyncFiles, + FilesWithRawResponse, + AsyncFilesWithRawResponse, + FilesWithStreamingResponse, + AsyncFilesWithStreamingResponse, +) +from .file_batches import ( + FileBatches, + AsyncFileBatches, + FileBatchesWithRawResponse, + AsyncFileBatchesWithRawResponse, + FileBatchesWithStreamingResponse, + AsyncFileBatchesWithStreamingResponse, +) +from .vector_stores import ( + VectorStores, + AsyncVectorStores, + VectorStoresWithRawResponse, + AsyncVectorStoresWithRawResponse, + VectorStoresWithStreamingResponse, + AsyncVectorStoresWithStreamingResponse, +) + +__all__ = [ + "Files", + "AsyncFiles", + "FilesWithRawResponse", + "AsyncFilesWithRawResponse", + "FilesWithStreamingResponse", + "AsyncFilesWithStreamingResponse", + "FileBatches", + "AsyncFileBatches", + "FileBatchesWithRawResponse", + "AsyncFileBatchesWithRawResponse", + "FileBatchesWithStreamingResponse", + "AsyncFileBatchesWithStreamingResponse", + "VectorStores", + "AsyncVectorStores", + "VectorStoresWithRawResponse", + "AsyncVectorStoresWithRawResponse", + "VectorStoresWithStreamingResponse", + "AsyncVectorStoresWithStreamingResponse", +] diff --git a/src/openai/resources/beta/vector_stores/file_batches.py b/src/openai/resources/beta/vector_stores/file_batches.py new file mode 100644 index 0000000000..55b30b08e3 --- /dev/null +++ b/src/openai/resources/beta/vector_stores/file_batches.py @@ -0,0 +1,739 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import asyncio +from typing import List, Iterable +from typing_extensions import Literal +from concurrent.futures import Future, ThreadPoolExecutor, as_completed + +import httpx +import sniffio + +from .... import _legacy_response +from ....types import FileObject +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes +from ...._utils import ( + is_given, + maybe_transform, + async_maybe_transform, +) +from ...._compat import cached_property +from ...._resource import SyncAPIResource, AsyncAPIResource +from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ....pagination import SyncCursorPage, AsyncCursorPage +from ...._base_client import ( + AsyncPaginator, + make_request_options, +) +from ....types.beta.vector_stores import ( + VectorStoreFile, + VectorStoreFileBatch, + file_batch_create_params, + file_batch_list_files_params, +) + +__all__ = ["FileBatches", "AsyncFileBatches"] + + +class FileBatches(SyncAPIResource): + @cached_property + def with_raw_response(self) -> FileBatchesWithRawResponse: + return FileBatchesWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> FileBatchesWithStreamingResponse: + return FileBatchesWithStreamingResponse(self) + + def create( + self, + vector_store_id: str, + *, + file_ids: List[str], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> VectorStoreFileBatch: + """ + Create a vector store file batch. + + Args: + file_ids: A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + the vector store should use. Useful for tools like `file_search` that can access + files. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return self._post( + f"/vector_stores/{vector_store_id}/file_batches", + body=maybe_transform({"file_ids": file_ids}, file_batch_create_params.FileBatchCreateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=VectorStoreFileBatch, + ) + + def retrieve( + self, + batch_id: str, + *, + vector_store_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> VectorStoreFileBatch: + """ + Retrieves a vector store file batch. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") + if not batch_id: + raise ValueError(f"Expected a non-empty value for `batch_id` but received {batch_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return self._get( + f"/vector_stores/{vector_store_id}/file_batches/{batch_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=VectorStoreFileBatch, + ) + + def cancel( + self, + batch_id: str, + *, + vector_store_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> VectorStoreFileBatch: + """Cancel a vector store file batch. + + This attempts to cancel the processing of + files in this batch as soon as possible. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") + if not batch_id: + raise ValueError(f"Expected a non-empty value for `batch_id` but received {batch_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return self._post( + f"/vector_stores/{vector_store_id}/file_batches/{batch_id}/cancel", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=VectorStoreFileBatch, + ) + + def create_and_poll( + self, + vector_store_id: str, + *, + file_ids: List[str], + poll_interval_ms: int | NotGiven = NOT_GIVEN, + ) -> VectorStoreFileBatch: + """Create a vector store batch and poll until all files have been processed.""" + batch = self.create( + vector_store_id=vector_store_id, + file_ids=file_ids, + ) + # TODO: don't poll unless necessary?? + return self.poll( + batch.id, + vector_store_id=vector_store_id, + poll_interval_ms=poll_interval_ms, + ) + + def list_files( + self, + batch_id: str, + *, + vector_store_id: str, + after: str | NotGiven = NOT_GIVEN, + before: str | NotGiven = NOT_GIVEN, + filter: Literal["in_progress", "completed", "failed", "cancelled"] | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> SyncCursorPage[VectorStoreFile]: + """ + Returns a list of vector store files in a batch. + + Args: + after: A cursor for use in pagination. `after` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include after=obj_foo in order to + fetch the next page of the list. + + before: A cursor for use in pagination. `before` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include before=obj_foo in order to + fetch the previous page of the list. + + filter: Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`. + + limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the default is 20. + + order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending + order and `desc` for descending order. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") + if not batch_id: + raise ValueError(f"Expected a non-empty value for `batch_id` but received {batch_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return self._get_api_list( + f"/vector_stores/{vector_store_id}/file_batches/{batch_id}/files", + page=SyncCursorPage[VectorStoreFile], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "before": before, + "filter": filter, + "limit": limit, + "order": order, + }, + file_batch_list_files_params.FileBatchListFilesParams, + ), + ), + model=VectorStoreFile, + ) + + def poll( + self, + batch_id: str, + *, + vector_store_id: str, + poll_interval_ms: int | NotGiven = NOT_GIVEN, + ) -> VectorStoreFileBatch: + """Wait for the given file batch to be processed. + + Note: this will return even if one of the files failed to process, you need to + check batch.file_counts.failed_count to handle this case. + """ + headers: dict[str, str] = {"X-Stainless-Poll-Helper": "true"} + if is_given(poll_interval_ms): + headers["X-Stainless-Custom-Poll-Interval"] = str(poll_interval_ms) + + while True: + response = self.with_raw_response.retrieve( + batch_id, + vector_store_id=vector_store_id, + extra_headers=headers, + ) + + batch = response.parse() + if batch.file_counts.in_progress > 0: + if not is_given(poll_interval_ms): + from_header = response.headers.get("openai-poll-after-ms") + if from_header is not None: + poll_interval_ms = int(from_header) + else: + poll_interval_ms = 1000 + + self._sleep(poll_interval_ms / 1000) + continue + + return batch + + def upload_and_poll( + self, + vector_store_id: str, + *, + files: Iterable[FileTypes], + max_concurrency: int = 5, + file_ids: List[str] = [], + poll_interval_ms: int | NotGiven = NOT_GIVEN, + ) -> VectorStoreFileBatch: + """Uploads the given files concurrently and then creates a vector store file batch. + + If you've already uploaded certain files that you want to include in this batch + then you can pass their IDs through the `file_ids` argument. + + By default, if any file upload fails then an exception will be eagerly raised. + + The number of concurrency uploads is configurable using the `max_concurrency` + parameter. + + Note: this method only supports `asyncio` or `trio` as the backing async + runtime. + """ + results: list[FileObject] = [] + + with ThreadPoolExecutor(max_workers=max_concurrency) as executor: + futures: list[Future[FileObject]] = [ + executor.submit( + self._client.files.create, + file=file, + purpose="assistants", + ) + for file in files + ] + + for future in as_completed(futures): + exc = future.exception() + if exc: + raise exc + + results.append(future.result()) + + batch = self.create_and_poll( + vector_store_id=vector_store_id, + file_ids=[*file_ids, *(f.id for f in results)], + poll_interval_ms=poll_interval_ms, + ) + return batch + + +class AsyncFileBatches(AsyncAPIResource): + @cached_property + def with_raw_response(self) -> AsyncFileBatchesWithRawResponse: + return AsyncFileBatchesWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncFileBatchesWithStreamingResponse: + return AsyncFileBatchesWithStreamingResponse(self) + + async def create( + self, + vector_store_id: str, + *, + file_ids: List[str], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> VectorStoreFileBatch: + """ + Create a vector store file batch. + + Args: + file_ids: A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + the vector store should use. Useful for tools like `file_search` that can access + files. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return await self._post( + f"/vector_stores/{vector_store_id}/file_batches", + body=await async_maybe_transform({"file_ids": file_ids}, file_batch_create_params.FileBatchCreateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=VectorStoreFileBatch, + ) + + async def retrieve( + self, + batch_id: str, + *, + vector_store_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> VectorStoreFileBatch: + """ + Retrieves a vector store file batch. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") + if not batch_id: + raise ValueError(f"Expected a non-empty value for `batch_id` but received {batch_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return await self._get( + f"/vector_stores/{vector_store_id}/file_batches/{batch_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=VectorStoreFileBatch, + ) + + async def cancel( + self, + batch_id: str, + *, + vector_store_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> VectorStoreFileBatch: + """Cancel a vector store file batch. + + This attempts to cancel the processing of + files in this batch as soon as possible. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") + if not batch_id: + raise ValueError(f"Expected a non-empty value for `batch_id` but received {batch_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return await self._post( + f"/vector_stores/{vector_store_id}/file_batches/{batch_id}/cancel", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=VectorStoreFileBatch, + ) + + async def create_and_poll( + self, + vector_store_id: str, + *, + file_ids: List[str], + poll_interval_ms: int | NotGiven = NOT_GIVEN, + ) -> VectorStoreFileBatch: + """Create a vector store batch and poll until all files have been processed.""" + batch = await self.create( + vector_store_id=vector_store_id, + file_ids=file_ids, + ) + # TODO: don't poll unless necessary?? + return await self.poll( + batch.id, + vector_store_id=vector_store_id, + poll_interval_ms=poll_interval_ms, + ) + + def list_files( + self, + batch_id: str, + *, + vector_store_id: str, + after: str | NotGiven = NOT_GIVEN, + before: str | NotGiven = NOT_GIVEN, + filter: Literal["in_progress", "completed", "failed", "cancelled"] | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncPaginator[VectorStoreFile, AsyncCursorPage[VectorStoreFile]]: + """ + Returns a list of vector store files in a batch. + + Args: + after: A cursor for use in pagination. `after` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include after=obj_foo in order to + fetch the next page of the list. + + before: A cursor for use in pagination. `before` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include before=obj_foo in order to + fetch the previous page of the list. + + filter: Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`. + + limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the default is 20. + + order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending + order and `desc` for descending order. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") + if not batch_id: + raise ValueError(f"Expected a non-empty value for `batch_id` but received {batch_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return self._get_api_list( + f"/vector_stores/{vector_store_id}/file_batches/{batch_id}/files", + page=AsyncCursorPage[VectorStoreFile], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "before": before, + "filter": filter, + "limit": limit, + "order": order, + }, + file_batch_list_files_params.FileBatchListFilesParams, + ), + ), + model=VectorStoreFile, + ) + + async def poll( + self, + batch_id: str, + *, + vector_store_id: str, + poll_interval_ms: int | NotGiven = NOT_GIVEN, + ) -> VectorStoreFileBatch: + """Wait for the given file batch to be processed. + + Note: this will return even if one of the files failed to process, you need to + check batch.file_counts.failed_count to handle this case. + """ + headers: dict[str, str] = {"X-Stainless-Poll-Helper": "true"} + if is_given(poll_interval_ms): + headers["X-Stainless-Custom-Poll-Interval"] = str(poll_interval_ms) + + while True: + response = await self.with_raw_response.retrieve( + batch_id, + vector_store_id=vector_store_id, + extra_headers=headers, + ) + + batch = response.parse() + if batch.file_counts.in_progress > 0: + if not is_given(poll_interval_ms): + from_header = response.headers.get("openai-poll-after-ms") + if from_header is not None: + poll_interval_ms = int(from_header) + else: + poll_interval_ms = 1000 + + await self._sleep(poll_interval_ms / 1000) + continue + + return batch + + async def upload_and_poll( + self, + vector_store_id: str, + *, + files: Iterable[FileTypes], + max_concurrency: int = 5, + file_ids: List[str] = [], + poll_interval_ms: int | NotGiven = NOT_GIVEN, + ) -> VectorStoreFileBatch: + """Uploads the given files concurrently and then creates a vector store file batch. + + If you've already uploaded certain files that you want to include in this batch + then you can pass their IDs through the `file_ids` argument. + + By default, if any file upload fails then an exception will be eagerly raised. + + The number of concurrency uploads is configurable using the `max_concurrency` + parameter. + + Note: this method only supports `asyncio` or `trio` as the backing async + runtime. + """ + uploaded_files: list[FileObject] = [] + + async_library = sniffio.current_async_library() + + if async_library == "asyncio": + + async def asyncio_upload_file(semaphore: asyncio.Semaphore, file: FileTypes) -> None: + async with semaphore: + file_obj = await self._client.files.create( + file=file, + purpose="assistants", + ) + uploaded_files.append(file_obj) + + semaphore = asyncio.Semaphore(max_concurrency) + + tasks = [asyncio_upload_file(semaphore, file) for file in files] + + await asyncio.gather(*tasks) + elif async_library == "trio": + # We only import if the library is being used. + # We support Python 3.7 so are using an older version of trio that does not have type information + import trio # type: ignore # pyright: ignore[reportMissingTypeStubs] + + async def trio_upload_file(limiter: trio.CapacityLimiter, file: FileTypes) -> None: + async with limiter: + file_obj = await self._client.files.create( + file=file, + purpose="assistants", + ) + uploaded_files.append(file_obj) + + limiter = trio.CapacityLimiter(max_concurrency) + + async with trio.open_nursery() as nursery: + for file in files: + nursery.start_soon(trio_upload_file, limiter, file) # pyright: ignore [reportUnknownMemberType] + else: + raise RuntimeError( + f"Async runtime {async_library} is not supported yet. Only asyncio or trio is supported", + ) + + batch = await self.create_and_poll( + vector_store_id=vector_store_id, + file_ids=[*file_ids, *(f.id for f in uploaded_files)], + poll_interval_ms=poll_interval_ms, + ) + return batch + + +class FileBatchesWithRawResponse: + def __init__(self, file_batches: FileBatches) -> None: + self._file_batches = file_batches + + self.create = _legacy_response.to_raw_response_wrapper( + file_batches.create, + ) + self.retrieve = _legacy_response.to_raw_response_wrapper( + file_batches.retrieve, + ) + self.cancel = _legacy_response.to_raw_response_wrapper( + file_batches.cancel, + ) + self.list_files = _legacy_response.to_raw_response_wrapper( + file_batches.list_files, + ) + + +class AsyncFileBatchesWithRawResponse: + def __init__(self, file_batches: AsyncFileBatches) -> None: + self._file_batches = file_batches + + self.create = _legacy_response.async_to_raw_response_wrapper( + file_batches.create, + ) + self.retrieve = _legacy_response.async_to_raw_response_wrapper( + file_batches.retrieve, + ) + self.cancel = _legacy_response.async_to_raw_response_wrapper( + file_batches.cancel, + ) + self.list_files = _legacy_response.async_to_raw_response_wrapper( + file_batches.list_files, + ) + + +class FileBatchesWithStreamingResponse: + def __init__(self, file_batches: FileBatches) -> None: + self._file_batches = file_batches + + self.create = to_streamed_response_wrapper( + file_batches.create, + ) + self.retrieve = to_streamed_response_wrapper( + file_batches.retrieve, + ) + self.cancel = to_streamed_response_wrapper( + file_batches.cancel, + ) + self.list_files = to_streamed_response_wrapper( + file_batches.list_files, + ) + + +class AsyncFileBatchesWithStreamingResponse: + def __init__(self, file_batches: AsyncFileBatches) -> None: + self._file_batches = file_batches + + self.create = async_to_streamed_response_wrapper( + file_batches.create, + ) + self.retrieve = async_to_streamed_response_wrapper( + file_batches.retrieve, + ) + self.cancel = async_to_streamed_response_wrapper( + file_batches.cancel, + ) + self.list_files = async_to_streamed_response_wrapper( + file_batches.list_files, + ) diff --git a/src/openai/resources/beta/assistants/files.py b/src/openai/resources/beta/vector_stores/files.py similarity index 57% rename from src/openai/resources/beta/assistants/files.py rename to src/openai/resources/beta/vector_stores/files.py index dc57dfb96c..6404b9d54c 100644 --- a/src/openai/resources/beta/assistants/files.py +++ b/src/openai/resources/beta/vector_stores/files.py @@ -2,13 +2,15 @@ from __future__ import annotations -from typing_extensions import Literal +from typing import TYPE_CHECKING +from typing_extensions import Literal, assert_never import httpx from .... import _legacy_response -from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from ...._utils import ( + is_given, maybe_transform, async_maybe_transform, ) @@ -20,7 +22,7 @@ AsyncPaginator, make_request_options, ) -from ....types.beta.assistants import AssistantFile, FileDeleteResponse, file_list_params, file_create_params +from ....types.beta.vector_stores import VectorStoreFile, VectorStoreFileDeleted, file_list_params, file_create_params __all__ = ["Files", "AsyncFiles"] @@ -36,7 +38,7 @@ def with_streaming_response(self) -> FilesWithStreamingResponse: def create( self, - assistant_id: str, + vector_store_id: str, *, file_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -45,16 +47,16 @@ def create( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> AssistantFile: + ) -> VectorStoreFile: """ - Create an assistant file by attaching a - [File](https://platform.openai.com/docs/api-reference/files) to an - [assistant](https://platform.openai.com/docs/api-reference/assistants). + Create a vector store file by attaching a + [File](https://platform.openai.com/docs/api-reference/files) to a + [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object). Args: - file_id: A [File](https://platform.openai.com/docs/api-reference/files) ID (with - `purpose="assistants"`) that the assistant should use. Useful for tools like - `retrieval` and `code_interpreter` that can access files. + file_id: A [File](https://platform.openai.com/docs/api-reference/files) ID that the + vector store should use. Useful for tools like `file_search` that can access + files. extra_headers: Send extra headers @@ -64,32 +66,32 @@ def create( timeout: Override the client-level default timeout for this request, in seconds """ - if not assistant_id: - raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._post( - f"/assistants/{assistant_id}/files", + f"/vector_stores/{vector_store_id}/files", body=maybe_transform({"file_id": file_id}, file_create_params.FileCreateParams), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), - cast_to=AssistantFile, + cast_to=VectorStoreFile, ) def retrieve( self, file_id: str, *, - assistant_id: str, + vector_store_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> AssistantFile: + ) -> VectorStoreFile: """ - Retrieves an AssistantFile. + Retrieves a vector store file. Args: extra_headers: Send extra headers @@ -100,25 +102,26 @@ def retrieve( timeout: Override the client-level default timeout for this request, in seconds """ - if not assistant_id: - raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") if not file_id: raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._get( - f"/assistants/{assistant_id}/files/{file_id}", + f"/vector_stores/{vector_store_id}/files/{file_id}", options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), - cast_to=AssistantFile, + cast_to=VectorStoreFile, ) def list( self, - assistant_id: str, + vector_store_id: str, *, after: str | NotGiven = NOT_GIVEN, before: str | NotGiven = NOT_GIVEN, + filter: Literal["in_progress", "completed", "failed", "cancelled"] | NotGiven = NOT_GIVEN, limit: int | NotGiven = NOT_GIVEN, order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -127,9 +130,9 @@ def list( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> SyncCursorPage[AssistantFile]: + ) -> SyncCursorPage[VectorStoreFile]: """ - Returns a list of assistant files. + Returns a list of vector store files. Args: after: A cursor for use in pagination. `after` is an object ID that defines your place @@ -142,6 +145,8 @@ def list( ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + filter: Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`. + limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. @@ -156,12 +161,12 @@ def list( timeout: Override the client-level default timeout for this request, in seconds """ - if not assistant_id: - raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._get_api_list( - f"/assistants/{assistant_id}/files", - page=SyncCursorPage[AssistantFile], + f"/vector_stores/{vector_store_id}/files", + page=SyncCursorPage[VectorStoreFile], options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, @@ -171,29 +176,34 @@ def list( { "after": after, "before": before, + "filter": filter, "limit": limit, "order": order, }, file_list_params.FileListParams, ), ), - model=AssistantFile, + model=VectorStoreFile, ) def delete( self, file_id: str, *, - assistant_id: str, + vector_store_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> FileDeleteResponse: - """ - Delete an assistant file. + ) -> VectorStoreFileDeleted: + """Delete a vector store file. + + This will remove the file from the vector store but + the file itself will not be deleted. To delete the file, use the + [delete file](https://platform.openai.com/docs/api-reference/files/delete) + endpoint. Args: extra_headers: Send extra headers @@ -204,17 +214,103 @@ def delete( timeout: Override the client-level default timeout for this request, in seconds """ - if not assistant_id: - raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") if not file_id: raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._delete( - f"/assistants/{assistant_id}/files/{file_id}", + f"/vector_stores/{vector_store_id}/files/{file_id}", options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), - cast_to=FileDeleteResponse, + cast_to=VectorStoreFileDeleted, + ) + + def create_and_poll( + self, + file_id: str, + *, + vector_store_id: str, + poll_interval_ms: int | NotGiven = NOT_GIVEN, + ) -> VectorStoreFile: + """Attach a file to the given vector store and wait for it to be processed.""" + self.create(vector_store_id=vector_store_id, file_id=file_id) + + return self.poll( + file_id, + vector_store_id=vector_store_id, + poll_interval_ms=poll_interval_ms, + ) + + def poll( + self, + file_id: str, + *, + vector_store_id: str, + poll_interval_ms: int | NotGiven = NOT_GIVEN, + ) -> VectorStoreFile: + """Wait for the vector store file to finish processing. + + Note: this will return even if the file failed to process, you need to check + file.last_error and file.status to handle these cases + """ + headers: dict[str, str] = {"X-Stainless-Poll-Helper": "true"} + if is_given(poll_interval_ms): + headers["X-Stainless-Custom-Poll-Interval"] = str(poll_interval_ms) + + while True: + response = self.with_raw_response.retrieve( + file_id, + vector_store_id=vector_store_id, + extra_headers=headers, + ) + + file = response.parse() + if file.status == "in_progress": + if not is_given(poll_interval_ms): + from_header = response.headers.get("openai-poll-after-ms") + if from_header is not None: + poll_interval_ms = int(from_header) + else: + poll_interval_ms = 1000 + + self._sleep(poll_interval_ms / 1000) + elif file.status == "cancelled" or file.status == "completed" or file.status == "failed": + return file + else: + if TYPE_CHECKING: # type: ignore[unreachable] + assert_never(file.status) + else: + return file + + def upload( + self, + *, + vector_store_id: str, + file: FileTypes, + ) -> VectorStoreFile: + """Upload a file to the `files` API and then attach it to the given vector store. + + Note the file will be asynchronously processed (you can use the alternative + polling helper method to wait for processing to complete). + """ + file_obj = self._client.files.create(file=file, purpose="assistants") + return self.create(vector_store_id=vector_store_id, file_id=file_obj.id) + + def upload_and_poll( + self, + *, + vector_store_id: str, + file: FileTypes, + poll_interval_ms: int | NotGiven = NOT_GIVEN, + ) -> VectorStoreFile: + """Add a file to a vector store and poll until processing is complete.""" + file_obj = self._client.files.create(file=file, purpose="assistants") + return self.create_and_poll( + vector_store_id=vector_store_id, + file_id=file_obj.id, + poll_interval_ms=poll_interval_ms, ) @@ -229,7 +325,7 @@ def with_streaming_response(self) -> AsyncFilesWithStreamingResponse: async def create( self, - assistant_id: str, + vector_store_id: str, *, file_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -238,16 +334,16 @@ async def create( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> AssistantFile: + ) -> VectorStoreFile: """ - Create an assistant file by attaching a - [File](https://platform.openai.com/docs/api-reference/files) to an - [assistant](https://platform.openai.com/docs/api-reference/assistants). + Create a vector store file by attaching a + [File](https://platform.openai.com/docs/api-reference/files) to a + [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object). Args: - file_id: A [File](https://platform.openai.com/docs/api-reference/files) ID (with - `purpose="assistants"`) that the assistant should use. Useful for tools like - `retrieval` and `code_interpreter` that can access files. + file_id: A [File](https://platform.openai.com/docs/api-reference/files) ID that the + vector store should use. Useful for tools like `file_search` that can access + files. extra_headers: Send extra headers @@ -257,32 +353,32 @@ async def create( timeout: Override the client-level default timeout for this request, in seconds """ - if not assistant_id: - raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._post( - f"/assistants/{assistant_id}/files", + f"/vector_stores/{vector_store_id}/files", body=await async_maybe_transform({"file_id": file_id}, file_create_params.FileCreateParams), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), - cast_to=AssistantFile, + cast_to=VectorStoreFile, ) async def retrieve( self, file_id: str, *, - assistant_id: str, + vector_store_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> AssistantFile: + ) -> VectorStoreFile: """ - Retrieves an AssistantFile. + Retrieves a vector store file. Args: extra_headers: Send extra headers @@ -293,25 +389,26 @@ async def retrieve( timeout: Override the client-level default timeout for this request, in seconds """ - if not assistant_id: - raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") if not file_id: raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._get( - f"/assistants/{assistant_id}/files/{file_id}", + f"/vector_stores/{vector_store_id}/files/{file_id}", options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), - cast_to=AssistantFile, + cast_to=VectorStoreFile, ) def list( self, - assistant_id: str, + vector_store_id: str, *, after: str | NotGiven = NOT_GIVEN, before: str | NotGiven = NOT_GIVEN, + filter: Literal["in_progress", "completed", "failed", "cancelled"] | NotGiven = NOT_GIVEN, limit: int | NotGiven = NOT_GIVEN, order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -320,9 +417,9 @@ def list( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> AsyncPaginator[AssistantFile, AsyncCursorPage[AssistantFile]]: + ) -> AsyncPaginator[VectorStoreFile, AsyncCursorPage[VectorStoreFile]]: """ - Returns a list of assistant files. + Returns a list of vector store files. Args: after: A cursor for use in pagination. `after` is an object ID that defines your place @@ -335,6 +432,8 @@ def list( ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + filter: Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`. + limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. @@ -349,12 +448,12 @@ def list( timeout: Override the client-level default timeout for this request, in seconds """ - if not assistant_id: - raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._get_api_list( - f"/assistants/{assistant_id}/files", - page=AsyncCursorPage[AssistantFile], + f"/vector_stores/{vector_store_id}/files", + page=AsyncCursorPage[VectorStoreFile], options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, @@ -364,29 +463,34 @@ def list( { "after": after, "before": before, + "filter": filter, "limit": limit, "order": order, }, file_list_params.FileListParams, ), ), - model=AssistantFile, + model=VectorStoreFile, ) async def delete( self, file_id: str, *, - assistant_id: str, + vector_store_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> FileDeleteResponse: - """ - Delete an assistant file. + ) -> VectorStoreFileDeleted: + """Delete a vector store file. + + This will remove the file from the vector store but + the file itself will not be deleted. To delete the file, use the + [delete file](https://platform.openai.com/docs/api-reference/files/delete) + endpoint. Args: extra_headers: Send extra headers @@ -397,17 +501,103 @@ async def delete( timeout: Override the client-level default timeout for this request, in seconds """ - if not assistant_id: - raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") if not file_id: raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") - extra_headers = {"OpenAI-Beta": "assistants=v1", **(extra_headers or {})} + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._delete( - f"/assistants/{assistant_id}/files/{file_id}", + f"/vector_stores/{vector_store_id}/files/{file_id}", options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), - cast_to=FileDeleteResponse, + cast_to=VectorStoreFileDeleted, + ) + + async def create_and_poll( + self, + file_id: str, + *, + vector_store_id: str, + poll_interval_ms: int | NotGiven = NOT_GIVEN, + ) -> VectorStoreFile: + """Attach a file to the given vector store and wait for it to be processed.""" + await self.create(vector_store_id=vector_store_id, file_id=file_id) + + return await self.poll( + file_id, + vector_store_id=vector_store_id, + poll_interval_ms=poll_interval_ms, + ) + + async def poll( + self, + file_id: str, + *, + vector_store_id: str, + poll_interval_ms: int | NotGiven = NOT_GIVEN, + ) -> VectorStoreFile: + """Wait for the vector store file to finish processing. + + Note: this will return even if the file failed to process, you need to check + file.last_error and file.status to handle these cases + """ + headers: dict[str, str] = {"X-Stainless-Poll-Helper": "true"} + if is_given(poll_interval_ms): + headers["X-Stainless-Custom-Poll-Interval"] = str(poll_interval_ms) + + while True: + response = await self.with_raw_response.retrieve( + file_id, + vector_store_id=vector_store_id, + extra_headers=headers, + ) + + file = response.parse() + if file.status == "in_progress": + if not is_given(poll_interval_ms): + from_header = response.headers.get("openai-poll-after-ms") + if from_header is not None: + poll_interval_ms = int(from_header) + else: + poll_interval_ms = 1000 + + await self._sleep(poll_interval_ms / 1000) + elif file.status == "cancelled" or file.status == "completed" or file.status == "failed": + return file + else: + if TYPE_CHECKING: # type: ignore[unreachable] + assert_never(file.status) + else: + return file + + async def upload( + self, + *, + vector_store_id: str, + file: FileTypes, + ) -> VectorStoreFile: + """Upload a file to the `files` API and then attach it to the given vector store. + + Note the file will be asynchronously processed (you can use the alternative + polling helper method to wait for processing to complete). + """ + file_obj = await self._client.files.create(file=file, purpose="assistants") + return await self.create(vector_store_id=vector_store_id, file_id=file_obj.id) + + async def upload_and_poll( + self, + *, + vector_store_id: str, + file: FileTypes, + poll_interval_ms: int | NotGiven = NOT_GIVEN, + ) -> VectorStoreFile: + """Add a file to a vector store and poll until processing is complete.""" + file_obj = await self._client.files.create(file=file, purpose="assistants") + return await self.create_and_poll( + vector_store_id=vector_store_id, + file_id=file_obj.id, + poll_interval_ms=poll_interval_ms, ) diff --git a/src/openai/resources/beta/vector_stores/vector_stores.py b/src/openai/resources/beta/vector_stores/vector_stores.py new file mode 100644 index 0000000000..6e2c9ab70c --- /dev/null +++ b/src/openai/resources/beta/vector_stores/vector_stores.py @@ -0,0 +1,688 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Literal + +import httpx + +from .... import _legacy_response +from .files import ( + Files, + AsyncFiles, + FilesWithRawResponse, + AsyncFilesWithRawResponse, + FilesWithStreamingResponse, + AsyncFilesWithStreamingResponse, +) +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ...._utils import ( + maybe_transform, + async_maybe_transform, +) +from ...._compat import cached_property +from ...._resource import SyncAPIResource, AsyncAPIResource +from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from .file_batches import ( + FileBatches, + AsyncFileBatches, + FileBatchesWithRawResponse, + AsyncFileBatchesWithRawResponse, + FileBatchesWithStreamingResponse, + AsyncFileBatchesWithStreamingResponse, +) +from ....pagination import SyncCursorPage, AsyncCursorPage +from ....types.beta import ( + VectorStore, + VectorStoreDeleted, + vector_store_list_params, + vector_store_create_params, + vector_store_update_params, +) +from ...._base_client import ( + AsyncPaginator, + make_request_options, +) + +__all__ = ["VectorStores", "AsyncVectorStores"] + + +class VectorStores(SyncAPIResource): + @cached_property + def files(self) -> Files: + return Files(self._client) + + @cached_property + def file_batches(self) -> FileBatches: + return FileBatches(self._client) + + @cached_property + def with_raw_response(self) -> VectorStoresWithRawResponse: + return VectorStoresWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> VectorStoresWithStreamingResponse: + return VectorStoresWithStreamingResponse(self) + + def create( + self, + *, + expires_after: vector_store_create_params.ExpiresAfter | NotGiven = NOT_GIVEN, + file_ids: List[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + name: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> VectorStore: + """ + Create a vector store. + + Args: + expires_after: The expiration policy for a vector store. + + file_ids: A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + the vector store should use. Useful for tools like `file_search` that can access + files. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + name: The name of the vector store. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return self._post( + "/vector_stores", + body=maybe_transform( + { + "expires_after": expires_after, + "file_ids": file_ids, + "metadata": metadata, + "name": name, + }, + vector_store_create_params.VectorStoreCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=VectorStore, + ) + + def retrieve( + self, + vector_store_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> VectorStore: + """ + Retrieves a vector store. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return self._get( + f"/vector_stores/{vector_store_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=VectorStore, + ) + + def update( + self, + vector_store_id: str, + *, + expires_after: Optional[vector_store_update_params.ExpiresAfter] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + name: Optional[str] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> VectorStore: + """ + Modifies a vector store. + + Args: + expires_after: The expiration policy for a vector store. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + name: The name of the vector store. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return self._post( + f"/vector_stores/{vector_store_id}", + body=maybe_transform( + { + "expires_after": expires_after, + "metadata": metadata, + "name": name, + }, + vector_store_update_params.VectorStoreUpdateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=VectorStore, + ) + + def list( + self, + *, + after: str | NotGiven = NOT_GIVEN, + before: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> SyncCursorPage[VectorStore]: + """Returns a list of vector stores. + + Args: + after: A cursor for use in pagination. + + `after` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include after=obj_foo in order to + fetch the next page of the list. + + before: A cursor for use in pagination. `before` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include before=obj_foo in order to + fetch the previous page of the list. + + limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the default is 20. + + order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending + order and `desc` for descending order. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return self._get_api_list( + "/vector_stores", + page=SyncCursorPage[VectorStore], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "before": before, + "limit": limit, + "order": order, + }, + vector_store_list_params.VectorStoreListParams, + ), + ), + model=VectorStore, + ) + + def delete( + self, + vector_store_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> VectorStoreDeleted: + """ + Delete a vector store. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return self._delete( + f"/vector_stores/{vector_store_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=VectorStoreDeleted, + ) + + +class AsyncVectorStores(AsyncAPIResource): + @cached_property + def files(self) -> AsyncFiles: + return AsyncFiles(self._client) + + @cached_property + def file_batches(self) -> AsyncFileBatches: + return AsyncFileBatches(self._client) + + @cached_property + def with_raw_response(self) -> AsyncVectorStoresWithRawResponse: + return AsyncVectorStoresWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncVectorStoresWithStreamingResponse: + return AsyncVectorStoresWithStreamingResponse(self) + + async def create( + self, + *, + expires_after: vector_store_create_params.ExpiresAfter | NotGiven = NOT_GIVEN, + file_ids: List[str] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + name: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> VectorStore: + """ + Create a vector store. + + Args: + expires_after: The expiration policy for a vector store. + + file_ids: A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + the vector store should use. Useful for tools like `file_search` that can access + files. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + name: The name of the vector store. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return await self._post( + "/vector_stores", + body=await async_maybe_transform( + { + "expires_after": expires_after, + "file_ids": file_ids, + "metadata": metadata, + "name": name, + }, + vector_store_create_params.VectorStoreCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=VectorStore, + ) + + async def retrieve( + self, + vector_store_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> VectorStore: + """ + Retrieves a vector store. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return await self._get( + f"/vector_stores/{vector_store_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=VectorStore, + ) + + async def update( + self, + vector_store_id: str, + *, + expires_after: Optional[vector_store_update_params.ExpiresAfter] | NotGiven = NOT_GIVEN, + metadata: Optional[object] | NotGiven = NOT_GIVEN, + name: Optional[str] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> VectorStore: + """ + Modifies a vector store. + + Args: + expires_after: The expiration policy for a vector store. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format. Keys + can be a maximum of 64 characters long and values can be a maxium of 512 + characters long. + + name: The name of the vector store. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return await self._post( + f"/vector_stores/{vector_store_id}", + body=await async_maybe_transform( + { + "expires_after": expires_after, + "metadata": metadata, + "name": name, + }, + vector_store_update_params.VectorStoreUpdateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=VectorStore, + ) + + def list( + self, + *, + after: str | NotGiven = NOT_GIVEN, + before: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncPaginator[VectorStore, AsyncCursorPage[VectorStore]]: + """Returns a list of vector stores. + + Args: + after: A cursor for use in pagination. + + `after` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include after=obj_foo in order to + fetch the next page of the list. + + before: A cursor for use in pagination. `before` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include before=obj_foo in order to + fetch the previous page of the list. + + limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the default is 20. + + order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending + order and `desc` for descending order. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return self._get_api_list( + "/vector_stores", + page=AsyncCursorPage[VectorStore], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "before": before, + "limit": limit, + "order": order, + }, + vector_store_list_params.VectorStoreListParams, + ), + ), + model=VectorStore, + ) + + async def delete( + self, + vector_store_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> VectorStoreDeleted: + """ + Delete a vector store. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return await self._delete( + f"/vector_stores/{vector_store_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=VectorStoreDeleted, + ) + + +class VectorStoresWithRawResponse: + def __init__(self, vector_stores: VectorStores) -> None: + self._vector_stores = vector_stores + + self.create = _legacy_response.to_raw_response_wrapper( + vector_stores.create, + ) + self.retrieve = _legacy_response.to_raw_response_wrapper( + vector_stores.retrieve, + ) + self.update = _legacy_response.to_raw_response_wrapper( + vector_stores.update, + ) + self.list = _legacy_response.to_raw_response_wrapper( + vector_stores.list, + ) + self.delete = _legacy_response.to_raw_response_wrapper( + vector_stores.delete, + ) + + @cached_property + def files(self) -> FilesWithRawResponse: + return FilesWithRawResponse(self._vector_stores.files) + + @cached_property + def file_batches(self) -> FileBatchesWithRawResponse: + return FileBatchesWithRawResponse(self._vector_stores.file_batches) + + +class AsyncVectorStoresWithRawResponse: + def __init__(self, vector_stores: AsyncVectorStores) -> None: + self._vector_stores = vector_stores + + self.create = _legacy_response.async_to_raw_response_wrapper( + vector_stores.create, + ) + self.retrieve = _legacy_response.async_to_raw_response_wrapper( + vector_stores.retrieve, + ) + self.update = _legacy_response.async_to_raw_response_wrapper( + vector_stores.update, + ) + self.list = _legacy_response.async_to_raw_response_wrapper( + vector_stores.list, + ) + self.delete = _legacy_response.async_to_raw_response_wrapper( + vector_stores.delete, + ) + + @cached_property + def files(self) -> AsyncFilesWithRawResponse: + return AsyncFilesWithRawResponse(self._vector_stores.files) + + @cached_property + def file_batches(self) -> AsyncFileBatchesWithRawResponse: + return AsyncFileBatchesWithRawResponse(self._vector_stores.file_batches) + + +class VectorStoresWithStreamingResponse: + def __init__(self, vector_stores: VectorStores) -> None: + self._vector_stores = vector_stores + + self.create = to_streamed_response_wrapper( + vector_stores.create, + ) + self.retrieve = to_streamed_response_wrapper( + vector_stores.retrieve, + ) + self.update = to_streamed_response_wrapper( + vector_stores.update, + ) + self.list = to_streamed_response_wrapper( + vector_stores.list, + ) + self.delete = to_streamed_response_wrapper( + vector_stores.delete, + ) + + @cached_property + def files(self) -> FilesWithStreamingResponse: + return FilesWithStreamingResponse(self._vector_stores.files) + + @cached_property + def file_batches(self) -> FileBatchesWithStreamingResponse: + return FileBatchesWithStreamingResponse(self._vector_stores.file_batches) + + +class AsyncVectorStoresWithStreamingResponse: + def __init__(self, vector_stores: AsyncVectorStores) -> None: + self._vector_stores = vector_stores + + self.create = async_to_streamed_response_wrapper( + vector_stores.create, + ) + self.retrieve = async_to_streamed_response_wrapper( + vector_stores.retrieve, + ) + self.update = async_to_streamed_response_wrapper( + vector_stores.update, + ) + self.list = async_to_streamed_response_wrapper( + vector_stores.list, + ) + self.delete = async_to_streamed_response_wrapper( + vector_stores.delete, + ) + + @cached_property + def files(self) -> AsyncFilesWithStreamingResponse: + return AsyncFilesWithStreamingResponse(self._vector_stores.files) + + @cached_property + def file_batches(self) -> AsyncFileBatchesWithStreamingResponse: + return AsyncFileBatchesWithStreamingResponse(self._vector_stores.file_batches) diff --git a/src/openai/resources/fine_tuning/jobs/jobs.py b/src/openai/resources/fine_tuning/jobs/jobs.py index 229f716c48..8e49571b14 100644 --- a/src/openai/resources/fine_tuning/jobs/jobs.py +++ b/src/openai/resources/fine_tuning/jobs/jobs.py @@ -85,7 +85,7 @@ def create( training_file: The ID of an uploaded file that contains training data. - See [upload file](https://platform.openai.com/docs/api-reference/files/upload) + See [upload file](https://platform.openai.com/docs/api-reference/files/create) for how to upload a file. Your dataset must be formatted as a JSONL file. Additionally, you must upload @@ -360,7 +360,7 @@ async def create( training_file: The ID of an uploaded file that contains training data. - See [upload file](https://platform.openai.com/docs/api-reference/files/upload) + See [upload file](https://platform.openai.com/docs/api-reference/files/create) for how to upload a file. Your dataset must be formatted as a JSONL file. Additionally, you must upload diff --git a/src/openai/types/beta/__init__.py b/src/openai/types/beta/__init__.py index 0171694587..d851a3619c 100644 --- a/src/openai/types/beta/__init__.py +++ b/src/openai/types/beta/__init__.py @@ -4,23 +4,28 @@ from .thread import Thread as Thread from .assistant import Assistant as Assistant +from .vector_store import VectorStore as VectorStore from .function_tool import FunctionTool as FunctionTool from .assistant_tool import AssistantTool as AssistantTool -from .retrieval_tool import RetrievalTool as RetrievalTool from .thread_deleted import ThreadDeleted as ThreadDeleted +from .file_search_tool import FileSearchTool as FileSearchTool from .assistant_deleted import AssistantDeleted as AssistantDeleted from .function_tool_param import FunctionToolParam as FunctionToolParam from .assistant_tool_param import AssistantToolParam as AssistantToolParam -from .retrieval_tool_param import RetrievalToolParam as RetrievalToolParam from .thread_create_params import ThreadCreateParams as ThreadCreateParams from .thread_update_params import ThreadUpdateParams as ThreadUpdateParams +from .vector_store_deleted import VectorStoreDeleted as VectorStoreDeleted from .assistant_list_params import AssistantListParams as AssistantListParams from .assistant_tool_choice import AssistantToolChoice as AssistantToolChoice from .code_interpreter_tool import CodeInterpreterTool as CodeInterpreterTool from .assistant_stream_event import AssistantStreamEvent as AssistantStreamEvent +from .file_search_tool_param import FileSearchToolParam as FileSearchToolParam from .assistant_create_params import AssistantCreateParams as AssistantCreateParams from .assistant_update_params import AssistantUpdateParams as AssistantUpdateParams +from .vector_store_list_params import VectorStoreListParams as VectorStoreListParams from .assistant_response_format import AssistantResponseFormat as AssistantResponseFormat +from .vector_store_create_params import VectorStoreCreateParams as VectorStoreCreateParams +from .vector_store_update_params import VectorStoreUpdateParams as VectorStoreUpdateParams from .assistant_tool_choice_param import AssistantToolChoiceParam as AssistantToolChoiceParam from .code_interpreter_tool_param import CodeInterpreterToolParam as CodeInterpreterToolParam from .assistant_tool_choice_option import AssistantToolChoiceOption as AssistantToolChoiceOption diff --git a/src/openai/types/beta/assistant.py b/src/openai/types/beta/assistant.py index 0a0d28ed01..fa09efb0cc 100644 --- a/src/openai/types/beta/assistant.py +++ b/src/openai/types/beta/assistant.py @@ -6,7 +6,32 @@ from ..._models import BaseModel from .assistant_tool import AssistantTool -__all__ = ["Assistant"] +__all__ = ["Assistant", "ToolResources", "ToolResourcesCodeInterpreter", "ToolResourcesFileSearch"] + + +class ToolResourcesCodeInterpreter(BaseModel): + file_ids: Optional[List[str]] = None + """ + A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made + available to the `code_interpreter`` tool. There can be a maximum of 20 files + associated with the tool. + """ + + +class ToolResourcesFileSearch(BaseModel): + vector_store_ids: Optional[List[str]] = None + """ + The ID of the + [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + attached to this assistant. There can be a maximum of 1 vector store attached to + the assistant. + """ + + +class ToolResources(BaseModel): + code_interpreter: Optional[ToolResourcesCodeInterpreter] = None + + file_search: Optional[ToolResourcesFileSearch] = None class Assistant(BaseModel): @@ -19,13 +44,6 @@ class Assistant(BaseModel): description: Optional[str] = None """The description of the assistant. The maximum length is 512 characters.""" - file_ids: List[str] - """ - A list of [file](https://platform.openai.com/docs/api-reference/files) IDs - attached to this assistant. There can be a maximum of 20 files attached to the - assistant. Files are ordered by their creation date in ascending order. - """ - instructions: Optional[str] = None """The system instructions that the assistant uses. @@ -60,5 +78,13 @@ class Assistant(BaseModel): """A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types - `code_interpreter`, `retrieval`, or `function`. + `code_interpreter`, `file_search`, or `function`. + """ + + tool_resources: Optional[ToolResources] = None + """A set of resources that are used by the assistant's tools. + + The resources are specific to the type of tool. For example, the + `code_interpreter` tool requires a list of file IDs, while the `file_search` + tool requires a list of vector store IDs. """ diff --git a/src/openai/types/beta/assistant_create_params.py b/src/openai/types/beta/assistant_create_params.py index 011121485f..925b85050f 100644 --- a/src/openai/types/beta/assistant_create_params.py +++ b/src/openai/types/beta/assistant_create_params.py @@ -6,8 +6,15 @@ from typing_extensions import Literal, Required, TypedDict from .assistant_tool_param import AssistantToolParam +from .assistant_response_format_option_param import AssistantResponseFormatOptionParam -__all__ = ["AssistantCreateParams"] +__all__ = [ + "AssistantCreateParams", + "ToolResources", + "ToolResourcesCodeInterpreter", + "ToolResourcesFileSearch", + "ToolResourcesFileSearchVectorStore", +] class AssistantCreateParams(TypedDict, total=False): @@ -48,13 +55,6 @@ class AssistantCreateParams(TypedDict, total=False): description: Optional[str] """The description of the assistant. The maximum length is 512 characters.""" - file_ids: List[str] - """ - A list of [file](https://platform.openai.com/docs/api-reference/files) IDs - attached to this assistant. There can be a maximum of 20 files attached to the - assistant. Files are ordered by their creation date in ascending order. - """ - instructions: Optional[str] """The system instructions that the assistant uses. @@ -72,9 +72,102 @@ class AssistantCreateParams(TypedDict, total=False): name: Optional[str] """The name of the assistant. The maximum length is 256 characters.""" + response_format: Optional[AssistantResponseFormatOptionParam] + """Specifies the format that the model must output. + + Compatible with + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. + """ + + temperature: Optional[float] + """What sampling temperature to use, between 0 and 2. + + Higher values like 0.8 will make the output more random, while lower values like + 0.2 will make it more focused and deterministic. + """ + + tool_resources: Optional[ToolResources] + """A set of resources that are used by the assistant's tools. + + The resources are specific to the type of tool. For example, the + `code_interpreter` tool requires a list of file IDs, while the `file_search` + tool requires a list of vector store IDs. + """ + tools: Iterable[AssistantToolParam] """A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types - `code_interpreter`, `retrieval`, or `function`. + `code_interpreter`, `file_search`, or `function`. + """ + + top_p: Optional[float] + """ + An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or temperature but not both. + """ + + +class ToolResourcesCodeInterpreter(TypedDict, total=False): + file_ids: List[str] + """ + A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made + available to the `code_interpreter` tool. There can be a maximum of 20 files + associated with the tool. + """ + + +class ToolResourcesFileSearchVectorStore(TypedDict, total=False): + file_ids: List[str] + """ + A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to + add to the vector store. There can be a maximum of 10000 files in a vector + store. + """ + + metadata: object + """Set of 16 key-value pairs that can be attached to a vector store. + + This can be useful for storing additional information about the vector store in + a structured format. Keys can be a maximum of 64 characters long and values can + be a maxium of 512 characters long. """ + + +class ToolResourcesFileSearch(TypedDict, total=False): + vector_store_ids: List[str] + """ + The + [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + attached to this assistant. There can be a maximum of 1 vector store attached to + the assistant. + """ + + vector_stores: Iterable[ToolResourcesFileSearchVectorStore] + """ + A helper to create a + [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + with file_ids and attach it to this assistant. There can be a maximum of 1 + vector store attached to the assistant. + """ + + +class ToolResources(TypedDict, total=False): + code_interpreter: ToolResourcesCodeInterpreter + + file_search: ToolResourcesFileSearch diff --git a/src/openai/types/beta/assistant_tool.py b/src/openai/types/beta/assistant_tool.py index a4420385e8..7832da48cc 100644 --- a/src/openai/types/beta/assistant_tool.py +++ b/src/openai/types/beta/assistant_tool.py @@ -5,9 +5,9 @@ from ..._utils import PropertyInfo from .function_tool import FunctionTool -from .retrieval_tool import RetrievalTool +from .file_search_tool import FileSearchTool from .code_interpreter_tool import CodeInterpreterTool __all__ = ["AssistantTool"] -AssistantTool = Annotated[Union[CodeInterpreterTool, RetrievalTool, FunctionTool], PropertyInfo(discriminator="type")] +AssistantTool = Annotated[Union[CodeInterpreterTool, FileSearchTool, FunctionTool], PropertyInfo(discriminator="type")] diff --git a/src/openai/types/beta/assistant_tool_choice.py b/src/openai/types/beta/assistant_tool_choice.py index 4314d4b41e..d73439f006 100644 --- a/src/openai/types/beta/assistant_tool_choice.py +++ b/src/openai/types/beta/assistant_tool_choice.py @@ -10,7 +10,7 @@ class AssistantToolChoice(BaseModel): - type: Literal["function", "code_interpreter", "retrieval"] + type: Literal["function", "code_interpreter", "file_search"] """The type of the tool. If type is `function`, the function name must be set""" function: Optional[AssistantToolChoiceFunction] = None diff --git a/src/openai/types/beta/assistant_tool_choice_param.py b/src/openai/types/beta/assistant_tool_choice_param.py index 5cf6ea27be..904f489e26 100644 --- a/src/openai/types/beta/assistant_tool_choice_param.py +++ b/src/openai/types/beta/assistant_tool_choice_param.py @@ -10,7 +10,7 @@ class AssistantToolChoiceParam(TypedDict, total=False): - type: Required[Literal["function", "code_interpreter", "retrieval"]] + type: Required[Literal["function", "code_interpreter", "file_search"]] """The type of the tool. If type is `function`, the function name must be set""" function: AssistantToolChoiceFunctionParam diff --git a/src/openai/types/beta/assistant_tool_param.py b/src/openai/types/beta/assistant_tool_param.py index d5758f169e..5b1d30ba2f 100644 --- a/src/openai/types/beta/assistant_tool_param.py +++ b/src/openai/types/beta/assistant_tool_param.py @@ -5,9 +5,9 @@ from typing import Union from .function_tool_param import FunctionToolParam -from .retrieval_tool_param import RetrievalToolParam +from .file_search_tool_param import FileSearchToolParam from .code_interpreter_tool_param import CodeInterpreterToolParam __all__ = ["AssistantToolParam"] -AssistantToolParam = Union[CodeInterpreterToolParam, RetrievalToolParam, FunctionToolParam] +AssistantToolParam = Union[CodeInterpreterToolParam, FileSearchToolParam, FunctionToolParam] diff --git a/src/openai/types/beta/assistant_update_params.py b/src/openai/types/beta/assistant_update_params.py index 6e9d9ed5db..1354b078a8 100644 --- a/src/openai/types/beta/assistant_update_params.py +++ b/src/openai/types/beta/assistant_update_params.py @@ -6,23 +6,15 @@ from typing_extensions import TypedDict from .assistant_tool_param import AssistantToolParam +from .assistant_response_format_option_param import AssistantResponseFormatOptionParam -__all__ = ["AssistantUpdateParams"] +__all__ = ["AssistantUpdateParams", "ToolResources", "ToolResourcesCodeInterpreter", "ToolResourcesFileSearch"] class AssistantUpdateParams(TypedDict, total=False): description: Optional[str] """The description of the assistant. The maximum length is 512 characters.""" - file_ids: List[str] - """ - A list of [File](https://platform.openai.com/docs/api-reference/files) IDs - attached to this assistant. There can be a maximum of 20 files attached to the - assistant. Files are ordered by their creation date in ascending order. If a - file was previously attached to the list but does not show up in the list, it - will be deleted from the assistant. - """ - instructions: Optional[str] """The system instructions that the assistant uses. @@ -50,9 +42,78 @@ class AssistantUpdateParams(TypedDict, total=False): name: Optional[str] """The name of the assistant. The maximum length is 256 characters.""" + response_format: Optional[AssistantResponseFormatOptionParam] + """Specifies the format that the model must output. + + Compatible with + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. + """ + + temperature: Optional[float] + """What sampling temperature to use, between 0 and 2. + + Higher values like 0.8 will make the output more random, while lower values like + 0.2 will make it more focused and deterministic. + """ + + tool_resources: Optional[ToolResources] + """A set of resources that are used by the assistant's tools. + + The resources are specific to the type of tool. For example, the + `code_interpreter` tool requires a list of file IDs, while the `file_search` + tool requires a list of vector store IDs. + """ + tools: Iterable[AssistantToolParam] """A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types - `code_interpreter`, `retrieval`, or `function`. + `code_interpreter`, `file_search`, or `function`. """ + + top_p: Optional[float] + """ + An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or temperature but not both. + """ + + +class ToolResourcesCodeInterpreter(TypedDict, total=False): + file_ids: List[str] + """ + Overrides the list of + [file](https://platform.openai.com/docs/api-reference/files) IDs made available + to the `code_interpreter` tool. There can be a maximum of 20 files associated + with the tool. + """ + + +class ToolResourcesFileSearch(TypedDict, total=False): + vector_store_ids: List[str] + """ + Overrides the + [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + attached to this assistant. There can be a maximum of 1 vector store attached to + the assistant. + """ + + +class ToolResources(TypedDict, total=False): + code_interpreter: ToolResourcesCodeInterpreter + + file_search: ToolResourcesFileSearch diff --git a/src/openai/types/beta/assistants/__init__.py b/src/openai/types/beta/assistants/__init__.py deleted file mode 100644 index d4dd2de018..0000000000 --- a/src/openai/types/beta/assistants/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -from __future__ import annotations - -from .assistant_file import AssistantFile as AssistantFile -from .file_list_params import FileListParams as FileListParams -from .file_create_params import FileCreateParams as FileCreateParams -from .file_delete_response import FileDeleteResponse as FileDeleteResponse diff --git a/src/openai/types/beta/assistants/assistant_file.py b/src/openai/types/beta/assistants/assistant_file.py deleted file mode 100644 index 25aec07b49..0000000000 --- a/src/openai/types/beta/assistants/assistant_file.py +++ /dev/null @@ -1,21 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -from typing_extensions import Literal - -from ...._models import BaseModel - -__all__ = ["AssistantFile"] - - -class AssistantFile(BaseModel): - id: str - """The identifier, which can be referenced in API endpoints.""" - - assistant_id: str - """The assistant ID that the file is attached to.""" - - created_at: int - """The Unix timestamp (in seconds) for when the assistant file was created.""" - - object: Literal["assistant.file"] - """The object type, which is always `assistant.file`.""" diff --git a/src/openai/types/beta/file_search_tool.py b/src/openai/types/beta/file_search_tool.py new file mode 100644 index 0000000000..eea55ea6ac --- /dev/null +++ b/src/openai/types/beta/file_search_tool.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["FileSearchTool"] + + +class FileSearchTool(BaseModel): + type: Literal["file_search"] + """The type of tool being defined: `file_search`""" diff --git a/src/openai/types/beta/retrieval_tool_param.py b/src/openai/types/beta/file_search_tool_param.py similarity index 50% rename from src/openai/types/beta/retrieval_tool_param.py rename to src/openai/types/beta/file_search_tool_param.py index d76c0beefc..d33fd06da4 100644 --- a/src/openai/types/beta/retrieval_tool_param.py +++ b/src/openai/types/beta/file_search_tool_param.py @@ -4,9 +4,9 @@ from typing_extensions import Literal, Required, TypedDict -__all__ = ["RetrievalToolParam"] +__all__ = ["FileSearchToolParam"] -class RetrievalToolParam(TypedDict, total=False): - type: Required[Literal["retrieval"]] - """The type of tool being defined: `retrieval`""" +class FileSearchToolParam(TypedDict, total=False): + type: Required[Literal["file_search"]] + """The type of tool being defined: `file_search`""" diff --git a/src/openai/types/beta/thread.py b/src/openai/types/beta/thread.py index 8fd1423068..6f7a6c7d0c 100644 --- a/src/openai/types/beta/thread.py +++ b/src/openai/types/beta/thread.py @@ -1,11 +1,36 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing import Optional +from typing import List, Optional from typing_extensions import Literal from ..._models import BaseModel -__all__ = ["Thread"] +__all__ = ["Thread", "ToolResources", "ToolResourcesCodeInterpreter", "ToolResourcesFileSearch"] + + +class ToolResourcesCodeInterpreter(BaseModel): + file_ids: Optional[List[str]] = None + """ + A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made + available to the `code_interpreter` tool. There can be a maximum of 20 files + associated with the tool. + """ + + +class ToolResourcesFileSearch(BaseModel): + vector_store_ids: Optional[List[str]] = None + """ + The + [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + attached to this thread. There can be a maximum of 1 vector store attached to + the thread. + """ + + +class ToolResources(BaseModel): + code_interpreter: Optional[ToolResourcesCodeInterpreter] = None + + file_search: Optional[ToolResourcesFileSearch] = None class Thread(BaseModel): @@ -25,3 +50,11 @@ class Thread(BaseModel): object: Literal["thread"] """The object type, which is always `thread`.""" + + tool_resources: Optional[ToolResources] = None + """ + A set of resources that are made available to the assistant's tools in this + thread. The resources are specific to the type of tool. For example, the + `code_interpreter` tool requires a list of file IDs, while the `file_search` + tool requires a list of vector store IDs. + """ diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index 50f947a40a..d7d5a758e8 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -6,7 +6,7 @@ from typing_extensions import Literal, Required, TypedDict from .function_tool_param import FunctionToolParam -from .retrieval_tool_param import RetrievalToolParam +from .file_search_tool_param import FileSearchToolParam from .code_interpreter_tool_param import CodeInterpreterToolParam from .assistant_tool_choice_option_param import AssistantToolChoiceOptionParam from .assistant_response_format_option_param import AssistantResponseFormatOptionParam @@ -15,6 +15,14 @@ "ThreadCreateAndRunParamsBase", "Thread", "ThreadMessage", + "ThreadMessageAttachment", + "ThreadToolResources", + "ThreadToolResourcesCodeInterpreter", + "ThreadToolResourcesFileSearch", + "ThreadToolResourcesFileSearchVectorStore", + "ToolResources", + "ToolResourcesCodeInterpreter", + "ToolResourcesFileSearch", "Tool", "TruncationStrategy", "ThreadCreateAndRunParamsNonStreaming", @@ -41,7 +49,7 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of - completion tokens specified, the run will end with status `complete`. See + completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. """ @@ -50,7 +58,7 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of - prompt tokens specified, the run will end with status `complete`. See + prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. """ @@ -132,15 +140,37 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): call that tool. """ + tool_resources: Optional[ToolResources] + """A set of resources that are used by the assistant's tools. + + The resources are specific to the type of tool. For example, the + `code_interpreter` tool requires a list of file IDs, while the `file_search` + tool requires a list of vector store IDs. + """ + tools: Optional[Iterable[Tool]] """Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. """ + top_p: Optional[float] + """ + An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + """ + truncation_strategy: Optional[TruncationStrategy] +class ThreadMessageAttachment(TypedDict, total=False): + add_to: List[Literal["file_search", "code_interpreter"]] + + file_id: str + """The ID of the file to attach to the message.""" + + class ThreadMessage(TypedDict, total=False): content: Required[str] """The content of the message.""" @@ -154,13 +184,8 @@ class ThreadMessage(TypedDict, total=False): value to insert messages from the assistant into the conversation. """ - file_ids: List[str] - """ - A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that - the message should use. There can be a maximum of 10 files attached to a - message. Useful for tools like `retrieval` and `code_interpreter` that can - access and use files. - """ + attachments: Optional[Iterable[ThreadMessageAttachment]] + """A list of files attached to the message, and the tools they should be added to.""" metadata: Optional[object] """Set of 16 key-value pairs that can be attached to an object. @@ -171,6 +196,56 @@ class ThreadMessage(TypedDict, total=False): """ +class ThreadToolResourcesCodeInterpreter(TypedDict, total=False): + file_ids: List[str] + """ + A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made + available to the `code_interpreter` tool. There can be a maximum of 20 files + associated with the tool. + """ + + +class ThreadToolResourcesFileSearchVectorStore(TypedDict, total=False): + file_ids: List[str] + """ + A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to + add to the vector store. There can be a maximum of 10000 files in a vector + store. + """ + + metadata: object + """Set of 16 key-value pairs that can be attached to a vector store. + + This can be useful for storing additional information about the vector store in + a structured format. Keys can be a maximum of 64 characters long and values can + be a maxium of 512 characters long. + """ + + +class ThreadToolResourcesFileSearch(TypedDict, total=False): + vector_store_ids: List[str] + """ + The + [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + attached to this thread. There can be a maximum of 1 vector store attached to + the thread. + """ + + vector_stores: Iterable[ThreadToolResourcesFileSearchVectorStore] + """ + A helper to create a + [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + with file_ids and attach it to this thread. There can be a maximum of 1 vector + store attached to the thread. + """ + + +class ThreadToolResources(TypedDict, total=False): + code_interpreter: ThreadToolResourcesCodeInterpreter + + file_search: ThreadToolResourcesFileSearch + + class Thread(TypedDict, total=False): messages: Iterable[ThreadMessage] """ @@ -186,8 +261,41 @@ class Thread(TypedDict, total=False): a maxium of 512 characters long. """ + tool_resources: Optional[ThreadToolResources] + """ + A set of resources that are made available to the assistant's tools in this + thread. The resources are specific to the type of tool. For example, the + `code_interpreter` tool requires a list of file IDs, while the `file_search` + tool requires a list of vector store IDs. + """ + + +class ToolResourcesCodeInterpreter(TypedDict, total=False): + file_ids: List[str] + """ + A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made + available to the `code_interpreter` tool. There can be a maximum of 20 files + associated with the tool. + """ + + +class ToolResourcesFileSearch(TypedDict, total=False): + vector_store_ids: List[str] + """ + The ID of the + [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + attached to this assistant. There can be a maximum of 1 vector store attached to + the assistant. + """ + + +class ToolResources(TypedDict, total=False): + code_interpreter: ToolResourcesCodeInterpreter + + file_search: ToolResourcesFileSearch + -Tool = Union[CodeInterpreterToolParam, RetrievalToolParam, FunctionToolParam] +Tool = Union[CodeInterpreterToolParam, FileSearchToolParam, FunctionToolParam] class TruncationStrategy(TypedDict, total=False): diff --git a/src/openai/types/beta/thread_create_params.py b/src/openai/types/beta/thread_create_params.py index 1b382186aa..84a98a74d7 100644 --- a/src/openai/types/beta/thread_create_params.py +++ b/src/openai/types/beta/thread_create_params.py @@ -5,7 +5,15 @@ from typing import List, Iterable, Optional from typing_extensions import Literal, Required, TypedDict -__all__ = ["ThreadCreateParams", "Message"] +__all__ = [ + "ThreadCreateParams", + "Message", + "MessageAttachment", + "ToolResources", + "ToolResourcesCodeInterpreter", + "ToolResourcesFileSearch", + "ToolResourcesFileSearchVectorStore", +] class ThreadCreateParams(TypedDict, total=False): @@ -23,6 +31,21 @@ class ThreadCreateParams(TypedDict, total=False): a maxium of 512 characters long. """ + tool_resources: Optional[ToolResources] + """ + A set of resources that are made available to the assistant's tools in this + thread. The resources are specific to the type of tool. For example, the + `code_interpreter` tool requires a list of file IDs, while the `file_search` + tool requires a list of vector store IDs. + """ + + +class MessageAttachment(TypedDict, total=False): + add_to: List[Literal["file_search", "code_interpreter"]] + + file_id: str + """The ID of the file to attach to the message.""" + class Message(TypedDict, total=False): content: Required[str] @@ -37,13 +60,8 @@ class Message(TypedDict, total=False): value to insert messages from the assistant into the conversation. """ - file_ids: List[str] - """ - A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that - the message should use. There can be a maximum of 10 files attached to a - message. Useful for tools like `retrieval` and `code_interpreter` that can - access and use files. - """ + attachments: Optional[Iterable[MessageAttachment]] + """A list of files attached to the message, and the tools they should be added to.""" metadata: Optional[object] """Set of 16 key-value pairs that can be attached to an object. @@ -52,3 +70,53 @@ class Message(TypedDict, total=False): structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. """ + + +class ToolResourcesCodeInterpreter(TypedDict, total=False): + file_ids: List[str] + """ + A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made + available to the `code_interpreter` tool. There can be a maximum of 20 files + associated with the tool. + """ + + +class ToolResourcesFileSearchVectorStore(TypedDict, total=False): + file_ids: List[str] + """ + A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to + add to the vector store. There can be a maximum of 10000 files in a vector + store. + """ + + metadata: object + """Set of 16 key-value pairs that can be attached to a vector store. + + This can be useful for storing additional information about the vector store in + a structured format. Keys can be a maximum of 64 characters long and values can + be a maxium of 512 characters long. + """ + + +class ToolResourcesFileSearch(TypedDict, total=False): + vector_store_ids: List[str] + """ + The + [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + attached to this thread. There can be a maximum of 1 vector store attached to + the thread. + """ + + vector_stores: Iterable[ToolResourcesFileSearchVectorStore] + """ + A helper to create a + [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + with file_ids and attach it to this thread. There can be a maximum of 1 vector + store attached to the thread. + """ + + +class ToolResources(TypedDict, total=False): + code_interpreter: ToolResourcesCodeInterpreter + + file_search: ToolResourcesFileSearch diff --git a/src/openai/types/beta/thread_update_params.py b/src/openai/types/beta/thread_update_params.py index 94f1b1e22e..7210ab77c9 100644 --- a/src/openai/types/beta/thread_update_params.py +++ b/src/openai/types/beta/thread_update_params.py @@ -2,10 +2,10 @@ from __future__ import annotations -from typing import Optional +from typing import List, Optional from typing_extensions import TypedDict -__all__ = ["ThreadUpdateParams"] +__all__ = ["ThreadUpdateParams", "ToolResources", "ToolResourcesCodeInterpreter", "ToolResourcesFileSearch"] class ThreadUpdateParams(TypedDict, total=False): @@ -16,3 +16,36 @@ class ThreadUpdateParams(TypedDict, total=False): structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. """ + + tool_resources: Optional[ToolResources] + """ + A set of resources that are made available to the assistant's tools in this + thread. The resources are specific to the type of tool. For example, the + `code_interpreter` tool requires a list of file IDs, while the `file_search` + tool requires a list of vector store IDs. + """ + + +class ToolResourcesCodeInterpreter(TypedDict, total=False): + file_ids: List[str] + """ + A list of [file](https://platform.openai.com/docs/api-reference/files) IDs made + available to the `code_interpreter` tool. There can be a maximum of 20 files + associated with the tool. + """ + + +class ToolResourcesFileSearch(TypedDict, total=False): + vector_store_ids: List[str] + """ + The + [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + attached to this thread. There can be a maximum of 1 vector store attached to + the thread. + """ + + +class ToolResources(TypedDict, total=False): + code_interpreter: ToolResourcesCodeInterpreter + + file_search: ToolResourcesFileSearch diff --git a/src/openai/types/beta/threads/message.py b/src/openai/types/beta/threads/message.py index bde0263975..42f0162734 100644 --- a/src/openai/types/beta/threads/message.py +++ b/src/openai/types/beta/threads/message.py @@ -6,7 +6,14 @@ from ...._models import BaseModel from .message_content import MessageContent -__all__ = ["Message", "IncompleteDetails"] +__all__ = ["Message", "Attachment", "IncompleteDetails"] + + +class Attachment(BaseModel): + add_to: Optional[List[Literal["file_search", "code_interpreter"]]] = None + + file_id: Optional[str] = None + """The ID of the file to attach to the message.""" class IncompleteDetails(BaseModel): @@ -25,6 +32,9 @@ class Message(BaseModel): authored this message. """ + attachments: Optional[List[Attachment]] = None + """A list of files attached to the message, and the tools they were added to.""" + completed_at: Optional[int] = None """The Unix timestamp (in seconds) for when the message was completed.""" @@ -34,13 +44,6 @@ class Message(BaseModel): created_at: int """The Unix timestamp (in seconds) for when the message was created.""" - file_ids: List[str] - """ - A list of [file](https://platform.openai.com/docs/api-reference/files) IDs that - the assistant should use. Useful for tools like retrieval and code_interpreter - that can access files. A maximum of 10 files can be attached to a message. - """ - incomplete_at: Optional[int] = None """The Unix timestamp (in seconds) for when the message was marked as incomplete.""" diff --git a/src/openai/types/beta/threads/message_create_params.py b/src/openai/types/beta/threads/message_create_params.py index 9b9467ef4d..1ef1d9ae10 100644 --- a/src/openai/types/beta/threads/message_create_params.py +++ b/src/openai/types/beta/threads/message_create_params.py @@ -2,10 +2,10 @@ from __future__ import annotations -from typing import List, Optional +from typing import List, Iterable, Optional from typing_extensions import Literal, Required, TypedDict -__all__ = ["MessageCreateParams"] +__all__ = ["MessageCreateParams", "Attachment"] class MessageCreateParams(TypedDict, total=False): @@ -21,13 +21,8 @@ class MessageCreateParams(TypedDict, total=False): value to insert messages from the assistant into the conversation. """ - file_ids: List[str] - """ - A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that - the message should use. There can be a maximum of 10 files attached to a - message. Useful for tools like `retrieval` and `code_interpreter` that can - access and use files. - """ + attachments: Optional[Iterable[Attachment]] + """A list of files attached to the message, and the tools they should be added to.""" metadata: Optional[object] """Set of 16 key-value pairs that can be attached to an object. @@ -36,3 +31,10 @@ class MessageCreateParams(TypedDict, total=False): structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. """ + + +class Attachment(TypedDict, total=False): + add_to: List[Literal["file_search", "code_interpreter"]] + + file_id: str + """The ID of the file to attach to the message.""" diff --git a/src/openai/types/beta/threads/message_delta.py b/src/openai/types/beta/threads/message_delta.py index 3a55e1442a..ecd0dfe319 100644 --- a/src/openai/types/beta/threads/message_delta.py +++ b/src/openai/types/beta/threads/message_delta.py @@ -13,12 +13,5 @@ class MessageDelta(BaseModel): content: Optional[List[MessageContentDelta]] = None """The content of the message in array of text and/or images.""" - file_ids: Optional[List[str]] = None - """ - A list of [file](https://platform.openai.com/docs/api-reference/files) IDs that - the assistant should use. Useful for tools like retrieval and code_interpreter - that can access files. A maximum of 10 files can be attached to a message. - """ - role: Optional[Literal["user", "assistant"]] = None """The entity that produced the message. One of `user` or `assistant`.""" diff --git a/src/openai/types/beta/threads/messages/__init__.py b/src/openai/types/beta/threads/messages/__init__.py deleted file mode 100644 index d129297620..0000000000 --- a/src/openai/types/beta/threads/messages/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -from __future__ import annotations - -from .message_file import MessageFile as MessageFile -from .file_list_params import FileListParams as FileListParams diff --git a/src/openai/types/beta/threads/messages/message_file.py b/src/openai/types/beta/threads/messages/message_file.py deleted file mode 100644 index 342479ab7b..0000000000 --- a/src/openai/types/beta/threads/messages/message_file.py +++ /dev/null @@ -1,25 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -from typing_extensions import Literal - -from ....._models import BaseModel - -__all__ = ["MessageFile"] - - -class MessageFile(BaseModel): - id: str - """The identifier, which can be referenced in API endpoints.""" - - created_at: int - """The Unix timestamp (in seconds) for when the message file was created.""" - - message_id: str - """ - The ID of the [message](https://platform.openai.com/docs/api-reference/messages) - that the [File](https://platform.openai.com/docs/api-reference/files) is - attached to. - """ - - object: Literal["thread.message.file"] - """The object type, which is always `thread.message.file`.""" diff --git a/src/openai/types/beta/threads/run.py b/src/openai/types/beta/threads/run.py index 2efc3c77fa..8f427ce6e8 100644 --- a/src/openai/types/beta/threads/run.py +++ b/src/openai/types/beta/threads/run.py @@ -105,13 +105,6 @@ class Run(BaseModel): failed_at: Optional[int] = None """The Unix timestamp (in seconds) for when the run failed.""" - file_ids: List[str] - """ - The list of [File](https://platform.openai.com/docs/api-reference/files) IDs the - [assistant](https://platform.openai.com/docs/api-reference/assistants) used for - this run. - """ - incomplete_details: Optional[IncompleteDetails] = None """Details on why the run is incomplete. @@ -227,3 +220,6 @@ class Run(BaseModel): temperature: Optional[float] = None """The sampling temperature used for this run. If not set, defaults to 1.""" + + top_p: Optional[float] = None + """The nucleus sampling value used for this run. If not set, defaults to 1.""" diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index 9f2d4ba18b..fd0b4e7920 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -12,6 +12,7 @@ __all__ = [ "RunCreateParamsBase", "AdditionalMessage", + "AdditionalMessageAttachment", "TruncationStrategy", "RunCreateParamsNonStreaming", "RunCreateParamsStreaming", @@ -142,9 +143,23 @@ class RunCreateParamsBase(TypedDict, total=False): This is useful for modifying the behavior on a per-run basis. """ + top_p: Optional[float] + """ + An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + """ + truncation_strategy: Optional[TruncationStrategy] +class AdditionalMessageAttachment(TypedDict, total=False): + add_to: List[Literal["file_search", "code_interpreter"]] + + file_id: str + """The ID of the file to attach to the message.""" + + class AdditionalMessage(TypedDict, total=False): content: Required[str] """The content of the message.""" @@ -158,13 +173,8 @@ class AdditionalMessage(TypedDict, total=False): value to insert messages from the assistant into the conversation. """ - file_ids: List[str] - """ - A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that - the message should use. There can be a maximum of 10 files attached to a - message. Useful for tools like `retrieval` and `code_interpreter` that can - access and use files. - """ + attachments: Optional[Iterable[AdditionalMessageAttachment]] + """A list of files attached to the message, and the tools they should be added to.""" metadata: Optional[object] """Set of 16 key-value pairs that can be attached to an object. diff --git a/src/openai/types/beta/threads/runs/__init__.py b/src/openai/types/beta/threads/runs/__init__.py index 256510dcc7..a312ce3df2 100644 --- a/src/openai/types/beta/threads/runs/__init__.py +++ b/src/openai/types/beta/threads/runs/__init__.py @@ -8,14 +8,14 @@ from .tool_call_delta import ToolCallDelta as ToolCallDelta from .step_list_params import StepListParams as StepListParams from .function_tool_call import FunctionToolCall as FunctionToolCall -from .retrieval_tool_call import RetrievalToolCall as RetrievalToolCall from .run_step_delta_event import RunStepDeltaEvent as RunStepDeltaEvent from .code_interpreter_logs import CodeInterpreterLogs as CodeInterpreterLogs +from .file_search_tool_call import FileSearchToolCall as FileSearchToolCall from .tool_call_delta_object import ToolCallDeltaObject as ToolCallDeltaObject from .tool_calls_step_details import ToolCallsStepDetails as ToolCallsStepDetails from .function_tool_call_delta import FunctionToolCallDelta as FunctionToolCallDelta -from .retrieval_tool_call_delta import RetrievalToolCallDelta as RetrievalToolCallDelta from .code_interpreter_tool_call import CodeInterpreterToolCall as CodeInterpreterToolCall +from .file_search_tool_call_delta import FileSearchToolCallDelta as FileSearchToolCallDelta from .run_step_delta_message_delta import RunStepDeltaMessageDelta as RunStepDeltaMessageDelta from .code_interpreter_output_image import CodeInterpreterOutputImage as CodeInterpreterOutputImage from .message_creation_step_details import MessageCreationStepDetails as MessageCreationStepDetails diff --git a/src/openai/types/beta/threads/runs/retrieval_tool_call.py b/src/openai/types/beta/threads/runs/file_search_tool_call.py similarity index 61% rename from src/openai/types/beta/threads/runs/retrieval_tool_call.py rename to src/openai/types/beta/threads/runs/file_search_tool_call.py index 48704ed331..57c0ca9a90 100644 --- a/src/openai/types/beta/threads/runs/retrieval_tool_call.py +++ b/src/openai/types/beta/threads/runs/file_search_tool_call.py @@ -4,18 +4,18 @@ from ....._models import BaseModel -__all__ = ["RetrievalToolCall"] +__all__ = ["FileSearchToolCall"] -class RetrievalToolCall(BaseModel): +class FileSearchToolCall(BaseModel): id: str """The ID of the tool call object.""" - retrieval: object + file_search: object """For now, this is always going to be an empty object.""" - type: Literal["retrieval"] + type: Literal["file_search"] """The type of tool call. - This is always going to be `retrieval` for this type of tool call. + This is always going to be `file_search` for this type of tool call. """ diff --git a/src/openai/types/beta/threads/runs/retrieval_tool_call_delta.py b/src/openai/types/beta/threads/runs/file_search_tool_call_delta.py similarity index 67% rename from src/openai/types/beta/threads/runs/retrieval_tool_call_delta.py rename to src/openai/types/beta/threads/runs/file_search_tool_call_delta.py index 3310079399..df5ac217dc 100644 --- a/src/openai/types/beta/threads/runs/retrieval_tool_call_delta.py +++ b/src/openai/types/beta/threads/runs/file_search_tool_call_delta.py @@ -5,21 +5,21 @@ from ....._models import BaseModel -__all__ = ["RetrievalToolCallDelta"] +__all__ = ["FileSearchToolCallDelta"] -class RetrievalToolCallDelta(BaseModel): +class FileSearchToolCallDelta(BaseModel): + file_search: object + """For now, this is always going to be an empty object.""" + index: int """The index of the tool call in the tool calls array.""" - type: Literal["retrieval"] + type: Literal["file_search"] """The type of tool call. - This is always going to be `retrieval` for this type of tool call. + This is always going to be `file_search` for this type of tool call. """ id: Optional[str] = None """The ID of the tool call object.""" - - retrieval: Optional[object] = None - """For now, this is always going to be an empty object.""" diff --git a/src/openai/types/beta/threads/runs/tool_call.py b/src/openai/types/beta/threads/runs/tool_call.py index dcca797bf0..77d86b46d9 100644 --- a/src/openai/types/beta/threads/runs/tool_call.py +++ b/src/openai/types/beta/threads/runs/tool_call.py @@ -5,11 +5,11 @@ from ....._utils import PropertyInfo from .function_tool_call import FunctionToolCall -from .retrieval_tool_call import RetrievalToolCall +from .file_search_tool_call import FileSearchToolCall from .code_interpreter_tool_call import CodeInterpreterToolCall __all__ = ["ToolCall"] ToolCall = Annotated[ - Union[CodeInterpreterToolCall, RetrievalToolCall, FunctionToolCall], PropertyInfo(discriminator="type") + Union[CodeInterpreterToolCall, FileSearchToolCall, FunctionToolCall], PropertyInfo(discriminator="type") ] diff --git a/src/openai/types/beta/threads/runs/tool_call_delta.py b/src/openai/types/beta/threads/runs/tool_call_delta.py index fc98981abf..90cfe0657e 100644 --- a/src/openai/types/beta/threads/runs/tool_call_delta.py +++ b/src/openai/types/beta/threads/runs/tool_call_delta.py @@ -5,12 +5,12 @@ from ....._utils import PropertyInfo from .function_tool_call_delta import FunctionToolCallDelta -from .retrieval_tool_call_delta import RetrievalToolCallDelta +from .file_search_tool_call_delta import FileSearchToolCallDelta from .code_interpreter_tool_call_delta import CodeInterpreterToolCallDelta __all__ = ["ToolCallDelta"] ToolCallDelta = Annotated[ - Union[CodeInterpreterToolCallDelta, RetrievalToolCallDelta, FunctionToolCallDelta], + Union[CodeInterpreterToolCallDelta, FileSearchToolCallDelta, FunctionToolCallDelta], PropertyInfo(discriminator="type"), ] diff --git a/src/openai/types/beta/threads/runs/tool_call_delta_object.py b/src/openai/types/beta/threads/runs/tool_call_delta_object.py index 9cd59a6e24..189dce772c 100644 --- a/src/openai/types/beta/threads/runs/tool_call_delta_object.py +++ b/src/openai/types/beta/threads/runs/tool_call_delta_object.py @@ -17,5 +17,5 @@ class ToolCallDeltaObject(BaseModel): """An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, - `retrieval`, or `function`. + `file_search`, or `function`. """ diff --git a/src/openai/types/beta/threads/runs/tool_calls_step_details.py b/src/openai/types/beta/threads/runs/tool_calls_step_details.py index ca08fabd0e..a084d387c7 100644 --- a/src/openai/types/beta/threads/runs/tool_calls_step_details.py +++ b/src/openai/types/beta/threads/runs/tool_calls_step_details.py @@ -14,7 +14,7 @@ class ToolCallsStepDetails(BaseModel): """An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, - `retrieval`, or `function`. + `file_search`, or `function`. """ type: Literal["tool_calls"] diff --git a/src/openai/types/beta/vector_store.py b/src/openai/types/beta/vector_store.py new file mode 100644 index 0000000000..122705734d --- /dev/null +++ b/src/openai/types/beta/vector_store.py @@ -0,0 +1,79 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["VectorStore", "FileCounts", "ExpiresAfter"] + + +class FileCounts(BaseModel): + cancelled: int + """The number of files that were cancelled.""" + + completed: int + """The number of files that have been successfully processed.""" + + failed: int + """The number of files that have failed to process.""" + + in_progress: int + """The number of files that are currently being processed.""" + + total: int + """The total number of files.""" + + +class ExpiresAfter(BaseModel): + anchor: Literal["last_active_at"] + """Anchor timestamp after which the expiration policy applies. + + Supported anchors: `last_active_at`. + """ + + days: int + """The number of days after the anchor time that the vector store will expire.""" + + +class VectorStore(BaseModel): + id: str + """The identifier, which can be referenced in API endpoints.""" + + bytes: int + """The byte size of the vector store.""" + + created_at: int + """The Unix timestamp (in seconds) for when the vector store was created.""" + + file_counts: FileCounts + + last_active_at: Optional[int] = None + """The Unix timestamp (in seconds) for when the vector store was last active.""" + + metadata: Optional[object] = None + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format. Keys can be a maximum of 64 characters long and values can be + a maxium of 512 characters long. + """ + + name: str + """The name of the vector store.""" + + object: Literal["vector_store"] + """The object type, which is always `vector_store`.""" + + status: Literal["expired", "in_progress", "completed"] + """ + The status of the vector store, which can be either `expired`, `in_progress`, or + `completed`. A status of `completed` indicates that the vector store is ready + for use. + """ + + expires_after: Optional[ExpiresAfter] = None + """The expiration policy for a vector store.""" + + expires_at: Optional[int] = None + """The Unix timestamp (in seconds) for when the vector store will expire.""" diff --git a/src/openai/types/beta/vector_store_create_params.py b/src/openai/types/beta/vector_store_create_params.py new file mode 100644 index 0000000000..f1a3abcbdf --- /dev/null +++ b/src/openai/types/beta/vector_store_create_params.py @@ -0,0 +1,42 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["VectorStoreCreateParams", "ExpiresAfter"] + + +class VectorStoreCreateParams(TypedDict, total=False): + expires_after: ExpiresAfter + """The expiration policy for a vector store.""" + + file_ids: List[str] + """ + A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + the vector store should use. Useful for tools like `file_search` that can access + files. + """ + + metadata: Optional[object] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format. Keys can be a maximum of 64 characters long and values can be + a maxium of 512 characters long. + """ + + name: str + """The name of the vector store.""" + + +class ExpiresAfter(TypedDict, total=False): + anchor: Required[Literal["last_active_at"]] + """Anchor timestamp after which the expiration policy applies. + + Supported anchors: `last_active_at`. + """ + + days: Required[int] + """The number of days after the anchor time that the vector store will expire.""" diff --git a/src/openai/types/beta/retrieval_tool.py b/src/openai/types/beta/vector_store_deleted.py similarity index 52% rename from src/openai/types/beta/retrieval_tool.py rename to src/openai/types/beta/vector_store_deleted.py index b07b785c66..21ccda1db5 100644 --- a/src/openai/types/beta/retrieval_tool.py +++ b/src/openai/types/beta/vector_store_deleted.py @@ -4,9 +4,12 @@ from ..._models import BaseModel -__all__ = ["RetrievalTool"] +__all__ = ["VectorStoreDeleted"] -class RetrievalTool(BaseModel): - type: Literal["retrieval"] - """The type of tool being defined: `retrieval`""" +class VectorStoreDeleted(BaseModel): + id: str + + deleted: bool + + object: Literal["vector_store.deleted"] diff --git a/src/openai/types/beta/assistants/file_list_params.py b/src/openai/types/beta/vector_store_list_params.py similarity index 92% rename from src/openai/types/beta/assistants/file_list_params.py rename to src/openai/types/beta/vector_store_list_params.py index 53c493b36a..f39f67266d 100644 --- a/src/openai/types/beta/assistants/file_list_params.py +++ b/src/openai/types/beta/vector_store_list_params.py @@ -4,10 +4,10 @@ from typing_extensions import Literal, TypedDict -__all__ = ["FileListParams"] +__all__ = ["VectorStoreListParams"] -class FileListParams(TypedDict, total=False): +class VectorStoreListParams(TypedDict, total=False): after: str """A cursor for use in pagination. diff --git a/src/openai/types/beta/vector_store_update_params.py b/src/openai/types/beta/vector_store_update_params.py new file mode 100644 index 0000000000..0f9593e476 --- /dev/null +++ b/src/openai/types/beta/vector_store_update_params.py @@ -0,0 +1,35 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["VectorStoreUpdateParams", "ExpiresAfter"] + + +class VectorStoreUpdateParams(TypedDict, total=False): + expires_after: Optional[ExpiresAfter] + """The expiration policy for a vector store.""" + + metadata: Optional[object] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format. Keys can be a maximum of 64 characters long and values can be + a maxium of 512 characters long. + """ + + name: Optional[str] + """The name of the vector store.""" + + +class ExpiresAfter(TypedDict, total=False): + anchor: Required[Literal["last_active_at"]] + """Anchor timestamp after which the expiration policy applies. + + Supported anchors: `last_active_at`. + """ + + days: Required[int] + """The number of days after the anchor time that the vector store will expire.""" diff --git a/src/openai/types/beta/vector_stores/__init__.py b/src/openai/types/beta/vector_stores/__init__.py new file mode 100644 index 0000000000..ff05dd63d8 --- /dev/null +++ b/src/openai/types/beta/vector_stores/__init__.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .file_list_params import FileListParams as FileListParams +from .vector_store_file import VectorStoreFile as VectorStoreFile +from .file_create_params import FileCreateParams as FileCreateParams +from .vector_store_file_batch import VectorStoreFileBatch as VectorStoreFileBatch +from .file_batch_create_params import FileBatchCreateParams as FileBatchCreateParams +from .vector_store_file_deleted import VectorStoreFileDeleted as VectorStoreFileDeleted +from .file_batch_list_files_params import FileBatchListFilesParams as FileBatchListFilesParams diff --git a/src/openai/types/beta/vector_stores/file_batch_create_params.py b/src/openai/types/beta/vector_stores/file_batch_create_params.py new file mode 100644 index 0000000000..0882829732 --- /dev/null +++ b/src/openai/types/beta/vector_stores/file_batch_create_params.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List +from typing_extensions import Required, TypedDict + +__all__ = ["FileBatchCreateParams"] + + +class FileBatchCreateParams(TypedDict, total=False): + file_ids: Required[List[str]] + """ + A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that + the vector store should use. Useful for tools like `file_search` that can access + files. + """ diff --git a/src/openai/types/beta/vector_stores/file_batch_list_files_params.py b/src/openai/types/beta/vector_stores/file_batch_list_files_params.py new file mode 100644 index 0000000000..24dee7d5a5 --- /dev/null +++ b/src/openai/types/beta/vector_stores/file_batch_list_files_params.py @@ -0,0 +1,47 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["FileBatchListFilesParams"] + + +class FileBatchListFilesParams(TypedDict, total=False): + vector_store_id: Required[str] + + after: str + """A cursor for use in pagination. + + `after` is an object ID that defines your place in the list. For instance, if + you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include after=obj_foo in order to fetch the next page of the + list. + """ + + before: str + """A cursor for use in pagination. + + `before` is an object ID that defines your place in the list. For instance, if + you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page + of the list. + """ + + filter: Literal["in_progress", "completed", "failed", "cancelled"] + """Filter by file status. + + One of `in_progress`, `completed`, `failed`, `cancelled`. + """ + + limit: int + """A limit on the number of objects to be returned. + + Limit can range between 1 and 100, and the default is 20. + """ + + order: Literal["asc", "desc"] + """Sort order by the `created_at` timestamp of the objects. + + `asc` for ascending order and `desc` for descending order. + """ diff --git a/src/openai/types/beta/assistants/file_create_params.py b/src/openai/types/beta/vector_stores/file_create_params.py similarity index 70% rename from src/openai/types/beta/assistants/file_create_params.py rename to src/openai/types/beta/vector_stores/file_create_params.py index 55f0e8cda1..2fee588abf 100644 --- a/src/openai/types/beta/assistants/file_create_params.py +++ b/src/openai/types/beta/vector_stores/file_create_params.py @@ -10,7 +10,7 @@ class FileCreateParams(TypedDict, total=False): file_id: Required[str] """ - A [File](https://platform.openai.com/docs/api-reference/files) ID (with - `purpose="assistants"`) that the assistant should use. Useful for tools like - `retrieval` and `code_interpreter` that can access files. + A [File](https://platform.openai.com/docs/api-reference/files) ID that the + vector store should use. Useful for tools like `file_search` that can access + files. """ diff --git a/src/openai/types/beta/threads/messages/file_list_params.py b/src/openai/types/beta/vector_stores/file_list_params.py similarity index 84% rename from src/openai/types/beta/threads/messages/file_list_params.py rename to src/openai/types/beta/vector_stores/file_list_params.py index 7e2d6136ec..23dd7f0d94 100644 --- a/src/openai/types/beta/threads/messages/file_list_params.py +++ b/src/openai/types/beta/vector_stores/file_list_params.py @@ -2,14 +2,12 @@ from __future__ import annotations -from typing_extensions import Literal, Required, TypedDict +from typing_extensions import Literal, TypedDict __all__ = ["FileListParams"] class FileListParams(TypedDict, total=False): - thread_id: Required[str] - after: str """A cursor for use in pagination. @@ -28,6 +26,12 @@ class FileListParams(TypedDict, total=False): of the list. """ + filter: Literal["in_progress", "completed", "failed", "cancelled"] + """Filter by file status. + + One of `in_progress`, `completed`, `failed`, `cancelled`. + """ + limit: int """A limit on the number of objects to be returned. diff --git a/src/openai/types/beta/vector_stores/vector_store_file.py b/src/openai/types/beta/vector_stores/vector_store_file.py new file mode 100644 index 0000000000..a878b281d5 --- /dev/null +++ b/src/openai/types/beta/vector_stores/vector_store_file.py @@ -0,0 +1,48 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["VectorStoreFile", "LastError"] + + +class LastError(BaseModel): + code: Literal["internal_error", "file_not_found", "parsing_error", "unhandled_mime_type"] + """One of `server_error` or `rate_limit_exceeded`.""" + + message: str + """A human-readable description of the error.""" + + +class VectorStoreFile(BaseModel): + id: str + """The identifier, which can be referenced in API endpoints.""" + + created_at: int + """The Unix timestamp (in seconds) for when the vector store file was created.""" + + last_error: Optional[LastError] = None + """The last error associated with this vector store file. + + Will be `null` if there are no errors. + """ + + object: Literal["vector_store.file"] + """The object type, which is always `vector_store.file`.""" + + status: Literal["in_progress", "completed", "cancelled", "failed"] + """ + The status of the vector store file, which can be either `in_progress`, + `completed`, `cancelled`, or `failed`. The status `completed` indicates that the + vector store file is ready for use. + """ + + vector_store_id: str + """ + The ID of the + [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + that the [File](https://platform.openai.com/docs/api-reference/files) is + attached to. + """ diff --git a/src/openai/types/beta/vector_stores/vector_store_file_batch.py b/src/openai/types/beta/vector_stores/vector_store_file_batch.py new file mode 100644 index 0000000000..df130a58de --- /dev/null +++ b/src/openai/types/beta/vector_stores/vector_store_file_batch.py @@ -0,0 +1,54 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["VectorStoreFileBatch", "FileCounts"] + + +class FileCounts(BaseModel): + cancelled: int + """The number of files that where cancelled.""" + + completed: int + """The number of files that have been processed.""" + + failed: int + """The number of files that have failed to process.""" + + in_progress: int + """The number of files that are currently being processed.""" + + total: int + """The total number of files.""" + + +class VectorStoreFileBatch(BaseModel): + id: str + """The identifier, which can be referenced in API endpoints.""" + + created_at: int + """ + The Unix timestamp (in seconds) for when the vector store files batch was + created. + """ + + file_counts: FileCounts + + object: Literal["vector_store.files_batch"] + """The object type, which is always `vector_store.file_batch`.""" + + status: Literal["in_progress", "completed", "cancelled", "failed"] + """ + The status of the vector store files batch, which can be either `in_progress`, + `completed`, `cancelled` or `failed`. + """ + + vector_store_id: str + """ + The ID of the + [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) + that the [File](https://platform.openai.com/docs/api-reference/files) is + attached to. + """ diff --git a/src/openai/types/beta/assistants/file_delete_response.py b/src/openai/types/beta/vector_stores/vector_store_file_deleted.py similarity index 60% rename from src/openai/types/beta/assistants/file_delete_response.py rename to src/openai/types/beta/vector_stores/vector_store_file_deleted.py index 685fb2a75c..ae37f84364 100644 --- a/src/openai/types/beta/assistants/file_delete_response.py +++ b/src/openai/types/beta/vector_stores/vector_store_file_deleted.py @@ -4,12 +4,12 @@ from ...._models import BaseModel -__all__ = ["FileDeleteResponse"] +__all__ = ["VectorStoreFileDeleted"] -class FileDeleteResponse(BaseModel): +class VectorStoreFileDeleted(BaseModel): id: str deleted: bool - object: Literal["assistant.file.deleted"] + object: Literal["vector_store.file.deleted"] diff --git a/src/openai/types/fine_tuning/job_create_params.py b/src/openai/types/fine_tuning/job_create_params.py index 892c737fa3..1925f90d12 100644 --- a/src/openai/types/fine_tuning/job_create_params.py +++ b/src/openai/types/fine_tuning/job_create_params.py @@ -19,7 +19,7 @@ class JobCreateParams(TypedDict, total=False): training_file: Required[str] """The ID of an uploaded file that contains training data. - See [upload file](https://platform.openai.com/docs/api-reference/files/upload) + See [upload file](https://platform.openai.com/docs/api-reference/files/create) for how to upload a file. Your dataset must be formatted as a JSONL file. Additionally, you must upload diff --git a/tests/api_resources/beta/test_assistants.py b/tests/api_resources/beta/test_assistants.py index a509627b8e..a92acb2ca5 100644 --- a/tests/api_resources/beta/test_assistants.py +++ b/tests/api_resources/beta/test_assistants.py @@ -33,11 +33,25 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: assistant = client.beta.assistants.create( model="gpt-4-turbo", description="string", - file_ids=["string", "string", "string"], instructions="string", metadata={}, name="string", + response_format="none", + temperature=1, + tool_resources={ + "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "file_search": { + "vector_store_ids": ["string"], + "vector_stores": [ + { + "file_ids": ["string", "string", "string"], + "metadata": {}, + } + ], + }, + }, tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + top_p=1, ) assert_matches_type(Assistant, assistant, path=["response"]) @@ -115,12 +129,18 @@ def test_method_update_with_all_params(self, client: OpenAI) -> None: assistant = client.beta.assistants.update( "string", description="string", - file_ids=["string", "string", "string"], instructions="string", metadata={}, model="string", name="string", + response_format="none", + temperature=1, + tool_resources={ + "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "file_search": {"vector_store_ids": ["string"]}, + }, tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + top_p=1, ) assert_matches_type(Assistant, assistant, path=["response"]) @@ -244,11 +264,25 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> assistant = await async_client.beta.assistants.create( model="gpt-4-turbo", description="string", - file_ids=["string", "string", "string"], instructions="string", metadata={}, name="string", + response_format="none", + temperature=1, + tool_resources={ + "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "file_search": { + "vector_store_ids": ["string"], + "vector_stores": [ + { + "file_ids": ["string", "string", "string"], + "metadata": {}, + } + ], + }, + }, tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + top_p=1, ) assert_matches_type(Assistant, assistant, path=["response"]) @@ -326,12 +360,18 @@ async def test_method_update_with_all_params(self, async_client: AsyncOpenAI) -> assistant = await async_client.beta.assistants.update( "string", description="string", - file_ids=["string", "string", "string"], instructions="string", metadata={}, model="string", name="string", + response_format="none", + temperature=1, + tool_resources={ + "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "file_search": {"vector_store_ids": ["string"]}, + }, tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + top_p=1, ) assert_matches_type(Assistant, assistant, path=["response"]) diff --git a/tests/api_resources/beta/test_threads.py b/tests/api_resources/beta/test_threads.py index 7c07251433..980fd9a75e 100644 --- a/tests/api_resources/beta/test_threads.py +++ b/tests/api_resources/beta/test_threads.py @@ -33,23 +33,74 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, ], metadata={}, + tool_resources={ + "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "file_search": { + "vector_store_ids": ["string"], + "vector_stores": [ + { + "file_ids": ["string", "string", "string"], + "metadata": {}, + } + ], + }, + }, ) assert_matches_type(Thread, thread, path=["response"]) @@ -123,6 +174,10 @@ def test_method_update_with_all_params(self, client: OpenAI) -> None: thread = client.beta.threads.update( "string", metadata={}, + tool_resources={ + "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "file_search": {"vector_store_ids": ["string"]}, + }, ) assert_matches_type(Thread, thread, path=["response"]) @@ -219,26 +274,82 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, ], + "tool_resources": { + "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "file_search": { + "vector_store_ids": ["string"], + "vector_stores": [ + { + "file_ids": ["string", "string", "string"], + "metadata": {}, + } + ], + }, + }, "metadata": {}, }, tool_choice="none", + tool_resources={ + "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "file_search": {"vector_store_ids": ["string"]}, + }, tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + top_p=1, truncation_strategy={ "type": "auto", "last_messages": 1, @@ -295,26 +406,82 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, ], + "tool_resources": { + "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "file_search": { + "vector_store_ids": ["string"], + "vector_stores": [ + { + "file_ids": ["string", "string", "string"], + "metadata": {}, + } + ], + }, + }, "metadata": {}, }, tool_choice="none", + tool_resources={ + "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "file_search": {"vector_store_ids": ["string"]}, + }, tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + top_p=1, truncation_strategy={ "type": "auto", "last_messages": 1, @@ -363,23 +530,74 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, ], metadata={}, + tool_resources={ + "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "file_search": { + "vector_store_ids": ["string"], + "vector_stores": [ + { + "file_ids": ["string", "string", "string"], + "metadata": {}, + } + ], + }, + }, ) assert_matches_type(Thread, thread, path=["response"]) @@ -453,6 +671,10 @@ async def test_method_update_with_all_params(self, async_client: AsyncOpenAI) -> thread = await async_client.beta.threads.update( "string", metadata={}, + tool_resources={ + "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "file_search": {"vector_store_ids": ["string"]}, + }, ) assert_matches_type(Thread, thread, path=["response"]) @@ -549,26 +771,82 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, ], + "tool_resources": { + "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "file_search": { + "vector_store_ids": ["string"], + "vector_stores": [ + { + "file_ids": ["string", "string", "string"], + "metadata": {}, + } + ], + }, + }, "metadata": {}, }, tool_choice="none", + tool_resources={ + "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "file_search": {"vector_store_ids": ["string"]}, + }, tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + top_p=1, truncation_strategy={ "type": "auto", "last_messages": 1, @@ -625,26 +903,82 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, ], + "tool_resources": { + "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "file_search": { + "vector_store_ids": ["string"], + "vector_stores": [ + { + "file_ids": ["string", "string", "string"], + "metadata": {}, + } + ], + }, + }, "metadata": {}, }, tool_choice="none", + tool_resources={ + "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "file_search": {"vector_store_ids": ["string"]}, + }, tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + top_p=1, truncation_strategy={ "type": "auto", "last_messages": 1, diff --git a/tests/api_resources/beta/test_vector_stores.py b/tests/api_resources/beta/test_vector_stores.py new file mode 100644 index 0000000000..e671c96a45 --- /dev/null +++ b/tests/api_resources/beta/test_vector_stores.py @@ -0,0 +1,426 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai.pagination import SyncCursorPage, AsyncCursorPage +from openai.types.beta import ( + VectorStore, + VectorStoreDeleted, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") + + +class TestVectorStores: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + def test_method_create(self, client: OpenAI) -> None: + vector_store = client.beta.vector_stores.create() + assert_matches_type(VectorStore, vector_store, path=["response"]) + + @parametrize + def test_method_create_with_all_params(self, client: OpenAI) -> None: + vector_store = client.beta.vector_stores.create( + expires_after={ + "anchor": "last_active_at", + "days": 1, + }, + file_ids=["string", "string", "string"], + metadata={}, + name="string", + ) + assert_matches_type(VectorStore, vector_store, path=["response"]) + + @parametrize + def test_raw_response_create(self, client: OpenAI) -> None: + response = client.beta.vector_stores.with_raw_response.create() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + vector_store = response.parse() + assert_matches_type(VectorStore, vector_store, path=["response"]) + + @parametrize + def test_streaming_response_create(self, client: OpenAI) -> None: + with client.beta.vector_stores.with_streaming_response.create() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + vector_store = response.parse() + assert_matches_type(VectorStore, vector_store, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_method_retrieve(self, client: OpenAI) -> None: + vector_store = client.beta.vector_stores.retrieve( + "string", + ) + assert_matches_type(VectorStore, vector_store, path=["response"]) + + @parametrize + def test_raw_response_retrieve(self, client: OpenAI) -> None: + response = client.beta.vector_stores.with_raw_response.retrieve( + "string", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + vector_store = response.parse() + assert_matches_type(VectorStore, vector_store, path=["response"]) + + @parametrize + def test_streaming_response_retrieve(self, client: OpenAI) -> None: + with client.beta.vector_stores.with_streaming_response.retrieve( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + vector_store = response.parse() + assert_matches_type(VectorStore, vector_store, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_retrieve(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + client.beta.vector_stores.with_raw_response.retrieve( + "", + ) + + @parametrize + def test_method_update(self, client: OpenAI) -> None: + vector_store = client.beta.vector_stores.update( + "string", + ) + assert_matches_type(VectorStore, vector_store, path=["response"]) + + @parametrize + def test_method_update_with_all_params(self, client: OpenAI) -> None: + vector_store = client.beta.vector_stores.update( + "string", + expires_after={ + "anchor": "last_active_at", + "days": 1, + }, + metadata={}, + name="string", + ) + assert_matches_type(VectorStore, vector_store, path=["response"]) + + @parametrize + def test_raw_response_update(self, client: OpenAI) -> None: + response = client.beta.vector_stores.with_raw_response.update( + "string", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + vector_store = response.parse() + assert_matches_type(VectorStore, vector_store, path=["response"]) + + @parametrize + def test_streaming_response_update(self, client: OpenAI) -> None: + with client.beta.vector_stores.with_streaming_response.update( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + vector_store = response.parse() + assert_matches_type(VectorStore, vector_store, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_update(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + client.beta.vector_stores.with_raw_response.update( + "", + ) + + @parametrize + def test_method_list(self, client: OpenAI) -> None: + vector_store = client.beta.vector_stores.list() + assert_matches_type(SyncCursorPage[VectorStore], vector_store, path=["response"]) + + @parametrize + def test_method_list_with_all_params(self, client: OpenAI) -> None: + vector_store = client.beta.vector_stores.list( + after="string", + before="string", + limit=0, + order="asc", + ) + assert_matches_type(SyncCursorPage[VectorStore], vector_store, path=["response"]) + + @parametrize + def test_raw_response_list(self, client: OpenAI) -> None: + response = client.beta.vector_stores.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + vector_store = response.parse() + assert_matches_type(SyncCursorPage[VectorStore], vector_store, path=["response"]) + + @parametrize + def test_streaming_response_list(self, client: OpenAI) -> None: + with client.beta.vector_stores.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + vector_store = response.parse() + assert_matches_type(SyncCursorPage[VectorStore], vector_store, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_method_delete(self, client: OpenAI) -> None: + vector_store = client.beta.vector_stores.delete( + "string", + ) + assert_matches_type(VectorStoreDeleted, vector_store, path=["response"]) + + @parametrize + def test_raw_response_delete(self, client: OpenAI) -> None: + response = client.beta.vector_stores.with_raw_response.delete( + "string", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + vector_store = response.parse() + assert_matches_type(VectorStoreDeleted, vector_store, path=["response"]) + + @parametrize + def test_streaming_response_delete(self, client: OpenAI) -> None: + with client.beta.vector_stores.with_streaming_response.delete( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + vector_store = response.parse() + assert_matches_type(VectorStoreDeleted, vector_store, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_delete(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + client.beta.vector_stores.with_raw_response.delete( + "", + ) + + +class TestAsyncVectorStores: + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + async def test_method_create(self, async_client: AsyncOpenAI) -> None: + vector_store = await async_client.beta.vector_stores.create() + assert_matches_type(VectorStore, vector_store, path=["response"]) + + @parametrize + async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: + vector_store = await async_client.beta.vector_stores.create( + expires_after={ + "anchor": "last_active_at", + "days": 1, + }, + file_ids=["string", "string", "string"], + metadata={}, + name="string", + ) + assert_matches_type(VectorStore, vector_store, path=["response"]) + + @parametrize + async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.vector_stores.with_raw_response.create() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + vector_store = response.parse() + assert_matches_type(VectorStore, vector_store, path=["response"]) + + @parametrize + async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.vector_stores.with_streaming_response.create() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + vector_store = await response.parse() + assert_matches_type(VectorStore, vector_store, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: + vector_store = await async_client.beta.vector_stores.retrieve( + "string", + ) + assert_matches_type(VectorStore, vector_store, path=["response"]) + + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.vector_stores.with_raw_response.retrieve( + "string", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + vector_store = response.parse() + assert_matches_type(VectorStore, vector_store, path=["response"]) + + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.vector_stores.with_streaming_response.retrieve( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + vector_store = await response.parse() + assert_matches_type(VectorStore, vector_store, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + await async_client.beta.vector_stores.with_raw_response.retrieve( + "", + ) + + @parametrize + async def test_method_update(self, async_client: AsyncOpenAI) -> None: + vector_store = await async_client.beta.vector_stores.update( + "string", + ) + assert_matches_type(VectorStore, vector_store, path=["response"]) + + @parametrize + async def test_method_update_with_all_params(self, async_client: AsyncOpenAI) -> None: + vector_store = await async_client.beta.vector_stores.update( + "string", + expires_after={ + "anchor": "last_active_at", + "days": 1, + }, + metadata={}, + name="string", + ) + assert_matches_type(VectorStore, vector_store, path=["response"]) + + @parametrize + async def test_raw_response_update(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.vector_stores.with_raw_response.update( + "string", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + vector_store = response.parse() + assert_matches_type(VectorStore, vector_store, path=["response"]) + + @parametrize + async def test_streaming_response_update(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.vector_stores.with_streaming_response.update( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + vector_store = await response.parse() + assert_matches_type(VectorStore, vector_store, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_update(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + await async_client.beta.vector_stores.with_raw_response.update( + "", + ) + + @parametrize + async def test_method_list(self, async_client: AsyncOpenAI) -> None: + vector_store = await async_client.beta.vector_stores.list() + assert_matches_type(AsyncCursorPage[VectorStore], vector_store, path=["response"]) + + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: + vector_store = await async_client.beta.vector_stores.list( + after="string", + before="string", + limit=0, + order="asc", + ) + assert_matches_type(AsyncCursorPage[VectorStore], vector_store, path=["response"]) + + @parametrize + async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.vector_stores.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + vector_store = response.parse() + assert_matches_type(AsyncCursorPage[VectorStore], vector_store, path=["response"]) + + @parametrize + async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.vector_stores.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + vector_store = await response.parse() + assert_matches_type(AsyncCursorPage[VectorStore], vector_store, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_method_delete(self, async_client: AsyncOpenAI) -> None: + vector_store = await async_client.beta.vector_stores.delete( + "string", + ) + assert_matches_type(VectorStoreDeleted, vector_store, path=["response"]) + + @parametrize + async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.vector_stores.with_raw_response.delete( + "string", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + vector_store = response.parse() + assert_matches_type(VectorStoreDeleted, vector_store, path=["response"]) + + @parametrize + async def test_streaming_response_delete(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.vector_stores.with_streaming_response.delete( + "string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + vector_store = await response.parse() + assert_matches_type(VectorStoreDeleted, vector_store, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_delete(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + await async_client.beta.vector_stores.with_raw_response.delete( + "", + ) diff --git a/tests/api_resources/beta/threads/messages/__init__.py b/tests/api_resources/beta/threads/messages/__init__.py deleted file mode 100644 index fd8019a9a1..0000000000 --- a/tests/api_resources/beta/threads/messages/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/beta/threads/messages/test_files.py b/tests/api_resources/beta/threads/messages/test_files.py deleted file mode 100644 index af4eea9377..0000000000 --- a/tests/api_resources/beta/threads/messages/test_files.py +++ /dev/null @@ -1,263 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -from __future__ import annotations - -import os -from typing import Any, cast - -import pytest - -from openai import OpenAI, AsyncOpenAI -from tests.utils import assert_matches_type -from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta.threads.messages import MessageFile - -base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") - - -class TestFiles: - parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) - - @parametrize - def test_method_retrieve(self, client: OpenAI) -> None: - file = client.beta.threads.messages.files.retrieve( - "file-abc123", - thread_id="thread_abc123", - message_id="msg_abc123", - ) - assert_matches_type(MessageFile, file, path=["response"]) - - @parametrize - def test_raw_response_retrieve(self, client: OpenAI) -> None: - response = client.beta.threads.messages.files.with_raw_response.retrieve( - "file-abc123", - thread_id="thread_abc123", - message_id="msg_abc123", - ) - - assert response.is_closed is True - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - file = response.parse() - assert_matches_type(MessageFile, file, path=["response"]) - - @parametrize - def test_streaming_response_retrieve(self, client: OpenAI) -> None: - with client.beta.threads.messages.files.with_streaming_response.retrieve( - "file-abc123", - thread_id="thread_abc123", - message_id="msg_abc123", - ) as response: - assert not response.is_closed - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - - file = response.parse() - assert_matches_type(MessageFile, file, path=["response"]) - - assert cast(Any, response.is_closed) is True - - @parametrize - def test_path_params_retrieve(self, client: OpenAI) -> None: - with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): - client.beta.threads.messages.files.with_raw_response.retrieve( - "file-abc123", - thread_id="", - message_id="msg_abc123", - ) - - with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): - client.beta.threads.messages.files.with_raw_response.retrieve( - "file-abc123", - thread_id="thread_abc123", - message_id="", - ) - - with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): - client.beta.threads.messages.files.with_raw_response.retrieve( - "", - thread_id="thread_abc123", - message_id="msg_abc123", - ) - - @parametrize - def test_method_list(self, client: OpenAI) -> None: - file = client.beta.threads.messages.files.list( - "string", - thread_id="string", - ) - assert_matches_type(SyncCursorPage[MessageFile], file, path=["response"]) - - @parametrize - def test_method_list_with_all_params(self, client: OpenAI) -> None: - file = client.beta.threads.messages.files.list( - "string", - thread_id="string", - after="string", - before="string", - limit=0, - order="asc", - ) - assert_matches_type(SyncCursorPage[MessageFile], file, path=["response"]) - - @parametrize - def test_raw_response_list(self, client: OpenAI) -> None: - response = client.beta.threads.messages.files.with_raw_response.list( - "string", - thread_id="string", - ) - - assert response.is_closed is True - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - file = response.parse() - assert_matches_type(SyncCursorPage[MessageFile], file, path=["response"]) - - @parametrize - def test_streaming_response_list(self, client: OpenAI) -> None: - with client.beta.threads.messages.files.with_streaming_response.list( - "string", - thread_id="string", - ) as response: - assert not response.is_closed - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - - file = response.parse() - assert_matches_type(SyncCursorPage[MessageFile], file, path=["response"]) - - assert cast(Any, response.is_closed) is True - - @parametrize - def test_path_params_list(self, client: OpenAI) -> None: - with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): - client.beta.threads.messages.files.with_raw_response.list( - "string", - thread_id="", - ) - - with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): - client.beta.threads.messages.files.with_raw_response.list( - "", - thread_id="string", - ) - - -class TestAsyncFiles: - parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) - - @parametrize - async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: - file = await async_client.beta.threads.messages.files.retrieve( - "file-abc123", - thread_id="thread_abc123", - message_id="msg_abc123", - ) - assert_matches_type(MessageFile, file, path=["response"]) - - @parametrize - async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: - response = await async_client.beta.threads.messages.files.with_raw_response.retrieve( - "file-abc123", - thread_id="thread_abc123", - message_id="msg_abc123", - ) - - assert response.is_closed is True - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - file = response.parse() - assert_matches_type(MessageFile, file, path=["response"]) - - @parametrize - async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: - async with async_client.beta.threads.messages.files.with_streaming_response.retrieve( - "file-abc123", - thread_id="thread_abc123", - message_id="msg_abc123", - ) as response: - assert not response.is_closed - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - - file = await response.parse() - assert_matches_type(MessageFile, file, path=["response"]) - - assert cast(Any, response.is_closed) is True - - @parametrize - async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: - with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): - await async_client.beta.threads.messages.files.with_raw_response.retrieve( - "file-abc123", - thread_id="", - message_id="msg_abc123", - ) - - with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): - await async_client.beta.threads.messages.files.with_raw_response.retrieve( - "file-abc123", - thread_id="thread_abc123", - message_id="", - ) - - with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): - await async_client.beta.threads.messages.files.with_raw_response.retrieve( - "", - thread_id="thread_abc123", - message_id="msg_abc123", - ) - - @parametrize - async def test_method_list(self, async_client: AsyncOpenAI) -> None: - file = await async_client.beta.threads.messages.files.list( - "string", - thread_id="string", - ) - assert_matches_type(AsyncCursorPage[MessageFile], file, path=["response"]) - - @parametrize - async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: - file = await async_client.beta.threads.messages.files.list( - "string", - thread_id="string", - after="string", - before="string", - limit=0, - order="asc", - ) - assert_matches_type(AsyncCursorPage[MessageFile], file, path=["response"]) - - @parametrize - async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: - response = await async_client.beta.threads.messages.files.with_raw_response.list( - "string", - thread_id="string", - ) - - assert response.is_closed is True - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - file = response.parse() - assert_matches_type(AsyncCursorPage[MessageFile], file, path=["response"]) - - @parametrize - async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: - async with async_client.beta.threads.messages.files.with_streaming_response.list( - "string", - thread_id="string", - ) as response: - assert not response.is_closed - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - - file = await response.parse() - assert_matches_type(AsyncCursorPage[MessageFile], file, path=["response"]) - - assert cast(Any, response.is_closed) is True - - @parametrize - async def test_path_params_list(self, async_client: AsyncOpenAI) -> None: - with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): - await async_client.beta.threads.messages.files.with_raw_response.list( - "string", - thread_id="", - ) - - with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): - await async_client.beta.threads.messages.files.with_raw_response.list( - "", - thread_id="string", - ) diff --git a/tests/api_resources/beta/threads/test_messages.py b/tests/api_resources/beta/threads/test_messages.py index 22198ccbc5..5ea5ac3bd5 100644 --- a/tests/api_resources/beta/threads/test_messages.py +++ b/tests/api_resources/beta/threads/test_messages.py @@ -33,7 +33,20 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "string", content="x", role="user", - file_ids=["string"], + attachments=[ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], metadata={}, ) assert_matches_type(Message, message, path=["response"]) @@ -249,7 +262,20 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "string", content="x", role="user", - file_ids=["string"], + attachments=[ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], metadata={}, ) assert_matches_type(Message, message, path=["response"]) diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index cf5b2998b9..3d8a6ce058 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -40,19 +40,58 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, ], @@ -66,6 +105,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: temperature=1, tool_choice="none", tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + top_p=1, truncation_strategy={ "type": "auto", "last_messages": 1, @@ -127,19 +167,58 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, ], @@ -152,6 +231,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: temperature=1, tool_choice="none", tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + top_p=1, truncation_strategy={ "type": "auto", "last_messages": 1, @@ -552,19 +632,58 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, ], @@ -578,6 +697,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn temperature=1, tool_choice="none", tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + top_p=1, truncation_strategy={ "type": "auto", "last_messages": 1, @@ -639,19 +759,58 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, { "role": "user", "content": "x", - "file_ids": ["string"], + "attachments": [ + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + { + "file_id": "string", + "add_to": ["file_search", "code_interpreter"], + }, + ], "metadata": {}, }, ], @@ -664,6 +823,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn temperature=1, tool_choice="none", tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + top_p=1, truncation_strategy={ "type": "auto", "last_messages": 1, diff --git a/tests/api_resources/beta/assistants/__init__.py b/tests/api_resources/beta/vector_stores/__init__.py similarity index 100% rename from tests/api_resources/beta/assistants/__init__.py rename to tests/api_resources/beta/vector_stores/__init__.py diff --git a/tests/api_resources/beta/vector_stores/test_file_batches.py b/tests/api_resources/beta/vector_stores/test_file_batches.py new file mode 100644 index 0000000000..9854d1a138 --- /dev/null +++ b/tests/api_resources/beta/vector_stores/test_file_batches.py @@ -0,0 +1,424 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai.pagination import SyncCursorPage, AsyncCursorPage +from openai.types.beta.vector_stores import ( + VectorStoreFile, + VectorStoreFileBatch, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") + + +class TestFileBatches: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + def test_method_create(self, client: OpenAI) -> None: + file_batch = client.beta.vector_stores.file_batches.create( + "vs_abc123", + file_ids=["string"], + ) + assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) + + @parametrize + def test_raw_response_create(self, client: OpenAI) -> None: + response = client.beta.vector_stores.file_batches.with_raw_response.create( + "vs_abc123", + file_ids=["string"], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file_batch = response.parse() + assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) + + @parametrize + def test_streaming_response_create(self, client: OpenAI) -> None: + with client.beta.vector_stores.file_batches.with_streaming_response.create( + "vs_abc123", + file_ids=["string"], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file_batch = response.parse() + assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_create(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + client.beta.vector_stores.file_batches.with_raw_response.create( + "", + file_ids=["string"], + ) + + @parametrize + def test_method_retrieve(self, client: OpenAI) -> None: + file_batch = client.beta.vector_stores.file_batches.retrieve( + "vsfb_abc123", + vector_store_id="vs_abc123", + ) + assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) + + @parametrize + def test_raw_response_retrieve(self, client: OpenAI) -> None: + response = client.beta.vector_stores.file_batches.with_raw_response.retrieve( + "vsfb_abc123", + vector_store_id="vs_abc123", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file_batch = response.parse() + assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) + + @parametrize + def test_streaming_response_retrieve(self, client: OpenAI) -> None: + with client.beta.vector_stores.file_batches.with_streaming_response.retrieve( + "vsfb_abc123", + vector_store_id="vs_abc123", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file_batch = response.parse() + assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_retrieve(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + client.beta.vector_stores.file_batches.with_raw_response.retrieve( + "vsfb_abc123", + vector_store_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `batch_id` but received ''"): + client.beta.vector_stores.file_batches.with_raw_response.retrieve( + "", + vector_store_id="vs_abc123", + ) + + @parametrize + def test_method_cancel(self, client: OpenAI) -> None: + file_batch = client.beta.vector_stores.file_batches.cancel( + "string", + vector_store_id="string", + ) + assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) + + @parametrize + def test_raw_response_cancel(self, client: OpenAI) -> None: + response = client.beta.vector_stores.file_batches.with_raw_response.cancel( + "string", + vector_store_id="string", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file_batch = response.parse() + assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) + + @parametrize + def test_streaming_response_cancel(self, client: OpenAI) -> None: + with client.beta.vector_stores.file_batches.with_streaming_response.cancel( + "string", + vector_store_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file_batch = response.parse() + assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_cancel(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + client.beta.vector_stores.file_batches.with_raw_response.cancel( + "string", + vector_store_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `batch_id` but received ''"): + client.beta.vector_stores.file_batches.with_raw_response.cancel( + "", + vector_store_id="string", + ) + + @parametrize + def test_method_list_files(self, client: OpenAI) -> None: + file_batch = client.beta.vector_stores.file_batches.list_files( + "string", + vector_store_id="string", + ) + assert_matches_type(SyncCursorPage[VectorStoreFile], file_batch, path=["response"]) + + @parametrize + def test_method_list_files_with_all_params(self, client: OpenAI) -> None: + file_batch = client.beta.vector_stores.file_batches.list_files( + "string", + vector_store_id="string", + after="string", + before="string", + filter="in_progress", + limit=0, + order="asc", + ) + assert_matches_type(SyncCursorPage[VectorStoreFile], file_batch, path=["response"]) + + @parametrize + def test_raw_response_list_files(self, client: OpenAI) -> None: + response = client.beta.vector_stores.file_batches.with_raw_response.list_files( + "string", + vector_store_id="string", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file_batch = response.parse() + assert_matches_type(SyncCursorPage[VectorStoreFile], file_batch, path=["response"]) + + @parametrize + def test_streaming_response_list_files(self, client: OpenAI) -> None: + with client.beta.vector_stores.file_batches.with_streaming_response.list_files( + "string", + vector_store_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file_batch = response.parse() + assert_matches_type(SyncCursorPage[VectorStoreFile], file_batch, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_list_files(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + client.beta.vector_stores.file_batches.with_raw_response.list_files( + "string", + vector_store_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `batch_id` but received ''"): + client.beta.vector_stores.file_batches.with_raw_response.list_files( + "", + vector_store_id="string", + ) + + +class TestAsyncFileBatches: + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + async def test_method_create(self, async_client: AsyncOpenAI) -> None: + file_batch = await async_client.beta.vector_stores.file_batches.create( + "vs_abc123", + file_ids=["string"], + ) + assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) + + @parametrize + async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.vector_stores.file_batches.with_raw_response.create( + "vs_abc123", + file_ids=["string"], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file_batch = response.parse() + assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) + + @parametrize + async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.vector_stores.file_batches.with_streaming_response.create( + "vs_abc123", + file_ids=["string"], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file_batch = await response.parse() + assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_create(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + await async_client.beta.vector_stores.file_batches.with_raw_response.create( + "", + file_ids=["string"], + ) + + @parametrize + async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: + file_batch = await async_client.beta.vector_stores.file_batches.retrieve( + "vsfb_abc123", + vector_store_id="vs_abc123", + ) + assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) + + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.vector_stores.file_batches.with_raw_response.retrieve( + "vsfb_abc123", + vector_store_id="vs_abc123", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file_batch = response.parse() + assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) + + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.vector_stores.file_batches.with_streaming_response.retrieve( + "vsfb_abc123", + vector_store_id="vs_abc123", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file_batch = await response.parse() + assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + await async_client.beta.vector_stores.file_batches.with_raw_response.retrieve( + "vsfb_abc123", + vector_store_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `batch_id` but received ''"): + await async_client.beta.vector_stores.file_batches.with_raw_response.retrieve( + "", + vector_store_id="vs_abc123", + ) + + @parametrize + async def test_method_cancel(self, async_client: AsyncOpenAI) -> None: + file_batch = await async_client.beta.vector_stores.file_batches.cancel( + "string", + vector_store_id="string", + ) + assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) + + @parametrize + async def test_raw_response_cancel(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.vector_stores.file_batches.with_raw_response.cancel( + "string", + vector_store_id="string", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file_batch = response.parse() + assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) + + @parametrize + async def test_streaming_response_cancel(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.vector_stores.file_batches.with_streaming_response.cancel( + "string", + vector_store_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file_batch = await response.parse() + assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_cancel(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + await async_client.beta.vector_stores.file_batches.with_raw_response.cancel( + "string", + vector_store_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `batch_id` but received ''"): + await async_client.beta.vector_stores.file_batches.with_raw_response.cancel( + "", + vector_store_id="string", + ) + + @parametrize + async def test_method_list_files(self, async_client: AsyncOpenAI) -> None: + file_batch = await async_client.beta.vector_stores.file_batches.list_files( + "string", + vector_store_id="string", + ) + assert_matches_type(AsyncCursorPage[VectorStoreFile], file_batch, path=["response"]) + + @parametrize + async def test_method_list_files_with_all_params(self, async_client: AsyncOpenAI) -> None: + file_batch = await async_client.beta.vector_stores.file_batches.list_files( + "string", + vector_store_id="string", + after="string", + before="string", + filter="in_progress", + limit=0, + order="asc", + ) + assert_matches_type(AsyncCursorPage[VectorStoreFile], file_batch, path=["response"]) + + @parametrize + async def test_raw_response_list_files(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.vector_stores.file_batches.with_raw_response.list_files( + "string", + vector_store_id="string", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file_batch = response.parse() + assert_matches_type(AsyncCursorPage[VectorStoreFile], file_batch, path=["response"]) + + @parametrize + async def test_streaming_response_list_files(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.vector_stores.file_batches.with_streaming_response.list_files( + "string", + vector_store_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file_batch = await response.parse() + assert_matches_type(AsyncCursorPage[VectorStoreFile], file_batch, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_list_files(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + await async_client.beta.vector_stores.file_batches.with_raw_response.list_files( + "string", + vector_store_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `batch_id` but received ''"): + await async_client.beta.vector_stores.file_batches.with_raw_response.list_files( + "", + vector_store_id="string", + ) diff --git a/tests/api_resources/beta/assistants/test_files.py b/tests/api_resources/beta/vector_stores/test_files.py similarity index 59% rename from tests/api_resources/beta/assistants/test_files.py rename to tests/api_resources/beta/vector_stores/test_files.py index 50106234aa..58301e2d37 100644 --- a/tests/api_resources/beta/assistants/test_files.py +++ b/tests/api_resources/beta/vector_stores/test_files.py @@ -10,7 +10,10 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta.assistants import AssistantFile, FileDeleteResponse +from openai.types.beta.vector_stores import ( + VectorStoreFile, + VectorStoreFileDeleted, +) base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") @@ -20,189 +23,190 @@ class TestFiles: @parametrize def test_method_create(self, client: OpenAI) -> None: - file = client.beta.assistants.files.create( - "file-abc123", + file = client.beta.vector_stores.files.create( + "vs_abc123", file_id="string", ) - assert_matches_type(AssistantFile, file, path=["response"]) + assert_matches_type(VectorStoreFile, file, path=["response"]) @parametrize def test_raw_response_create(self, client: OpenAI) -> None: - response = client.beta.assistants.files.with_raw_response.create( - "file-abc123", + response = client.beta.vector_stores.files.with_raw_response.create( + "vs_abc123", file_id="string", ) assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() - assert_matches_type(AssistantFile, file, path=["response"]) + assert_matches_type(VectorStoreFile, file, path=["response"]) @parametrize def test_streaming_response_create(self, client: OpenAI) -> None: - with client.beta.assistants.files.with_streaming_response.create( - "file-abc123", + with client.beta.vector_stores.files.with_streaming_response.create( + "vs_abc123", file_id="string", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() - assert_matches_type(AssistantFile, file, path=["response"]) + assert_matches_type(VectorStoreFile, file, path=["response"]) assert cast(Any, response.is_closed) is True @parametrize def test_path_params_create(self, client: OpenAI) -> None: - with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): - client.beta.assistants.files.with_raw_response.create( + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + client.beta.vector_stores.files.with_raw_response.create( "", file_id="string", ) @parametrize def test_method_retrieve(self, client: OpenAI) -> None: - file = client.beta.assistants.files.retrieve( - "string", - assistant_id="string", + file = client.beta.vector_stores.files.retrieve( + "file-abc123", + vector_store_id="vs_abc123", ) - assert_matches_type(AssistantFile, file, path=["response"]) + assert_matches_type(VectorStoreFile, file, path=["response"]) @parametrize def test_raw_response_retrieve(self, client: OpenAI) -> None: - response = client.beta.assistants.files.with_raw_response.retrieve( - "string", - assistant_id="string", + response = client.beta.vector_stores.files.with_raw_response.retrieve( + "file-abc123", + vector_store_id="vs_abc123", ) assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() - assert_matches_type(AssistantFile, file, path=["response"]) + assert_matches_type(VectorStoreFile, file, path=["response"]) @parametrize def test_streaming_response_retrieve(self, client: OpenAI) -> None: - with client.beta.assistants.files.with_streaming_response.retrieve( - "string", - assistant_id="string", + with client.beta.vector_stores.files.with_streaming_response.retrieve( + "file-abc123", + vector_store_id="vs_abc123", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() - assert_matches_type(AssistantFile, file, path=["response"]) + assert_matches_type(VectorStoreFile, file, path=["response"]) assert cast(Any, response.is_closed) is True @parametrize def test_path_params_retrieve(self, client: OpenAI) -> None: - with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): - client.beta.assistants.files.with_raw_response.retrieve( - "string", - assistant_id="", + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + client.beta.vector_stores.files.with_raw_response.retrieve( + "file-abc123", + vector_store_id="", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): - client.beta.assistants.files.with_raw_response.retrieve( + client.beta.vector_stores.files.with_raw_response.retrieve( "", - assistant_id="string", + vector_store_id="vs_abc123", ) @parametrize def test_method_list(self, client: OpenAI) -> None: - file = client.beta.assistants.files.list( + file = client.beta.vector_stores.files.list( "string", ) - assert_matches_type(SyncCursorPage[AssistantFile], file, path=["response"]) + assert_matches_type(SyncCursorPage[VectorStoreFile], file, path=["response"]) @parametrize def test_method_list_with_all_params(self, client: OpenAI) -> None: - file = client.beta.assistants.files.list( + file = client.beta.vector_stores.files.list( "string", after="string", before="string", + filter="in_progress", limit=0, order="asc", ) - assert_matches_type(SyncCursorPage[AssistantFile], file, path=["response"]) + assert_matches_type(SyncCursorPage[VectorStoreFile], file, path=["response"]) @parametrize def test_raw_response_list(self, client: OpenAI) -> None: - response = client.beta.assistants.files.with_raw_response.list( + response = client.beta.vector_stores.files.with_raw_response.list( "string", ) assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() - assert_matches_type(SyncCursorPage[AssistantFile], file, path=["response"]) + assert_matches_type(SyncCursorPage[VectorStoreFile], file, path=["response"]) @parametrize def test_streaming_response_list(self, client: OpenAI) -> None: - with client.beta.assistants.files.with_streaming_response.list( + with client.beta.vector_stores.files.with_streaming_response.list( "string", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() - assert_matches_type(SyncCursorPage[AssistantFile], file, path=["response"]) + assert_matches_type(SyncCursorPage[VectorStoreFile], file, path=["response"]) assert cast(Any, response.is_closed) is True @parametrize def test_path_params_list(self, client: OpenAI) -> None: - with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): - client.beta.assistants.files.with_raw_response.list( + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + client.beta.vector_stores.files.with_raw_response.list( "", ) @parametrize def test_method_delete(self, client: OpenAI) -> None: - file = client.beta.assistants.files.delete( + file = client.beta.vector_stores.files.delete( "string", - assistant_id="string", + vector_store_id="string", ) - assert_matches_type(FileDeleteResponse, file, path=["response"]) + assert_matches_type(VectorStoreFileDeleted, file, path=["response"]) @parametrize def test_raw_response_delete(self, client: OpenAI) -> None: - response = client.beta.assistants.files.with_raw_response.delete( + response = client.beta.vector_stores.files.with_raw_response.delete( "string", - assistant_id="string", + vector_store_id="string", ) assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() - assert_matches_type(FileDeleteResponse, file, path=["response"]) + assert_matches_type(VectorStoreFileDeleted, file, path=["response"]) @parametrize def test_streaming_response_delete(self, client: OpenAI) -> None: - with client.beta.assistants.files.with_streaming_response.delete( + with client.beta.vector_stores.files.with_streaming_response.delete( "string", - assistant_id="string", + vector_store_id="string", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() - assert_matches_type(FileDeleteResponse, file, path=["response"]) + assert_matches_type(VectorStoreFileDeleted, file, path=["response"]) assert cast(Any, response.is_closed) is True @parametrize def test_path_params_delete(self, client: OpenAI) -> None: - with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): - client.beta.assistants.files.with_raw_response.delete( + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + client.beta.vector_stores.files.with_raw_response.delete( "string", - assistant_id="", + vector_store_id="", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): - client.beta.assistants.files.with_raw_response.delete( + client.beta.vector_stores.files.with_raw_response.delete( "", - assistant_id="string", + vector_store_id="string", ) @@ -211,187 +215,188 @@ class TestAsyncFiles: @parametrize async def test_method_create(self, async_client: AsyncOpenAI) -> None: - file = await async_client.beta.assistants.files.create( - "file-abc123", + file = await async_client.beta.vector_stores.files.create( + "vs_abc123", file_id="string", ) - assert_matches_type(AssistantFile, file, path=["response"]) + assert_matches_type(VectorStoreFile, file, path=["response"]) @parametrize async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: - response = await async_client.beta.assistants.files.with_raw_response.create( - "file-abc123", + response = await async_client.beta.vector_stores.files.with_raw_response.create( + "vs_abc123", file_id="string", ) assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() - assert_matches_type(AssistantFile, file, path=["response"]) + assert_matches_type(VectorStoreFile, file, path=["response"]) @parametrize async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: - async with async_client.beta.assistants.files.with_streaming_response.create( - "file-abc123", + async with async_client.beta.vector_stores.files.with_streaming_response.create( + "vs_abc123", file_id="string", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = await response.parse() - assert_matches_type(AssistantFile, file, path=["response"]) + assert_matches_type(VectorStoreFile, file, path=["response"]) assert cast(Any, response.is_closed) is True @parametrize async def test_path_params_create(self, async_client: AsyncOpenAI) -> None: - with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): - await async_client.beta.assistants.files.with_raw_response.create( + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + await async_client.beta.vector_stores.files.with_raw_response.create( "", file_id="string", ) @parametrize async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: - file = await async_client.beta.assistants.files.retrieve( - "string", - assistant_id="string", + file = await async_client.beta.vector_stores.files.retrieve( + "file-abc123", + vector_store_id="vs_abc123", ) - assert_matches_type(AssistantFile, file, path=["response"]) + assert_matches_type(VectorStoreFile, file, path=["response"]) @parametrize async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: - response = await async_client.beta.assistants.files.with_raw_response.retrieve( - "string", - assistant_id="string", + response = await async_client.beta.vector_stores.files.with_raw_response.retrieve( + "file-abc123", + vector_store_id="vs_abc123", ) assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() - assert_matches_type(AssistantFile, file, path=["response"]) + assert_matches_type(VectorStoreFile, file, path=["response"]) @parametrize async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: - async with async_client.beta.assistants.files.with_streaming_response.retrieve( - "string", - assistant_id="string", + async with async_client.beta.vector_stores.files.with_streaming_response.retrieve( + "file-abc123", + vector_store_id="vs_abc123", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = await response.parse() - assert_matches_type(AssistantFile, file, path=["response"]) + assert_matches_type(VectorStoreFile, file, path=["response"]) assert cast(Any, response.is_closed) is True @parametrize async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: - with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): - await async_client.beta.assistants.files.with_raw_response.retrieve( - "string", - assistant_id="", + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + await async_client.beta.vector_stores.files.with_raw_response.retrieve( + "file-abc123", + vector_store_id="", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): - await async_client.beta.assistants.files.with_raw_response.retrieve( + await async_client.beta.vector_stores.files.with_raw_response.retrieve( "", - assistant_id="string", + vector_store_id="vs_abc123", ) @parametrize async def test_method_list(self, async_client: AsyncOpenAI) -> None: - file = await async_client.beta.assistants.files.list( + file = await async_client.beta.vector_stores.files.list( "string", ) - assert_matches_type(AsyncCursorPage[AssistantFile], file, path=["response"]) + assert_matches_type(AsyncCursorPage[VectorStoreFile], file, path=["response"]) @parametrize async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: - file = await async_client.beta.assistants.files.list( + file = await async_client.beta.vector_stores.files.list( "string", after="string", before="string", + filter="in_progress", limit=0, order="asc", ) - assert_matches_type(AsyncCursorPage[AssistantFile], file, path=["response"]) + assert_matches_type(AsyncCursorPage[VectorStoreFile], file, path=["response"]) @parametrize async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: - response = await async_client.beta.assistants.files.with_raw_response.list( + response = await async_client.beta.vector_stores.files.with_raw_response.list( "string", ) assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() - assert_matches_type(AsyncCursorPage[AssistantFile], file, path=["response"]) + assert_matches_type(AsyncCursorPage[VectorStoreFile], file, path=["response"]) @parametrize async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: - async with async_client.beta.assistants.files.with_streaming_response.list( + async with async_client.beta.vector_stores.files.with_streaming_response.list( "string", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = await response.parse() - assert_matches_type(AsyncCursorPage[AssistantFile], file, path=["response"]) + assert_matches_type(AsyncCursorPage[VectorStoreFile], file, path=["response"]) assert cast(Any, response.is_closed) is True @parametrize async def test_path_params_list(self, async_client: AsyncOpenAI) -> None: - with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): - await async_client.beta.assistants.files.with_raw_response.list( + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + await async_client.beta.vector_stores.files.with_raw_response.list( "", ) @parametrize async def test_method_delete(self, async_client: AsyncOpenAI) -> None: - file = await async_client.beta.assistants.files.delete( + file = await async_client.beta.vector_stores.files.delete( "string", - assistant_id="string", + vector_store_id="string", ) - assert_matches_type(FileDeleteResponse, file, path=["response"]) + assert_matches_type(VectorStoreFileDeleted, file, path=["response"]) @parametrize async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None: - response = await async_client.beta.assistants.files.with_raw_response.delete( + response = await async_client.beta.vector_stores.files.with_raw_response.delete( "string", - assistant_id="string", + vector_store_id="string", ) assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() - assert_matches_type(FileDeleteResponse, file, path=["response"]) + assert_matches_type(VectorStoreFileDeleted, file, path=["response"]) @parametrize async def test_streaming_response_delete(self, async_client: AsyncOpenAI) -> None: - async with async_client.beta.assistants.files.with_streaming_response.delete( + async with async_client.beta.vector_stores.files.with_streaming_response.delete( "string", - assistant_id="string", + vector_store_id="string", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = await response.parse() - assert_matches_type(FileDeleteResponse, file, path=["response"]) + assert_matches_type(VectorStoreFileDeleted, file, path=["response"]) assert cast(Any, response.is_closed) is True @parametrize async def test_path_params_delete(self, async_client: AsyncOpenAI) -> None: - with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): - await async_client.beta.assistants.files.with_raw_response.delete( + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + await async_client.beta.vector_stores.files.with_raw_response.delete( "string", - assistant_id="", + vector_store_id="", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): - await async_client.beta.assistants.files.with_raw_response.delete( + await async_client.beta.vector_stores.files.with_raw_response.delete( "", - assistant_id="string", + vector_store_id="string", ) From ba3beaf3134ca390f1d9f6633b75f43ea6f4680b Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 17 Apr 2024 12:35:51 -0400 Subject: [PATCH 301/816] release: 1.21.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 69eb19a7b0..ba231b0760 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.20.0" + ".": "1.21.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index a39d5faa30..4a3607f6a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.21.0 (2024-04-17) + +Full Changelog: [v1.20.0...v1.21.0](https://github.com/openai/openai-python/compare/v1.20.0...v1.21.0) + +### Features + +* **api:** add vector stores ([#1325](https://github.com/openai/openai-python/issues/1325)) ([038a3c5](https://github.com/openai/openai-python/commit/038a3c50db7b6a88f54ff1cd1ff6cbaef2caf87f)) + ## 1.20.0 (2024-04-16) Full Changelog: [v1.19.0...v1.20.0](https://github.com/openai/openai-python/compare/v1.19.0...v1.20.0) diff --git a/pyproject.toml b/pyproject.toml index 6c3ae2b592..978e82ae86 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.20.0" +version = "1.21.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 32723952ed..6f0fc92f2e 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.20.0" # x-release-please-version +__version__ = "1.21.0" # x-release-please-version From bb95fe35ad4b480ebce57aa5b48df620df8d761b Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 17 Apr 2024 15:33:37 -0400 Subject: [PATCH 302/816] release: 1.21.1 (#1328) * chore(api): docs and response_format response property (#1327) * release: 1.21.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- src/openai/resources/beta/assistants.py | 8 +- .../resources/beta/threads/runs/runs.py | 78 +++++++++++++------ src/openai/resources/beta/threads/threads.py | 54 ++++++++++--- src/openai/types/beta/assistant.py | 36 +++++++++ .../types/beta/assistant_create_params.py | 2 +- .../types/beta/assistant_update_params.py | 2 +- .../beta/thread_create_and_run_params.py | 10 ++- src/openai/types/beta/threads/run.py | 8 +- .../types/beta/threads/run_create_params.py | 14 +++- 13 files changed, 173 insertions(+), 53 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index ba231b0760..9e1cdeda32 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.21.0" + ".": "1.21.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a3607f6a2..20e8976936 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.21.1 (2024-04-17) + +Full Changelog: [v1.21.0...v1.21.1](https://github.com/openai/openai-python/compare/v1.21.0...v1.21.1) + +### Chores + +* **api:** docs and response_format response property ([#1327](https://github.com/openai/openai-python/issues/1327)) ([7a6d142](https://github.com/openai/openai-python/commit/7a6d142f013994c4eb9a4f55888464c885f8baf0)) + ## 1.21.0 (2024-04-17) Full Changelog: [v1.20.0...v1.21.0](https://github.com/openai/openai-python/compare/v1.20.0...v1.21.0) diff --git a/pyproject.toml b/pyproject.toml index 978e82ae86..0ab25048b1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.21.0" +version = "1.21.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 6f0fc92f2e..4bb6604548 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.21.0" # x-release-please-version +__version__ = "1.21.1" # x-release-please-version diff --git a/src/openai/resources/beta/assistants.py b/src/openai/resources/beta/assistants.py index 8695a949ca..c0338164e2 100644 --- a/src/openai/resources/beta/assistants.py +++ b/src/openai/resources/beta/assistants.py @@ -109,7 +109,7 @@ def create( response_format: Specifies the format that the model must output. Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -253,7 +253,7 @@ def update( response_format: Specifies the format that the model must output. Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -494,7 +494,7 @@ async def create( response_format: Specifies the format that the model must output. Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -638,7 +638,7 @@ async def update( response_format: Specifies the format that the model must output. Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 7aab17a30d..e2488316b5 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -145,13 +145,13 @@ def create( max_completion_tokens: The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of - completion tokens specified, the run will end with status `complete`. See + completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of - prompt tokens specified, the run will end with status `complete`. See + prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful @@ -166,7 +166,7 @@ def create( response_format: Specifies the format that the model must output. Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -190,7 +190,7 @@ def create( tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. @@ -201,6 +201,11 @@ def create( model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. + We generally recommend altering this or temperature but not both. + + truncation_strategy: Controls for how a thread will be truncated prior to the run. Use this to + control the intial context window of the run. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -287,13 +292,13 @@ def create( max_completion_tokens: The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of - completion tokens specified, the run will end with status `complete`. See + completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of - prompt tokens specified, the run will end with status `complete`. See + prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful @@ -308,7 +313,7 @@ def create( response_format: Specifies the format that the model must output. Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -328,7 +333,7 @@ def create( tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. @@ -339,6 +344,11 @@ def create( model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. + We generally recommend altering this or temperature but not both. + + truncation_strategy: Controls for how a thread will be truncated prior to the run. Use this to + control the intial context window of the run. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -425,13 +435,13 @@ def create( max_completion_tokens: The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of - completion tokens specified, the run will end with status `complete`. See + completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of - prompt tokens specified, the run will end with status `complete`. See + prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful @@ -446,7 +456,7 @@ def create( response_format: Specifies the format that the model must output. Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -466,7 +476,7 @@ def create( tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. @@ -477,6 +487,11 @@ def create( model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. + We generally recommend altering this or temperature but not both. + + truncation_strategy: Controls for how a thread will be truncated prior to the run. Use this to + control the intial context window of the run. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -1659,13 +1674,13 @@ async def create( max_completion_tokens: The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of - completion tokens specified, the run will end with status `complete`. See + completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of - prompt tokens specified, the run will end with status `complete`. See + prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful @@ -1680,7 +1695,7 @@ async def create( response_format: Specifies the format that the model must output. Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -1704,7 +1719,7 @@ async def create( tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. @@ -1715,6 +1730,11 @@ async def create( model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. + We generally recommend altering this or temperature but not both. + + truncation_strategy: Controls for how a thread will be truncated prior to the run. Use this to + control the intial context window of the run. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -1801,13 +1821,13 @@ async def create( max_completion_tokens: The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of - completion tokens specified, the run will end with status `complete`. See + completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of - prompt tokens specified, the run will end with status `complete`. See + prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful @@ -1822,7 +1842,7 @@ async def create( response_format: Specifies the format that the model must output. Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -1842,7 +1862,7 @@ async def create( tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. @@ -1853,6 +1873,11 @@ async def create( model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. + We generally recommend altering this or temperature but not both. + + truncation_strategy: Controls for how a thread will be truncated prior to the run. Use this to + control the intial context window of the run. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -1939,13 +1964,13 @@ async def create( max_completion_tokens: The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of - completion tokens specified, the run will end with status `complete`. See + completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of - prompt tokens specified, the run will end with status `complete`. See + prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful @@ -1960,7 +1985,7 @@ async def create( response_format: Specifies the format that the model must output. Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -1980,7 +2005,7 @@ async def create( tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. @@ -1991,6 +2016,11 @@ async def create( model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. + We generally recommend altering this or temperature but not both. + + truncation_strategy: Controls for how a thread will be truncated prior to the run. Use this to + control the intial context window of the run. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 678c621a10..6e54faf469 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -340,7 +340,7 @@ def create_and_run( response_format: Specifies the format that the model must output. Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -366,7 +366,7 @@ def create_and_run( tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. @@ -382,6 +382,11 @@ def create_and_run( model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. + We generally recommend altering this or temperature but not both. + + truncation_strategy: Controls for how a thread will be truncated prior to the run. Use this to + control the intial context window of the run. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -481,7 +486,7 @@ def create_and_run( response_format: Specifies the format that the model must output. Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -503,7 +508,7 @@ def create_and_run( tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. @@ -519,6 +524,11 @@ def create_and_run( model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. + We generally recommend altering this or temperature but not both. + + truncation_strategy: Controls for how a thread will be truncated prior to the run. Use this to + control the intial context window of the run. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -618,7 +628,7 @@ def create_and_run( response_format: Specifies the format that the model must output. Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -640,7 +650,7 @@ def create_and_run( tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. @@ -656,6 +666,11 @@ def create_and_run( model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. + We generally recommend altering this or temperature but not both. + + truncation_strategy: Controls for how a thread will be truncated prior to the run. Use this to + control the intial context window of the run. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -1296,7 +1311,7 @@ async def create_and_run( response_format: Specifies the format that the model must output. Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -1322,7 +1337,7 @@ async def create_and_run( tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. @@ -1338,6 +1353,11 @@ async def create_and_run( model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. + We generally recommend altering this or temperature but not both. + + truncation_strategy: Controls for how a thread will be truncated prior to the run. Use this to + control the intial context window of the run. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -1437,7 +1457,7 @@ async def create_and_run( response_format: Specifies the format that the model must output. Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -1459,7 +1479,7 @@ async def create_and_run( tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. @@ -1475,6 +1495,11 @@ async def create_and_run( model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. + We generally recommend altering this or temperature but not both. + + truncation_strategy: Controls for how a thread will be truncated prior to the run. Use this to + control the intial context window of the run. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -1574,7 +1599,7 @@ async def create_and_run( response_format: Specifies the format that the model must output. Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -1596,7 +1621,7 @@ async def create_and_run( tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. @@ -1612,6 +1637,11 @@ async def create_and_run( model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. + We generally recommend altering this or temperature but not both. + + truncation_strategy: Controls for how a thread will be truncated prior to the run. Use this to + control the intial context window of the run. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request diff --git a/src/openai/types/beta/assistant.py b/src/openai/types/beta/assistant.py index fa09efb0cc..0b997e0b0e 100644 --- a/src/openai/types/beta/assistant.py +++ b/src/openai/types/beta/assistant.py @@ -5,6 +5,7 @@ from ..._models import BaseModel from .assistant_tool import AssistantTool +from .assistant_response_format_option import AssistantResponseFormatOption __all__ = ["Assistant", "ToolResources", "ToolResourcesCodeInterpreter", "ToolResourcesFileSearch"] @@ -81,6 +82,32 @@ class Assistant(BaseModel): `code_interpreter`, `file_search`, or `function`. """ + response_format: Optional[AssistantResponseFormatOption] = None + """Specifies the format that the model must output. + + Compatible with + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + message the model generates is valid JSON. + + **Important:** when using JSON mode, you **must** also instruct the model to + produce JSON yourself via a system or user message. Without this, the model may + generate an unending stream of whitespace until the generation reaches the token + limit, resulting in a long-running and seemingly "stuck" request. Also note that + the message content may be partially cut off if `finish_reason="length"`, which + indicates the generation exceeded `max_tokens` or the conversation exceeded the + max context length. + """ + + temperature: Optional[float] = None + """What sampling temperature to use, between 0 and 2. + + Higher values like 0.8 will make the output more random, while lower values like + 0.2 will make it more focused and deterministic. + """ + tool_resources: Optional[ToolResources] = None """A set of resources that are used by the assistant's tools. @@ -88,3 +115,12 @@ class Assistant(BaseModel): `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs. """ + + top_p: Optional[float] = None + """ + An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or temperature but not both. + """ diff --git a/src/openai/types/beta/assistant_create_params.py b/src/openai/types/beta/assistant_create_params.py index 925b85050f..e9ff66dfc3 100644 --- a/src/openai/types/beta/assistant_create_params.py +++ b/src/openai/types/beta/assistant_create_params.py @@ -77,7 +77,7 @@ class AssistantCreateParams(TypedDict, total=False): Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. diff --git a/src/openai/types/beta/assistant_update_params.py b/src/openai/types/beta/assistant_update_params.py index 1354b078a8..55c846ce4e 100644 --- a/src/openai/types/beta/assistant_update_params.py +++ b/src/openai/types/beta/assistant_update_params.py @@ -47,7 +47,7 @@ class AssistantUpdateParams(TypedDict, total=False): Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index d7d5a758e8..0c102db705 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -106,7 +106,7 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -135,7 +135,7 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. """ @@ -159,9 +159,15 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or temperature but not both. """ truncation_strategy: Optional[TruncationStrategy] + """Controls for how a thread will be truncated prior to the run. + + Use this to control the intial context window of the run. + """ class ThreadMessageAttachment(TypedDict, total=False): diff --git a/src/openai/types/beta/threads/run.py b/src/openai/types/beta/threads/run.py index 8f427ce6e8..4fd5103348 100644 --- a/src/openai/types/beta/threads/run.py +++ b/src/openai/types/beta/threads/run.py @@ -162,7 +162,7 @@ class Run(BaseModel): Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -197,7 +197,7 @@ class Run(BaseModel): Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. """ @@ -210,6 +210,10 @@ class Run(BaseModel): """ truncation_strategy: Optional[TruncationStrategy] = None + """Controls for how a thread will be truncated prior to the run. + + Use this to control the intial context window of the run. + """ usage: Optional[Usage] = None """Usage statistics related to the run. diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index fd0b4e7920..c1bb8ba62a 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -49,7 +49,7 @@ class RunCreateParamsBase(TypedDict, total=False): The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of - completion tokens specified, the run will end with status `complete`. See + completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. """ @@ -58,7 +58,7 @@ class RunCreateParamsBase(TypedDict, total=False): The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of - prompt tokens specified, the run will end with status `complete`. See + prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. """ @@ -106,7 +106,7 @@ class RunCreateParamsBase(TypedDict, total=False): Compatible with [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -132,7 +132,7 @@ class RunCreateParamsBase(TypedDict, total=False): Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "TOOL_TYPE"}` or + Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. """ @@ -148,9 +148,15 @@ class RunCreateParamsBase(TypedDict, total=False): An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or temperature but not both. """ truncation_strategy: Optional[TruncationStrategy] + """Controls for how a thread will be truncated prior to the run. + + Use this to control the intial context window of the run. + """ class AdditionalMessageAttachment(TypedDict, total=False): From b8f7ee516721cd060c6c19df942e10f2d4d3a580 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 17 Apr 2024 16:43:20 -0400 Subject: [PATCH 303/816] chore(internal): add lru_cache helper function (#1329) --- src/openai/_utils/__init__.py | 1 + src/openai/_utils/_utils.py | 8 ++++++++ 2 files changed, 9 insertions(+) diff --git a/src/openai/_utils/__init__.py b/src/openai/_utils/__init__.py index 5697894192..31b5b22799 100644 --- a/src/openai/_utils/__init__.py +++ b/src/openai/_utils/__init__.py @@ -6,6 +6,7 @@ is_list as is_list, is_given as is_given, is_tuple as is_tuple, + lru_cache as lru_cache, is_mapping as is_mapping, is_tuple_t as is_tuple_t, parse_date as parse_date, diff --git a/src/openai/_utils/_utils.py b/src/openai/_utils/_utils.py index 93c95517a9..5123a230f1 100644 --- a/src/openai/_utils/_utils.py +++ b/src/openai/_utils/_utils.py @@ -389,3 +389,11 @@ def get_async_library() -> str: return sniffio.current_async_library() except Exception: return "false" + + +def lru_cache(*, maxsize: int | None = 128) -> Callable[[CallableT], CallableT]: + """A version of functools.lru_cache that retains the type signature + for the wrapped function arguments. + """ + wrapper = functools.lru_cache(maxsize=maxsize) + return cast(Any, wrapper) # type: ignore[no-any-return] From a853ee20cf3ae3733407d2156b6107fd14a63d00 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 17 Apr 2024 16:43:46 -0400 Subject: [PATCH 304/816] release: 1.21.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 9e1cdeda32..e5c9603757 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.21.1" + ".": "1.21.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 20e8976936..889e26f7d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.21.2 (2024-04-17) + +Full Changelog: [v1.21.1...v1.21.2](https://github.com/openai/openai-python/compare/v1.21.1...v1.21.2) + +### Chores + +* **internal:** add lru_cache helper function ([#1329](https://github.com/openai/openai-python/issues/1329)) ([cbeebfc](https://github.com/openai/openai-python/commit/cbeebfcca8bf1a3feb4462a79e10099bda5bed84)) + ## 1.21.1 (2024-04-17) Full Changelog: [v1.21.0...v1.21.1](https://github.com/openai/openai-python/compare/v1.21.0...v1.21.1) diff --git a/pyproject.toml b/pyproject.toml index 0ab25048b1..b593179128 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.21.1" +version = "1.21.2" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 4bb6604548..df70bd1a2c 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.21.1" # x-release-please-version +__version__ = "1.21.2" # x-release-please-version From 674c6eeb216e4544a940f94b362a926e3a9981cb Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 17 Apr 2024 18:47:58 -0400 Subject: [PATCH 305/816] chore(internal): ban usage of lru_cache (#1331) --- pyproject.toml | 7 ++++++- src/openai/_base_client.py | 3 +-- src/openai/_models.py | 2 +- src/openai/_utils/_utils.py | 4 +++- 4 files changed, 11 insertions(+), 5 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index b593179128..dd6d2f10aa 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -167,7 +167,9 @@ select = [ "T201", "T203", # misuse of typing.TYPE_CHECKING - "TCH004" + "TCH004", + # import rules + "TID251", ] ignore = [ # mutable defaults @@ -183,6 +185,9 @@ ignore-init-module-imports = true [tool.ruff.format] docstring-code-format = true +[tool.ruff.lint.flake8-tidy-imports.banned-api] +"functools.lru_cache".msg = "This function does not retain type information for the wrapped function's arguments; The `lru_cache` function from `_utils` should be used instead" + [tool.ruff.lint.isort] length-sort = true length-sort-straight = true diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 0bb284a211..cd8361607e 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -29,7 +29,6 @@ cast, overload, ) -from functools import lru_cache from typing_extensions import Literal, override, get_origin import anyio @@ -61,7 +60,7 @@ RequestOptions, ModelBuilderProtocol, ) -from ._utils import is_dict, is_list, is_given, is_mapping +from ._utils import is_dict, is_list, is_given, lru_cache, is_mapping from ._compat import model_copy, model_dump from ._models import GenericModel, FinalRequestOptions, validate_type, construct_type from ._response import ( diff --git a/src/openai/_models.py b/src/openai/_models.py index 80ab51256f..ff93fbd846 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -4,7 +4,6 @@ import inspect from typing import TYPE_CHECKING, Any, Type, Union, Generic, TypeVar, Callable, cast from datetime import date, datetime -from functools import lru_cache from typing_extensions import ( Unpack, Literal, @@ -37,6 +36,7 @@ PropertyInfo, is_list, is_given, + lru_cache, is_mapping, parse_date, coerce_boolean, diff --git a/src/openai/_utils/_utils.py b/src/openai/_utils/_utils.py index 5123a230f1..fd3a8a4d15 100644 --- a/src/openai/_utils/_utils.py +++ b/src/openai/_utils/_utils.py @@ -395,5 +395,7 @@ def lru_cache(*, maxsize: int | None = 128) -> Callable[[CallableT], CallableT]: """A version of functools.lru_cache that retains the type signature for the wrapped function arguments. """ - wrapper = functools.lru_cache(maxsize=maxsize) + wrapper = functools.lru_cache( # noqa: TID251 + maxsize=maxsize, + ) return cast(Any, wrapper) # type: ignore[no-any-return] From 7a7e4bcca772620bf6d39c4e20c253ad5af02c48 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 18 Apr 2024 10:40:51 -0400 Subject: [PATCH 306/816] chore(internal): bump pyright to 1.1.359 (#1337) --- pyproject.toml | 2 +- requirements-dev.lock | 8 ++++---- src/openai/_models.py | 2 +- src/openai/_utils/_utils.py | 2 ++ 4 files changed, 8 insertions(+), 6 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index dd6d2f10aa..e0ab23a049 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -50,7 +50,7 @@ openai = "openai.cli:main" managed = true # version pins are in requirements-dev.lock dev-dependencies = [ - "pyright", + "pyright>=1.1.359", "mypy", "respx", "pytest", diff --git a/requirements-dev.lock b/requirements-dev.lock index 657e6cb810..8cfefdd93b 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -24,7 +24,7 @@ attrs==23.1.0 azure-core==1.30.1 # via azure-identity azure-identity==1.15.0 -black==24.3.0 +black==24.4.0 # via inline-snapshot certifi==2023.7.22 # via httpcore @@ -109,7 +109,7 @@ portalocker==2.8.2 # via msal-extensions py==1.11.0 # via pytest -pycparser==2.21 +pycparser==2.22 # via cffi pydantic==2.4.2 # via openai @@ -117,7 +117,7 @@ pydantic-core==2.10.1 # via pydantic pyjwt==2.8.0 # via msal -pyright==1.1.353 +pyright==1.1.359 pytest==7.1.1 # via pytest-asyncio pytest-asyncio==0.21.1 @@ -156,7 +156,7 @@ tqdm==4.66.1 # via openai trio==0.22.2 types-pyaudio==0.2.16.20240106 -types-pytz==2024.1.0.20240203 +types-pytz==2024.1.0.20240417 # via pandas-stubs types-toml==0.10.8.20240310 # via inline-snapshot diff --git a/src/openai/_models.py b/src/openai/_models.py index ff93fbd846..ff3f54e2cd 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -378,7 +378,7 @@ def construct_type(*, value: object, type_: object) -> object: # unwrap `Annotated[T, ...]` -> `T` if is_annotated_type(type_): - meta = get_args(type_)[1:] + meta: tuple[Any, ...] = get_args(type_)[1:] type_ = extract_type_arg(type_, 0) else: meta = tuple() diff --git a/src/openai/_utils/_utils.py b/src/openai/_utils/_utils.py index fd3a8a4d15..17904ce60d 100644 --- a/src/openai/_utils/_utils.py +++ b/src/openai/_utils/_utils.py @@ -265,6 +265,8 @@ def wrapper(*args: object, **kwargs: object) -> object: ) msg = f"Missing required arguments; Expected either {variations} arguments to be given" else: + assert len(variants) > 0 + # TODO: this error message is not deterministic missing = list(set(variants[0]) - given_params) if len(missing) > 1: From 2edeeb1faee1b4ca2b49cdfcb0e493d59d422244 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 18 Apr 2024 10:49:14 -0400 Subject: [PATCH 307/816] feat(api): batch list endpoint (#1338) --- .stats.yml | 2 +- api.md | 1 + src/openai/resources/batches.py | 120 +++++++++++++++++++++++++- src/openai/types/__init__.py | 1 + src/openai/types/batch_list_params.py | 24 ++++++ tests/api_resources/test_batches.py | 67 ++++++++++++++ 6 files changed, 213 insertions(+), 2 deletions(-) create mode 100644 src/openai/types/batch_list_params.py diff --git a/.stats.yml b/.stats.yml index 2814bb7778..c9a9bfa4a8 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1 +1 @@ -configured_endpoints: 62 +configured_endpoints: 63 diff --git a/api.md b/api.md index 962ed7b7c5..30247e8f7f 100644 --- a/api.md +++ b/api.md @@ -405,4 +405,5 @@ Methods: - client.batches.create(\*\*params) -> Batch - client.batches.retrieve(batch_id) -> Batch +- client.batches.list(\*\*params) -> SyncCursorPage[Batch] - client.batches.cancel(batch_id) -> Batch diff --git a/src/openai/resources/batches.py b/src/openai/resources/batches.py index 0921ccb194..dc311b2e12 100644 --- a/src/openai/resources/batches.py +++ b/src/openai/resources/batches.py @@ -8,7 +8,7 @@ import httpx from .. import _legacy_response -from ..types import Batch, batch_create_params +from ..types import Batch, batch_list_params, batch_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import ( maybe_transform, @@ -17,7 +17,9 @@ from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ..pagination import SyncCursorPage, AsyncCursorPage from .._base_client import ( + AsyncPaginator, make_request_options, ) @@ -125,6 +127,58 @@ def retrieve( cast_to=Batch, ) + def list( + self, + *, + after: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> SyncCursorPage[Batch]: + """List your organization's batches. + + Args: + after: A cursor for use in pagination. + + `after` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include after=obj_foo in order to + fetch the next page of the list. + + limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the default is 20. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get_api_list( + "/batches", + page=SyncCursorPage[Batch], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "limit": limit, + }, + batch_list_params.BatchListParams, + ), + ), + model=Batch, + ) + def cancel( self, batch_id: str, @@ -260,6 +314,58 @@ async def retrieve( cast_to=Batch, ) + def list( + self, + *, + after: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncPaginator[Batch, AsyncCursorPage[Batch]]: + """List your organization's batches. + + Args: + after: A cursor for use in pagination. + + `after` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include after=obj_foo in order to + fetch the next page of the list. + + limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the default is 20. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get_api_list( + "/batches", + page=AsyncCursorPage[Batch], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "limit": limit, + }, + batch_list_params.BatchListParams, + ), + ), + model=Batch, + ) + async def cancel( self, batch_id: str, @@ -304,6 +410,9 @@ def __init__(self, batches: Batches) -> None: self.retrieve = _legacy_response.to_raw_response_wrapper( batches.retrieve, ) + self.list = _legacy_response.to_raw_response_wrapper( + batches.list, + ) self.cancel = _legacy_response.to_raw_response_wrapper( batches.cancel, ) @@ -319,6 +428,9 @@ def __init__(self, batches: AsyncBatches) -> None: self.retrieve = _legacy_response.async_to_raw_response_wrapper( batches.retrieve, ) + self.list = _legacy_response.async_to_raw_response_wrapper( + batches.list, + ) self.cancel = _legacy_response.async_to_raw_response_wrapper( batches.cancel, ) @@ -334,6 +446,9 @@ def __init__(self, batches: Batches) -> None: self.retrieve = to_streamed_response_wrapper( batches.retrieve, ) + self.list = to_streamed_response_wrapper( + batches.list, + ) self.cancel = to_streamed_response_wrapper( batches.cancel, ) @@ -349,6 +464,9 @@ def __init__(self, batches: AsyncBatches) -> None: self.retrieve = async_to_streamed_response_wrapper( batches.retrieve, ) + self.list = async_to_streamed_response_wrapper( + batches.list, + ) self.cancel = async_to_streamed_response_wrapper( batches.cancel, ) diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index b6f35cfecf..7873efb34f 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -22,6 +22,7 @@ from .images_response import ImagesResponse as ImagesResponse from .completion_usage import CompletionUsage as CompletionUsage from .file_list_params import FileListParams as FileListParams +from .batch_list_params import BatchListParams as BatchListParams from .completion_choice import CompletionChoice as CompletionChoice from .image_edit_params import ImageEditParams as ImageEditParams from .file_create_params import FileCreateParams as FileCreateParams diff --git a/src/openai/types/batch_list_params.py b/src/openai/types/batch_list_params.py new file mode 100644 index 0000000000..ef5e966b79 --- /dev/null +++ b/src/openai/types/batch_list_params.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["BatchListParams"] + + +class BatchListParams(TypedDict, total=False): + after: str + """A cursor for use in pagination. + + `after` is an object ID that defines your place in the list. For instance, if + you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include after=obj_foo in order to fetch the next page of the + list. + """ + + limit: int + """A limit on the number of objects to be returned. + + Limit can range between 1 and 100, and the default is 20. + """ diff --git a/tests/api_resources/test_batches.py b/tests/api_resources/test_batches.py index aafeff8116..6f9b598e61 100644 --- a/tests/api_resources/test_batches.py +++ b/tests/api_resources/test_batches.py @@ -10,6 +10,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.types import Batch +from openai.pagination import SyncCursorPage, AsyncCursorPage base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") @@ -102,6 +103,39 @@ def test_path_params_retrieve(self, client: OpenAI) -> None: "", ) + @parametrize + def test_method_list(self, client: OpenAI) -> None: + batch = client.batches.list() + assert_matches_type(SyncCursorPage[Batch], batch, path=["response"]) + + @parametrize + def test_method_list_with_all_params(self, client: OpenAI) -> None: + batch = client.batches.list( + after="string", + limit=0, + ) + assert_matches_type(SyncCursorPage[Batch], batch, path=["response"]) + + @parametrize + def test_raw_response_list(self, client: OpenAI) -> None: + response = client.batches.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + batch = response.parse() + assert_matches_type(SyncCursorPage[Batch], batch, path=["response"]) + + @parametrize + def test_streaming_response_list(self, client: OpenAI) -> None: + with client.batches.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + batch = response.parse() + assert_matches_type(SyncCursorPage[Batch], batch, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize def test_method_cancel(self, client: OpenAI) -> None: batch = client.batches.cancel( @@ -229,6 +263,39 @@ async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: "", ) + @parametrize + async def test_method_list(self, async_client: AsyncOpenAI) -> None: + batch = await async_client.batches.list() + assert_matches_type(AsyncCursorPage[Batch], batch, path=["response"]) + + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: + batch = await async_client.batches.list( + after="string", + limit=0, + ) + assert_matches_type(AsyncCursorPage[Batch], batch, path=["response"]) + + @parametrize + async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: + response = await async_client.batches.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + batch = response.parse() + assert_matches_type(AsyncCursorPage[Batch], batch, path=["response"]) + + @parametrize + async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: + async with async_client.batches.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + batch = await response.parse() + assert_matches_type(AsyncCursorPage[Batch], batch, path=["response"]) + + assert cast(Any, response.is_closed) is True + @parametrize async def test_method_cancel(self, async_client: AsyncOpenAI) -> None: batch = await async_client.batches.cancel( From 2390c320f96f6f1f5f0abb73a3d6590a55629d28 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 18 Apr 2024 10:49:42 -0400 Subject: [PATCH 308/816] release: 1.22.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 14 ++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 17 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index e5c9603757..397c4203e3 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.21.2" + ".": "1.22.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 889e26f7d3..ee52ac72e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,19 @@ # Changelog +## 1.22.0 (2024-04-18) + +Full Changelog: [v1.21.2...v1.22.0](https://github.com/openai/openai-python/compare/v1.21.2...v1.22.0) + +### Features + +* **api:** batch list endpoint ([#1338](https://github.com/openai/openai-python/issues/1338)) ([a776f38](https://github.com/openai/openai-python/commit/a776f387e3159f9a8f4dcaa7d0d3b78c2a884f91)) + + +### Chores + +* **internal:** ban usage of lru_cache ([#1331](https://github.com/openai/openai-python/issues/1331)) ([8f9223b](https://github.com/openai/openai-python/commit/8f9223bfe13200c685fc97c25ada3015a69c6df7)) +* **internal:** bump pyright to 1.1.359 ([#1337](https://github.com/openai/openai-python/issues/1337)) ([feec0dd](https://github.com/openai/openai-python/commit/feec0dd1dd243941a279c3224c5ca1d727d76676)) + ## 1.21.2 (2024-04-17) Full Changelog: [v1.21.1...v1.21.2](https://github.com/openai/openai-python/compare/v1.21.1...v1.21.2) diff --git a/pyproject.toml b/pyproject.toml index e0ab23a049..17f4a86dc9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.21.2" +version = "1.22.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index df70bd1a2c..6e11c61a18 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.21.2" # x-release-please-version +__version__ = "1.22.0" # x-release-please-version From 88323c4e3a47bbca498d3b55bada2b579142b410 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 18 Apr 2024 17:18:27 -0400 Subject: [PATCH 309/816] docs(helpers): fix example snippets (#1339) --- helpers.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/helpers.md b/helpers.md index cf738f3f16..3508b59a33 100644 --- a/helpers.md +++ b/helpers.md @@ -33,11 +33,13 @@ class EventHandler(AssistantEventHandler): def on_text_delta(self, delta: TextDelta, snapshot: Text): print(delta.value, end="", flush=True) + @override def on_tool_call_created(self, tool_call: ToolCall): print(f"\nassistant > {tool_call.type}\n", flush=True) + @override def on_tool_call_delta(self, delta: ToolCallDelta, snapshot: ToolCall): - if delta.type == 'code_interpreter': + if delta.type == "code_interpreter" and delta.code_interpreter: if delta.code_interpreter.input: print(delta.code_interpreter.input, end="", flush=True) if delta.code_interpreter.outputs: @@ -69,7 +71,7 @@ with client.beta.threads.runs.stream( ) as stream: for event in stream: # Print the text from text delta events - if event.type == "thread.message.delta" and event.data.delta.content: + if event.event == "thread.message.delta" and event.data.delta.content: print(event.data.delta.content[0].text) ``` From 0311d6b5f13682163d49c5981abf9305d11f80d6 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 18 Apr 2024 17:28:03 -0400 Subject: [PATCH 310/816] feat(api): add request id property to response classes (#1341) --- examples/demo.py | 15 +++++++++++++++ src/openai/_legacy_response.py | 4 ++++ src/openai/_response.py | 8 ++++++++ 3 files changed, 27 insertions(+) diff --git a/examples/demo.py b/examples/demo.py index 37830e3e97..ac1710f3e0 100755 --- a/examples/demo.py +++ b/examples/demo.py @@ -36,3 +36,18 @@ print(chunk.choices[0].delta.content, end="") print() + +# Response headers: +print("----- custom response headers test -----") +response = client.chat.completions.with_raw_response.create( + model="gpt-4", + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], +) +completion = response.parse() +print(response.request_id) +print(completion.choices[0].message.content) diff --git a/src/openai/_legacy_response.py b/src/openai/_legacy_response.py index 4585cd7423..1de906b167 100644 --- a/src/openai/_legacy_response.py +++ b/src/openai/_legacy_response.py @@ -71,6 +71,10 @@ def __init__( self._options = options self.http_response = raw + @property + def request_id(self) -> str | None: + return self.http_response.headers.get("x-request-id") # type: ignore[no-any-return] + @overload def parse(self, *, to: type[_T]) -> _T: ... diff --git a/src/openai/_response.py b/src/openai/_response.py index 47f484ef7a..4ba2ae681c 100644 --- a/src/openai/_response.py +++ b/src/openai/_response.py @@ -258,6 +258,10 @@ def _parse(self, *, to: type[_T] | None = None) -> R | _T: class APIResponse(BaseAPIResponse[R]): + @property + def request_id(self) -> str | None: + return self.http_response.headers.get("x-request-id") # type: ignore[no-any-return] + @overload def parse(self, *, to: type[_T]) -> _T: ... @@ -362,6 +366,10 @@ def iter_lines(self) -> Iterator[str]: class AsyncAPIResponse(BaseAPIResponse[R]): + @property + def request_id(self) -> str | None: + return self.http_response.headers.get("x-request-id") # type: ignore[no-any-return] + @overload async def parse(self, *, to: type[_T]) -> _T: ... From 9e0ea648e2059bc0e61c26664f0bc7f67fe7726b Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 18 Apr 2024 17:28:29 -0400 Subject: [PATCH 311/816] release: 1.23.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 397c4203e3..cdcf20eb76 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.22.0" + ".": "1.23.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index ee52ac72e0..ef3e8ecada 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.23.0 (2024-04-18) + +Full Changelog: [v1.22.0...v1.23.0](https://github.com/openai/openai-python/compare/v1.22.0...v1.23.0) + +### Features + +* **api:** add request id property to response classes ([#1341](https://github.com/openai/openai-python/issues/1341)) ([444d680](https://github.com/openai/openai-python/commit/444d680cbb3745adbc27788213ae3312567136a8)) + + +### Documentation + +* **helpers:** fix example snippets ([#1339](https://github.com/openai/openai-python/issues/1339)) ([8929088](https://github.com/openai/openai-python/commit/8929088b206a04b4c5b85fb69b0b983fb56f9b03)) + ## 1.22.0 (2024-04-18) Full Changelog: [v1.21.2...v1.22.0](https://github.com/openai/openai-python/compare/v1.21.2...v1.22.0) diff --git a/pyproject.toml b/pyproject.toml index 17f4a86dc9..6c8a890e71 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.22.0" +version = "1.23.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 6e11c61a18..3b31c9d5ea 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.22.0" # x-release-please-version +__version__ = "1.23.0" # x-release-please-version From abc8cd07ef4b4540ad87e65febce2a79871d5487 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 18 Apr 2024 18:33:02 -0400 Subject: [PATCH 312/816] fix(api): correct types for attachments (#1342) --- .../beta/thread_create_and_run_params.py | 4 +- src/openai/types/beta/thread_create_params.py | 4 +- src/openai/types/beta/threads/message.py | 4 +- .../beta/threads/message_create_params.py | 4 +- .../types/beta/threads/run_create_params.py | 4 +- tests/api_resources/beta/test_threads.py | 108 +++++++++--------- .../beta/threads/test_messages.py | 12 +- tests/api_resources/beta/threads/test_runs.py | 72 ++++++------ 8 files changed, 106 insertions(+), 106 deletions(-) diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index 0c102db705..036d8a78da 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -171,11 +171,11 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): class ThreadMessageAttachment(TypedDict, total=False): - add_to: List[Literal["file_search", "code_interpreter"]] - file_id: str """The ID of the file to attach to the message.""" + tools: List[Literal["file_search", "code_interpreter"]] + class ThreadMessage(TypedDict, total=False): content: Required[str] diff --git a/src/openai/types/beta/thread_create_params.py b/src/openai/types/beta/thread_create_params.py index 84a98a74d7..ac85e3c9e1 100644 --- a/src/openai/types/beta/thread_create_params.py +++ b/src/openai/types/beta/thread_create_params.py @@ -41,11 +41,11 @@ class ThreadCreateParams(TypedDict, total=False): class MessageAttachment(TypedDict, total=False): - add_to: List[Literal["file_search", "code_interpreter"]] - file_id: str """The ID of the file to attach to the message.""" + tools: List[Literal["file_search", "code_interpreter"]] + class Message(TypedDict, total=False): content: Required[str] diff --git a/src/openai/types/beta/threads/message.py b/src/openai/types/beta/threads/message.py index 42f0162734..ffc64545db 100644 --- a/src/openai/types/beta/threads/message.py +++ b/src/openai/types/beta/threads/message.py @@ -10,11 +10,11 @@ class Attachment(BaseModel): - add_to: Optional[List[Literal["file_search", "code_interpreter"]]] = None - file_id: Optional[str] = None """The ID of the file to attach to the message.""" + tools: Optional[List[Literal["file_search", "code_interpreter"]]] = None + class IncompleteDetails(BaseModel): reason: Literal["content_filter", "max_tokens", "run_cancelled", "run_expired", "run_failed"] diff --git a/src/openai/types/beta/threads/message_create_params.py b/src/openai/types/beta/threads/message_create_params.py index 1ef1d9ae10..4d47de84f1 100644 --- a/src/openai/types/beta/threads/message_create_params.py +++ b/src/openai/types/beta/threads/message_create_params.py @@ -34,7 +34,7 @@ class MessageCreateParams(TypedDict, total=False): class Attachment(TypedDict, total=False): - add_to: List[Literal["file_search", "code_interpreter"]] - file_id: str """The ID of the file to attach to the message.""" + + tools: List[Literal["file_search", "code_interpreter"]] diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index c1bb8ba62a..0d62b7949f 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -160,11 +160,11 @@ class RunCreateParamsBase(TypedDict, total=False): class AdditionalMessageAttachment(TypedDict, total=False): - add_to: List[Literal["file_search", "code_interpreter"]] - file_id: str """The ID of the file to attach to the message.""" + tools: List[Literal["file_search", "code_interpreter"]] + class AdditionalMessage(TypedDict, total=False): content: Required[str] diff --git a/tests/api_resources/beta/test_threads.py b/tests/api_resources/beta/test_threads.py index 980fd9a75e..9b3de393f0 100644 --- a/tests/api_resources/beta/test_threads.py +++ b/tests/api_resources/beta/test_threads.py @@ -36,15 +36,15 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -55,15 +55,15 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -74,15 +74,15 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -277,15 +277,15 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -296,15 +296,15 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -315,15 +315,15 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -409,15 +409,15 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -428,15 +428,15 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -447,15 +447,15 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -533,15 +533,15 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -552,15 +552,15 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -571,15 +571,15 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -774,15 +774,15 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -793,15 +793,15 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -812,15 +812,15 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -906,15 +906,15 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -925,15 +925,15 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -944,15 +944,15 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, diff --git a/tests/api_resources/beta/threads/test_messages.py b/tests/api_resources/beta/threads/test_messages.py index 5ea5ac3bd5..c6492464da 100644 --- a/tests/api_resources/beta/threads/test_messages.py +++ b/tests/api_resources/beta/threads/test_messages.py @@ -36,15 +36,15 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: attachments=[ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], metadata={}, @@ -265,15 +265,15 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> attachments=[ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], metadata={}, diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index 3d8a6ce058..43065133d6 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -43,15 +43,15 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -62,15 +62,15 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -81,15 +81,15 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -170,15 +170,15 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -189,15 +189,15 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -208,15 +208,15 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -635,15 +635,15 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -654,15 +654,15 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -673,15 +673,15 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -762,15 +762,15 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -781,15 +781,15 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, @@ -800,15 +800,15 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn "attachments": [ { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, { "file_id": "string", - "add_to": ["file_search", "code_interpreter"], + "tools": ["file_search", "code_interpreter"], }, ], "metadata": {}, From 10dde6d20312794818cd51d467d6f45d295e6601 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 18 Apr 2024 18:33:25 -0400 Subject: [PATCH 313/816] release: 1.23.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index cdcf20eb76..276cb37a71 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.23.0" + ".": "1.23.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index ef3e8ecada..3800012663 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.23.1 (2024-04-18) + +Full Changelog: [v1.23.0...v1.23.1](https://github.com/openai/openai-python/compare/v1.23.0...v1.23.1) + +### Bug Fixes + +* **api:** correct types for attachments ([#1342](https://github.com/openai/openai-python/issues/1342)) ([542d30c](https://github.com/openai/openai-python/commit/542d30c6dad4e139bf3eb443936d42b7b42dad54)) + ## 1.23.0 (2024-04-18) Full Changelog: [v1.22.0...v1.23.0](https://github.com/openai/openai-python/compare/v1.22.0...v1.23.0) diff --git a/pyproject.toml b/pyproject.toml index 6c8a890e71..674c120340 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.23.0" +version = "1.23.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 3b31c9d5ea..08c0d250a1 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.23.0" # x-release-please-version +__version__ = "1.23.1" # x-release-please-version From f73996b7239246f9df38613c543b39c5178488f5 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 19 Apr 2024 13:43:01 -0400 Subject: [PATCH 314/816] fix(api): correct types for message attachment tools (#1348) --- .../beta/thread_create_and_run_params.py | 7 +- src/openai/types/beta/thread_create_params.py | 12 +- src/openai/types/beta/threads/message.py | 11 +- .../beta/threads/message_create_params.py | 13 +- .../types/beta/threads/run_create_params.py | 11 +- tests/api_resources/beta/test_threads.py | 324 +++++++++++++++--- .../beta/threads/test_messages.py | 12 +- tests/api_resources/beta/threads/test_runs.py | 216 ++++++++++-- 8 files changed, 499 insertions(+), 107 deletions(-) diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index 036d8a78da..9adb049843 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -16,6 +16,7 @@ "Thread", "ThreadMessage", "ThreadMessageAttachment", + "ThreadMessageAttachmentTool", "ThreadToolResources", "ThreadToolResourcesCodeInterpreter", "ThreadToolResourcesFileSearch", @@ -170,11 +171,15 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): """ +ThreadMessageAttachmentTool = Union[CodeInterpreterToolParam, FileSearchToolParam] + + class ThreadMessageAttachment(TypedDict, total=False): file_id: str """The ID of the file to attach to the message.""" - tools: List[Literal["file_search", "code_interpreter"]] + tools: Iterable[ThreadMessageAttachmentTool] + """The tools to add this file to.""" class ThreadMessage(TypedDict, total=False): diff --git a/src/openai/types/beta/thread_create_params.py b/src/openai/types/beta/thread_create_params.py index ac85e3c9e1..ab2df21ed7 100644 --- a/src/openai/types/beta/thread_create_params.py +++ b/src/openai/types/beta/thread_create_params.py @@ -2,13 +2,17 @@ from __future__ import annotations -from typing import List, Iterable, Optional +from typing import List, Union, Iterable, Optional from typing_extensions import Literal, Required, TypedDict +from .file_search_tool_param import FileSearchToolParam +from .code_interpreter_tool_param import CodeInterpreterToolParam + __all__ = [ "ThreadCreateParams", "Message", "MessageAttachment", + "MessageAttachmentTool", "ToolResources", "ToolResourcesCodeInterpreter", "ToolResourcesFileSearch", @@ -40,11 +44,15 @@ class ThreadCreateParams(TypedDict, total=False): """ +MessageAttachmentTool = Union[CodeInterpreterToolParam, FileSearchToolParam] + + class MessageAttachment(TypedDict, total=False): file_id: str """The ID of the file to attach to the message.""" - tools: List[Literal["file_search", "code_interpreter"]] + tools: Iterable[MessageAttachmentTool] + """The tools to add this file to.""" class Message(TypedDict, total=False): diff --git a/src/openai/types/beta/threads/message.py b/src/openai/types/beta/threads/message.py index ffc64545db..ebaabdb0f5 100644 --- a/src/openai/types/beta/threads/message.py +++ b/src/openai/types/beta/threads/message.py @@ -1,19 +1,24 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing import List, Optional +from typing import List, Union, Optional from typing_extensions import Literal from ...._models import BaseModel from .message_content import MessageContent +from ..file_search_tool import FileSearchTool +from ..code_interpreter_tool import CodeInterpreterTool -__all__ = ["Message", "Attachment", "IncompleteDetails"] +__all__ = ["Message", "Attachment", "AttachmentTool", "IncompleteDetails"] + +AttachmentTool = Union[CodeInterpreterTool, FileSearchTool] class Attachment(BaseModel): file_id: Optional[str] = None """The ID of the file to attach to the message.""" - tools: Optional[List[Literal["file_search", "code_interpreter"]]] = None + tools: Optional[List[AttachmentTool]] = None + """The tools to add this file to.""" class IncompleteDetails(BaseModel): diff --git a/src/openai/types/beta/threads/message_create_params.py b/src/openai/types/beta/threads/message_create_params.py index 4d47de84f1..5cead598f0 100644 --- a/src/openai/types/beta/threads/message_create_params.py +++ b/src/openai/types/beta/threads/message_create_params.py @@ -2,10 +2,13 @@ from __future__ import annotations -from typing import List, Iterable, Optional +from typing import Union, Iterable, Optional from typing_extensions import Literal, Required, TypedDict -__all__ = ["MessageCreateParams", "Attachment"] +from ..file_search_tool_param import FileSearchToolParam +from ..code_interpreter_tool_param import CodeInterpreterToolParam + +__all__ = ["MessageCreateParams", "Attachment", "AttachmentTool"] class MessageCreateParams(TypedDict, total=False): @@ -33,8 +36,12 @@ class MessageCreateParams(TypedDict, total=False): """ +AttachmentTool = Union[CodeInterpreterToolParam, FileSearchToolParam] + + class Attachment(TypedDict, total=False): file_id: str """The ID of the file to attach to the message.""" - tools: List[Literal["file_search", "code_interpreter"]] + tools: Iterable[AttachmentTool] + """The tools to add this file to.""" diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index 0d62b7949f..f4780b7f09 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -2,10 +2,12 @@ from __future__ import annotations -from typing import List, Union, Iterable, Optional +from typing import Union, Iterable, Optional from typing_extensions import Literal, Required, TypedDict from ..assistant_tool_param import AssistantToolParam +from ..file_search_tool_param import FileSearchToolParam +from ..code_interpreter_tool_param import CodeInterpreterToolParam from ..assistant_tool_choice_option_param import AssistantToolChoiceOptionParam from ..assistant_response_format_option_param import AssistantResponseFormatOptionParam @@ -13,6 +15,7 @@ "RunCreateParamsBase", "AdditionalMessage", "AdditionalMessageAttachment", + "AdditionalMessageAttachmentTool", "TruncationStrategy", "RunCreateParamsNonStreaming", "RunCreateParamsStreaming", @@ -159,11 +162,15 @@ class RunCreateParamsBase(TypedDict, total=False): """ +AdditionalMessageAttachmentTool = Union[CodeInterpreterToolParam, FileSearchToolParam] + + class AdditionalMessageAttachment(TypedDict, total=False): file_id: str """The ID of the file to attach to the message.""" - tools: List[Literal["file_search", "code_interpreter"]] + tools: Iterable[AdditionalMessageAttachmentTool] + """The tools to add this file to.""" class AdditionalMessage(TypedDict, total=False): diff --git a/tests/api_resources/beta/test_threads.py b/tests/api_resources/beta/test_threads.py index 9b3de393f0..715e3e8726 100644 --- a/tests/api_resources/beta/test_threads.py +++ b/tests/api_resources/beta/test_threads.py @@ -36,15 +36,27 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -55,15 +67,27 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -74,15 +98,27 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -277,15 +313,27 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -296,15 +344,27 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -315,15 +375,27 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -409,15 +481,27 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -428,15 +512,27 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -447,15 +543,27 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -533,15 +641,27 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -552,15 +672,27 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -571,15 +703,27 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -774,15 +918,27 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -793,15 +949,27 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -812,15 +980,27 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -906,15 +1086,27 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -925,15 +1117,27 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -944,15 +1148,27 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, diff --git a/tests/api_resources/beta/threads/test_messages.py b/tests/api_resources/beta/threads/test_messages.py index c6492464da..26eb09acdd 100644 --- a/tests/api_resources/beta/threads/test_messages.py +++ b/tests/api_resources/beta/threads/test_messages.py @@ -36,15 +36,15 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: attachments=[ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], }, ], metadata={}, @@ -265,15 +265,15 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> attachments=[ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], }, ], metadata={}, diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index 43065133d6..429c9bdeeb 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -43,15 +43,27 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -62,15 +74,27 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -81,15 +105,27 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -170,15 +206,27 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -189,15 +237,27 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -208,15 +268,27 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -635,15 +707,27 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -654,15 +738,27 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -673,15 +769,27 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -762,15 +870,27 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -781,15 +901,27 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, @@ -800,15 +932,27 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn "attachments": [ { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, { "file_id": "string", - "tools": ["file_search", "code_interpreter"], + "tools": [ + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + {"type": "code_interpreter"}, + ], }, ], "metadata": {}, From c117779c3ba1069e34ba2142578b15788d157342 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 19 Apr 2024 13:43:29 -0400 Subject: [PATCH 315/816] release: 1.23.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 276cb37a71..d9381b3d10 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.23.1" + ".": "1.23.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 3800012663..21d72ba863 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.23.2 (2024-04-19) + +Full Changelog: [v1.23.1...v1.23.2](https://github.com/openai/openai-python/compare/v1.23.1...v1.23.2) + +### Bug Fixes + +* **api:** correct types for message attachment tools ([#1348](https://github.com/openai/openai-python/issues/1348)) ([78a6261](https://github.com/openai/openai-python/commit/78a6261eaad7839284903287d4f647d9cb4ced0b)) + ## 1.23.1 (2024-04-18) Full Changelog: [v1.23.0...v1.23.1](https://github.com/openai/openai-python/compare/v1.23.0...v1.23.1) diff --git a/pyproject.toml b/pyproject.toml index 674c120340..350ccec220 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.23.1" +version = "1.23.2" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 08c0d250a1..0ab9ce59a2 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.23.1" # x-release-please-version +__version__ = "1.23.2" # x-release-please-version From e4a9553eaedc4fb0ada3917e867d147d03740f60 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 23 Apr 2024 19:16:49 -0400 Subject: [PATCH 316/816] release: 1.23.3 (#1360) * chore(internal): restructure imports (#1359) * release: 1.23.3 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- src/openai/resources/audio/transcriptions.py | 3 ++- src/openai/resources/audio/translations.py | 3 ++- src/openai/resources/batches.py | 3 ++- src/openai/resources/beta/assistants.py | 8 ++++---- src/openai/resources/beta/threads/messages.py | 3 ++- src/openai/resources/beta/threads/runs/runs.py | 12 +++++------- src/openai/resources/beta/threads/runs/steps.py | 3 ++- src/openai/resources/beta/threads/threads.py | 12 ++++++------ .../resources/beta/vector_stores/file_batches.py | 9 +++------ src/openai/resources/beta/vector_stores/files.py | 4 +++- .../beta/vector_stores/vector_stores.py | 10 +++------- src/openai/resources/chat/completions.py | 16 +++++++--------- src/openai/resources/completions.py | 3 ++- src/openai/resources/embeddings.py | 3 ++- src/openai/resources/files.py | 4 +++- .../resources/fine_tuning/jobs/checkpoints.py | 3 ++- src/openai/resources/fine_tuning/jobs/jobs.py | 10 +++------- src/openai/resources/images.py | 8 ++------ src/openai/resources/models.py | 3 ++- src/openai/resources/moderations.py | 3 ++- src/openai/types/beta/assistant_stream_event.py | 9 ++++++--- src/openai/types/beta/function_tool.py | 2 +- tests/api_resources/audio/test_transcriptions.py | 2 +- tests/api_resources/audio/test_translations.py | 2 +- tests/api_resources/beta/test_assistants.py | 6 ++---- tests/api_resources/beta/test_threads.py | 8 +++----- tests/api_resources/beta/test_vector_stores.py | 6 ++---- .../beta/threads/runs/test_steps.py | 2 +- .../api_resources/beta/threads/test_messages.py | 2 +- tests/api_resources/beta/threads/test_runs.py | 4 +--- .../beta/vector_stores/test_file_batches.py | 6 ++---- .../beta/vector_stores/test_files.py | 6 ++---- tests/api_resources/chat/test_completions.py | 2 +- .../fine_tuning/jobs/test_checkpoints.py | 2 +- tests/api_resources/fine_tuning/test_jobs.py | 6 ++---- tests/api_resources/test_batches.py | 2 +- tests/api_resources/test_completions.py | 2 +- tests/api_resources/test_embeddings.py | 2 +- tests/api_resources/test_files.py | 3 ++- tests/api_resources/test_images.py | 2 +- tests/api_resources/test_models.py | 3 ++- tests/api_resources/test_moderations.py | 2 +- 46 files changed, 106 insertions(+), 112 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index d9381b3d10..75baea2d17 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.23.2" + ".": "1.23.3" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 21d72ba863..eed20091bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.23.3 (2024-04-23) + +Full Changelog: [v1.23.2...v1.23.3](https://github.com/openai/openai-python/compare/v1.23.2...v1.23.3) + +### Chores + +* **internal:** restructure imports ([#1359](https://github.com/openai/openai-python/issues/1359)) ([4e5eb37](https://github.com/openai/openai-python/commit/4e5eb374ea0545a6117db657bb05f6417bc62d18)) + ## 1.23.2 (2024-04-19) Full Changelog: [v1.23.1...v1.23.2](https://github.com/openai/openai-python/compare/v1.23.1...v1.23.2) diff --git a/pyproject.toml b/pyproject.toml index 350ccec220..fbda5414f6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.23.2" +version = "1.23.3" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 0ab9ce59a2..ab45006b24 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.23.2" # x-release-please-version +__version__ = "1.23.3" # x-release-please-version diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index 353f28ab05..995680186b 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -18,10 +18,11 @@ from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper -from ...types.audio import Transcription, transcription_create_params +from ...types.audio import transcription_create_params from ..._base_client import ( make_request_options, ) +from ...types.audio.transcription import Transcription __all__ = ["Transcriptions", "AsyncTranscriptions"] diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index 79020a5ece..d711ee2fbd 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -18,10 +18,11 @@ from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper -from ...types.audio import Translation, translation_create_params +from ...types.audio import translation_create_params from ..._base_client import ( make_request_options, ) +from ...types.audio.translation import Translation __all__ = ["Translations", "AsyncTranslations"] diff --git a/src/openai/resources/batches.py b/src/openai/resources/batches.py index dc311b2e12..9b52958efc 100644 --- a/src/openai/resources/batches.py +++ b/src/openai/resources/batches.py @@ -8,7 +8,7 @@ import httpx from .. import _legacy_response -from ..types import Batch, batch_list_params, batch_create_params +from ..types import batch_list_params, batch_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import ( maybe_transform, @@ -18,6 +18,7 @@ from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ..pagination import SyncCursorPage, AsyncCursorPage +from ..types.batch import Batch from .._base_client import ( AsyncPaginator, make_request_options, diff --git a/src/openai/resources/beta/assistants.py b/src/openai/resources/beta/assistants.py index c0338164e2..923ad95a54 100644 --- a/src/openai/resources/beta/assistants.py +++ b/src/openai/resources/beta/assistants.py @@ -18,10 +18,6 @@ from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ...pagination import SyncCursorPage, AsyncCursorPage from ...types.beta import ( - Assistant, - AssistantDeleted, - AssistantToolParam, - AssistantResponseFormatOptionParam, assistant_list_params, assistant_create_params, assistant_update_params, @@ -30,6 +26,10 @@ AsyncPaginator, make_request_options, ) +from ...types.beta.assistant import Assistant +from ...types.beta.assistant_deleted import AssistantDeleted +from ...types.beta.assistant_tool_param import AssistantToolParam +from ...types.beta.assistant_response_format_option_param import AssistantResponseFormatOptionParam __all__ = ["Assistants", "AsyncAssistants"] diff --git a/src/openai/resources/beta/threads/messages.py b/src/openai/resources/beta/threads/messages.py index 7a24b80dea..a938c5e15d 100644 --- a/src/openai/resources/beta/threads/messages.py +++ b/src/openai/resources/beta/threads/messages.py @@ -21,7 +21,8 @@ AsyncPaginator, make_request_options, ) -from ....types.beta.threads import Message, message_list_params, message_create_params, message_update_params +from ....types.beta.threads import message_list_params, message_create_params, message_update_params +from ....types.beta.threads.message import Message __all__ = ["Messages", "AsyncMessages"] diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index e2488316b5..e572a14a19 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -31,12 +31,6 @@ from ....._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ....._streaming import Stream, AsyncStream from .....pagination import SyncCursorPage, AsyncCursorPage -from .....types.beta import ( - AssistantToolParam, - AssistantStreamEvent, - AssistantToolChoiceOptionParam, - AssistantResponseFormatOptionParam, -) from ....._base_client import ( AsyncPaginator, make_request_options, @@ -50,12 +44,16 @@ AsyncAssistantStreamManager, ) from .....types.beta.threads import ( - Run, run_list_params, run_create_params, run_update_params, run_submit_tool_outputs_params, ) +from .....types.beta.threads.run import Run +from .....types.beta.assistant_tool_param import AssistantToolParam +from .....types.beta.assistant_stream_event import AssistantStreamEvent +from .....types.beta.assistant_tool_choice_option_param import AssistantToolChoiceOptionParam +from .....types.beta.assistant_response_format_option_param import AssistantResponseFormatOptionParam __all__ = ["Runs", "AsyncRuns"] diff --git a/src/openai/resources/beta/threads/runs/steps.py b/src/openai/resources/beta/threads/runs/steps.py index 986ef2997a..512008939c 100644 --- a/src/openai/resources/beta/threads/runs/steps.py +++ b/src/openai/resources/beta/threads/runs/steps.py @@ -17,7 +17,8 @@ AsyncPaginator, make_request_options, ) -from .....types.beta.threads.runs import RunStep, step_list_params +from .....types.beta.threads.runs import step_list_params +from .....types.beta.threads.runs.run_step import RunStep __all__ = ["Steps", "AsyncSteps"] diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 6e54faf469..1c516bcea6 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -37,11 +37,6 @@ from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ...._streaming import Stream, AsyncStream from ....types.beta import ( - Thread, - ThreadDeleted, - AssistantStreamEvent, - AssistantToolChoiceOptionParam, - AssistantResponseFormatOptionParam, thread_create_params, thread_update_params, thread_create_and_run_params, @@ -57,7 +52,12 @@ AsyncAssistantEventHandlerT, AsyncAssistantStreamManager, ) -from ....types.beta.threads import Run +from ....types.beta.thread import Thread +from ....types.beta.threads.run import Run +from ....types.beta.thread_deleted import ThreadDeleted +from ....types.beta.assistant_stream_event import AssistantStreamEvent +from ....types.beta.assistant_tool_choice_option_param import AssistantToolChoiceOptionParam +from ....types.beta.assistant_response_format_option_param import AssistantResponseFormatOptionParam __all__ = ["Threads", "AsyncThreads"] diff --git a/src/openai/resources/beta/vector_stores/file_batches.py b/src/openai/resources/beta/vector_stores/file_batches.py index 55b30b08e3..f1ced51700 100644 --- a/src/openai/resources/beta/vector_stores/file_batches.py +++ b/src/openai/resources/beta/vector_stores/file_batches.py @@ -26,12 +26,9 @@ AsyncPaginator, make_request_options, ) -from ....types.beta.vector_stores import ( - VectorStoreFile, - VectorStoreFileBatch, - file_batch_create_params, - file_batch_list_files_params, -) +from ....types.beta.vector_stores import file_batch_create_params, file_batch_list_files_params +from ....types.beta.vector_stores.vector_store_file import VectorStoreFile +from ....types.beta.vector_stores.vector_store_file_batch import VectorStoreFileBatch __all__ = ["FileBatches", "AsyncFileBatches"] diff --git a/src/openai/resources/beta/vector_stores/files.py b/src/openai/resources/beta/vector_stores/files.py index 6404b9d54c..5c3db27619 100644 --- a/src/openai/resources/beta/vector_stores/files.py +++ b/src/openai/resources/beta/vector_stores/files.py @@ -22,7 +22,9 @@ AsyncPaginator, make_request_options, ) -from ....types.beta.vector_stores import VectorStoreFile, VectorStoreFileDeleted, file_list_params, file_create_params +from ....types.beta.vector_stores import file_list_params, file_create_params +from ....types.beta.vector_stores.vector_store_file import VectorStoreFile +from ....types.beta.vector_stores.vector_store_file_deleted import VectorStoreFileDeleted __all__ = ["Files", "AsyncFiles"] diff --git a/src/openai/resources/beta/vector_stores/vector_stores.py b/src/openai/resources/beta/vector_stores/vector_stores.py index 6e2c9ab70c..8a177c2864 100644 --- a/src/openai/resources/beta/vector_stores/vector_stores.py +++ b/src/openai/resources/beta/vector_stores/vector_stores.py @@ -33,17 +33,13 @@ AsyncFileBatchesWithStreamingResponse, ) from ....pagination import SyncCursorPage, AsyncCursorPage -from ....types.beta import ( - VectorStore, - VectorStoreDeleted, - vector_store_list_params, - vector_store_create_params, - vector_store_update_params, -) +from ....types.beta import vector_store_list_params, vector_store_create_params, vector_store_update_params from ...._base_client import ( AsyncPaginator, make_request_options, ) +from ....types.beta.vector_store import VectorStore +from ....types.beta.vector_store_deleted import VectorStoreDeleted __all__ = ["VectorStores", "AsyncVectorStores"] diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index 3b070b716e..2a6a0e7738 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -8,7 +8,6 @@ import httpx from ... import _legacy_response -from ...types import ChatModel from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ..._utils import ( required_args, @@ -19,17 +18,16 @@ from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ..._streaming import Stream, AsyncStream -from ...types.chat import ( - ChatCompletion, - ChatCompletionChunk, - ChatCompletionToolParam, - ChatCompletionMessageParam, - ChatCompletionToolChoiceOptionParam, - completion_create_params, -) +from ...types.chat import completion_create_params from ..._base_client import ( make_request_options, ) +from ...types.chat_model import ChatModel +from ...types.chat.chat_completion import ChatCompletion +from ...types.chat.chat_completion_chunk import ChatCompletionChunk +from ...types.chat.chat_completion_tool_param import ChatCompletionToolParam +from ...types.chat.chat_completion_message_param import ChatCompletionMessageParam +from ...types.chat.chat_completion_tool_choice_option_param import ChatCompletionToolChoiceOptionParam __all__ = ["Completions", "AsyncCompletions"] diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index db87c83ca2..eb6ca31048 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -8,7 +8,7 @@ import httpx from .. import _legacy_response -from ..types import Completion, completion_create_params +from ..types import completion_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import ( required_args, @@ -22,6 +22,7 @@ from .._base_client import ( make_request_options, ) +from ..types.completion import Completion __all__ = ["Completions", "AsyncCompletions"] diff --git a/src/openai/resources/embeddings.py b/src/openai/resources/embeddings.py index a083b6269a..773b6f0968 100644 --- a/src/openai/resources/embeddings.py +++ b/src/openai/resources/embeddings.py @@ -9,7 +9,7 @@ import httpx from .. import _legacy_response -from ..types import CreateEmbeddingResponse, embedding_create_params +from ..types import embedding_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import is_given, maybe_transform from .._compat import cached_property @@ -19,6 +19,7 @@ from .._base_client import ( make_request_options, ) +from ..types.create_embedding_response import CreateEmbeddingResponse __all__ = ["Embeddings", "AsyncEmbeddings"] diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index 33860adad5..fa03a9c0e2 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -10,7 +10,7 @@ import httpx from .. import _legacy_response -from ..types import FileObject, FileDeleted, file_list_params, file_create_params +from ..types import file_list_params, file_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from .._utils import ( extract_files, @@ -33,6 +33,8 @@ AsyncPaginator, make_request_options, ) +from ..types.file_object import FileObject +from ..types.file_deleted import FileDeleted __all__ = ["Files", "AsyncFiles"] diff --git a/src/openai/resources/fine_tuning/jobs/checkpoints.py b/src/openai/resources/fine_tuning/jobs/checkpoints.py index e9ea6aad9a..67f5739a02 100644 --- a/src/openai/resources/fine_tuning/jobs/checkpoints.py +++ b/src/openai/resources/fine_tuning/jobs/checkpoints.py @@ -15,7 +15,8 @@ AsyncPaginator, make_request_options, ) -from ....types.fine_tuning.jobs import FineTuningJobCheckpoint, checkpoint_list_params +from ....types.fine_tuning.jobs import checkpoint_list_params +from ....types.fine_tuning.jobs.fine_tuning_job_checkpoint import FineTuningJobCheckpoint __all__ = ["Checkpoints", "AsyncCheckpoints"] diff --git a/src/openai/resources/fine_tuning/jobs/jobs.py b/src/openai/resources/fine_tuning/jobs/jobs.py index 8e49571b14..f38956e6be 100644 --- a/src/openai/resources/fine_tuning/jobs/jobs.py +++ b/src/openai/resources/fine_tuning/jobs/jobs.py @@ -29,13 +29,9 @@ AsyncPaginator, make_request_options, ) -from ....types.fine_tuning import ( - FineTuningJob, - FineTuningJobEvent, - job_list_params, - job_create_params, - job_list_events_params, -) +from ....types.fine_tuning import job_list_params, job_create_params, job_list_events_params +from ....types.fine_tuning.fine_tuning_job import FineTuningJob +from ....types.fine_tuning.fine_tuning_job_event import FineTuningJobEvent __all__ = ["Jobs", "AsyncJobs"] diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py index e12fa51bd9..74b2a46a3f 100644 --- a/src/openai/resources/images.py +++ b/src/openai/resources/images.py @@ -8,12 +8,7 @@ import httpx from .. import _legacy_response -from ..types import ( - ImagesResponse, - image_edit_params, - image_generate_params, - image_create_variation_params, -) +from ..types import image_edit_params, image_generate_params, image_create_variation_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from .._utils import ( extract_files, @@ -27,6 +22,7 @@ from .._base_client import ( make_request_options, ) +from ..types.images_response import ImagesResponse __all__ = ["Images", "AsyncImages"] diff --git a/src/openai/resources/models.py b/src/openai/resources/models.py index 4e36e20801..e76c496ffa 100644 --- a/src/openai/resources/models.py +++ b/src/openai/resources/models.py @@ -5,16 +5,17 @@ import httpx from .. import _legacy_response -from ..types import Model, ModelDeleted from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ..pagination import SyncPage, AsyncPage +from ..types.model import Model from .._base_client import ( AsyncPaginator, make_request_options, ) +from ..types.model_deleted import ModelDeleted __all__ = ["Models", "AsyncModels"] diff --git a/src/openai/resources/moderations.py b/src/openai/resources/moderations.py index 385b672f28..9386e50dae 100644 --- a/src/openai/resources/moderations.py +++ b/src/openai/resources/moderations.py @@ -8,7 +8,7 @@ import httpx from .. import _legacy_response -from ..types import ModerationCreateResponse, moderation_create_params +from ..types import moderation_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import ( maybe_transform, @@ -20,6 +20,7 @@ from .._base_client import ( make_request_options, ) +from ..types.moderation_create_response import ModerationCreateResponse __all__ = ["Moderations", "AsyncModerations"] diff --git a/src/openai/types/beta/assistant_stream_event.py b/src/openai/types/beta/assistant_stream_event.py index 90471f7daa..91925e93b3 100644 --- a/src/openai/types/beta/assistant_stream_event.py +++ b/src/openai/types/beta/assistant_stream_event.py @@ -4,11 +4,14 @@ from typing_extensions import Literal, Annotated from .thread import Thread -from ..shared import ErrorObject -from .threads import Run, Message, MessageDeltaEvent from ..._utils import PropertyInfo from ..._models import BaseModel -from .threads.runs import RunStep, RunStepDeltaEvent +from .threads.run import Run +from .threads.message import Message +from ..shared.error_object import ErrorObject +from .threads.runs.run_step import RunStep +from .threads.message_delta_event import MessageDeltaEvent +from .threads.runs.run_step_delta_event import RunStepDeltaEvent __all__ = [ "AssistantStreamEvent", diff --git a/src/openai/types/beta/function_tool.py b/src/openai/types/beta/function_tool.py index 5d278e7487..f9227678df 100644 --- a/src/openai/types/beta/function_tool.py +++ b/src/openai/types/beta/function_tool.py @@ -2,8 +2,8 @@ from typing_extensions import Literal -from ..shared import FunctionDefinition from ..._models import BaseModel +from ..shared.function_definition import FunctionDefinition __all__ = ["FunctionTool"] diff --git a/tests/api_resources/audio/test_transcriptions.py b/tests/api_resources/audio/test_transcriptions.py index ba8e9e4099..0c59cea09f 100644 --- a/tests/api_resources/audio/test_transcriptions.py +++ b/tests/api_resources/audio/test_transcriptions.py @@ -9,7 +9,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai.types.audio import Transcription +from openai.types.audio.transcription import Transcription base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/audio/test_translations.py b/tests/api_resources/audio/test_translations.py index f5c6c68f0b..5463fcff63 100644 --- a/tests/api_resources/audio/test_translations.py +++ b/tests/api_resources/audio/test_translations.py @@ -9,7 +9,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai.types.audio import Translation +from openai.types.audio.translation import Translation base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/beta/test_assistants.py b/tests/api_resources/beta/test_assistants.py index a92acb2ca5..428fe41e93 100644 --- a/tests/api_resources/beta/test_assistants.py +++ b/tests/api_resources/beta/test_assistants.py @@ -10,10 +10,8 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta import ( - Assistant, - AssistantDeleted, -) +from openai.types.beta.assistant import Assistant +from openai.types.beta.assistant_deleted import AssistantDeleted base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/beta/test_threads.py b/tests/api_resources/beta/test_threads.py index 715e3e8726..29a0a8d91c 100644 --- a/tests/api_resources/beta/test_threads.py +++ b/tests/api_resources/beta/test_threads.py @@ -9,11 +9,9 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai.types.beta import ( - Thread, - ThreadDeleted, -) -from openai.types.beta.threads import Run +from openai.types.beta.thread import Thread +from openai.types.beta.threads.run import Run +from openai.types.beta.thread_deleted import ThreadDeleted base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/beta/test_vector_stores.py b/tests/api_resources/beta/test_vector_stores.py index e671c96a45..742b5c0ed4 100644 --- a/tests/api_resources/beta/test_vector_stores.py +++ b/tests/api_resources/beta/test_vector_stores.py @@ -10,10 +10,8 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta import ( - VectorStore, - VectorStoreDeleted, -) +from openai.types.beta.vector_store import VectorStore +from openai.types.beta.vector_store_deleted import VectorStoreDeleted base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/beta/threads/runs/test_steps.py b/tests/api_resources/beta/threads/runs/test_steps.py index e6108d8dad..3b40b36e37 100644 --- a/tests/api_resources/beta/threads/runs/test_steps.py +++ b/tests/api_resources/beta/threads/runs/test_steps.py @@ -10,7 +10,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta.threads.runs import RunStep +from openai.types.beta.threads.runs.run_step import RunStep base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/beta/threads/test_messages.py b/tests/api_resources/beta/threads/test_messages.py index 26eb09acdd..f06db4fce5 100644 --- a/tests/api_resources/beta/threads/test_messages.py +++ b/tests/api_resources/beta/threads/test_messages.py @@ -10,7 +10,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta.threads import Message +from openai.types.beta.threads.message import Message base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index 429c9bdeeb..f8dbdbf449 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -10,9 +10,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta.threads import ( - Run, -) +from openai.types.beta.threads.run import Run # pyright: reportDeprecated=false diff --git a/tests/api_resources/beta/vector_stores/test_file_batches.py b/tests/api_resources/beta/vector_stores/test_file_batches.py index 9854d1a138..7e9b2e85de 100644 --- a/tests/api_resources/beta/vector_stores/test_file_batches.py +++ b/tests/api_resources/beta/vector_stores/test_file_batches.py @@ -10,10 +10,8 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta.vector_stores import ( - VectorStoreFile, - VectorStoreFileBatch, -) +from openai.types.beta.vector_stores.vector_store_file import VectorStoreFile +from openai.types.beta.vector_stores.vector_store_file_batch import VectorStoreFileBatch base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/beta/vector_stores/test_files.py b/tests/api_resources/beta/vector_stores/test_files.py index 58301e2d37..09f5c259bd 100644 --- a/tests/api_resources/beta/vector_stores/test_files.py +++ b/tests/api_resources/beta/vector_stores/test_files.py @@ -10,10 +10,8 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta.vector_stores import ( - VectorStoreFile, - VectorStoreFileDeleted, -) +from openai.types.beta.vector_stores.vector_store_file import VectorStoreFile +from openai.types.beta.vector_stores.vector_store_file_deleted import VectorStoreFileDeleted base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index c54b56a37d..ddba1ca085 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -9,7 +9,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai.types.chat import ChatCompletion +from openai.types.chat.chat_completion import ChatCompletion base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/fine_tuning/jobs/test_checkpoints.py b/tests/api_resources/fine_tuning/jobs/test_checkpoints.py index 915d5c6f63..6ebf2225ae 100644 --- a/tests/api_resources/fine_tuning/jobs/test_checkpoints.py +++ b/tests/api_resources/fine_tuning/jobs/test_checkpoints.py @@ -10,7 +10,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.fine_tuning.jobs import FineTuningJobCheckpoint +from openai.types.fine_tuning.jobs.fine_tuning_job_checkpoint import FineTuningJobCheckpoint base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/fine_tuning/test_jobs.py b/tests/api_resources/fine_tuning/test_jobs.py index 1ff6d63b31..29a96feb2d 100644 --- a/tests/api_resources/fine_tuning/test_jobs.py +++ b/tests/api_resources/fine_tuning/test_jobs.py @@ -10,10 +10,8 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.fine_tuning import ( - FineTuningJob, - FineTuningJobEvent, -) +from openai.types.fine_tuning.fine_tuning_job import FineTuningJob +from openai.types.fine_tuning.fine_tuning_job_event import FineTuningJobEvent base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/test_batches.py b/tests/api_resources/test_batches.py index 6f9b598e61..7967634128 100644 --- a/tests/api_resources/test_batches.py +++ b/tests/api_resources/test_batches.py @@ -9,8 +9,8 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai.types import Batch from openai.pagination import SyncCursorPage, AsyncCursorPage +from openai.types.batch import Batch base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/test_completions.py b/tests/api_resources/test_completions.py index 691c4ff77f..249744b531 100644 --- a/tests/api_resources/test_completions.py +++ b/tests/api_resources/test_completions.py @@ -9,7 +9,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai.types import Completion +from openai.types.completion import Completion base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/test_embeddings.py b/tests/api_resources/test_embeddings.py index e75545b4e2..9c4e55a5a8 100644 --- a/tests/api_resources/test_embeddings.py +++ b/tests/api_resources/test_embeddings.py @@ -9,7 +9,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai.types import CreateEmbeddingResponse +from openai.types.create_embedding_response import CreateEmbeddingResponse base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/test_files.py b/tests/api_resources/test_files.py index e5466e9eda..3b6817e27b 100644 --- a/tests/api_resources/test_files.py +++ b/tests/api_resources/test_files.py @@ -12,8 +12,9 @@ import openai._legacy_response as _legacy_response from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai.types import FileObject, FileDeleted from openai.pagination import SyncPage, AsyncPage +from openai.types.file_object import FileObject +from openai.types.file_deleted import FileDeleted # pyright: reportDeprecated=false diff --git a/tests/api_resources/test_images.py b/tests/api_resources/test_images.py index 2e31f3354a..8d857d2f45 100644 --- a/tests/api_resources/test_images.py +++ b/tests/api_resources/test_images.py @@ -9,7 +9,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai.types import ImagesResponse +from openai.types.images_response import ImagesResponse base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/test_models.py b/tests/api_resources/test_models.py index 71f8e5834b..2351d64a33 100644 --- a/tests/api_resources/test_models.py +++ b/tests/api_resources/test_models.py @@ -9,8 +9,9 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai.types import Model, ModelDeleted from openai.pagination import SyncPage, AsyncPage +from openai.types.model import Model +from openai.types.model_deleted import ModelDeleted base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/test_moderations.py b/tests/api_resources/test_moderations.py index 94b9ecd31b..52436ad0a9 100644 --- a/tests/api_resources/test_moderations.py +++ b/tests/api_resources/test_moderations.py @@ -9,7 +9,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai.types import ModerationCreateResponse +from openai.types.moderation_create_response import ModerationCreateResponse base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") From 7931ebaab06afaf42ed51bf6d6b17397c8ddcfd0 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 24 Apr 2024 11:58:54 -0400 Subject: [PATCH 317/816] fix(docs): doc improvements (#1364) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 84d9017e45..b8a0d9b0cb 100644 --- a/README.md +++ b/README.md @@ -521,7 +521,7 @@ The context manager is required so that the response will reliably be closed. ### Making custom/undocumented requests -This library is typed for convenient access the documented API. +This library is typed for convenient access to the documented API. If you need to access undocumented endpoints, params, or response properties, the library can still be used. From 9a1f013120ac9359602286d2547852a8fe60eaff Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 24 Apr 2024 14:24:04 -0400 Subject: [PATCH 318/816] chore(tests): rename test file (#1366) --- tests/api_resources/beta/chat/__init__.py | 1 - 1 file changed, 1 deletion(-) delete mode 100644 tests/api_resources/beta/chat/__init__.py diff --git a/tests/api_resources/beta/chat/__init__.py b/tests/api_resources/beta/chat/__init__.py deleted file mode 100644 index fd8019a9a1..0000000000 --- a/tests/api_resources/beta/chat/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. From 55f07f31c9d0cb2886ea37a9d8ed3379b46890e3 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 24 Apr 2024 14:33:44 -0400 Subject: [PATCH 319/816] fix(api): change timestamps to unix integers (#1367) --- src/openai/resources/batches.py | 10 ++++++---- src/openai/types/batch.py | 18 +++++++++--------- src/openai/types/batch_create_params.py | 5 +++-- src/openai/types/beta/vector_store.py | 6 +++--- .../beta/vector_stores/vector_store_file.py | 6 ++++++ 5 files changed, 27 insertions(+), 18 deletions(-) diff --git a/src/openai/resources/batches.py b/src/openai/resources/batches.py index 9b52958efc..a2a0272a7d 100644 --- a/src/openai/resources/batches.py +++ b/src/openai/resources/batches.py @@ -65,8 +65,9 @@ def create( See [upload file](https://platform.openai.com/docs/api-reference/files/create) for how to upload a file. - Your input file must be formatted as a JSONL file, and must be uploaded with the - purpose `batch`. + Your input file must be formatted as a + [JSONL file](https://platform.openai.com/docs/api-reference/batch/requestInput), + and must be uploaded with the purpose `batch`. metadata: Optional custom metadata for the batch. @@ -252,8 +253,9 @@ async def create( See [upload file](https://platform.openai.com/docs/api-reference/files/create) for how to upload a file. - Your input file must be formatted as a JSONL file, and must be uploaded with the - purpose `batch`. + Your input file must be formatted as a + [JSONL file](https://platform.openai.com/docs/api-reference/batch/requestInput), + and must be uploaded with the purpose `batch`. metadata: Optional custom metadata for the batch. diff --git a/src/openai/types/batch.py b/src/openai/types/batch.py index bde04d1a24..90f6d79572 100644 --- a/src/openai/types/batch.py +++ b/src/openai/types/batch.py @@ -24,7 +24,7 @@ class Batch(BaseModel): completion_window: str """The time frame within which the batch should be processed.""" - created_at: str + created_at: int """The Unix timestamp (in seconds) for when the batch was created.""" endpoint: str @@ -41,13 +41,13 @@ class Batch(BaseModel): ] """The current status of the batch.""" - cancelled_at: Optional[str] = None + cancelled_at: Optional[int] = None """The Unix timestamp (in seconds) for when the batch was cancelled.""" - cancelling_at: Optional[str] = None + cancelling_at: Optional[int] = None """The Unix timestamp (in seconds) for when the batch started cancelling.""" - completed_at: Optional[str] = None + completed_at: Optional[int] = None """The Unix timestamp (in seconds) for when the batch was completed.""" error_file_id: Optional[str] = None @@ -55,19 +55,19 @@ class Batch(BaseModel): errors: Optional[Errors] = None - expired_at: Optional[str] = None + expired_at: Optional[int] = None """The Unix timestamp (in seconds) for when the batch expired.""" - expires_at: Optional[str] = None + expires_at: Optional[int] = None """The Unix timestamp (in seconds) for when the batch will expire.""" - failed_at: Optional[str] = None + failed_at: Optional[int] = None """The Unix timestamp (in seconds) for when the batch failed.""" - finalizing_at: Optional[str] = None + finalizing_at: Optional[int] = None """The Unix timestamp (in seconds) for when the batch started finalizing.""" - in_progress_at: Optional[str] = None + in_progress_at: Optional[int] = None """The Unix timestamp (in seconds) for when the batch started processing.""" metadata: Optional[builtins.object] = None diff --git a/src/openai/types/batch_create_params.py b/src/openai/types/batch_create_params.py index 6a22be8626..a67aaa1e5e 100644 --- a/src/openai/types/batch_create_params.py +++ b/src/openai/types/batch_create_params.py @@ -27,8 +27,9 @@ class BatchCreateParams(TypedDict, total=False): See [upload file](https://platform.openai.com/docs/api-reference/files/create) for how to upload a file. - Your input file must be formatted as a JSONL file, and must be uploaded with the - purpose `batch`. + Your input file must be formatted as a + [JSONL file](https://platform.openai.com/docs/api-reference/batch/requestInput), + and must be uploaded with the purpose `batch`. """ metadata: Optional[Dict[str, str]] diff --git a/src/openai/types/beta/vector_store.py b/src/openai/types/beta/vector_store.py index 122705734d..488961b444 100644 --- a/src/openai/types/beta/vector_store.py +++ b/src/openai/types/beta/vector_store.py @@ -40,9 +40,6 @@ class VectorStore(BaseModel): id: str """The identifier, which can be referenced in API endpoints.""" - bytes: int - """The byte size of the vector store.""" - created_at: int """The Unix timestamp (in seconds) for when the vector store was created.""" @@ -72,6 +69,9 @@ class VectorStore(BaseModel): for use. """ + usage_bytes: int + """The total number of bytes used by the files in the vector store.""" + expires_after: Optional[ExpiresAfter] = None """The expiration policy for a vector store.""" diff --git a/src/openai/types/beta/vector_stores/vector_store_file.py b/src/openai/types/beta/vector_stores/vector_store_file.py index a878b281d5..3fab489602 100644 --- a/src/openai/types/beta/vector_stores/vector_store_file.py +++ b/src/openai/types/beta/vector_stores/vector_store_file.py @@ -39,6 +39,12 @@ class VectorStoreFile(BaseModel): vector store file is ready for use. """ + usage_bytes: int + """The total vector store usage in bytes. + + Note that this may be different from the original file size. + """ + vector_store_id: str """ The ID of the From 19410c6e7ebf9de243c5040681896bdc0277ad07 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 24 Apr 2024 14:34:10 -0400 Subject: [PATCH 320/816] release: 1.23.4 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 14 ++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 17 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 75baea2d17..9fbf60ba41 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.23.3" + ".": "1.23.4" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index eed20091bf..48ab946491 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,19 @@ # Changelog +## 1.23.4 (2024-04-24) + +Full Changelog: [v1.23.3...v1.23.4](https://github.com/openai/openai-python/compare/v1.23.3...v1.23.4) + +### Bug Fixes + +* **api:** change timestamps to unix integers ([#1367](https://github.com/openai/openai-python/issues/1367)) ([fbc0e15](https://github.com/openai/openai-python/commit/fbc0e15f422971bd15499d4ea5f42a1c885c7004)) +* **docs:** doc improvements ([#1364](https://github.com/openai/openai-python/issues/1364)) ([8c3a005](https://github.com/openai/openai-python/commit/8c3a005247ea045b9a95e7459eba2a90067daf71)) + + +### Chores + +* **tests:** rename test file ([#1366](https://github.com/openai/openai-python/issues/1366)) ([4204e63](https://github.com/openai/openai-python/commit/4204e63e27584c68ad27825261225603d7a87008)) + ## 1.23.3 (2024-04-23) Full Changelog: [v1.23.2...v1.23.3](https://github.com/openai/openai-python/compare/v1.23.2...v1.23.3) diff --git a/pyproject.toml b/pyproject.toml index fbda5414f6..9cde315623 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.23.3" +version = "1.23.4" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index ab45006b24..943be8e435 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.23.3" # x-release-please-version +__version__ = "1.23.4" # x-release-please-version From 290e7ada3a6f7b4bf1fbbbe285086013853e9418 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 24 Apr 2024 20:25:51 -0400 Subject: [PATCH 321/816] release: 1.23.5 (#1369) * chore(internal): use actions/checkout@v4 for codeflow (#1368) * release: 1.23.5 --- .github/workflows/create-releases.yml | 2 +- .github/workflows/publish-pypi.yml | 2 +- .github/workflows/release-doctor.yml | 2 +- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 7 files changed, 14 insertions(+), 6 deletions(-) diff --git a/.github/workflows/create-releases.yml b/.github/workflows/create-releases.yml index 9e76fcc471..a641be287b 100644 --- a/.github/workflows/create-releases.yml +++ b/.github/workflows/create-releases.yml @@ -14,7 +14,7 @@ jobs: environment: publish steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: stainless-api/trigger-release-please@v1 id: release diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml index f779a19ac1..2f88f86407 100644 --- a/.github/workflows/publish-pypi.yml +++ b/.github/workflows/publish-pypi.yml @@ -10,7 +10,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Install Rye run: | diff --git a/.github/workflows/release-doctor.yml b/.github/workflows/release-doctor.yml index 108aa5973a..e078964a6f 100644 --- a/.github/workflows/release-doctor.yml +++ b/.github/workflows/release-doctor.yml @@ -13,7 +13,7 @@ jobs: if: github.repository == 'openai/openai-python' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch' || startsWith(github.head_ref, 'release-please') || github.head_ref == 'next') steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Check release environment run: | diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 9fbf60ba41..dd9e0bd0b2 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.23.4" + ".": "1.23.5" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 48ab946491..9ac6cd139d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.23.5 (2024-04-24) + +Full Changelog: [v1.23.4...v1.23.5](https://github.com/openai/openai-python/compare/v1.23.4...v1.23.5) + +### Chores + +* **internal:** use actions/checkout@v4 for codeflow ([#1368](https://github.com/openai/openai-python/issues/1368)) ([d1edf8b](https://github.com/openai/openai-python/commit/d1edf8beb806ebaefdcc2cb6e39f99e1811a2668)) + ## 1.23.4 (2024-04-24) Full Changelog: [v1.23.3...v1.23.4](https://github.com/openai/openai-python/compare/v1.23.3...v1.23.4) diff --git a/pyproject.toml b/pyproject.toml index 9cde315623..18949f6652 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.23.4" +version = "1.23.5" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 943be8e435..460a2542b1 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.23.4" # x-release-please-version +__version__ = "1.23.5" # x-release-please-version From e9724398d2bdd87ba41f199c3577303f1b80f2c7 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 25 Apr 2024 00:19:39 -0400 Subject: [PATCH 322/816] release: 1.23.6 (#1372) * chore(internal): update test helper function (#1371) * release: 1.23.6 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- tests/utils.py | 17 ++++++++++++++++- 5 files changed, 27 insertions(+), 4 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index dd9e0bd0b2..89bd0ec2f7 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.23.5" + ".": "1.23.6" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ac6cd139d..a25cd549b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.23.6 (2024-04-25) + +Full Changelog: [v1.23.5...v1.23.6](https://github.com/openai/openai-python/compare/v1.23.5...v1.23.6) + +### Chores + +* **internal:** update test helper function ([#1371](https://github.com/openai/openai-python/issues/1371)) ([6607c4a](https://github.com/openai/openai-python/commit/6607c4a491fd1912f9222d6fe464ccef6e865eac)) + ## 1.23.5 (2024-04-24) Full Changelog: [v1.23.4...v1.23.5](https://github.com/openai/openai-python/compare/v1.23.4...v1.23.5) diff --git a/pyproject.toml b/pyproject.toml index 18949f6652..d82615a4ad 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.23.5" +version = "1.23.6" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 460a2542b1..7ca1a0a78b 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.23.5" # x-release-please-version +__version__ = "1.23.6" # x-release-please-version diff --git a/tests/utils.py b/tests/utils.py index 43c3cb5cfe..060b99339f 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -97,7 +97,22 @@ def assert_matches_type( assert_matches_type(key_type, key, path=[*path, ""]) assert_matches_type(items_type, item, path=[*path, ""]) elif is_union_type(type_): - for i, variant in enumerate(get_args(type_)): + variants = get_args(type_) + + try: + none_index = variants.index(type(None)) + except ValueError: + pass + else: + # special case Optional[T] for better error messages + if len(variants) == 2: + if value is None: + # valid + return + + return assert_matches_type(type_=variants[not none_index], value=value, path=path) + + for i, variant in enumerate(variants): try: assert_matches_type(variant, value, path=[*path, f"variant {i}"]) return From 4a0f0fa053904d1a9b1ee4e268e59c7799f9c0ac Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 26 Apr 2024 09:48:35 -0400 Subject: [PATCH 323/816] chore(internal): reformat imports (#1375) --- tests/api_resources/audio/test_transcriptions.py | 2 +- tests/api_resources/audio/test_translations.py | 2 +- tests/api_resources/beta/test_assistants.py | 6 ++++-- tests/api_resources/beta/test_threads.py | 8 +++++--- tests/api_resources/beta/test_vector_stores.py | 6 ++++-- tests/api_resources/beta/threads/runs/test_steps.py | 2 +- tests/api_resources/beta/threads/test_messages.py | 2 +- tests/api_resources/beta/threads/test_runs.py | 4 +++- .../api_resources/beta/vector_stores/test_file_batches.py | 6 ++++-- tests/api_resources/beta/vector_stores/test_files.py | 6 ++++-- tests/api_resources/chat/test_completions.py | 2 +- tests/api_resources/fine_tuning/jobs/test_checkpoints.py | 2 +- tests/api_resources/fine_tuning/test_jobs.py | 6 ++++-- tests/api_resources/test_batches.py | 2 +- tests/api_resources/test_completions.py | 2 +- tests/api_resources/test_embeddings.py | 2 +- tests/api_resources/test_files.py | 3 +-- tests/api_resources/test_images.py | 2 +- tests/api_resources/test_models.py | 3 +-- tests/api_resources/test_moderations.py | 2 +- 20 files changed, 41 insertions(+), 29 deletions(-) diff --git a/tests/api_resources/audio/test_transcriptions.py b/tests/api_resources/audio/test_transcriptions.py index 0c59cea09f..ba8e9e4099 100644 --- a/tests/api_resources/audio/test_transcriptions.py +++ b/tests/api_resources/audio/test_transcriptions.py @@ -9,7 +9,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai.types.audio.transcription import Transcription +from openai.types.audio import Transcription base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/audio/test_translations.py b/tests/api_resources/audio/test_translations.py index 5463fcff63..f5c6c68f0b 100644 --- a/tests/api_resources/audio/test_translations.py +++ b/tests/api_resources/audio/test_translations.py @@ -9,7 +9,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai.types.audio.translation import Translation +from openai.types.audio import Translation base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/beta/test_assistants.py b/tests/api_resources/beta/test_assistants.py index 428fe41e93..a92acb2ca5 100644 --- a/tests/api_resources/beta/test_assistants.py +++ b/tests/api_resources/beta/test_assistants.py @@ -10,8 +10,10 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta.assistant import Assistant -from openai.types.beta.assistant_deleted import AssistantDeleted +from openai.types.beta import ( + Assistant, + AssistantDeleted, +) base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/beta/test_threads.py b/tests/api_resources/beta/test_threads.py index 29a0a8d91c..715e3e8726 100644 --- a/tests/api_resources/beta/test_threads.py +++ b/tests/api_resources/beta/test_threads.py @@ -9,9 +9,11 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai.types.beta.thread import Thread -from openai.types.beta.threads.run import Run -from openai.types.beta.thread_deleted import ThreadDeleted +from openai.types.beta import ( + Thread, + ThreadDeleted, +) +from openai.types.beta.threads import Run base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/beta/test_vector_stores.py b/tests/api_resources/beta/test_vector_stores.py index 742b5c0ed4..e671c96a45 100644 --- a/tests/api_resources/beta/test_vector_stores.py +++ b/tests/api_resources/beta/test_vector_stores.py @@ -10,8 +10,10 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta.vector_store import VectorStore -from openai.types.beta.vector_store_deleted import VectorStoreDeleted +from openai.types.beta import ( + VectorStore, + VectorStoreDeleted, +) base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/beta/threads/runs/test_steps.py b/tests/api_resources/beta/threads/runs/test_steps.py index 3b40b36e37..e6108d8dad 100644 --- a/tests/api_resources/beta/threads/runs/test_steps.py +++ b/tests/api_resources/beta/threads/runs/test_steps.py @@ -10,7 +10,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta.threads.runs.run_step import RunStep +from openai.types.beta.threads.runs import RunStep base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/beta/threads/test_messages.py b/tests/api_resources/beta/threads/test_messages.py index f06db4fce5..26eb09acdd 100644 --- a/tests/api_resources/beta/threads/test_messages.py +++ b/tests/api_resources/beta/threads/test_messages.py @@ -10,7 +10,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta.threads.message import Message +from openai.types.beta.threads import Message base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index f8dbdbf449..429c9bdeeb 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -10,7 +10,9 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta.threads.run import Run +from openai.types.beta.threads import ( + Run, +) # pyright: reportDeprecated=false diff --git a/tests/api_resources/beta/vector_stores/test_file_batches.py b/tests/api_resources/beta/vector_stores/test_file_batches.py index 7e9b2e85de..9854d1a138 100644 --- a/tests/api_resources/beta/vector_stores/test_file_batches.py +++ b/tests/api_resources/beta/vector_stores/test_file_batches.py @@ -10,8 +10,10 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta.vector_stores.vector_store_file import VectorStoreFile -from openai.types.beta.vector_stores.vector_store_file_batch import VectorStoreFileBatch +from openai.types.beta.vector_stores import ( + VectorStoreFile, + VectorStoreFileBatch, +) base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/beta/vector_stores/test_files.py b/tests/api_resources/beta/vector_stores/test_files.py index 09f5c259bd..58301e2d37 100644 --- a/tests/api_resources/beta/vector_stores/test_files.py +++ b/tests/api_resources/beta/vector_stores/test_files.py @@ -10,8 +10,10 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta.vector_stores.vector_store_file import VectorStoreFile -from openai.types.beta.vector_stores.vector_store_file_deleted import VectorStoreFileDeleted +from openai.types.beta.vector_stores import ( + VectorStoreFile, + VectorStoreFileDeleted, +) base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index ddba1ca085..c54b56a37d 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -9,7 +9,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai.types.chat.chat_completion import ChatCompletion +from openai.types.chat import ChatCompletion base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/fine_tuning/jobs/test_checkpoints.py b/tests/api_resources/fine_tuning/jobs/test_checkpoints.py index 6ebf2225ae..915d5c6f63 100644 --- a/tests/api_resources/fine_tuning/jobs/test_checkpoints.py +++ b/tests/api_resources/fine_tuning/jobs/test_checkpoints.py @@ -10,7 +10,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.fine_tuning.jobs.fine_tuning_job_checkpoint import FineTuningJobCheckpoint +from openai.types.fine_tuning.jobs import FineTuningJobCheckpoint base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/fine_tuning/test_jobs.py b/tests/api_resources/fine_tuning/test_jobs.py index 29a96feb2d..1ff6d63b31 100644 --- a/tests/api_resources/fine_tuning/test_jobs.py +++ b/tests/api_resources/fine_tuning/test_jobs.py @@ -10,8 +10,10 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.fine_tuning.fine_tuning_job import FineTuningJob -from openai.types.fine_tuning.fine_tuning_job_event import FineTuningJobEvent +from openai.types.fine_tuning import ( + FineTuningJob, + FineTuningJobEvent, +) base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/test_batches.py b/tests/api_resources/test_batches.py index 7967634128..6f9b598e61 100644 --- a/tests/api_resources/test_batches.py +++ b/tests/api_resources/test_batches.py @@ -9,8 +9,8 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type +from openai.types import Batch from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.batch import Batch base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/test_completions.py b/tests/api_resources/test_completions.py index 249744b531..691c4ff77f 100644 --- a/tests/api_resources/test_completions.py +++ b/tests/api_resources/test_completions.py @@ -9,7 +9,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai.types.completion import Completion +from openai.types import Completion base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/test_embeddings.py b/tests/api_resources/test_embeddings.py index 9c4e55a5a8..e75545b4e2 100644 --- a/tests/api_resources/test_embeddings.py +++ b/tests/api_resources/test_embeddings.py @@ -9,7 +9,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai.types.create_embedding_response import CreateEmbeddingResponse +from openai.types import CreateEmbeddingResponse base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/test_files.py b/tests/api_resources/test_files.py index 3b6817e27b..e5466e9eda 100644 --- a/tests/api_resources/test_files.py +++ b/tests/api_resources/test_files.py @@ -12,9 +12,8 @@ import openai._legacy_response as _legacy_response from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type +from openai.types import FileObject, FileDeleted from openai.pagination import SyncPage, AsyncPage -from openai.types.file_object import FileObject -from openai.types.file_deleted import FileDeleted # pyright: reportDeprecated=false diff --git a/tests/api_resources/test_images.py b/tests/api_resources/test_images.py index 8d857d2f45..2e31f3354a 100644 --- a/tests/api_resources/test_images.py +++ b/tests/api_resources/test_images.py @@ -9,7 +9,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai.types.images_response import ImagesResponse +from openai.types import ImagesResponse base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/test_models.py b/tests/api_resources/test_models.py index 2351d64a33..71f8e5834b 100644 --- a/tests/api_resources/test_models.py +++ b/tests/api_resources/test_models.py @@ -9,9 +9,8 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type +from openai.types import Model, ModelDeleted from openai.pagination import SyncPage, AsyncPage -from openai.types.model import Model -from openai.types.model_deleted import ModelDeleted base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/api_resources/test_moderations.py b/tests/api_resources/test_moderations.py index 52436ad0a9..94b9ecd31b 100644 --- a/tests/api_resources/test_moderations.py +++ b/tests/api_resources/test_moderations.py @@ -9,7 +9,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai.types.moderation_create_response import ModerationCreateResponse +from openai.types import ModerationCreateResponse base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") From ffa8483dcf7ff811e8c1522d190a554cbf73fa9e Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 26 Apr 2024 13:49:34 -0400 Subject: [PATCH 324/816] chore(internal): minor reformatting (#1377) --- src/openai/types/audio/transcription.py | 2 ++ src/openai/types/audio/translation.py | 2 ++ src/openai/types/batch_request_counts.py | 2 ++ src/openai/types/beta/assistant_tool_choice_function.py | 2 ++ src/openai/types/beta/threads/image_file.py | 2 ++ src/openai/types/completion_usage.py | 2 ++ src/openai/types/model_deleted.py | 2 ++ src/openai/types/moderation.py | 1 + tests/test_client.py | 1 - 9 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/openai/types/audio/transcription.py b/src/openai/types/audio/transcription.py index fa512e27f9..0b6ab39e78 100644 --- a/src/openai/types/audio/transcription.py +++ b/src/openai/types/audio/transcription.py @@ -1,5 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + from ..._models import BaseModel __all__ = ["Transcription"] diff --git a/src/openai/types/audio/translation.py b/src/openai/types/audio/translation.py index efc56f7f9b..3d9ede2939 100644 --- a/src/openai/types/audio/translation.py +++ b/src/openai/types/audio/translation.py @@ -1,5 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + from ..._models import BaseModel __all__ = ["Translation"] diff --git a/src/openai/types/batch_request_counts.py b/src/openai/types/batch_request_counts.py index 068b071af1..ef6c84a0a1 100644 --- a/src/openai/types/batch_request_counts.py +++ b/src/openai/types/batch_request_counts.py @@ -1,5 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + from .._models import BaseModel __all__ = ["BatchRequestCounts"] diff --git a/src/openai/types/beta/assistant_tool_choice_function.py b/src/openai/types/beta/assistant_tool_choice_function.py index 87f38310ca..d0d4255357 100644 --- a/src/openai/types/beta/assistant_tool_choice_function.py +++ b/src/openai/types/beta/assistant_tool_choice_function.py @@ -1,5 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + from ..._models import BaseModel __all__ = ["AssistantToolChoiceFunction"] diff --git a/src/openai/types/beta/threads/image_file.py b/src/openai/types/beta/threads/image_file.py index db0d6e823a..651a247d21 100644 --- a/src/openai/types/beta/threads/image_file.py +++ b/src/openai/types/beta/threads/image_file.py @@ -1,5 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + from ...._models import BaseModel __all__ = ["ImageFile"] diff --git a/src/openai/types/completion_usage.py b/src/openai/types/completion_usage.py index e185a5cc38..0d57b96595 100644 --- a/src/openai/types/completion_usage.py +++ b/src/openai/types/completion_usage.py @@ -1,5 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + from .._models import BaseModel __all__ = ["CompletionUsage"] diff --git a/src/openai/types/model_deleted.py b/src/openai/types/model_deleted.py index e7601f74e4..d9a48bb1b5 100644 --- a/src/openai/types/model_deleted.py +++ b/src/openai/types/model_deleted.py @@ -1,5 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + from .._models import BaseModel __all__ = ["ModelDeleted"] diff --git a/src/openai/types/moderation.py b/src/openai/types/moderation.py index 2a2e5c5d7a..5aa691823a 100644 --- a/src/openai/types/moderation.py +++ b/src/openai/types/moderation.py @@ -1,5 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + from pydantic import Field as FieldInfo from .._models import BaseModel diff --git a/tests/test_client.py b/tests/test_client.py index ba85fd9d5f..c1e545e66f 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -17,7 +17,6 @@ from pydantic import ValidationError from openai import OpenAI, AsyncOpenAI, APIResponseValidationError -from openai._client import OpenAI, AsyncOpenAI from openai._models import BaseModel, FinalRequestOptions from openai._constants import RAW_RESPONSE_HEADER from openai._streaming import Stream, AsyncStream From a669541138e95c11e6fe7e5e82e3d95f435f89f1 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 29 Apr 2024 13:02:12 -0400 Subject: [PATCH 325/816] feat(api): add required tool_choice (#1382) --- .../resources/beta/threads/runs/runs.py | 30 ++++--- src/openai/resources/beta/threads/threads.py | 30 ++++--- src/openai/resources/chat/completions.py | 84 +++++++++---------- .../beta/assistant_tool_choice_option.py | 2 +- .../assistant_tool_choice_option_param.py | 2 +- .../beta/thread_create_and_run_params.py | 5 +- src/openai/types/beta/threads/run.py | 5 +- .../types/beta/threads/run_create_params.py | 5 +- ...hat_completion_tool_choice_option_param.py | 2 +- .../types/chat/completion_create_params.py | 14 ++-- 10 files changed, 97 insertions(+), 82 deletions(-) diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index e572a14a19..4268d41390 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -187,8 +187,9 @@ def create( tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value - and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "file_search"}` or + and means the model can pick between generating a message or calling one or more + tools. `required` means the model must call one or more tools before responding + to the user. Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. @@ -330,8 +331,9 @@ def create( tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value - and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "file_search"}` or + and means the model can pick between generating a message or calling one or more + tools. `required` means the model must call one or more tools before responding + to the user. Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. @@ -473,8 +475,9 @@ def create( tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value - and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "file_search"}` or + and means the model can pick between generating a message or calling one or more + tools. `required` means the model must call one or more tools before responding + to the user. Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. @@ -1716,8 +1719,9 @@ async def create( tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value - and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "file_search"}` or + and means the model can pick between generating a message or calling one or more + tools. `required` means the model must call one or more tools before responding + to the user. Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. @@ -1859,8 +1863,9 @@ async def create( tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value - and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "file_search"}` or + and means the model can pick between generating a message or calling one or more + tools. `required` means the model must call one or more tools before responding + to the user. Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. @@ -2002,8 +2007,9 @@ async def create( tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value - and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "file_search"}` or + and means the model can pick between generating a message or calling one or more + tools. `required` means the model must call one or more tools before responding + to the user. Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 1c516bcea6..2455272658 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -365,8 +365,9 @@ def create_and_run( tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value - and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "file_search"}` or + and means the model can pick between generating a message or calling one or more + tools. `required` means the model must call one or more tools before responding + to the user. Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. @@ -507,8 +508,9 @@ def create_and_run( tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value - and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "file_search"}` or + and means the model can pick between generating a message or calling one or more + tools. `required` means the model must call one or more tools before responding + to the user. Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. @@ -649,8 +651,9 @@ def create_and_run( tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value - and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "file_search"}` or + and means the model can pick between generating a message or calling one or more + tools. `required` means the model must call one or more tools before responding + to the user. Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. @@ -1336,8 +1339,9 @@ async def create_and_run( tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value - and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "file_search"}` or + and means the model can pick between generating a message or calling one or more + tools. `required` means the model must call one or more tools before responding + to the user. Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. @@ -1478,8 +1482,9 @@ async def create_and_run( tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value - and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "file_search"}` or + and means the model can pick between generating a message or calling one or more + tools. `required` means the model must call one or more tools before responding + to the user. Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. @@ -1620,8 +1625,9 @@ async def create_and_run( tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value - and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "file_search"}` or + and means the model can pick between generating a message or calling one or more + tools. `required` means the model must call one or more tools before responding + to the user. Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index 2a6a0e7738..5104cd6136 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -171,15 +171,15 @@ def create( We generally recommend altering this or `top_p` but not both. - tool_choice: Controls which (if any) function is called by the model. `none` means the model - will not call a function and instead generates a message. `auto` means the model - can pick between generating a message or calling a function. Specifying a - particular function via + tool_choice: Controls which (if any) tool is called by the model. `none` means the model will + not call any tool and instead generates a message. `auto` means the model can + pick between generating a message or calling one or more tools. `required` means + the model must call one or more tools. Specifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces the model to - call that function. + call that tool. - `none` is the default when no functions are present. `auto` is the default if - functions are present. + `none` is the default when no tools are present. `auto` is the default if tools + are present. tools: A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs @@ -339,15 +339,15 @@ def create( We generally recommend altering this or `top_p` but not both. - tool_choice: Controls which (if any) function is called by the model. `none` means the model - will not call a function and instead generates a message. `auto` means the model - can pick between generating a message or calling a function. Specifying a - particular function via + tool_choice: Controls which (if any) tool is called by the model. `none` means the model will + not call any tool and instead generates a message. `auto` means the model can + pick between generating a message or calling one or more tools. `required` means + the model must call one or more tools. Specifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces the model to - call that function. + call that tool. - `none` is the default when no functions are present. `auto` is the default if - functions are present. + `none` is the default when no tools are present. `auto` is the default if tools + are present. tools: A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs @@ -507,15 +507,15 @@ def create( We generally recommend altering this or `top_p` but not both. - tool_choice: Controls which (if any) function is called by the model. `none` means the model - will not call a function and instead generates a message. `auto` means the model - can pick between generating a message or calling a function. Specifying a - particular function via + tool_choice: Controls which (if any) tool is called by the model. `none` means the model will + not call any tool and instead generates a message. `auto` means the model can + pick between generating a message or calling one or more tools. `required` means + the model must call one or more tools. Specifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces the model to - call that function. + call that tool. - `none` is the default when no functions are present. `auto` is the default if - functions are present. + `none` is the default when no tools are present. `auto` is the default if tools + are present. tools: A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs @@ -751,15 +751,15 @@ async def create( We generally recommend altering this or `top_p` but not both. - tool_choice: Controls which (if any) function is called by the model. `none` means the model - will not call a function and instead generates a message. `auto` means the model - can pick between generating a message or calling a function. Specifying a - particular function via + tool_choice: Controls which (if any) tool is called by the model. `none` means the model will + not call any tool and instead generates a message. `auto` means the model can + pick between generating a message or calling one or more tools. `required` means + the model must call one or more tools. Specifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces the model to - call that function. + call that tool. - `none` is the default when no functions are present. `auto` is the default if - functions are present. + `none` is the default when no tools are present. `auto` is the default if tools + are present. tools: A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs @@ -919,15 +919,15 @@ async def create( We generally recommend altering this or `top_p` but not both. - tool_choice: Controls which (if any) function is called by the model. `none` means the model - will not call a function and instead generates a message. `auto` means the model - can pick between generating a message or calling a function. Specifying a - particular function via + tool_choice: Controls which (if any) tool is called by the model. `none` means the model will + not call any tool and instead generates a message. `auto` means the model can + pick between generating a message or calling one or more tools. `required` means + the model must call one or more tools. Specifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces the model to - call that function. + call that tool. - `none` is the default when no functions are present. `auto` is the default if - functions are present. + `none` is the default when no tools are present. `auto` is the default if tools + are present. tools: A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs @@ -1087,15 +1087,15 @@ async def create( We generally recommend altering this or `top_p` but not both. - tool_choice: Controls which (if any) function is called by the model. `none` means the model - will not call a function and instead generates a message. `auto` means the model - can pick between generating a message or calling a function. Specifying a - particular function via + tool_choice: Controls which (if any) tool is called by the model. `none` means the model will + not call any tool and instead generates a message. `auto` means the model can + pick between generating a message or calling one or more tools. `required` means + the model must call one or more tools. Specifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces the model to - call that function. + call that tool. - `none` is the default when no functions are present. `auto` is the default if - functions are present. + `none` is the default when no tools are present. `auto` is the default if tools + are present. tools: A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs diff --git a/src/openai/types/beta/assistant_tool_choice_option.py b/src/openai/types/beta/assistant_tool_choice_option.py index 0045a5986e..8958bc8fb0 100644 --- a/src/openai/types/beta/assistant_tool_choice_option.py +++ b/src/openai/types/beta/assistant_tool_choice_option.py @@ -7,4 +7,4 @@ __all__ = ["AssistantToolChoiceOption"] -AssistantToolChoiceOption = Union[Literal["none", "auto"], AssistantToolChoice] +AssistantToolChoiceOption = Union[Literal["none", "auto", "required"], AssistantToolChoice] diff --git a/src/openai/types/beta/assistant_tool_choice_option_param.py b/src/openai/types/beta/assistant_tool_choice_option_param.py index 618e7bff98..81b7f15136 100644 --- a/src/openai/types/beta/assistant_tool_choice_option_param.py +++ b/src/openai/types/beta/assistant_tool_choice_option_param.py @@ -9,4 +9,4 @@ __all__ = ["AssistantToolChoiceOptionParam"] -AssistantToolChoiceOptionParam = Union[Literal["none", "auto"], AssistantToolChoiceParam] +AssistantToolChoiceOptionParam = Union[Literal["none", "auto", "required"], AssistantToolChoiceParam] diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index 9adb049843..60510965a2 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -135,8 +135,9 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): """ Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value - and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "file_search"}` or + and means the model can pick between generating a message or calling one or more + tools. `required` means the model must call one or more tools before responding + to the user. Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. """ diff --git a/src/openai/types/beta/threads/run.py b/src/openai/types/beta/threads/run.py index 4fd5103348..6c118f27c1 100644 --- a/src/openai/types/beta/threads/run.py +++ b/src/openai/types/beta/threads/run.py @@ -196,8 +196,9 @@ class Run(BaseModel): """ Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value - and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "file_search"}` or + and means the model can pick between generating a message or calling one or more + tools. `required` means the model must call one or more tools before responding + to the user. Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. """ diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index f4780b7f09..2e4823bacd 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -134,8 +134,9 @@ class RunCreateParamsBase(TypedDict, total=False): """ Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value - and means the model can pick between generating a message or calling a tool. - Specifying a particular tool like `{"type": "file_search"}` or + and means the model can pick between generating a message or calling one or more + tools. `required` means the model must call one or more tools before responding + to the user. Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. """ diff --git a/src/openai/types/chat/chat_completion_tool_choice_option_param.py b/src/openai/types/chat/chat_completion_tool_choice_option_param.py index 9c0ae22528..1d3c2506ab 100644 --- a/src/openai/types/chat/chat_completion_tool_choice_option_param.py +++ b/src/openai/types/chat/chat_completion_tool_choice_option_param.py @@ -9,4 +9,4 @@ __all__ = ["ChatCompletionToolChoiceOptionParam"] -ChatCompletionToolChoiceOptionParam = Union[Literal["none", "auto"], ChatCompletionNamedToolChoiceParam] +ChatCompletionToolChoiceOptionParam = Union[Literal["none", "auto", "required"], ChatCompletionNamedToolChoiceParam] diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 964b246c41..d30da60b16 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -152,15 +152,15 @@ class CompletionCreateParamsBase(TypedDict, total=False): tool_choice: ChatCompletionToolChoiceOptionParam """ - Controls which (if any) function is called by the model. `none` means the model - will not call a function and instead generates a message. `auto` means the model - can pick between generating a message or calling a function. Specifying a - particular function via + Controls which (if any) tool is called by the model. `none` means the model will + not call any tool and instead generates a message. `auto` means the model can + pick between generating a message or calling one or more tools. `required` means + the model must call one or more tools. Specifying a particular tool via `{"type": "function", "function": {"name": "my_function"}}` forces the model to - call that function. + call that tool. - `none` is the default when no functions are present. `auto` is the default if - functions are present. + `none` is the default when no tools are present. `auto` is the default if tools + are present. """ tools: Iterable[ChatCompletionToolParam] From 155d0de3c032a41d57c719a321f916c65e7e9e89 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 29 Apr 2024 13:30:24 -0400 Subject: [PATCH 326/816] chore(client): log response headers in debug mode (#1383) --- src/openai/_base_client.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index cd8361607e..5d5d25fca9 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -946,6 +946,8 @@ def _request( if self.custom_auth is not None: kwargs["auth"] = self.custom_auth + log.debug("Sending HTTP Request: %s %s", request.method, request.url) + try: response = self._client.send( request, @@ -984,8 +986,14 @@ def _request( raise APIConnectionError(request=request) from err log.debug( - 'HTTP Request: %s %s "%i %s"', request.method, request.url, response.status_code, response.reason_phrase + 'HTTP Response: %s %s "%i %s" %s', + request.method, + request.url, + response.status_code, + response.reason_phrase, + response.headers, ) + log.debug("request_id: %s", response.headers.get("x-request-id")) try: response.raise_for_status() From 39845c7a2fc166e1d295a3f9a7d82a13a383b69b Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 29 Apr 2024 13:30:52 -0400 Subject: [PATCH 327/816] release: 1.24.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 15 +++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 18 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 89bd0ec2f7..bfaab56f68 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.23.6" + ".": "1.24.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index a25cd549b7..da1a4c27a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## 1.24.0 (2024-04-29) + +Full Changelog: [v1.23.6...v1.24.0](https://github.com/openai/openai-python/compare/v1.23.6...v1.24.0) + +### Features + +* **api:** add required tool_choice ([#1382](https://github.com/openai/openai-python/issues/1382)) ([c558f65](https://github.com/openai/openai-python/commit/c558f651df39f61425cd4109318f78ed94cbf163)) + + +### Chores + +* **client:** log response headers in debug mode ([#1383](https://github.com/openai/openai-python/issues/1383)) ([f31a426](https://github.com/openai/openai-python/commit/f31a4261adc4ebd92582cee264e41eb6a6dafc57)) +* **internal:** minor reformatting ([#1377](https://github.com/openai/openai-python/issues/1377)) ([7003dbb](https://github.com/openai/openai-python/commit/7003dbb863b6e16381070b8b86ac24aa070a3799)) +* **internal:** reformat imports ([#1375](https://github.com/openai/openai-python/issues/1375)) ([2ad0c3b](https://github.com/openai/openai-python/commit/2ad0c3b8e0b746ed20db3c84a9c6a369aa10bf5d)) + ## 1.23.6 (2024-04-25) Full Changelog: [v1.23.5...v1.23.6](https://github.com/openai/openai-python/compare/v1.23.5...v1.23.6) diff --git a/pyproject.toml b/pyproject.toml index d82615a4ad..d1006b3b70 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.23.6" +version = "1.24.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 7ca1a0a78b..5b3383adc3 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.23.6" # x-release-please-version +__version__ = "1.24.0" # x-release-please-version From 11460b5ed97080ee8e7a4311c1e90e495c59d370 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 30 Apr 2024 14:06:35 -0400 Subject: [PATCH 328/816] release: 1.24.1 (#1386) * chore(internal): add link to openapi spec (#1385) * release: 1.24.1 --- .release-please-manifest.json | 2 +- .stats.yml | 1 + CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 5 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index bfaab56f68..347a18e529 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.24.0" + ".": "1.24.1" } \ No newline at end of file diff --git a/.stats.yml b/.stats.yml index c9a9bfa4a8..e904583dae 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1 +1,2 @@ configured_endpoints: 63 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-0839c14b2b61dad4e830884410cfc3695546682ced009e50583c8bb5c44512d7.yml diff --git a/CHANGELOG.md b/CHANGELOG.md index da1a4c27a4..53385512db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.24.1 (2024-04-30) + +Full Changelog: [v1.24.0...v1.24.1](https://github.com/openai/openai-python/compare/v1.24.0...v1.24.1) + +### Chores + +* **internal:** add link to openapi spec ([#1385](https://github.com/openai/openai-python/issues/1385)) ([b315d04](https://github.com/openai/openai-python/commit/b315d04e9624ec3a841d7c51813bb553640c23ce)) + ## 1.24.0 (2024-04-29) Full Changelog: [v1.23.6...v1.24.0](https://github.com/openai/openai-python/compare/v1.23.6...v1.24.0) diff --git a/pyproject.toml b/pyproject.toml index d1006b3b70..66fee29b6d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.24.0" +version = "1.24.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 5b3383adc3..346ec5ec8d 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.24.0" # x-release-please-version +__version__ = "1.24.1" # x-release-please-version From d2738d4259aa1c58e206ec23e388855fa218d3f9 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 1 May 2024 00:00:17 -0400 Subject: [PATCH 329/816] feat(api): delete messages (#1388) --- .github/workflows/ci.yml | 22 +++- .gitignore | 1 + .stats.yml | 4 +- Brewfile | 2 + api.md | 1 + bin/check-env-state.py | 40 ------- bin/check-test-server | 50 --------- bin/test | 3 - pyproject.toml | 3 +- scripts/bootstrap | 19 ++++ scripts/format | 8 ++ scripts/lint | 8 ++ scripts/mock | 41 +++++++ scripts/test | 57 ++++++++++ {bin => scripts/utils}/ruffen-docs.py | 0 src/openai/resources/batches.py | 12 +-- src/openai/resources/beta/threads/messages.py | 87 +++++++++++++++ src/openai/types/batch_create_params.py | 4 +- src/openai/types/beta/threads/__init__.py | 1 + .../types/beta/threads/message_deleted.py | 15 +++ .../types/fine_tuning/fine_tuning_job.py | 6 ++ .../beta/threads/test_messages.py | 101 +++++++++++++++++- 22 files changed, 379 insertions(+), 106 deletions(-) create mode 100644 Brewfile delete mode 100644 bin/check-env-state.py delete mode 100755 bin/check-test-server delete mode 100755 bin/test create mode 100755 scripts/bootstrap create mode 100755 scripts/format create mode 100755 scripts/lint create mode 100755 scripts/mock create mode 100755 scripts/test rename {bin => scripts/utils}/ruffen-docs.py (100%) create mode 100644 src/openai/types/beta/threads/message_deleted.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c44028d96c..9cbc077a8c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,5 +39,25 @@ jobs: - name: Ensure importable run: | rye run python -c 'import openai' + test: + name: test + runs-on: ubuntu-latest + if: github.repository == 'openai/openai-python' + + steps: + - uses: actions/checkout@v4 + + - name: Install Rye + run: | + curl -sSf https://rye-up.com/get | bash + echo "$HOME/.rye/shims" >> $GITHUB_PATH + env: + RYE_VERSION: 0.24.0 + RYE_INSTALL_OPTION: '--yes' + + - name: Bootstrap + run: ./scripts/bootstrap + + - name: Run tests + run: ./scripts/test - diff --git a/.gitignore b/.gitignore index a4b2f8c0bd..0f9a66a976 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,4 @@ dist .env .envrc codegen.log +Brewfile.lock.json diff --git a/.stats.yml b/.stats.yml index e904583dae..9797002bf7 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ -configured_endpoints: 63 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-0839c14b2b61dad4e830884410cfc3695546682ced009e50583c8bb5c44512d7.yml +configured_endpoints: 64 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-97c9a5f089049dc9eb5cee9475558049003e37e42202cab39e59d75e08b4c613.yml diff --git a/Brewfile b/Brewfile new file mode 100644 index 0000000000..492ca37bb0 --- /dev/null +++ b/Brewfile @@ -0,0 +1,2 @@ +brew "rye" + diff --git a/api.md b/api.md index 30247e8f7f..9dc42f0f0f 100644 --- a/api.md +++ b/api.md @@ -392,6 +392,7 @@ Methods: - client.beta.threads.messages.retrieve(message_id, \*, thread_id) -> Message - client.beta.threads.messages.update(message_id, \*, thread_id, \*\*params) -> Message - client.beta.threads.messages.list(thread_id, \*\*params) -> SyncCursorPage[Message] +- client.beta.threads.messages.delete(message_id, \*, thread_id) -> MessageDeleted # Batches diff --git a/bin/check-env-state.py b/bin/check-env-state.py deleted file mode 100644 index e1b8b6cb39..0000000000 --- a/bin/check-env-state.py +++ /dev/null @@ -1,40 +0,0 @@ -"""Script that exits 1 if the current environment is not -in sync with the `requirements-dev.lock` file. -""" - -from pathlib import Path - -import importlib_metadata - - -def should_run_sync() -> bool: - dev_lock = Path(__file__).parent.parent.joinpath("requirements-dev.lock") - - for line in dev_lock.read_text().splitlines(): - if not line or line.startswith("#") or line.startswith("-e"): - continue - - dep, lock_version = line.split("==") - - try: - version = importlib_metadata.version(dep) - - if lock_version != version: - print(f"mismatch for {dep} current={version} lock={lock_version}") - return True - except Exception: - print(f"could not import {dep}") - return True - - return False - - -def main() -> None: - if should_run_sync(): - exit(1) - else: - exit(0) - - -if __name__ == "__main__": - main() diff --git a/bin/check-test-server b/bin/check-test-server deleted file mode 100755 index a6fa34950d..0000000000 --- a/bin/check-test-server +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env bash - -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[0;33m' -NC='\033[0m' # No Color - -function prism_is_running() { - curl --silent "http://localhost:4010/" >/dev/null 2>&1 -} - -function is_overriding_api_base_url() { - [ -n "$TEST_API_BASE_URL" ] -} - -if is_overriding_api_base_url ; then - # If someone is running the tests against the live API, we can trust they know - # what they're doing and exit early. - echo -e "${GREEN}✔ Running tests against ${TEST_API_BASE_URL}${NC}" - - exit 0 -elif prism_is_running ; then - echo -e "${GREEN}✔ Mock prism server is running with your OpenAPI spec${NC}" - echo - - exit 0 -else - echo -e "${RED}ERROR:${NC} The test suite will not run without a mock Prism server" - echo -e "running against your OpenAPI spec." - echo - echo -e "${YELLOW}To fix:${NC}" - echo - echo -e "1. Install Prism (requires Node 16+):" - echo - echo -e " With npm:" - echo -e " \$ ${YELLOW}npm install -g @stoplight/prism-cli${NC}" - echo - echo -e " With yarn:" - echo -e " \$ ${YELLOW}yarn global add @stoplight/prism-cli${NC}" - echo - echo -e "2. Run the mock server" - echo - echo -e " To run the server, pass in the path of your OpenAPI" - echo -e " spec to the prism command:" - echo - echo -e " \$ ${YELLOW}prism mock path/to/your.openapi.yml${NC}" - echo - - exit 1 -fi diff --git a/bin/test b/bin/test deleted file mode 100755 index 60ede7a842..0000000000 --- a/bin/test +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env bash - -bin/check-test-server && rye run pytest "$@" diff --git a/pyproject.toml b/pyproject.toml index 66fee29b6d..10a756a22b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -74,7 +74,7 @@ format = { chain = [ "fix:ruff", ]} "format:black" = "black ." -"format:docs" = "python bin/ruffen-docs.py README.md api.md" +"format:docs" = "python scripts/utils/ruffen-docs.py README.md api.md" "format:ruff" = "ruff format" "format:isort" = "isort ." @@ -197,5 +197,6 @@ known-first-party = ["openai", "tests"] [tool.ruff.per-file-ignores] "bin/**.py" = ["T201", "T203"] +"scripts/**.py" = ["T201", "T203"] "tests/**.py" = ["T201", "T203"] "examples/**.py" = ["T201", "T203"] diff --git a/scripts/bootstrap b/scripts/bootstrap new file mode 100755 index 0000000000..29df07e77b --- /dev/null +++ b/scripts/bootstrap @@ -0,0 +1,19 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +if [ -f "Brewfile" ] && [ "$(uname -s)" = "Darwin" ]; then + brew bundle check >/dev/null 2>&1 || { + echo "==> Installing Homebrew dependencies…" + brew bundle + } +fi + +echo "==> Installing Python dependencies…" + +# experimental uv support makes installations significantly faster +rye config --set-bool behavior.use-uv=true + +rye sync diff --git a/scripts/format b/scripts/format new file mode 100755 index 0000000000..2a9ea4664b --- /dev/null +++ b/scripts/format @@ -0,0 +1,8 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +rye run format + diff --git a/scripts/lint b/scripts/lint new file mode 100755 index 0000000000..0cc68b5157 --- /dev/null +++ b/scripts/lint @@ -0,0 +1,8 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +rye run lint + diff --git a/scripts/mock b/scripts/mock new file mode 100755 index 0000000000..5a8c35b725 --- /dev/null +++ b/scripts/mock @@ -0,0 +1,41 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +if [[ -n "$1" && "$1" != '--'* ]]; then + URL="$1" + shift +else + URL="$(grep 'openapi_spec_url' .stats.yml | cut -d' ' -f2)" +fi + +# Check if the URL is empty +if [ -z "$URL" ]; then + echo "Error: No OpenAPI spec path/url provided or found in .stats.yml" + exit 1 +fi + +echo "==> Starting mock server with URL ${URL}" + +# Run prism mock on the given spec +if [ "$1" == "--daemon" ]; then + npm exec --package=@stoplight/prism-cli@~5.3.2 -- prism mock "$URL" &> .prism.log & + + # Wait for server to come online + echo -n "Waiting for server" + while ! grep -q "✖ fatal\|Prism is listening" ".prism.log" ; do + echo -n "." + sleep 0.1 + done + + if grep -q "✖ fatal" ".prism.log"; then + cat .prism.log + exit 1 + fi + + echo +else + npm exec --package=@stoplight/prism-cli@~5.3.2 -- prism mock "$URL" +fi diff --git a/scripts/test b/scripts/test new file mode 100755 index 0000000000..be01d04473 --- /dev/null +++ b/scripts/test @@ -0,0 +1,57 @@ +#!/usr/bin/env bash + +set -e + +cd "$(dirname "$0")/.." + +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[0;33m' +NC='\033[0m' # No Color + +function prism_is_running() { + curl --silent "http://localhost:4010/" >/dev/null 2>&1 +} + +kill_server_on_port() { + pids=$(lsof -t -i tcp:"$1" || echo "") + if [ "$pids" != "" ]; then + kill "$pids" + echo "Stopped $pids." + fi +} + +function is_overriding_api_base_url() { + [ -n "$TEST_API_BASE_URL" ] +} + +if ! is_overriding_api_base_url && ! prism_is_running ; then + # When we exit this script, make sure to kill the background mock server process + trap 'kill_server_on_port 4010' EXIT + + # Start the dev server + ./scripts/mock --daemon +fi + +if is_overriding_api_base_url ; then + echo -e "${GREEN}✔ Running tests against ${TEST_API_BASE_URL}${NC}" + echo +elif ! prism_is_running ; then + echo -e "${RED}ERROR:${NC} The test suite will not run without a mock Prism server" + echo -e "running against your OpenAPI spec." + echo + echo -e "To run the server, pass in the path or url of your OpenAPI" + echo -e "spec to the prism command:" + echo + echo -e " \$ ${YELLOW}npm exec --package=@stoplight/prism-cli@~5.3.2 -- prism mock path/to/your.openapi.yml${NC}" + echo + + exit 1 +else + echo -e "${GREEN}✔ Mock prism server is running with your OpenAPI spec${NC}" + echo +fi + +# Run tests +echo "==> Running tests" +rye run pytest "$@" diff --git a/bin/ruffen-docs.py b/scripts/utils/ruffen-docs.py similarity index 100% rename from bin/ruffen-docs.py rename to scripts/utils/ruffen-docs.py diff --git a/src/openai/resources/batches.py b/src/openai/resources/batches.py index a2a0272a7d..64a3014c37 100644 --- a/src/openai/resources/batches.py +++ b/src/openai/resources/batches.py @@ -40,7 +40,7 @@ def create( self, *, completion_window: Literal["24h"], - endpoint: Literal["/v1/chat/completions"], + endpoint: Literal["/v1/chat/completions", "/v1/embeddings"], input_file_id: str, metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -57,8 +57,8 @@ def create( completion_window: The time frame within which the batch should be processed. Currently only `24h` is supported. - endpoint: The endpoint to be used for all requests in the batch. Currently only - `/v1/chat/completions` is supported. + endpoint: The endpoint to be used for all requests in the batch. Currently + `/v1/chat/completions` and `/v1/embeddings` are supported. input_file_id: The ID of an uploaded file that contains requests for the new batch. @@ -228,7 +228,7 @@ async def create( self, *, completion_window: Literal["24h"], - endpoint: Literal["/v1/chat/completions"], + endpoint: Literal["/v1/chat/completions", "/v1/embeddings"], input_file_id: str, metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -245,8 +245,8 @@ async def create( completion_window: The time frame within which the batch should be processed. Currently only `24h` is supported. - endpoint: The endpoint to be used for all requests in the batch. Currently only - `/v1/chat/completions` is supported. + endpoint: The endpoint to be used for all requests in the batch. Currently + `/v1/chat/completions` and `/v1/embeddings` are supported. input_file_id: The ID of an uploaded file that contains requests for the new batch. diff --git a/src/openai/resources/beta/threads/messages.py b/src/openai/resources/beta/threads/messages.py index a938c5e15d..0799feed23 100644 --- a/src/openai/resources/beta/threads/messages.py +++ b/src/openai/resources/beta/threads/messages.py @@ -23,6 +23,7 @@ ) from ....types.beta.threads import message_list_params, message_create_params, message_update_params from ....types.beta.threads.message import Message +from ....types.beta.threads.message_deleted import MessageDeleted __all__ = ["Messages", "AsyncMessages"] @@ -252,6 +253,43 @@ def list( model=Message, ) + def delete( + self, + message_id: str, + *, + thread_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> MessageDeleted: + """ + Deletes a message. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + if not message_id: + raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return self._delete( + f"/threads/{thread_id}/messages/{message_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=MessageDeleted, + ) + class AsyncMessages(AsyncAPIResource): @cached_property @@ -478,6 +516,43 @@ def list( model=Message, ) + async def delete( + self, + message_id: str, + *, + thread_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> MessageDeleted: + """ + Deletes a message. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not thread_id: + raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") + if not message_id: + raise ValueError(f"Expected a non-empty value for `message_id` but received {message_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return await self._delete( + f"/threads/{thread_id}/messages/{message_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=MessageDeleted, + ) + class MessagesWithRawResponse: def __init__(self, messages: Messages) -> None: @@ -495,6 +570,9 @@ def __init__(self, messages: Messages) -> None: self.list = _legacy_response.to_raw_response_wrapper( messages.list, ) + self.delete = _legacy_response.to_raw_response_wrapper( + messages.delete, + ) class AsyncMessagesWithRawResponse: @@ -513,6 +591,9 @@ def __init__(self, messages: AsyncMessages) -> None: self.list = _legacy_response.async_to_raw_response_wrapper( messages.list, ) + self.delete = _legacy_response.async_to_raw_response_wrapper( + messages.delete, + ) class MessagesWithStreamingResponse: @@ -531,6 +612,9 @@ def __init__(self, messages: Messages) -> None: self.list = to_streamed_response_wrapper( messages.list, ) + self.delete = to_streamed_response_wrapper( + messages.delete, + ) class AsyncMessagesWithStreamingResponse: @@ -549,3 +633,6 @@ def __init__(self, messages: AsyncMessages) -> None: self.list = async_to_streamed_response_wrapper( messages.list, ) + self.delete = async_to_streamed_response_wrapper( + messages.delete, + ) diff --git a/src/openai/types/batch_create_params.py b/src/openai/types/batch_create_params.py index a67aaa1e5e..63b4fae91b 100644 --- a/src/openai/types/batch_create_params.py +++ b/src/openai/types/batch_create_params.py @@ -15,10 +15,10 @@ class BatchCreateParams(TypedDict, total=False): Currently only `24h` is supported. """ - endpoint: Required[Literal["/v1/chat/completions"]] + endpoint: Required[Literal["/v1/chat/completions", "/v1/embeddings"]] """The endpoint to be used for all requests in the batch. - Currently only `/v1/chat/completions` is supported. + Currently `/v1/chat/completions` and `/v1/embeddings` are supported. """ input_file_id: Required[str] diff --git a/src/openai/types/beta/threads/__init__.py b/src/openai/types/beta/threads/__init__.py index b57ebccb3a..1e38d5eaa1 100644 --- a/src/openai/types/beta/threads/__init__.py +++ b/src/openai/types/beta/threads/__init__.py @@ -11,6 +11,7 @@ from .text_delta import TextDelta as TextDelta from .message_delta import MessageDelta as MessageDelta from .message_content import MessageContent as MessageContent +from .message_deleted import MessageDeleted as MessageDeleted from .run_list_params import RunListParams as RunListParams from .annotation_delta import AnnotationDelta as AnnotationDelta from .image_file_delta import ImageFileDelta as ImageFileDelta diff --git a/src/openai/types/beta/threads/message_deleted.py b/src/openai/types/beta/threads/message_deleted.py new file mode 100644 index 0000000000..48210777fa --- /dev/null +++ b/src/openai/types/beta/threads/message_deleted.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["MessageDeleted"] + + +class MessageDeleted(BaseModel): + id: str + + deleted: bool + + object: Literal["thread.message.deleted"] diff --git a/src/openai/types/fine_tuning/fine_tuning_job.py b/src/openai/types/fine_tuning/fine_tuning_job.py index 1593bf50c7..7ac8792787 100644 --- a/src/openai/types/fine_tuning/fine_tuning_job.py +++ b/src/openai/types/fine_tuning/fine_tuning_job.py @@ -110,5 +110,11 @@ class FineTuningJob(BaseModel): [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). """ + estimated_finish: Optional[int] = None + """ + The Unix timestamp (in seconds) for when the fine-tuning job is estimated to + finish. The value will be null if the fine-tuning job is not running. + """ + integrations: Optional[List[FineTuningJobWandbIntegrationObject]] = None """A list of integrations to enable for this fine-tuning job.""" diff --git a/tests/api_resources/beta/threads/test_messages.py b/tests/api_resources/beta/threads/test_messages.py index 26eb09acdd..fb42d509a1 100644 --- a/tests/api_resources/beta/threads/test_messages.py +++ b/tests/api_resources/beta/threads/test_messages.py @@ -10,7 +10,10 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta.threads import Message +from openai.types.beta.threads import ( + Message, + MessageDeleted, +) base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") @@ -243,6 +246,54 @@ def test_path_params_list(self, client: OpenAI) -> None: "", ) + @parametrize + def test_method_delete(self, client: OpenAI) -> None: + message = client.beta.threads.messages.delete( + "string", + thread_id="string", + ) + assert_matches_type(MessageDeleted, message, path=["response"]) + + @parametrize + def test_raw_response_delete(self, client: OpenAI) -> None: + response = client.beta.threads.messages.with_raw_response.delete( + "string", + thread_id="string", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + message = response.parse() + assert_matches_type(MessageDeleted, message, path=["response"]) + + @parametrize + def test_streaming_response_delete(self, client: OpenAI) -> None: + with client.beta.threads.messages.with_streaming_response.delete( + "string", + thread_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + message = response.parse() + assert_matches_type(MessageDeleted, message, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_delete(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + client.beta.threads.messages.with_raw_response.delete( + "string", + thread_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): + client.beta.threads.messages.with_raw_response.delete( + "", + thread_id="string", + ) + class TestAsyncMessages: parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) @@ -471,3 +522,51 @@ async def test_path_params_list(self, async_client: AsyncOpenAI) -> None: await async_client.beta.threads.messages.with_raw_response.list( "", ) + + @parametrize + async def test_method_delete(self, async_client: AsyncOpenAI) -> None: + message = await async_client.beta.threads.messages.delete( + "string", + thread_id="string", + ) + assert_matches_type(MessageDeleted, message, path=["response"]) + + @parametrize + async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.threads.messages.with_raw_response.delete( + "string", + thread_id="string", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + message = response.parse() + assert_matches_type(MessageDeleted, message, path=["response"]) + + @parametrize + async def test_streaming_response_delete(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.threads.messages.with_streaming_response.delete( + "string", + thread_id="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + message = await response.parse() + assert_matches_type(MessageDeleted, message, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_delete(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): + await async_client.beta.threads.messages.with_raw_response.delete( + "string", + thread_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `message_id` but received ''"): + await async_client.beta.threads.messages.with_raw_response.delete( + "", + thread_id="string", + ) From ec52e89ccd87744fb38e2ae785ed7013241e476a Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 1 May 2024 00:00:46 -0400 Subject: [PATCH 330/816] release: 1.25.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 347a18e529..0c0c0c3576 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.24.1" + ".": "1.25.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 53385512db..c71e1c89ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.25.0 (2024-05-01) + +Full Changelog: [v1.24.1...v1.25.0](https://github.com/openai/openai-python/compare/v1.24.1...v1.25.0) + +### Features + +* **api:** delete messages ([#1388](https://github.com/openai/openai-python/issues/1388)) ([d0597cd](https://github.com/openai/openai-python/commit/d0597cdc1813cddffacbaa50565e86d2420d1873)) + ## 1.24.1 (2024-04-30) Full Changelog: [v1.24.0...v1.24.1](https://github.com/openai/openai-python/compare/v1.24.0...v1.24.1) diff --git a/pyproject.toml b/pyproject.toml index 10a756a22b..ffc98fd2ef 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.24.1" +version = "1.25.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 346ec5ec8d..8326c22065 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.24.1" # x-release-please-version +__version__ = "1.25.0" # x-release-please-version From aed1e43745cd6358b4bafd3a39b3dfeee5e31a03 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 2 May 2024 11:51:34 -0400 Subject: [PATCH 331/816] release: 1.25.1 (#1391) * chore(internal): bump prism version (#1390) * release: 1.25.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- scripts/mock | 4 ++-- src/openai/_version.py | 2 +- 5 files changed, 13 insertions(+), 5 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 0c0c0c3576..f5cfbcb39d 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.25.0" + ".": "1.25.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index c71e1c89ff..3920956dde 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.25.1 (2024-05-02) + +Full Changelog: [v1.25.0...v1.25.1](https://github.com/openai/openai-python/compare/v1.25.0...v1.25.1) + +### Chores + +* **internal:** bump prism version ([#1390](https://github.com/openai/openai-python/issues/1390)) ([a5830fc](https://github.com/openai/openai-python/commit/a5830fc1c5ffd21e2010490905084ad5614212a3)) + ## 1.25.0 (2024-05-01) Full Changelog: [v1.24.1...v1.25.0](https://github.com/openai/openai-python/compare/v1.24.1...v1.25.0) diff --git a/pyproject.toml b/pyproject.toml index ffc98fd2ef..8480f27440 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.25.0" +version = "1.25.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/scripts/mock b/scripts/mock index 5a8c35b725..fe89a1d084 100755 --- a/scripts/mock +++ b/scripts/mock @@ -21,7 +21,7 @@ echo "==> Starting mock server with URL ${URL}" # Run prism mock on the given spec if [ "$1" == "--daemon" ]; then - npm exec --package=@stoplight/prism-cli@~5.3.2 -- prism mock "$URL" &> .prism.log & + npm exec --package=@stoplight/prism-cli@~5.8 -- prism mock "$URL" &> .prism.log & # Wait for server to come online echo -n "Waiting for server" @@ -37,5 +37,5 @@ if [ "$1" == "--daemon" ]; then echo else - npm exec --package=@stoplight/prism-cli@~5.3.2 -- prism mock "$URL" + npm exec --package=@stoplight/prism-cli@~5.8 -- prism mock "$URL" fi diff --git a/src/openai/_version.py b/src/openai/_version.py index 8326c22065..30fa8f2070 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.25.0" # x-release-please-version +__version__ = "1.25.1" # x-release-please-version From 2a678e30a6fdc37d9c944288a8186c8ad4b4b053 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Sun, 5 May 2024 21:00:00 +0100 Subject: [PATCH 332/816] release: 1.25.2 (#1394) --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ README.md | 2 +- pyproject.toml | 2 +- src/openai/_version.py | 2 +- 5 files changed, 12 insertions(+), 4 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index f5cfbcb39d..6994d4cb49 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.25.1" + ".": "1.25.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 3920956dde..3fa4fc4dc1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.25.2 (2024-05-05) + +Full Changelog: [v1.25.1...v1.25.2](https://github.com/openai/openai-python/compare/v1.25.1...v1.25.2) + +### Documentation + +* **readme:** fix misleading timeout example value ([#1393](https://github.com/openai/openai-python/issues/1393)) ([3eba8e7](https://github.com/openai/openai-python/commit/3eba8e7573ec1bf4231a304c8eabc8a8d077f46d)) + ## 1.25.1 (2024-05-02) Full Changelog: [v1.25.0...v1.25.1](https://github.com/openai/openai-python/compare/v1.25.0...v1.25.1) diff --git a/README.md b/README.md index b8a0d9b0cb..e566a2f8d0 100644 --- a/README.md +++ b/README.md @@ -424,7 +424,7 @@ client = OpenAI( ) # Override per-request: -client.with_options(timeout=5 * 1000).chat.completions.create( +client.with_options(timeout=5.0).chat.completions.create( messages=[ { "role": "user", diff --git a/pyproject.toml b/pyproject.toml index 8480f27440..de0eb72023 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.25.1" +version = "1.25.2" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 30fa8f2070..c4c92f77ad 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.25.1" # x-release-please-version +__version__ = "1.25.2" # x-release-please-version From 6cc515874f5f4b26b35f408d6afc3c14b4dfe3b0 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 6 May 2024 15:07:30 -0400 Subject: [PATCH 333/816] feat(api): add usage metadata when streaming (#1395) --- .stats.yml | 2 +- api.md | 1 + src/openai/resources/chat/completions.py | 23 +++++++++++++++++++ src/openai/resources/completions.py | 23 +++++++++++++++++++ src/openai/types/chat/__init__.py | 1 + .../types/chat/chat_completion_chunk.py | 12 +++++++++- .../chat_completion_stream_options_param.py | 17 ++++++++++++++ .../types/chat/completion_create_params.py | 4 ++++ src/openai/types/completion_create_params.py | 5 ++++ tests/api_resources/chat/test_completions.py | 8 ++++++- tests/api_resources/test_completions.py | 4 ++++ 11 files changed, 97 insertions(+), 3 deletions(-) create mode 100644 src/openai/types/chat/chat_completion_stream_options_param.py diff --git a/.stats.yml b/.stats.yml index 9797002bf7..49956282b7 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 64 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-97c9a5f089049dc9eb5cee9475558049003e37e42202cab39e59d75e08b4c613.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-edb5af3ade0cd27cf366b0654b90c7a81c43c433e11fc3f6e621e2c779de10d4.yml diff --git a/api.md b/api.md index 9dc42f0f0f..696075eff3 100644 --- a/api.md +++ b/api.md @@ -43,6 +43,7 @@ from openai.types.chat import ( ChatCompletionMessageToolCall, ChatCompletionNamedToolChoice, ChatCompletionRole, + ChatCompletionStreamOptions, ChatCompletionSystemMessageParam, ChatCompletionTokenLogprob, ChatCompletionTool, diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index 5104cd6136..aa25bc1858 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -27,6 +27,7 @@ from ...types.chat.chat_completion_chunk import ChatCompletionChunk from ...types.chat.chat_completion_tool_param import ChatCompletionToolParam from ...types.chat.chat_completion_message_param import ChatCompletionMessageParam +from ...types.chat.chat_completion_stream_options_param import ChatCompletionStreamOptionsParam from ...types.chat.chat_completion_tool_choice_option_param import ChatCompletionToolChoiceOptionParam __all__ = ["Completions", "AsyncCompletions"] @@ -59,6 +60,7 @@ def create( seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, + stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, @@ -165,6 +167,8 @@ def create( message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + stream_options: Options for streaming response. Only set this when you set `stream: true`. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. @@ -227,6 +231,7 @@ def create( response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, @@ -333,6 +338,8 @@ def create( stop: Up to 4 sequences where the API will stop generating further tokens. + stream_options: Options for streaming response. Only set this when you set `stream: true`. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. @@ -395,6 +402,7 @@ def create( response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, @@ -501,6 +509,8 @@ def create( stop: Up to 4 sequences where the API will stop generating further tokens. + stream_options: Options for streaming response. Only set this when you set `stream: true`. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. @@ -563,6 +573,7 @@ def create( seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, @@ -594,6 +605,7 @@ def create( "seed": seed, "stop": stop, "stream": stream, + "stream_options": stream_options, "temperature": temperature, "tool_choice": tool_choice, "tools": tools, @@ -639,6 +651,7 @@ async def create( seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, + stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, @@ -745,6 +758,8 @@ async def create( message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + stream_options: Options for streaming response. Only set this when you set `stream: true`. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. @@ -807,6 +822,7 @@ async def create( response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, @@ -913,6 +929,8 @@ async def create( stop: Up to 4 sequences where the API will stop generating further tokens. + stream_options: Options for streaming response. Only set this when you set `stream: true`. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. @@ -975,6 +993,7 @@ async def create( response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, @@ -1081,6 +1100,8 @@ async def create( stop: Up to 4 sequences where the API will stop generating further tokens. + stream_options: Options for streaming response. Only set this when you set `stream: true`. + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. @@ -1143,6 +1164,7 @@ async def create( seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, @@ -1174,6 +1196,7 @@ async def create( "seed": seed, "stop": stop, "stream": stream, + "stream_options": stream_options, "temperature": temperature, "tool_choice": tool_choice, "tools": tools, diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index eb6ca31048..0812000f78 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -23,6 +23,7 @@ make_request_options, ) from ..types.completion import Completion +from ..types.chat.chat_completion_stream_options_param import ChatCompletionStreamOptionsParam __all__ = ["Completions", "AsyncCompletions"] @@ -53,6 +54,7 @@ def create( seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, + stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, suffix: Optional[str] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, @@ -156,6 +158,8 @@ def create( message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + stream_options: Options for streaming response. Only set this when you set `stream: true`. + suffix: The suffix that comes after a completion of inserted text. This parameter is only supported for `gpt-3.5-turbo-instruct`. @@ -203,6 +207,7 @@ def create( presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, + stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, suffix: Optional[str] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, @@ -306,6 +311,8 @@ def create( stop: Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. + stream_options: Options for streaming response. Only set this when you set `stream: true`. + suffix: The suffix that comes after a completion of inserted text. This parameter is only supported for `gpt-3.5-turbo-instruct`. @@ -353,6 +360,7 @@ def create( presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, + stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, suffix: Optional[str] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, @@ -456,6 +464,8 @@ def create( stop: Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. + stream_options: Options for streaming response. Only set this when you set `stream: true`. + suffix: The suffix that comes after a completion of inserted text. This parameter is only supported for `gpt-3.5-turbo-instruct`. @@ -503,6 +513,7 @@ def create( seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, suffix: Optional[str] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, @@ -531,6 +542,7 @@ def create( "seed": seed, "stop": stop, "stream": stream, + "stream_options": stream_options, "suffix": suffix, "temperature": temperature, "top_p": top_p, @@ -573,6 +585,7 @@ async def create( seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, + stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, suffix: Optional[str] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, @@ -676,6 +689,8 @@ async def create( message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + stream_options: Options for streaming response. Only set this when you set `stream: true`. + suffix: The suffix that comes after a completion of inserted text. This parameter is only supported for `gpt-3.5-turbo-instruct`. @@ -723,6 +738,7 @@ async def create( presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, + stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, suffix: Optional[str] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, @@ -826,6 +842,8 @@ async def create( stop: Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. + stream_options: Options for streaming response. Only set this when you set `stream: true`. + suffix: The suffix that comes after a completion of inserted text. This parameter is only supported for `gpt-3.5-turbo-instruct`. @@ -873,6 +891,7 @@ async def create( presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, + stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, suffix: Optional[str] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, @@ -976,6 +995,8 @@ async def create( stop: Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. + stream_options: Options for streaming response. Only set this when you set `stream: true`. + suffix: The suffix that comes after a completion of inserted text. This parameter is only supported for `gpt-3.5-turbo-instruct`. @@ -1023,6 +1044,7 @@ async def create( seed: Optional[int] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, suffix: Optional[str] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, @@ -1051,6 +1073,7 @@ async def create( "seed": seed, "stop": stop, "stream": stream, + "stream_options": stream_options, "suffix": suffix, "temperature": temperature, "top_p": top_p, diff --git a/src/openai/types/chat/__init__.py b/src/openai/types/chat/__init__.py index 5d122d2020..0ba812ff9b 100644 --- a/src/openai/types/chat/__init__.py +++ b/src/openai/types/chat/__init__.py @@ -14,6 +14,7 @@ from .chat_completion_content_part_param import ChatCompletionContentPartParam as ChatCompletionContentPartParam from .chat_completion_tool_message_param import ChatCompletionToolMessageParam as ChatCompletionToolMessageParam from .chat_completion_user_message_param import ChatCompletionUserMessageParam as ChatCompletionUserMessageParam +from .chat_completion_stream_options_param import ChatCompletionStreamOptionsParam as ChatCompletionStreamOptionsParam from .chat_completion_system_message_param import ChatCompletionSystemMessageParam as ChatCompletionSystemMessageParam from .chat_completion_function_message_param import ( ChatCompletionFunctionMessageParam as ChatCompletionFunctionMessageParam, diff --git a/src/openai/types/chat/chat_completion_chunk.py b/src/openai/types/chat/chat_completion_chunk.py index c2f18bcb74..084a5fcc07 100644 --- a/src/openai/types/chat/chat_completion_chunk.py +++ b/src/openai/types/chat/chat_completion_chunk.py @@ -4,6 +4,7 @@ from typing_extensions import Literal from ..._models import BaseModel +from ..completion_usage import CompletionUsage from .chat_completion_token_logprob import ChatCompletionTokenLogprob __all__ = [ @@ -105,7 +106,8 @@ class ChatCompletionChunk(BaseModel): choices: List[Choice] """A list of chat completion choices. - Can be more than one if `n` is greater than 1. + Can contain more than one elements if `n` is greater than 1. Can also be empty + for the last chunk if you set `stream_options: {"include_usage": true}`. """ created: int @@ -126,3 +128,11 @@ class ChatCompletionChunk(BaseModel): Can be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism. """ + + usage: Optional[CompletionUsage] = None + """ + An optional field that will only be present when you set + `stream_options: {"include_usage": true}` in your request. When present, it + contains a null value except for the last chunk which contains the token usage + statistics for the entire request. + """ diff --git a/src/openai/types/chat/chat_completion_stream_options_param.py b/src/openai/types/chat/chat_completion_stream_options_param.py new file mode 100644 index 0000000000..fbf7291821 --- /dev/null +++ b/src/openai/types/chat/chat_completion_stream_options_param.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["ChatCompletionStreamOptionsParam"] + + +class ChatCompletionStreamOptionsParam(TypedDict, total=False): + include_usage: bool + """If set, an additional chunk will be streamed before the `data: [DONE]` message. + + The `usage` field on this chunk shows the token usage statistics for the entire + request, and the `choices` field will always be an empty array. All other chunks + will also include a `usage` field, but with a null value. + """ diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index d30da60b16..226cf15882 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -9,6 +9,7 @@ from ..chat_model import ChatModel from .chat_completion_tool_param import ChatCompletionToolParam from .chat_completion_message_param import ChatCompletionMessageParam +from .chat_completion_stream_options_param import ChatCompletionStreamOptionsParam from .chat_completion_tool_choice_option_param import ChatCompletionToolChoiceOptionParam from .chat_completion_function_call_option_param import ChatCompletionFunctionCallOptionParam @@ -141,6 +142,9 @@ class CompletionCreateParamsBase(TypedDict, total=False): stop: Union[Optional[str], List[str]] """Up to 4 sequences where the API will stop generating further tokens.""" + stream_options: Optional[ChatCompletionStreamOptionsParam] + """Options for streaming response. Only set this when you set `stream: true`.""" + temperature: Optional[float] """What sampling temperature to use, between 0 and 2. diff --git a/src/openai/types/completion_create_params.py b/src/openai/types/completion_create_params.py index 36267e9061..9fe22fe3c9 100644 --- a/src/openai/types/completion_create_params.py +++ b/src/openai/types/completion_create_params.py @@ -5,6 +5,8 @@ from typing import Dict, List, Union, Iterable, Optional from typing_extensions import Literal, Required, TypedDict +from .chat.chat_completion_stream_options_param import ChatCompletionStreamOptionsParam + __all__ = ["CompletionCreateParamsBase", "CompletionCreateParamsNonStreaming", "CompletionCreateParamsStreaming"] @@ -123,6 +125,9 @@ class CompletionCreateParamsBase(TypedDict, total=False): The returned text will not contain the stop sequence. """ + stream_options: Optional[ChatCompletionStreamOptionsParam] + """Options for streaming response. Only set this when you set `stream: true`.""" + suffix: Optional[str] """The suffix that comes after a completion of inserted text. diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index c54b56a37d..1c195c4001 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -9,7 +9,9 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai.types.chat import ChatCompletion +from openai.types.chat import ( + ChatCompletion, +) base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") @@ -59,6 +61,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: seed=-9223372036854776000, stop="string", stream=False, + stream_options={"include_usage": True}, temperature=1, tool_choice="none", tools=[ @@ -172,6 +175,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: response_format={"type": "json_object"}, seed=-9223372036854776000, stop="string", + stream_options={"include_usage": True}, temperature=1, tool_choice="none", tools=[ @@ -289,6 +293,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn seed=-9223372036854776000, stop="string", stream=False, + stream_options={"include_usage": True}, temperature=1, tool_choice="none", tools=[ @@ -402,6 +407,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn response_format={"type": "json_object"}, seed=-9223372036854776000, stop="string", + stream_options={"include_usage": True}, temperature=1, tool_choice="none", tools=[ diff --git a/tests/api_resources/test_completions.py b/tests/api_resources/test_completions.py index 691c4ff77f..69d914200f 100644 --- a/tests/api_resources/test_completions.py +++ b/tests/api_resources/test_completions.py @@ -41,6 +41,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: seed=-9223372036854776000, stop="\n", stream=False, + stream_options={"include_usage": True}, suffix="test.", temperature=1, top_p=1, @@ -99,6 +100,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: presence_penalty=-2, seed=-9223372036854776000, stop="\n", + stream_options={"include_usage": True}, suffix="test.", temperature=1, top_p=1, @@ -161,6 +163,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn seed=-9223372036854776000, stop="\n", stream=False, + stream_options={"include_usage": True}, suffix="test.", temperature=1, top_p=1, @@ -219,6 +222,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn presence_penalty=-2, seed=-9223372036854776000, stop="\n", + stream_options={"include_usage": True}, suffix="test.", temperature=1, top_p=1, From 89478ce06e2161fda416c685b774a97a041ae185 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 6 May 2024 15:07:59 -0400 Subject: [PATCH 334/816] release: 1.26.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 6994d4cb49..f3dbfd2ad2 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.25.2" + ".": "1.26.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 3fa4fc4dc1..37dacdd9a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.26.0 (2024-05-06) + +Full Changelog: [v1.25.2...v1.26.0](https://github.com/openai/openai-python/compare/v1.25.2...v1.26.0) + +### Features + +* **api:** add usage metadata when streaming ([#1395](https://github.com/openai/openai-python/issues/1395)) ([3cb064b](https://github.com/openai/openai-python/commit/3cb064b10d661dbcc74b6bc1ed7d8e635ab2876a)) + ## 1.25.2 (2024-05-05) Full Changelog: [v1.25.1...v1.25.2](https://github.com/openai/openai-python/compare/v1.25.1...v1.25.2) diff --git a/pyproject.toml b/pyproject.toml index de0eb72023..bdaccf4068 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.25.2" +version = "1.26.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index c4c92f77ad..49495e5c24 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.25.2" # x-release-please-version +__version__ = "1.26.0" # x-release-please-version From c4a1dbc265ba78246e0e412a9c3e4981158c9bba Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 8 May 2024 16:11:15 -0400 Subject: [PATCH 335/816] feat(api): adding file purposes (#1401) --- .stats.yml | 2 +- src/openai/resources/files.py | 22 ++++++++++------------ src/openai/types/file_create_params.py | 11 +++++------ src/openai/types/file_object.py | 6 +++--- tests/api_resources/test_files.py | 12 ++++++------ 5 files changed, 25 insertions(+), 28 deletions(-) diff --git a/.stats.yml b/.stats.yml index 49956282b7..50c6b293dd 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 64 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-edb5af3ade0cd27cf366b0654b90c7a81c43c433e11fc3f6e621e2c779de10d4.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-2e14236d4015bf3b956290ea8b656224a0c7b206a356c6af2a7ae43fdbceb04c.yml diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index fa03a9c0e2..086745b470 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -52,7 +52,7 @@ def create( self, *, file: FileTypes, - purpose: Literal["fine-tune", "assistants"], + purpose: Literal["assistants", "batch", "fine-tune"], # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -79,12 +79,11 @@ def create( purpose: The intended purpose of the uploaded file. - Use "fine-tune" for - [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning) and - "assistants" for + Use "assistants" for [Assistants](https://platform.openai.com/docs/api-reference/assistants) and - [Messages](https://platform.openai.com/docs/api-reference/messages). This allows - us to validate the format of the uploaded file is correct for fine-tuning. + [Messages](https://platform.openai.com/docs/api-reference/messages), "batch" for + [Batch API](https://platform.openai.com/docs/guides/batch), and "fine-tune" for + [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning). extra_headers: Send extra headers @@ -325,7 +324,7 @@ async def create( self, *, file: FileTypes, - purpose: Literal["fine-tune", "assistants"], + purpose: Literal["assistants", "batch", "fine-tune"], # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -352,12 +351,11 @@ async def create( purpose: The intended purpose of the uploaded file. - Use "fine-tune" for - [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning) and - "assistants" for + Use "assistants" for [Assistants](https://platform.openai.com/docs/api-reference/assistants) and - [Messages](https://platform.openai.com/docs/api-reference/messages). This allows - us to validate the format of the uploaded file is correct for fine-tuning. + [Messages](https://platform.openai.com/docs/api-reference/messages), "batch" for + [Batch API](https://platform.openai.com/docs/guides/batch), and "fine-tune" for + [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning). extra_headers: Send extra headers diff --git a/src/openai/types/file_create_params.py b/src/openai/types/file_create_params.py index 26e2da3372..3867fcb06e 100644 --- a/src/openai/types/file_create_params.py +++ b/src/openai/types/file_create_params.py @@ -13,13 +13,12 @@ class FileCreateParams(TypedDict, total=False): file: Required[FileTypes] """The File object (not file name) to be uploaded.""" - purpose: Required[Literal["fine-tune", "assistants"]] + purpose: Required[Literal["assistants", "batch", "fine-tune"]] """The intended purpose of the uploaded file. - Use "fine-tune" for - [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning) and - "assistants" for + Use "assistants" for [Assistants](https://platform.openai.com/docs/api-reference/assistants) and - [Messages](https://platform.openai.com/docs/api-reference/messages). This allows - us to validate the format of the uploaded file is correct for fine-tuning. + [Messages](https://platform.openai.com/docs/api-reference/messages), "batch" for + [Batch API](https://platform.openai.com/docs/guides/batch), and "fine-tune" for + [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning). """ diff --git a/src/openai/types/file_object.py b/src/openai/types/file_object.py index 589a1faf38..d24a5b1a8d 100644 --- a/src/openai/types/file_object.py +++ b/src/openai/types/file_object.py @@ -24,11 +24,11 @@ class FileObject(BaseModel): object: Literal["file"] """The object type, which is always `file`.""" - purpose: Literal["fine-tune", "fine-tune-results", "assistants", "assistants_output"] + purpose: Literal["assistants", "assistants_output", "batch", "batch_output", "fine-tune", "fine-tune-results"] """The intended purpose of the file. - Supported values are `fine-tune`, `fine-tune-results`, `assistants`, and - `assistants_output`. + Supported values are `assistants`, `assistants_output`, `batch`, `batch_output`, + `fine-tune`, and `fine-tune-results`. """ status: Literal["uploaded", "processed", "error"] diff --git a/tests/api_resources/test_files.py b/tests/api_resources/test_files.py index e5466e9eda..882f0ddbe7 100644 --- a/tests/api_resources/test_files.py +++ b/tests/api_resources/test_files.py @@ -27,7 +27,7 @@ class TestFiles: def test_method_create(self, client: OpenAI) -> None: file = client.files.create( file=b"raw file contents", - purpose="fine-tune", + purpose="assistants", ) assert_matches_type(FileObject, file, path=["response"]) @@ -35,7 +35,7 @@ def test_method_create(self, client: OpenAI) -> None: def test_raw_response_create(self, client: OpenAI) -> None: response = client.files.with_raw_response.create( file=b"raw file contents", - purpose="fine-tune", + purpose="assistants", ) assert response.is_closed is True @@ -47,7 +47,7 @@ def test_raw_response_create(self, client: OpenAI) -> None: def test_streaming_response_create(self, client: OpenAI) -> None: with client.files.with_streaming_response.create( file=b"raw file contents", - purpose="fine-tune", + purpose="assistants", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -263,7 +263,7 @@ class TestAsyncFiles: async def test_method_create(self, async_client: AsyncOpenAI) -> None: file = await async_client.files.create( file=b"raw file contents", - purpose="fine-tune", + purpose="assistants", ) assert_matches_type(FileObject, file, path=["response"]) @@ -271,7 +271,7 @@ async def test_method_create(self, async_client: AsyncOpenAI) -> None: async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: response = await async_client.files.with_raw_response.create( file=b"raw file contents", - purpose="fine-tune", + purpose="assistants", ) assert response.is_closed is True @@ -283,7 +283,7 @@ async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: async with async_client.files.with_streaming_response.create( file=b"raw file contents", - purpose="fine-tune", + purpose="assistants", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" From 064a34a70b108093efea4c05c51279e217e58afd Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 8 May 2024 16:11:44 -0400 Subject: [PATCH 336/816] release: 1.27.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index f3dbfd2ad2..4eb89879b8 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.26.0" + ".": "1.27.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 37dacdd9a5..3d451d36f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.27.0 (2024-05-08) + +Full Changelog: [v1.26.0...v1.27.0](https://github.com/openai/openai-python/compare/v1.26.0...v1.27.0) + +### Features + +* **api:** adding file purposes ([#1401](https://github.com/openai/openai-python/issues/1401)) ([2e9d0bd](https://github.com/openai/openai-python/commit/2e9d0bd0e4bf677ed9b21c6448e804313e026441)) + ## 1.26.0 (2024-05-06) Full Changelog: [v1.25.2...v1.26.0](https://github.com/openai/openai-python/compare/v1.25.2...v1.26.0) diff --git a/pyproject.toml b/pyproject.toml index bdaccf4068..81d7e75746 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.26.0" +version = "1.27.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 49495e5c24..4a8c619a1a 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.26.0" # x-release-please-version +__version__ = "1.27.0" # x-release-please-version From 79a0b401537c5b1eef0d91487ba5fb37b01e3d5a Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 9 May 2024 16:19:42 -0400 Subject: [PATCH 337/816] feat(api): add message image content (#1405) --- .stats.yml | 2 +- api.md | 6 ++++ src/openai/resources/beta/threads/messages.py | 11 +++--- src/openai/resources/files.py | 6 ++-- .../beta/thread_create_and_run_params.py | 5 +-- src/openai/types/beta/thread_create_params.py | 5 +-- src/openai/types/beta/threads/__init__.py | 10 ++++++ src/openai/types/beta/threads/image_file.py | 12 +++++-- .../threads/image_file_content_block_param.py | 16 +++++++++ .../types/beta/threads/image_file_delta.py | 10 +++++- .../types/beta/threads/image_file_param.py | 22 ++++++++++++ src/openai/types/beta/threads/image_url.py | 23 ++++++++++++ .../beta/threads/image_url_content_block.py | 15 ++++++++ .../threads/image_url_content_block_param.py | 16 +++++++++ .../types/beta/threads/image_url_delta.py | 22 ++++++++++++ .../beta/threads/image_url_delta_block.py | 19 ++++++++++ .../types/beta/threads/image_url_param.py | 22 ++++++++++++ .../types/beta/threads/message_content.py | 5 ++- .../beta/threads/message_content_delta.py | 5 ++- .../threads/message_content_part_param.py | 13 +++++++ .../beta/threads/message_create_params.py | 5 +-- .../types/beta/threads/run_create_params.py | 5 +-- .../beta/threads/text_content_block_param.py | 15 ++++++++ src/openai/types/file_create_params.py | 3 +- src/openai/types/file_object.py | 6 ++-- tests/api_resources/beta/test_threads.py | 36 +++++++++---------- .../beta/threads/test_messages.py | 20 +++++------ tests/api_resources/beta/threads/test_runs.py | 24 ++++++------- 28 files changed, 295 insertions(+), 64 deletions(-) create mode 100644 src/openai/types/beta/threads/image_file_content_block_param.py create mode 100644 src/openai/types/beta/threads/image_file_param.py create mode 100644 src/openai/types/beta/threads/image_url.py create mode 100644 src/openai/types/beta/threads/image_url_content_block.py create mode 100644 src/openai/types/beta/threads/image_url_content_block_param.py create mode 100644 src/openai/types/beta/threads/image_url_delta.py create mode 100644 src/openai/types/beta/threads/image_url_delta_block.py create mode 100644 src/openai/types/beta/threads/image_url_param.py create mode 100644 src/openai/types/beta/threads/message_content_part_param.py create mode 100644 src/openai/types/beta/threads/text_content_block_param.py diff --git a/.stats.yml b/.stats.yml index 50c6b293dd..52e87d1b58 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 64 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-2e14236d4015bf3b956290ea8b656224a0c7b206a356c6af2a7ae43fdbceb04c.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-084b8f68408c6b689a55200a78bcf233769bfcd8e999d9fadaeb399152b05bcd.yml diff --git a/api.md b/api.md index 696075eff3..de69f11dca 100644 --- a/api.md +++ b/api.md @@ -374,14 +374,20 @@ from openai.types.beta.threads import ( ImageFileContentBlock, ImageFileDelta, ImageFileDeltaBlock, + ImageURL, + ImageURLContentBlock, + ImageURLDelta, + ImageURLDeltaBlock, Message, MessageContent, MessageContentDelta, + MessageContentPartParam, MessageDeleted, MessageDelta, MessageDeltaEvent, Text, TextContentBlock, + TextContentBlockParam, TextDelta, TextDeltaBlock, ) diff --git a/src/openai/resources/beta/threads/messages.py b/src/openai/resources/beta/threads/messages.py index 0799feed23..f0832515ce 100644 --- a/src/openai/resources/beta/threads/messages.py +++ b/src/openai/resources/beta/threads/messages.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Iterable, Optional +from typing import Union, Iterable, Optional from typing_extensions import Literal import httpx @@ -24,6 +24,7 @@ from ....types.beta.threads import message_list_params, message_create_params, message_update_params from ....types.beta.threads.message import Message from ....types.beta.threads.message_deleted import MessageDeleted +from ....types.beta.threads.message_content_part_param import MessageContentPartParam __all__ = ["Messages", "AsyncMessages"] @@ -41,7 +42,7 @@ def create( self, thread_id: str, *, - content: str, + content: Union[str, Iterable[MessageContentPartParam]], role: Literal["user", "assistant"], attachments: Optional[Iterable[message_create_params.Attachment]] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, @@ -56,7 +57,7 @@ def create( Create a message. Args: - content: The content of the message. + content: The text contents of the message. role: The role of the entity that is creating the message. Allowed values include: @@ -304,7 +305,7 @@ async def create( self, thread_id: str, *, - content: str, + content: Union[str, Iterable[MessageContentPartParam]], role: Literal["user", "assistant"], attachments: Optional[Iterable[message_create_params.Attachment]] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, @@ -319,7 +320,7 @@ async def create( Create a message. Args: - content: The content of the message. + content: The text contents of the message. role: The role of the entity that is creating the message. Allowed values include: diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index 086745b470..32f5111340 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -81,7 +81,8 @@ def create( Use "assistants" for [Assistants](https://platform.openai.com/docs/api-reference/assistants) and - [Messages](https://platform.openai.com/docs/api-reference/messages), "batch" for + [Message](https://platform.openai.com/docs/api-reference/messages) files, + "vision" for Assistants image file inputs, "batch" for [Batch API](https://platform.openai.com/docs/guides/batch), and "fine-tune" for [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning). @@ -353,7 +354,8 @@ async def create( Use "assistants" for [Assistants](https://platform.openai.com/docs/api-reference/assistants) and - [Messages](https://platform.openai.com/docs/api-reference/messages), "batch" for + [Message](https://platform.openai.com/docs/api-reference/messages) files, + "vision" for Assistants image file inputs, "batch" for [Batch API](https://platform.openai.com/docs/guides/batch), and "fine-tune" for [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning). diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index 60510965a2..80349678c2 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -9,6 +9,7 @@ from .file_search_tool_param import FileSearchToolParam from .code_interpreter_tool_param import CodeInterpreterToolParam from .assistant_tool_choice_option_param import AssistantToolChoiceOptionParam +from .threads.message_content_part_param import MessageContentPartParam from .assistant_response_format_option_param import AssistantResponseFormatOptionParam __all__ = [ @@ -184,8 +185,8 @@ class ThreadMessageAttachment(TypedDict, total=False): class ThreadMessage(TypedDict, total=False): - content: Required[str] - """The content of the message.""" + content: Required[Union[str, Iterable[MessageContentPartParam]]] + """The text contents of the message.""" role: Required[Literal["user", "assistant"]] """The role of the entity that is creating the message. Allowed values include: diff --git a/src/openai/types/beta/thread_create_params.py b/src/openai/types/beta/thread_create_params.py index ab2df21ed7..ccf50d58dc 100644 --- a/src/openai/types/beta/thread_create_params.py +++ b/src/openai/types/beta/thread_create_params.py @@ -7,6 +7,7 @@ from .file_search_tool_param import FileSearchToolParam from .code_interpreter_tool_param import CodeInterpreterToolParam +from .threads.message_content_part_param import MessageContentPartParam __all__ = [ "ThreadCreateParams", @@ -56,8 +57,8 @@ class MessageAttachment(TypedDict, total=False): class Message(TypedDict, total=False): - content: Required[str] - """The content of the message.""" + content: Required[Union[str, Iterable[MessageContentPartParam]]] + """The text contents of the message.""" role: Required[Literal["user", "assistant"]] """The role of the entity that is creating the message. Allowed values include: diff --git a/src/openai/types/beta/threads/__init__.py b/src/openai/types/beta/threads/__init__.py index 1e38d5eaa1..023d76fc13 100644 --- a/src/openai/types/beta/threads/__init__.py +++ b/src/openai/types/beta/threads/__init__.py @@ -5,16 +5,20 @@ from .run import Run as Run from .text import Text as Text from .message import Message as Message +from .image_url import ImageURL as ImageURL from .annotation import Annotation as Annotation from .image_file import ImageFile as ImageFile from .run_status import RunStatus as RunStatus from .text_delta import TextDelta as TextDelta from .message_delta import MessageDelta as MessageDelta +from .image_url_delta import ImageURLDelta as ImageURLDelta +from .image_url_param import ImageURLParam as ImageURLParam from .message_content import MessageContent as MessageContent from .message_deleted import MessageDeleted as MessageDeleted from .run_list_params import RunListParams as RunListParams from .annotation_delta import AnnotationDelta as AnnotationDelta from .image_file_delta import ImageFileDelta as ImageFileDelta +from .image_file_param import ImageFileParam as ImageFileParam from .text_delta_block import TextDeltaBlock as TextDeltaBlock from .run_create_params import RunCreateParams as RunCreateParams from .run_update_params import RunUpdateParams as RunUpdateParams @@ -22,13 +26,19 @@ from .message_delta_event import MessageDeltaEvent as MessageDeltaEvent from .message_list_params import MessageListParams as MessageListParams from .file_path_annotation import FilePathAnnotation as FilePathAnnotation +from .image_url_delta_block import ImageURLDeltaBlock as ImageURLDeltaBlock from .message_content_delta import MessageContentDelta as MessageContentDelta from .message_create_params import MessageCreateParams as MessageCreateParams from .message_update_params import MessageUpdateParams as MessageUpdateParams from .image_file_delta_block import ImageFileDeltaBlock as ImageFileDeltaBlock +from .image_url_content_block import ImageURLContentBlock as ImageURLContentBlock from .file_citation_annotation import FileCitationAnnotation as FileCitationAnnotation from .image_file_content_block import ImageFileContentBlock as ImageFileContentBlock +from .text_content_block_param import TextContentBlockParam as TextContentBlockParam from .file_path_delta_annotation import FilePathDeltaAnnotation as FilePathDeltaAnnotation +from .message_content_part_param import MessageContentPartParam as MessageContentPartParam +from .image_url_content_block_param import ImageURLContentBlockParam as ImageURLContentBlockParam from .file_citation_delta_annotation import FileCitationDeltaAnnotation as FileCitationDeltaAnnotation +from .image_file_content_block_param import ImageFileContentBlockParam as ImageFileContentBlockParam from .run_submit_tool_outputs_params import RunSubmitToolOutputsParams as RunSubmitToolOutputsParams from .required_action_function_tool_call import RequiredActionFunctionToolCall as RequiredActionFunctionToolCall diff --git a/src/openai/types/beta/threads/image_file.py b/src/openai/types/beta/threads/image_file.py index 651a247d21..6000d97500 100644 --- a/src/openai/types/beta/threads/image_file.py +++ b/src/openai/types/beta/threads/image_file.py @@ -1,6 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - +from typing import Optional +from typing_extensions import Literal from ...._models import BaseModel @@ -11,5 +12,12 @@ class ImageFile(BaseModel): file_id: str """ The [File](https://platform.openai.com/docs/api-reference/files) ID of the image - in the message content. + in the message content. Set `purpose="vision"` when uploading the File if you + need to later display the file content. + """ + + detail: Optional[Literal["auto", "low", "high"]] = None + """Specifies the detail level of the image if specified by the user. + + `low` uses fewer tokens, you can opt in to high resolution using `high`. """ diff --git a/src/openai/types/beta/threads/image_file_content_block_param.py b/src/openai/types/beta/threads/image_file_content_block_param.py new file mode 100644 index 0000000000..48d94bee36 --- /dev/null +++ b/src/openai/types/beta/threads/image_file_content_block_param.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +from .image_file_param import ImageFileParam + +__all__ = ["ImageFileContentBlockParam"] + + +class ImageFileContentBlockParam(TypedDict, total=False): + image_file: Required[ImageFileParam] + + type: Required[Literal["image_file"]] + """Always `image_file`.""" diff --git a/src/openai/types/beta/threads/image_file_delta.py b/src/openai/types/beta/threads/image_file_delta.py index b0b1d32fa2..4581184c7a 100644 --- a/src/openai/types/beta/threads/image_file_delta.py +++ b/src/openai/types/beta/threads/image_file_delta.py @@ -1,6 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Optional +from typing_extensions import Literal from ...._models import BaseModel @@ -8,8 +9,15 @@ class ImageFileDelta(BaseModel): + detail: Optional[Literal["auto", "low", "high"]] = None + """Specifies the detail level of the image if specified by the user. + + `low` uses fewer tokens, you can opt in to high resolution using `high`. + """ + file_id: Optional[str] = None """ The [File](https://platform.openai.com/docs/api-reference/files) ID of the image - in the message content. + in the message content. Set `purpose="vision"` when uploading the File if you + need to later display the file content. """ diff --git a/src/openai/types/beta/threads/image_file_param.py b/src/openai/types/beta/threads/image_file_param.py new file mode 100644 index 0000000000..e4a85358b9 --- /dev/null +++ b/src/openai/types/beta/threads/image_file_param.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ImageFileParam"] + + +class ImageFileParam(TypedDict, total=False): + file_id: Required[str] + """ + The [File](https://platform.openai.com/docs/api-reference/files) ID of the image + in the message content. Set `purpose="vision"` when uploading the File if you + need to later display the file content. + """ + + detail: Literal["auto", "low", "high"] + """Specifies the detail level of the image if specified by the user. + + `low` uses fewer tokens, you can opt in to high resolution using `high`. + """ diff --git a/src/openai/types/beta/threads/image_url.py b/src/openai/types/beta/threads/image_url.py new file mode 100644 index 0000000000..d1fac147b2 --- /dev/null +++ b/src/openai/types/beta/threads/image_url.py @@ -0,0 +1,23 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["ImageURL"] + + +class ImageURL(BaseModel): + url: str + """ + The external URL of the image, must be a supported image types: jpeg, jpg, png, + gif, webp. + """ + + detail: Optional[Literal["auto", "low", "high"]] = None + """Specifies the detail level of the image. + + `low` uses fewer tokens, you can opt in to high resolution using `high`. Default + value is `auto` + """ diff --git a/src/openai/types/beta/threads/image_url_content_block.py b/src/openai/types/beta/threads/image_url_content_block.py new file mode 100644 index 0000000000..40a16c1df8 --- /dev/null +++ b/src/openai/types/beta/threads/image_url_content_block.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from .image_url import ImageURL +from ...._models import BaseModel + +__all__ = ["ImageURLContentBlock"] + + +class ImageURLContentBlock(BaseModel): + image_url: ImageURL + + type: Literal["image_url"] + """The type of the content part.""" diff --git a/src/openai/types/beta/threads/image_url_content_block_param.py b/src/openai/types/beta/threads/image_url_content_block_param.py new file mode 100644 index 0000000000..585b926c58 --- /dev/null +++ b/src/openai/types/beta/threads/image_url_content_block_param.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +from .image_url_param import ImageURLParam + +__all__ = ["ImageURLContentBlockParam"] + + +class ImageURLContentBlockParam(TypedDict, total=False): + image_url: Required[ImageURLParam] + + type: Required[Literal["image_url"]] + """The type of the content part.""" diff --git a/src/openai/types/beta/threads/image_url_delta.py b/src/openai/types/beta/threads/image_url_delta.py new file mode 100644 index 0000000000..e402671908 --- /dev/null +++ b/src/openai/types/beta/threads/image_url_delta.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["ImageURLDelta"] + + +class ImageURLDelta(BaseModel): + detail: Optional[Literal["auto", "low", "high"]] = None + """Specifies the detail level of the image. + + `low` uses fewer tokens, you can opt in to high resolution using `high`. + """ + + url: Optional[str] = None + """ + The URL of the image, must be a supported image types: jpeg, jpg, png, gif, + webp. + """ diff --git a/src/openai/types/beta/threads/image_url_delta_block.py b/src/openai/types/beta/threads/image_url_delta_block.py new file mode 100644 index 0000000000..5252da12dd --- /dev/null +++ b/src/openai/types/beta/threads/image_url_delta_block.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel +from .image_url_delta import ImageURLDelta + +__all__ = ["ImageURLDeltaBlock"] + + +class ImageURLDeltaBlock(BaseModel): + index: int + """The index of the content part in the message.""" + + type: Literal["image_url"] + """Always `image_url`.""" + + image_url: Optional[ImageURLDelta] = None diff --git a/src/openai/types/beta/threads/image_url_param.py b/src/openai/types/beta/threads/image_url_param.py new file mode 100644 index 0000000000..6b7e427edd --- /dev/null +++ b/src/openai/types/beta/threads/image_url_param.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ImageURLParam"] + + +class ImageURLParam(TypedDict, total=False): + url: Required[str] + """ + The external URL of the image, must be a supported image types: jpeg, jpg, png, + gif, webp. + """ + + detail: Literal["auto", "low", "high"] + """Specifies the detail level of the image. + + `low` uses fewer tokens, you can opt in to high resolution using `high`. Default + value is `auto` + """ diff --git a/src/openai/types/beta/threads/message_content.py b/src/openai/types/beta/threads/message_content.py index bc79b39fd4..4f17d14786 100644 --- a/src/openai/types/beta/threads/message_content.py +++ b/src/openai/types/beta/threads/message_content.py @@ -5,8 +5,11 @@ from ...._utils import PropertyInfo from .text_content_block import TextContentBlock +from .image_url_content_block import ImageURLContentBlock from .image_file_content_block import ImageFileContentBlock __all__ = ["MessageContent"] -MessageContent = Annotated[Union[ImageFileContentBlock, TextContentBlock], PropertyInfo(discriminator="type")] +MessageContent = Annotated[ + Union[ImageFileContentBlock, ImageURLContentBlock, TextContentBlock], PropertyInfo(discriminator="type") +] diff --git a/src/openai/types/beta/threads/message_content_delta.py b/src/openai/types/beta/threads/message_content_delta.py index 3cbc22c94b..6c5f732b12 100644 --- a/src/openai/types/beta/threads/message_content_delta.py +++ b/src/openai/types/beta/threads/message_content_delta.py @@ -5,8 +5,11 @@ from ...._utils import PropertyInfo from .text_delta_block import TextDeltaBlock +from .image_url_delta_block import ImageURLDeltaBlock from .image_file_delta_block import ImageFileDeltaBlock __all__ = ["MessageContentDelta"] -MessageContentDelta = Annotated[Union[ImageFileDeltaBlock, TextDeltaBlock], PropertyInfo(discriminator="type")] +MessageContentDelta = Annotated[ + Union[ImageFileDeltaBlock, TextDeltaBlock, ImageURLDeltaBlock], PropertyInfo(discriminator="type") +] diff --git a/src/openai/types/beta/threads/message_content_part_param.py b/src/openai/types/beta/threads/message_content_part_param.py new file mode 100644 index 0000000000..d11442a3a9 --- /dev/null +++ b/src/openai/types/beta/threads/message_content_part_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union + +from .text_content_block_param import TextContentBlockParam +from .image_url_content_block_param import ImageURLContentBlockParam +from .image_file_content_block_param import ImageFileContentBlockParam + +__all__ = ["MessageContentPartParam"] + +MessageContentPartParam = Union[ImageFileContentBlockParam, ImageURLContentBlockParam, TextContentBlockParam] diff --git a/src/openai/types/beta/threads/message_create_params.py b/src/openai/types/beta/threads/message_create_params.py index 5cead598f0..3668df950d 100644 --- a/src/openai/types/beta/threads/message_create_params.py +++ b/src/openai/types/beta/threads/message_create_params.py @@ -6,14 +6,15 @@ from typing_extensions import Literal, Required, TypedDict from ..file_search_tool_param import FileSearchToolParam +from .message_content_part_param import MessageContentPartParam from ..code_interpreter_tool_param import CodeInterpreterToolParam __all__ = ["MessageCreateParams", "Attachment", "AttachmentTool"] class MessageCreateParams(TypedDict, total=False): - content: Required[str] - """The content of the message.""" + content: Required[Union[str, Iterable[MessageContentPartParam]]] + """The text contents of the message.""" role: Required[Literal["user", "assistant"]] """The role of the entity that is creating the message. Allowed values include: diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index 2e4823bacd..9f534045ae 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -7,6 +7,7 @@ from ..assistant_tool_param import AssistantToolParam from ..file_search_tool_param import FileSearchToolParam +from .message_content_part_param import MessageContentPartParam from ..code_interpreter_tool_param import CodeInterpreterToolParam from ..assistant_tool_choice_option_param import AssistantToolChoiceOptionParam from ..assistant_response_format_option_param import AssistantResponseFormatOptionParam @@ -175,8 +176,8 @@ class AdditionalMessageAttachment(TypedDict, total=False): class AdditionalMessage(TypedDict, total=False): - content: Required[str] - """The content of the message.""" + content: Required[Union[str, Iterable[MessageContentPartParam]]] + """The text contents of the message.""" role: Required[Literal["user", "assistant"]] """The role of the entity that is creating the message. Allowed values include: diff --git a/src/openai/types/beta/threads/text_content_block_param.py b/src/openai/types/beta/threads/text_content_block_param.py new file mode 100644 index 0000000000..6313de32cc --- /dev/null +++ b/src/openai/types/beta/threads/text_content_block_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["TextContentBlockParam"] + + +class TextContentBlockParam(TypedDict, total=False): + text: Required[str] + """Text content to be sent to the model""" + + type: Required[Literal["text"]] + """Always `text`.""" diff --git a/src/openai/types/file_create_params.py b/src/openai/types/file_create_params.py index 3867fcb06e..caa913d4d2 100644 --- a/src/openai/types/file_create_params.py +++ b/src/openai/types/file_create_params.py @@ -18,7 +18,8 @@ class FileCreateParams(TypedDict, total=False): Use "assistants" for [Assistants](https://platform.openai.com/docs/api-reference/assistants) and - [Messages](https://platform.openai.com/docs/api-reference/messages), "batch" for + [Message](https://platform.openai.com/docs/api-reference/messages) files, + "vision" for Assistants image file inputs, "batch" for [Batch API](https://platform.openai.com/docs/guides/batch), and "fine-tune" for [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning). """ diff --git a/src/openai/types/file_object.py b/src/openai/types/file_object.py index d24a5b1a8d..6e2bf310a4 100644 --- a/src/openai/types/file_object.py +++ b/src/openai/types/file_object.py @@ -24,11 +24,13 @@ class FileObject(BaseModel): object: Literal["file"] """The object type, which is always `file`.""" - purpose: Literal["assistants", "assistants_output", "batch", "batch_output", "fine-tune", "fine-tune-results"] + purpose: Literal[ + "assistants", "assistants_output", "batch", "batch_output", "fine-tune", "fine-tune-results", "vision" + ] """The intended purpose of the file. Supported values are `assistants`, `assistants_output`, `batch`, `batch_output`, - `fine-tune`, and `fine-tune-results`. + `fine-tune`, `fine-tune-results` and `vision`. """ status: Literal["uploaded", "processed", "error"] diff --git a/tests/api_resources/beta/test_threads.py b/tests/api_resources/beta/test_threads.py index 715e3e8726..02c6e2586e 100644 --- a/tests/api_resources/beta/test_threads.py +++ b/tests/api_resources/beta/test_threads.py @@ -32,7 +32,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: messages=[ { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -63,7 +63,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: }, { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -94,7 +94,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: }, { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -309,7 +309,7 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) "messages": [ { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -340,7 +340,7 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) }, { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -371,7 +371,7 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) }, { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -477,7 +477,7 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) "messages": [ { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -508,7 +508,7 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) }, { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -539,7 +539,7 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) }, { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -637,7 +637,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> messages=[ { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -668,7 +668,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> }, { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -699,7 +699,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> }, { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -914,7 +914,7 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie "messages": [ { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -945,7 +945,7 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie }, { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -976,7 +976,7 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie }, { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -1082,7 +1082,7 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie "messages": [ { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -1113,7 +1113,7 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie }, { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -1144,7 +1144,7 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie }, { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", diff --git a/tests/api_resources/beta/threads/test_messages.py b/tests/api_resources/beta/threads/test_messages.py index fb42d509a1..b5be32a421 100644 --- a/tests/api_resources/beta/threads/test_messages.py +++ b/tests/api_resources/beta/threads/test_messages.py @@ -25,7 +25,7 @@ class TestMessages: def test_method_create(self, client: OpenAI) -> None: message = client.beta.threads.messages.create( "string", - content="x", + content="string", role="user", ) assert_matches_type(Message, message, path=["response"]) @@ -34,7 +34,7 @@ def test_method_create(self, client: OpenAI) -> None: def test_method_create_with_all_params(self, client: OpenAI) -> None: message = client.beta.threads.messages.create( "string", - content="x", + content="string", role="user", attachments=[ { @@ -58,7 +58,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: def test_raw_response_create(self, client: OpenAI) -> None: response = client.beta.threads.messages.with_raw_response.create( "string", - content="x", + content="string", role="user", ) @@ -71,7 +71,7 @@ def test_raw_response_create(self, client: OpenAI) -> None: def test_streaming_response_create(self, client: OpenAI) -> None: with client.beta.threads.messages.with_streaming_response.create( "string", - content="x", + content="string", role="user", ) as response: assert not response.is_closed @@ -87,7 +87,7 @@ def test_path_params_create(self, client: OpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): client.beta.threads.messages.with_raw_response.create( "", - content="x", + content="string", role="user", ) @@ -302,7 +302,7 @@ class TestAsyncMessages: async def test_method_create(self, async_client: AsyncOpenAI) -> None: message = await async_client.beta.threads.messages.create( "string", - content="x", + content="string", role="user", ) assert_matches_type(Message, message, path=["response"]) @@ -311,7 +311,7 @@ async def test_method_create(self, async_client: AsyncOpenAI) -> None: async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: message = await async_client.beta.threads.messages.create( "string", - content="x", + content="string", role="user", attachments=[ { @@ -335,7 +335,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: response = await async_client.beta.threads.messages.with_raw_response.create( "string", - content="x", + content="string", role="user", ) @@ -348,7 +348,7 @@ async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: async with async_client.beta.threads.messages.with_streaming_response.create( "string", - content="x", + content="string", role="user", ) as response: assert not response.is_closed @@ -364,7 +364,7 @@ async def test_path_params_create(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `thread_id` but received ''"): await async_client.beta.threads.messages.with_raw_response.create( "", - content="x", + content="string", role="user", ) diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index 429c9bdeeb..089dd1253e 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -39,7 +39,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: additional_messages=[ { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -70,7 +70,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: }, { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -101,7 +101,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: }, { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -202,7 +202,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: additional_messages=[ { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -233,7 +233,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: }, { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -264,7 +264,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: }, { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -703,7 +703,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn additional_messages=[ { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -734,7 +734,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn }, { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -765,7 +765,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn }, { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -866,7 +866,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn additional_messages=[ { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -897,7 +897,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn }, { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", @@ -928,7 +928,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn }, { "role": "user", - "content": "x", + "content": "string", "attachments": [ { "file_id": "string", From 9111ae02cecee700ad84d2e285f6e7cb1268c3fb Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 9 May 2024 16:20:09 -0400 Subject: [PATCH 338/816] release: 1.28.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 4eb89879b8..31d8238881 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.27.0" + ".": "1.28.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d451d36f8..1feb7e4967 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.28.0 (2024-05-09) + +Full Changelog: [v1.27.0...v1.28.0](https://github.com/openai/openai-python/compare/v1.27.0...v1.28.0) + +### Features + +* **api:** add message image content ([#1405](https://github.com/openai/openai-python/issues/1405)) ([a115de6](https://github.com/openai/openai-python/commit/a115de60ce1ca503a7659bb9a19c18699d4d9bcb)) + ## 1.27.0 (2024-05-08) Full Changelog: [v1.26.0...v1.27.0](https://github.com/openai/openai-python/compare/v1.26.0...v1.27.0) diff --git a/pyproject.toml b/pyproject.toml index 81d7e75746..1295864815 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.27.0" +version = "1.28.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 4a8c619a1a..eaeadf5932 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.27.0" # x-release-please-version +__version__ = "1.28.0" # x-release-please-version From 1aeaf02f662e6e925180ddfcaa26508408b2f2a4 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 10 May 2024 15:31:12 -0400 Subject: [PATCH 339/816] chore(docs): add SECURITY.md (#1408) --- SECURITY.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 SECURITY.md diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000000..c54acaf331 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,29 @@ +# Security Policy + +## Reporting Security Issues + +This SDK is generated by [Stainless Software Inc](http://stainlessapi.com). Stainless takes security seriously, and encourages you to report any security vulnerability promptly so that appropriate action can be taken. + +To report a security issue, please contact the Stainless team at security@stainlessapi.com. + +## Responsible Disclosure + +We appreciate the efforts of security researchers and individuals who help us maintain the security of +SDKs we generate. If you believe you have found a security vulnerability, please adhere to responsible +disclosure practices by allowing us a reasonable amount of time to investigate and address the issue +before making any information public. + +## Reporting Non-SDK Related Security Issues + +If you encounter security issues that are not directly related to SDKs but pertain to the services +or products provided by OpenAI please follow the respective company's security reporting guidelines. + +### OpenAI Terms and Policies + +Our Security Policy can be found at [Security Policy URL](https://openai.com/policies/coordinated-vulnerability-disclosure-policy). + +Please contact disclosure@openai.com for any questions or concerns regarding security of our services. + +--- + +Thank you for helping us keep the SDKs and systems they interact with secure. From 906ece0e45235cb170bc062902182eb8b55698b9 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Sat, 11 May 2024 01:03:42 -0400 Subject: [PATCH 340/816] release: 1.28.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 31d8238881..a2b1280ba0 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.28.0" + ".": "1.28.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 1feb7e4967..81b5596198 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.28.1 (2024-05-11) + +Full Changelog: [v1.28.0...v1.28.1](https://github.com/openai/openai-python/compare/v1.28.0...v1.28.1) + +### Chores + +* **docs:** add SECURITY.md ([#1408](https://github.com/openai/openai-python/issues/1408)) ([119970a](https://github.com/openai/openai-python/commit/119970a31b67e88c623d50855290ccf3847c10eb)) + ## 1.28.0 (2024-05-09) Full Changelog: [v1.27.0...v1.28.0](https://github.com/openai/openai-python/compare/v1.27.0...v1.28.0) diff --git a/pyproject.toml b/pyproject.toml index 1295864815..3a2351761d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.28.0" +version = "1.28.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index eaeadf5932..893c4e49a2 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.28.0" # x-release-please-version +__version__ = "1.28.1" # x-release-please-version From 3480e5061d1188cd377f34b638665772ff75b90e Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 13 May 2024 08:07:15 -0400 Subject: [PATCH 341/816] chore(internal): bump pydantic dependency (#1413) --- requirements-dev.lock | 8 ++++---- requirements.lock | 8 ++++---- src/openai/_models.py | 20 ++++++++++++++++---- tests/test_models.py | 8 ++++---- tests/test_transform.py | 22 ++++++++++++---------- 5 files changed, 40 insertions(+), 26 deletions(-) diff --git a/requirements-dev.lock b/requirements-dev.lock index 8cfefdd93b..6a4e12022a 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -24,7 +24,7 @@ attrs==23.1.0 azure-core==1.30.1 # via azure-identity azure-identity==1.15.0 -black==24.4.0 +black==24.4.2 # via inline-snapshot certifi==2023.7.22 # via httpcore @@ -39,7 +39,7 @@ click==8.1.7 # via inline-snapshot colorlog==6.7.0 # via nox -cryptography==42.0.5 +cryptography==42.0.7 # via azure-identity # via msal # via pyjwt @@ -111,9 +111,9 @@ py==1.11.0 # via pytest pycparser==2.22 # via cffi -pydantic==2.4.2 +pydantic==2.7.1 # via openai -pydantic-core==2.10.1 +pydantic-core==2.18.2 # via pydantic pyjwt==2.8.0 # via msal diff --git a/requirements.lock b/requirements.lock index c933d6c90e..47cf8a40e9 100644 --- a/requirements.lock +++ b/requirements.lock @@ -33,13 +33,13 @@ numpy==1.26.4 # via openai # via pandas # via pandas-stubs -pandas==2.2.1 +pandas==2.2.2 # via openai pandas-stubs==2.2.1.240316 # via openai -pydantic==2.4.2 +pydantic==2.7.1 # via openai -pydantic-core==2.10.1 +pydantic-core==2.18.2 # via pydantic python-dateutil==2.9.0.post0 # via pandas @@ -53,7 +53,7 @@ sniffio==1.3.0 # via openai tqdm==4.66.1 # via openai -types-pytz==2024.1.0.20240203 +types-pytz==2024.1.0.20240417 # via pandas-stubs typing-extensions==4.8.0 # via openai diff --git a/src/openai/_models.py b/src/openai/_models.py index ff3f54e2cd..75c68cc730 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -62,7 +62,7 @@ from ._constants import RAW_RESPONSE_HEADER if TYPE_CHECKING: - from pydantic_core.core_schema import ModelField, ModelFieldsSchema + from pydantic_core.core_schema import ModelField, LiteralSchema, ModelFieldsSchema __all__ = ["BaseModel", "GenericModel"] @@ -251,7 +251,9 @@ def model_dump( exclude_defaults: bool = False, exclude_none: bool = False, round_trip: bool = False, - warnings: bool = True, + warnings: bool | Literal["none", "warn", "error"] = True, + context: dict[str, Any] | None = None, + serialize_as_any: bool = False, ) -> dict[str, Any]: """Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump @@ -279,6 +281,10 @@ def model_dump( raise ValueError("round_trip is only supported in Pydantic v2") if warnings != True: raise ValueError("warnings is only supported in Pydantic v2") + if context is not None: + raise ValueError("context is only supported in Pydantic v2") + if serialize_as_any != False: + raise ValueError("serialize_as_any is only supported in Pydantic v2") return super().dict( # pyright: ignore[reportDeprecated] include=include, exclude=exclude, @@ -300,7 +306,9 @@ def model_dump_json( exclude_defaults: bool = False, exclude_none: bool = False, round_trip: bool = False, - warnings: bool = True, + warnings: bool | Literal["none", "warn", "error"] = True, + context: dict[str, Any] | None = None, + serialize_as_any: bool = False, ) -> str: """Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump_json @@ -324,6 +332,10 @@ def model_dump_json( raise ValueError("round_trip is only supported in Pydantic v2") if warnings != True: raise ValueError("warnings is only supported in Pydantic v2") + if context is not None: + raise ValueError("context is only supported in Pydantic v2") + if serialize_as_any != False: + raise ValueError("serialize_as_any is only supported in Pydantic v2") return super().json( # type: ignore[reportDeprecated] indent=indent, include=include, @@ -550,7 +562,7 @@ def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any, field_schema = field["schema"] if field_schema["type"] == "literal": - for entry in field_schema["expected"]: + for entry in cast("LiteralSchema", field_schema)["expected"]: if isinstance(entry, str): mapping[entry] = variant else: diff --git a/tests/test_models.py b/tests/test_models.py index 969e4eb315..b703444248 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -31,7 +31,7 @@ class NestedModel(BaseModel): # mismatched types m = NestedModel.construct(nested="hello!") - assert m.nested == "hello!" + assert cast(Any, m.nested) == "hello!" def test_optional_nested_model() -> None: @@ -48,7 +48,7 @@ class NestedModel(BaseModel): # mismatched types m3 = NestedModel.construct(nested={"foo"}) assert isinstance(cast(Any, m3.nested), set) - assert m3.nested == {"foo"} + assert cast(Any, m3.nested) == {"foo"} def test_list_nested_model() -> None: @@ -323,7 +323,7 @@ class Model(BaseModel): assert len(m.items) == 2 assert isinstance(m.items[0], Submodel1) assert m.items[0].level == -1 - assert m.items[1] == 156 + assert cast(Any, m.items[1]) == 156 def test_union_of_lists() -> None: @@ -355,7 +355,7 @@ class Model(BaseModel): assert len(m.items) == 2 assert isinstance(m.items[0], SubModel1) assert m.items[0].level == -1 - assert m.items[1] == 156 + assert cast(Any, m.items[1]) == 156 def test_dict_of_union() -> None: diff --git a/tests/test_transform.py b/tests/test_transform.py index 0d17e8a972..1eb6cde9d6 100644 --- a/tests/test_transform.py +++ b/tests/test_transform.py @@ -260,20 +260,22 @@ class MyModel(BaseModel): @parametrize @pytest.mark.asyncio async def test_pydantic_model_to_dictionary(use_async: bool) -> None: - assert await transform(MyModel(foo="hi!"), Any, use_async) == {"foo": "hi!"} - assert await transform(MyModel.construct(foo="hi!"), Any, use_async) == {"foo": "hi!"} + assert cast(Any, await transform(MyModel(foo="hi!"), Any, use_async)) == {"foo": "hi!"} + assert cast(Any, await transform(MyModel.construct(foo="hi!"), Any, use_async)) == {"foo": "hi!"} @parametrize @pytest.mark.asyncio async def test_pydantic_empty_model(use_async: bool) -> None: - assert await transform(MyModel.construct(), Any, use_async) == {} + assert cast(Any, await transform(MyModel.construct(), Any, use_async)) == {} @parametrize @pytest.mark.asyncio async def test_pydantic_unknown_field(use_async: bool) -> None: - assert await transform(MyModel.construct(my_untyped_field=True), Any, use_async) == {"my_untyped_field": True} + assert cast(Any, await transform(MyModel.construct(my_untyped_field=True), Any, use_async)) == { + "my_untyped_field": True + } @parametrize @@ -285,7 +287,7 @@ async def test_pydantic_mismatched_types(use_async: bool) -> None: params = await transform(model, Any, use_async) else: params = await transform(model, Any, use_async) - assert params == {"foo": True} + assert cast(Any, params) == {"foo": True} @parametrize @@ -297,7 +299,7 @@ async def test_pydantic_mismatched_object_type(use_async: bool) -> None: params = await transform(model, Any, use_async) else: params = await transform(model, Any, use_async) - assert params == {"foo": {"hello": "world"}} + assert cast(Any, params) == {"foo": {"hello": "world"}} class ModelNestedObjects(BaseModel): @@ -309,7 +311,7 @@ class ModelNestedObjects(BaseModel): async def test_pydantic_nested_objects(use_async: bool) -> None: model = ModelNestedObjects.construct(nested={"foo": "stainless"}) assert isinstance(model.nested, MyModel) - assert await transform(model, Any, use_async) == {"nested": {"foo": "stainless"}} + assert cast(Any, await transform(model, Any, use_async)) == {"nested": {"foo": "stainless"}} class ModelWithDefaultField(BaseModel): @@ -325,19 +327,19 @@ async def test_pydantic_default_field(use_async: bool) -> None: model = ModelWithDefaultField.construct() assert model.with_none_default is None assert model.with_str_default == "foo" - assert await transform(model, Any, use_async) == {} + assert cast(Any, await transform(model, Any, use_async)) == {} # should be included when the default value is explicitly given model = ModelWithDefaultField.construct(with_none_default=None, with_str_default="foo") assert model.with_none_default is None assert model.with_str_default == "foo" - assert await transform(model, Any, use_async) == {"with_none_default": None, "with_str_default": "foo"} + assert cast(Any, await transform(model, Any, use_async)) == {"with_none_default": None, "with_str_default": "foo"} # should be included when a non-default value is explicitly given model = ModelWithDefaultField.construct(with_none_default="bar", with_str_default="baz") assert model.with_none_default == "bar" assert model.with_str_default == "baz" - assert await transform(model, Any, use_async) == {"with_none_default": "bar", "with_str_default": "baz"} + assert cast(Any, await transform(model, Any, use_async)) == {"with_none_default": "bar", "with_str_default": "baz"} class TypedDictIterableUnion(TypedDict): From 2dc6d42a35a870068f3bb900731b1798ffe5ea52 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 13 May 2024 09:46:56 -0400 Subject: [PATCH 342/816] fix(client): accidental blocking sleep in async code (#1415) --- src/openai/resources/beta/threads/runs/runs.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 4268d41390..2cd6e60239 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -2,7 +2,6 @@ from __future__ import annotations -import time import typing_extensions from typing import Union, Iterable, Optional, overload from functools import partial @@ -1105,7 +1104,7 @@ def poll( else: poll_interval_ms = 1000 - time.sleep(poll_interval_ms / 1000) + self._sleep(poll_interval_ms / 1000) @overload def stream( @@ -2639,7 +2638,7 @@ async def poll( else: poll_interval_ms = 1000 - time.sleep(poll_interval_ms / 1000) + await self._sleep(poll_interval_ms / 1000) @overload def stream( From c0afbc75155ce0fe090f759152e0bc683a9b77a5 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 13 May 2024 09:47:25 -0400 Subject: [PATCH 343/816] release: 1.28.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index a2b1280ba0..cad349f4b9 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.28.1" + ".": "1.28.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 81b5596198..a68877e8d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.28.2 (2024-05-13) + +Full Changelog: [v1.28.1...v1.28.2](https://github.com/openai/openai-python/compare/v1.28.1...v1.28.2) + +### Bug Fixes + +* **client:** accidental blocking sleep in async code ([#1415](https://github.com/openai/openai-python/issues/1415)) ([0ac6ecb](https://github.com/openai/openai-python/commit/0ac6ecb8d4e52f895bc3ae1f589f22ddaaef6204)) + + +### Chores + +* **internal:** bump pydantic dependency ([#1413](https://github.com/openai/openai-python/issues/1413)) ([ed73d1d](https://github.com/openai/openai-python/commit/ed73d1db540714e29a1ba30e3aa6429aae8b1dd8)) + ## 1.28.1 (2024-05-11) Full Changelog: [v1.28.0...v1.28.1](https://github.com/openai/openai-python/compare/v1.28.0...v1.28.1) diff --git a/pyproject.toml b/pyproject.toml index 3a2351761d..86e30d4097 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.28.1" +version = "1.28.2" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 893c4e49a2..2ae163b1c6 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.28.1" # x-release-please-version +__version__ = "1.28.2" # x-release-please-version From ac6c9004d26e5d553bc84516ebd6ba9de9ec090b Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 13 May 2024 14:15:32 -0400 Subject: [PATCH 344/816] feat(api): add gpt-4o model (#1417) --- .stats.yml | 2 +- src/openai/resources/beta/assistants.py | 4 ++ .../resources/beta/threads/runs/runs.py | 44 +++++++++++++++++++ src/openai/resources/beta/threads/threads.py | 32 ++++++++++++++ .../types/beta/assistant_create_params.py | 2 + .../beta/thread_create_and_run_params.py | 2 + .../types/beta/threads/run_create_params.py | 2 + src/openai/types/chat_model.py | 2 + 8 files changed, 89 insertions(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index 52e87d1b58..f44b9b46af 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 64 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-084b8f68408c6b689a55200a78bcf233769bfcd8e999d9fadaeb399152b05bcd.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-47007cc1aa5bc7b74107a99b377925978a0bd376ed67bdae724e80d5d0b63d57.yml diff --git a/src/openai/resources/beta/assistants.py b/src/openai/resources/beta/assistants.py index 923ad95a54..2304452493 100644 --- a/src/openai/resources/beta/assistants.py +++ b/src/openai/resources/beta/assistants.py @@ -49,6 +49,8 @@ def create( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -434,6 +436,8 @@ async def create( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 2cd6e60239..84b0d63c25 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -85,6 +85,8 @@ def create( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -230,6 +232,8 @@ def create( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -374,6 +378,8 @@ def create( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -517,6 +523,8 @@ def create( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -784,6 +792,8 @@ def create_and_poll( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -874,6 +884,8 @@ def create_and_stream( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -928,6 +940,8 @@ def create_and_stream( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -982,6 +996,8 @@ def create_and_stream( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -1120,6 +1136,8 @@ def stream( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -1173,6 +1191,8 @@ def stream( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -1226,6 +1246,8 @@ def stream( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -1617,6 +1639,8 @@ async def create( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -1762,6 +1786,8 @@ async def create( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -1906,6 +1932,8 @@ async def create( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -2049,6 +2077,8 @@ async def create( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -2316,6 +2346,8 @@ async def create_and_poll( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -2406,6 +2438,8 @@ def create_and_stream( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -2460,6 +2494,8 @@ def create_and_stream( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -2514,6 +2550,8 @@ def create_and_stream( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -2654,6 +2692,8 @@ def stream( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -2707,6 +2747,8 @@ def stream( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -2760,6 +2802,8 @@ def stream( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 2455272658..a68cbe0ddd 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -267,6 +267,8 @@ def create_and_run( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -411,6 +413,8 @@ def create_and_run( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -554,6 +558,8 @@ def create_and_run( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -696,6 +702,8 @@ def create_and_run( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -776,6 +784,8 @@ def create_and_run_poll( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -854,6 +864,8 @@ def create_and_run_stream( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -906,6 +918,8 @@ def create_and_run_stream( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -958,6 +972,8 @@ def create_and_run_stream( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -1241,6 +1257,8 @@ async def create_and_run( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -1385,6 +1403,8 @@ async def create_and_run( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -1528,6 +1548,8 @@ async def create_and_run( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -1670,6 +1692,8 @@ async def create_and_run( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -1750,6 +1774,8 @@ async def create_and_run_poll( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -1830,6 +1856,8 @@ def create_and_run_stream( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -1882,6 +1910,8 @@ def create_and_run_stream( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -1934,6 +1964,8 @@ def create_and_run_stream( model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", diff --git a/src/openai/types/beta/assistant_create_params.py b/src/openai/types/beta/assistant_create_params.py index e9ff66dfc3..d44e15f4ca 100644 --- a/src/openai/types/beta/assistant_create_params.py +++ b/src/openai/types/beta/assistant_create_params.py @@ -22,6 +22,8 @@ class AssistantCreateParams(TypedDict, total=False): Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index 80349678c2..9567c8320a 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -75,6 +75,8 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index 9f534045ae..dca47a5c73 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -77,6 +77,8 @@ class RunCreateParamsBase(TypedDict, total=False): model: Union[ str, Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", diff --git a/src/openai/types/chat_model.py b/src/openai/types/chat_model.py index 219dab5138..0d2937ea32 100644 --- a/src/openai/types/chat_model.py +++ b/src/openai/types/chat_model.py @@ -5,6 +5,8 @@ __all__ = ["ChatModel"] ChatModel = Literal[ + "gpt-4o", + "gpt-4o-2024-05-13", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", From 0b4a180f3da5a018d937686aa70e54000edef878 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 13 May 2024 14:15:58 -0400 Subject: [PATCH 345/816] release: 1.29.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index cad349f4b9..b8af36c3aa 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.28.2" + ".": "1.29.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index a68877e8d6..d74404aecd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.29.0 (2024-05-13) + +Full Changelog: [v1.28.2...v1.29.0](https://github.com/openai/openai-python/compare/v1.28.2...v1.29.0) + +### Features + +* **api:** add gpt-4o model ([#1417](https://github.com/openai/openai-python/issues/1417)) ([4f09f8c](https://github.com/openai/openai-python/commit/4f09f8c6cc4450f5e61f158f1bd54c513063a1a8)) + ## 1.28.2 (2024-05-13) Full Changelog: [v1.28.1...v1.28.2](https://github.com/openai/openai-python/compare/v1.28.1...v1.28.2) diff --git a/pyproject.toml b/pyproject.toml index 86e30d4097..c8f549500d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.28.2" +version = "1.29.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 2ae163b1c6..48332e626e 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.28.2" # x-release-please-version +__version__ = "1.29.0" # x-release-please-version From d4c2c7a34850bd1d28123704f9b9febba8a0781d Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 14 May 2024 07:29:45 -0400 Subject: [PATCH 346/816] feat(api): add incomplete state (#1420) --- .stats.yml | 2 +- src/openai/resources/batches.py | 18 ++++++---- src/openai/resources/beta/assistants.py | 20 ++++++----- .../resources/beta/threads/runs/runs.py | 34 ++++++++++-------- src/openai/resources/beta/threads/threads.py | 30 +++++++++------- src/openai/resources/files.py | 36 +++++++++++-------- src/openai/types/batch_create_params.py | 9 +++-- src/openai/types/beta/assistant.py | 6 ++-- .../types/beta/assistant_create_params.py | 6 ++-- .../types/beta/assistant_update_params.py | 6 ++-- .../beta/thread_create_and_run_params.py | 6 ++-- src/openai/types/beta/threads/run.py | 10 +++--- .../types/beta/threads/run_create_params.py | 6 ++-- src/openai/types/beta/threads/run_status.py | 10 +++++- 14 files changed, 120 insertions(+), 79 deletions(-) diff --git a/.stats.yml b/.stats.yml index f44b9b46af..2e5c705a0d 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 64 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-47007cc1aa5bc7b74107a99b377925978a0bd376ed67bdae724e80d5d0b63d57.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-363dd904e5d6e65b3a323fc88e6b502fb23a6aa319be219273e3ee47c7530993.yml diff --git a/src/openai/resources/batches.py b/src/openai/resources/batches.py index 64a3014c37..db4c4da235 100644 --- a/src/openai/resources/batches.py +++ b/src/openai/resources/batches.py @@ -40,7 +40,7 @@ def create( self, *, completion_window: Literal["24h"], - endpoint: Literal["/v1/chat/completions", "/v1/embeddings"], + endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"], input_file_id: str, metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -58,7 +58,9 @@ def create( is supported. endpoint: The endpoint to be used for all requests in the batch. Currently - `/v1/chat/completions` and `/v1/embeddings` are supported. + `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` are supported. + Note that `/v1/embeddings` batches are also restricted to a maximum of 50,000 + embedding inputs across all requests in the batch. input_file_id: The ID of an uploaded file that contains requests for the new batch. @@ -67,7 +69,8 @@ def create( Your input file must be formatted as a [JSONL file](https://platform.openai.com/docs/api-reference/batch/requestInput), - and must be uploaded with the purpose `batch`. + and must be uploaded with the purpose `batch`. The file can contain up to 50,000 + requests, and can be up to 100 MB in size. metadata: Optional custom metadata for the batch. @@ -228,7 +231,7 @@ async def create( self, *, completion_window: Literal["24h"], - endpoint: Literal["/v1/chat/completions", "/v1/embeddings"], + endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"], input_file_id: str, metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -246,7 +249,9 @@ async def create( is supported. endpoint: The endpoint to be used for all requests in the batch. Currently - `/v1/chat/completions` and `/v1/embeddings` are supported. + `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` are supported. + Note that `/v1/embeddings` batches are also restricted to a maximum of 50,000 + embedding inputs across all requests in the batch. input_file_id: The ID of an uploaded file that contains requests for the new batch. @@ -255,7 +260,8 @@ async def create( Your input file must be formatted as a [JSONL file](https://platform.openai.com/docs/api-reference/batch/requestInput), - and must be uploaded with the purpose `batch`. + and must be uploaded with the purpose `batch`. The file can contain up to 50,000 + requests, and can be up to 100 MB in size. metadata: Optional custom metadata for the batch. diff --git a/src/openai/resources/beta/assistants.py b/src/openai/resources/beta/assistants.py index 2304452493..5912aff77a 100644 --- a/src/openai/resources/beta/assistants.py +++ b/src/openai/resources/beta/assistants.py @@ -110,8 +110,9 @@ def create( name: The name of the assistant. The maximum length is 256 characters. response_format: Specifies the format that the model must output. Compatible with - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -254,8 +255,9 @@ def update( name: The name of the assistant. The maximum length is 256 characters. response_format: Specifies the format that the model must output. Compatible with - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -497,8 +499,9 @@ async def create( name: The name of the assistant. The maximum length is 256 characters. response_format: Specifies the format that the model must output. Compatible with - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -641,8 +644,9 @@ async def update( name: The name of the assistant. The maximum length is 256 characters. response_format: Specifies the format that the model must output. Compatible with - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 84b0d63c25..c37071529c 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -164,8 +164,9 @@ def create( assistant will be used. response_format: Specifies the format that the model must output. Compatible with - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -314,8 +315,9 @@ def create( assistant will be used. response_format: Specifies the format that the model must output. Compatible with - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -460,8 +462,9 @@ def create( assistant will be used. response_format: Specifies the format that the model must output. Compatible with - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -1097,7 +1100,7 @@ def poll( if is_given(poll_interval_ms): extra_headers["X-Stainless-Custom-Poll-Interval"] = str(poll_interval_ms) - terminal_states = {"requires_action", "cancelled", "completed", "failed", "expired"} + terminal_states = {"requires_action", "cancelled", "completed", "failed", "expired", "incomplete"} while True: response = self.with_raw_response.retrieve( thread_id=thread_id, @@ -1718,8 +1721,9 @@ async def create( assistant will be used. response_format: Specifies the format that the model must output. Compatible with - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -1868,8 +1872,9 @@ async def create( assistant will be used. response_format: Specifies the format that the model must output. Compatible with - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -2014,8 +2019,9 @@ async def create( assistant will be used. response_format: Specifies the format that the model must output. Compatible with - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -2653,7 +2659,7 @@ async def poll( if is_given(poll_interval_ms): extra_headers["X-Stainless-Custom-Poll-Interval"] = str(poll_interval_ms) - terminal_states = {"requires_action", "cancelled", "completed", "failed", "expired"} + terminal_states = {"requires_action", "cancelled", "completed", "failed", "expired", "incomplete"} while True: response = await self.with_raw_response.retrieve( thread_id=thread_id, diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index a68cbe0ddd..36cdd03f91 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -341,8 +341,9 @@ def create_and_run( assistant will be used. response_format: Specifies the format that the model must output. Compatible with - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -490,8 +491,9 @@ def create_and_run( assistant will be used. response_format: Specifies the format that the model must output. Compatible with - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -635,8 +637,9 @@ def create_and_run( assistant will be used. response_format: Specifies the format that the model must output. Compatible with - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -1331,8 +1334,9 @@ async def create_and_run( assistant will be used. response_format: Specifies the format that the model must output. Compatible with - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -1480,8 +1484,9 @@ async def create_and_run( assistant will be used. response_format: Specifies the format that the model must output. Compatible with - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -1625,8 +1630,9 @@ async def create_and_run( assistant will be used. response_format: Specifies the format that the model must output. Compatible with - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index 32f5111340..aed0829dfe 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -62,14 +62,18 @@ def create( ) -> FileObject: """Upload a file that can be used across various endpoints. - The size of all the - files uploaded by one organization can be up to 100 GB. + Individual files can be + up to 512 MB, and the size of all files uploaded by one organization can be up + to 100 GB. - The size of individual files can be a maximum of 512 MB or 2 million tokens for - Assistants. See the - [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) to - learn more about the types of files supported. The Fine-tuning API only supports - `.jsonl` files. + The Assistants API supports files up to 2 million tokens and of specific file + types. See the + [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for + details. + + The Fine-tuning API only supports `.jsonl` files. + + The Batch API only supports `.jsonl` files up to 100 MB in size. Please [contact us](https://help.openai.com/) if you need to increase these storage limits. @@ -335,14 +339,18 @@ async def create( ) -> FileObject: """Upload a file that can be used across various endpoints. - The size of all the - files uploaded by one organization can be up to 100 GB. + Individual files can be + up to 512 MB, and the size of all files uploaded by one organization can be up + to 100 GB. + + The Assistants API supports files up to 2 million tokens and of specific file + types. See the + [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for + details. + + The Fine-tuning API only supports `.jsonl` files. - The size of individual files can be a maximum of 512 MB or 2 million tokens for - Assistants. See the - [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) to - learn more about the types of files supported. The Fine-tuning API only supports - `.jsonl` files. + The Batch API only supports `.jsonl` files up to 100 MB in size. Please [contact us](https://help.openai.com/) if you need to increase these storage limits. diff --git a/src/openai/types/batch_create_params.py b/src/openai/types/batch_create_params.py index 63b4fae91b..140380d417 100644 --- a/src/openai/types/batch_create_params.py +++ b/src/openai/types/batch_create_params.py @@ -15,10 +15,12 @@ class BatchCreateParams(TypedDict, total=False): Currently only `24h` is supported. """ - endpoint: Required[Literal["/v1/chat/completions", "/v1/embeddings"]] + endpoint: Required[Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"]] """The endpoint to be used for all requests in the batch. - Currently `/v1/chat/completions` and `/v1/embeddings` are supported. + Currently `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` are + supported. Note that `/v1/embeddings` batches are also restricted to a maximum + of 50,000 embedding inputs across all requests in the batch. """ input_file_id: Required[str] @@ -29,7 +31,8 @@ class BatchCreateParams(TypedDict, total=False): Your input file must be formatted as a [JSONL file](https://platform.openai.com/docs/api-reference/batch/requestInput), - and must be uploaded with the purpose `batch`. + and must be uploaded with the purpose `batch`. The file can contain up to 50,000 + requests, and can be up to 100 MB in size. """ metadata: Optional[Dict[str, str]] diff --git a/src/openai/types/beta/assistant.py b/src/openai/types/beta/assistant.py index 0b997e0b0e..4e5adc766e 100644 --- a/src/openai/types/beta/assistant.py +++ b/src/openai/types/beta/assistant.py @@ -85,9 +85,9 @@ class Assistant(BaseModel): response_format: Optional[AssistantResponseFormatOption] = None """Specifies the format that the model must output. - Compatible with - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. diff --git a/src/openai/types/beta/assistant_create_params.py b/src/openai/types/beta/assistant_create_params.py index d44e15f4ca..67e7f7e78c 100644 --- a/src/openai/types/beta/assistant_create_params.py +++ b/src/openai/types/beta/assistant_create_params.py @@ -77,9 +77,9 @@ class AssistantCreateParams(TypedDict, total=False): response_format: Optional[AssistantResponseFormatOptionParam] """Specifies the format that the model must output. - Compatible with - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. diff --git a/src/openai/types/beta/assistant_update_params.py b/src/openai/types/beta/assistant_update_params.py index 55c846ce4e..b401e1a891 100644 --- a/src/openai/types/beta/assistant_update_params.py +++ b/src/openai/types/beta/assistant_update_params.py @@ -45,9 +45,9 @@ class AssistantUpdateParams(TypedDict, total=False): response_format: Optional[AssistantResponseFormatOptionParam] """Specifies the format that the model must output. - Compatible with - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index 9567c8320a..6efe6e7aee 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -108,9 +108,9 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): response_format: Optional[AssistantResponseFormatOptionParam] """Specifies the format that the model must output. - Compatible with - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. diff --git a/src/openai/types/beta/threads/run.py b/src/openai/types/beta/threads/run.py index 6c118f27c1..8244ffd598 100644 --- a/src/openai/types/beta/threads/run.py +++ b/src/openai/types/beta/threads/run.py @@ -160,9 +160,9 @@ class Run(BaseModel): response_format: Optional[AssistantResponseFormatOption] = None """Specifies the format that the model must output. - Compatible with - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -182,8 +182,8 @@ class Run(BaseModel): status: RunStatus """ The status of the run, which can be either `queued`, `in_progress`, - `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, or - `expired`. + `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, + `incomplete`, or `expired`. """ thread_id: str diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index dca47a5c73..90c9708596 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -110,9 +110,9 @@ class RunCreateParamsBase(TypedDict, total=False): response_format: Optional[AssistantResponseFormatOptionParam] """Specifies the format that the model must output. - Compatible with - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and - all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. diff --git a/src/openai/types/beta/threads/run_status.py b/src/openai/types/beta/threads/run_status.py index bf9b4e7bbf..6666d00e5a 100644 --- a/src/openai/types/beta/threads/run_status.py +++ b/src/openai/types/beta/threads/run_status.py @@ -5,5 +5,13 @@ __all__ = ["RunStatus"] RunStatus = Literal[ - "queued", "in_progress", "requires_action", "cancelling", "cancelled", "failed", "completed", "expired" + "queued", + "in_progress", + "requires_action", + "cancelling", + "cancelled", + "failed", + "completed", + "incomplete", + "expired", ] From e2214ce7243c027c4e04e39b5a11986d5e361e37 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 14 May 2024 07:30:14 -0400 Subject: [PATCH 347/816] release: 1.30.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index b8af36c3aa..35c30adcff 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.29.0" + ".": "1.30.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index d74404aecd..00ba4410e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.30.0 (2024-05-14) + +Full Changelog: [v1.29.0...v1.30.0](https://github.com/openai/openai-python/compare/v1.29.0...v1.30.0) + +### Features + +* **api:** add incomplete state ([#1420](https://github.com/openai/openai-python/issues/1420)) ([6484984](https://github.com/openai/openai-python/commit/648498412d1c7740e6b67ed4d0a55b89ff29d3b1)) + ## 1.29.0 (2024-05-13) Full Changelog: [v1.28.2...v1.29.0](https://github.com/openai/openai-python/compare/v1.28.2...v1.29.0) diff --git a/pyproject.toml b/pyproject.toml index c8f549500d..d7f05594b5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.29.0" +version = "1.30.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 48332e626e..817eb239fd 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.29.0" # x-release-please-version +__version__ = "1.30.0" # x-release-please-version From 526a05ebd81256baa6a65fbcb649357e2b70cf51 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 14 May 2024 10:46:55 -0400 Subject: [PATCH 348/816] chore(internal): add slightly better logging to scripts (#1422) --- .github/workflows/ci.yml | 16 +++------------- scripts/format | 2 +- scripts/lint | 4 ++++ scripts/test | 1 - 4 files changed, 8 insertions(+), 15 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9cbc077a8c..76655ed7d6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,20 +25,10 @@ jobs: RYE_INSTALL_OPTION: '--yes' - name: Install dependencies - run: | - rye sync --all-features - - - name: Run ruff - run: | - rye run check:ruff + run: rye sync --all-features - - name: Run type checking - run: | - rye run typecheck - - - name: Ensure importable - run: | - rye run python -c 'import openai' + - name: Run lints + run: ./scripts/lint test: name: test runs-on: ubuntu-latest diff --git a/scripts/format b/scripts/format index 2a9ea4664b..667ec2d7af 100755 --- a/scripts/format +++ b/scripts/format @@ -4,5 +4,5 @@ set -e cd "$(dirname "$0")/.." +echo "==> Running formatters" rye run format - diff --git a/scripts/lint b/scripts/lint index 0cc68b5157..64495ee345 100755 --- a/scripts/lint +++ b/scripts/lint @@ -4,5 +4,9 @@ set -e cd "$(dirname "$0")/.." +echo "==> Running lints" rye run lint +echo "==> Making sure it imports" +rye run python -c 'import openai' + diff --git a/scripts/test b/scripts/test index be01d04473..b3ace9013b 100755 --- a/scripts/test +++ b/scripts/test @@ -52,6 +52,5 @@ else echo fi -# Run tests echo "==> Running tests" rye run pytest "$@" From 5a89126ad208c58b9e1dbd1fbdb698e4c00f7d8e Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 14 May 2024 10:47:23 -0400 Subject: [PATCH 349/816] release: 1.30.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 35c30adcff..1f79fd2d11 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.30.0" + ".": "1.30.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 00ba4410e4..e41c8f4a93 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.30.1 (2024-05-14) + +Full Changelog: [v1.30.0...v1.30.1](https://github.com/openai/openai-python/compare/v1.30.0...v1.30.1) + +### Chores + +* **internal:** add slightly better logging to scripts ([#1422](https://github.com/openai/openai-python/issues/1422)) ([43dffab](https://github.com/openai/openai-python/commit/43dffabb3bed4edf8a6e523cbb289f733a5f9b24)) + ## 1.30.0 (2024-05-14) Full Changelog: [v1.29.0...v1.30.0](https://github.com/openai/openai-python/compare/v1.29.0...v1.30.0) diff --git a/pyproject.toml b/pyproject.toml index d7f05594b5..a33e167244 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.30.0" +version = "1.30.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 817eb239fd..83411041ae 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.30.0" # x-release-please-version +__version__ = "1.30.1" # x-release-please-version From 534582307ae8cf19d5ebea9e8b030dc0aaf0484f Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 23 May 2024 10:49:18 +0100 Subject: [PATCH 350/816] chore(ci): update rye install location (#1436) the site is currently down due to DNS issues --- .devcontainer/Dockerfile | 2 +- .github/workflows/ci.yml | 4 ++-- .github/workflows/create-releases.yml | 2 +- .github/workflows/publish-pypi.yml | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index dd93962010..e9841a168d 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -3,7 +3,7 @@ FROM mcr.microsoft.com/vscode/devcontainers/python:0-${VARIANT} USER vscode -RUN curl -sSf https://rye-up.com/get | RYE_VERSION="0.24.0" RYE_INSTALL_OPTION="--yes" bash +RUN curl -sSf https://raw.githubusercontent.com/astral-sh/rye/main/scripts/install.sh | RYE_VERSION="0.24.0" RYE_INSTALL_OPTION="--yes" bash ENV PATH=/home/vscode/.rye/shims:$PATH RUN echo "[[ -d .venv ]] && source .venv/bin/activate" >> /home/vscode/.bashrc diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 76655ed7d6..c084831fa9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,7 +18,7 @@ jobs: - name: Install Rye run: | - curl -sSf https://rye-up.com/get | bash + curl -sSf https://raw.githubusercontent.com/astral-sh/rye/main/scripts/install.sh | bash echo "$HOME/.rye/shims" >> $GITHUB_PATH env: RYE_VERSION: 0.24.0 @@ -39,7 +39,7 @@ jobs: - name: Install Rye run: | - curl -sSf https://rye-up.com/get | bash + curl -sSf https://raw.githubusercontent.com/astral-sh/rye/main/scripts/install.sh | bash echo "$HOME/.rye/shims" >> $GITHUB_PATH env: RYE_VERSION: 0.24.0 diff --git a/.github/workflows/create-releases.yml b/.github/workflows/create-releases.yml index a641be287b..ddc4de19ef 100644 --- a/.github/workflows/create-releases.yml +++ b/.github/workflows/create-releases.yml @@ -25,7 +25,7 @@ jobs: - name: Install Rye if: ${{ steps.release.outputs.releases_created }} run: | - curl -sSf https://rye-up.com/get | bash + curl -sSf https://raw.githubusercontent.com/astral-sh/rye/main/scripts/install.sh | bash echo "$HOME/.rye/shims" >> $GITHUB_PATH env: RYE_VERSION: 0.24.0 diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml index 2f88f86407..db855cbbd9 100644 --- a/.github/workflows/publish-pypi.yml +++ b/.github/workflows/publish-pypi.yml @@ -14,7 +14,7 @@ jobs: - name: Install Rye run: | - curl -sSf https://rye-up.com/get | bash + curl -sSf https://raw.githubusercontent.com/astral-sh/rye/main/scripts/install.sh | bash echo "$HOME/.rye/shims" >> $GITHUB_PATH env: RYE_VERSION: 0.24.0 From 5dfe791aa0760d2641f10945cbfc8875496b16c7 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 23 May 2024 10:49:51 +0100 Subject: [PATCH 351/816] release: 1.30.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 1f79fd2d11..623a7e2107 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.30.1" + ".": "1.30.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index e41c8f4a93..68b9700f77 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.30.2 (2024-05-23) + +Full Changelog: [v1.30.1...v1.30.2](https://github.com/openai/openai-python/compare/v1.30.1...v1.30.2) + +### Chores + +* **ci:** update rye install location ([#1436](https://github.com/openai/openai-python/issues/1436)) ([f7cc4e7](https://github.com/openai/openai-python/commit/f7cc4e7d5d0964a4a5d53e602379770c2576e1aa)) + ## 1.30.1 (2024-05-14) Full Changelog: [v1.30.0...v1.30.1](https://github.com/openai/openai-python/compare/v1.30.0...v1.30.1) diff --git a/pyproject.toml b/pyproject.toml index a33e167244..5c16d92b76 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.30.1" +version = "1.30.2" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 83411041ae..fc87a446a4 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.30.1" # x-release-please-version +__version__ = "1.30.2" # x-release-please-version From 001965be0a2e147e9250cf3a94f84af869fc5e05 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 23 May 2024 20:03:38 +0100 Subject: [PATCH 352/816] chore(ci): update rye install location (#1440) --- .devcontainer/Dockerfile | 2 +- .github/workflows/ci.yml | 4 ++-- .github/workflows/create-releases.yml | 2 +- .github/workflows/publish-pypi.yml | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index e9841a168d..83bca8f716 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -3,7 +3,7 @@ FROM mcr.microsoft.com/vscode/devcontainers/python:0-${VARIANT} USER vscode -RUN curl -sSf https://raw.githubusercontent.com/astral-sh/rye/main/scripts/install.sh | RYE_VERSION="0.24.0" RYE_INSTALL_OPTION="--yes" bash +RUN curl -sSf https://rye.astral.sh/get | RYE_VERSION="0.24.0" RYE_INSTALL_OPTION="--yes" bash ENV PATH=/home/vscode/.rye/shims:$PATH RUN echo "[[ -d .venv ]] && source .venv/bin/activate" >> /home/vscode/.bashrc diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c084831fa9..6fc5b36597 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,7 +18,7 @@ jobs: - name: Install Rye run: | - curl -sSf https://raw.githubusercontent.com/astral-sh/rye/main/scripts/install.sh | bash + curl -sSf https://rye.astral.sh/get | bash echo "$HOME/.rye/shims" >> $GITHUB_PATH env: RYE_VERSION: 0.24.0 @@ -39,7 +39,7 @@ jobs: - name: Install Rye run: | - curl -sSf https://raw.githubusercontent.com/astral-sh/rye/main/scripts/install.sh | bash + curl -sSf https://rye.astral.sh/get | bash echo "$HOME/.rye/shims" >> $GITHUB_PATH env: RYE_VERSION: 0.24.0 diff --git a/.github/workflows/create-releases.yml b/.github/workflows/create-releases.yml index ddc4de19ef..1ac03ede3f 100644 --- a/.github/workflows/create-releases.yml +++ b/.github/workflows/create-releases.yml @@ -25,7 +25,7 @@ jobs: - name: Install Rye if: ${{ steps.release.outputs.releases_created }} run: | - curl -sSf https://raw.githubusercontent.com/astral-sh/rye/main/scripts/install.sh | bash + curl -sSf https://rye.astral.sh/get | bash echo "$HOME/.rye/shims" >> $GITHUB_PATH env: RYE_VERSION: 0.24.0 diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml index db855cbbd9..aae985b27e 100644 --- a/.github/workflows/publish-pypi.yml +++ b/.github/workflows/publish-pypi.yml @@ -14,7 +14,7 @@ jobs: - name: Install Rye run: | - curl -sSf https://raw.githubusercontent.com/astral-sh/rye/main/scripts/install.sh | bash + curl -sSf https://rye.astral.sh/get | bash echo "$HOME/.rye/shims" >> $GITHUB_PATH env: RYE_VERSION: 0.24.0 From 17c2876d97fb68b9d38d052cff66e414962b7f4e Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Fri, 24 May 2024 08:46:27 +0000 Subject: [PATCH 353/816] chore(internal): bump pyright (#1442) --- requirements-dev.lock | 2 +- src/openai/_utils/_utils.py | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/requirements-dev.lock b/requirements-dev.lock index 6a4e12022a..c5416cd4db 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -117,7 +117,7 @@ pydantic-core==2.18.2 # via pydantic pyjwt==2.8.0 # via msal -pyright==1.1.359 +pyright==1.1.364 pytest==7.1.1 # via pytest-asyncio pytest-asyncio==0.21.1 diff --git a/src/openai/_utils/_utils.py b/src/openai/_utils/_utils.py index 17904ce60d..34797c2905 100644 --- a/src/openai/_utils/_utils.py +++ b/src/openai/_utils/_utils.py @@ -20,7 +20,7 @@ import sniffio -from .._types import Headers, NotGiven, FileTypes, NotGivenOr, HeadersLike +from .._types import NotGiven, FileTypes, NotGivenOr, HeadersLike from .._compat import parse_date as parse_date, parse_datetime as parse_datetime _T = TypeVar("_T") @@ -370,7 +370,6 @@ def file_from_path(path: str) -> FileTypes: def get_required_header(headers: HeadersLike, header: str) -> str: lower_header = header.lower() if isinstance(headers, Mapping): - headers = cast(Headers, headers) for k, v in headers.items(): if k.lower() == lower_header and isinstance(v, str): return v From 302f45a425850c13f94a2bbdd67618bfe3c33758 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Fri, 24 May 2024 15:39:44 +0100 Subject: [PATCH 354/816] chore(internal): fix lint issue (#1444) --- src/openai/lib/azure.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/openai/lib/azure.py b/src/openai/lib/azure.py index b76b83c61c..165b9b82e2 100644 --- a/src/openai/lib/azure.py +++ b/src/openai/lib/azure.py @@ -2,7 +2,7 @@ import os import inspect -from typing import Any, Union, Mapping, TypeVar, Callable, Awaitable, overload +from typing import Any, Union, Mapping, TypeVar, Callable, Awaitable, cast, overload from typing_extensions import Self, override import httpx @@ -515,7 +515,7 @@ async def _get_azure_ad_token(self) -> str | None: token = provider() if inspect.isawaitable(token): token = await token - if not token or not isinstance(token, str): + if not token or not isinstance(cast(Any, token), str): raise ValueError( f"Expected `azure_ad_token_provider` argument to return a string but it returned {token}", ) From 99f493961c926e87b5ea8d826301f8be7b07088e Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Fri, 24 May 2024 14:54:22 +0000 Subject: [PATCH 355/816] docs(contributing): update references to rye-up.com --- src/openai/lib/azure.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/openai/lib/azure.py b/src/openai/lib/azure.py index 165b9b82e2..b76b83c61c 100644 --- a/src/openai/lib/azure.py +++ b/src/openai/lib/azure.py @@ -2,7 +2,7 @@ import os import inspect -from typing import Any, Union, Mapping, TypeVar, Callable, Awaitable, cast, overload +from typing import Any, Union, Mapping, TypeVar, Callable, Awaitable, overload from typing_extensions import Self, override import httpx @@ -515,7 +515,7 @@ async def _get_azure_ad_token(self) -> str | None: token = provider() if inspect.isawaitable(token): token = await token - if not token or not isinstance(cast(Any, token), str): + if not token or not isinstance(token, str): raise ValueError( f"Expected `azure_ad_token_provider` argument to return a string but it returned {token}", ) From 7fff7c842918e718e1e9dc3954f0e66aebfc2601 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 24 May 2024 15:54:48 +0100 Subject: [PATCH 356/816] release: 1.30.3 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 15 +++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 18 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 623a7e2107..6c6045ba02 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.30.2" + ".": "1.30.3" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 68b9700f77..7276bd8c03 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## 1.30.3 (2024-05-24) + +Full Changelog: [v1.30.2...v1.30.3](https://github.com/openai/openai-python/compare/v1.30.2...v1.30.3) + +### Chores + +* **ci:** update rye install location ([#1440](https://github.com/openai/openai-python/issues/1440)) ([8a0e5bf](https://github.com/openai/openai-python/commit/8a0e5bf4c03d9c714799fad43be68ac9c2b1f37a)) +* **internal:** bump pyright ([#1442](https://github.com/openai/openai-python/issues/1442)) ([64a151e](https://github.com/openai/openai-python/commit/64a151eae705d55484f870df461434c0a6961e2b)) +* **internal:** fix lint issue ([#1444](https://github.com/openai/openai-python/issues/1444)) ([b0eb458](https://github.com/openai/openai-python/commit/b0eb4582e050b0a25af3d80d2cb584bfc7cd11ab)) + + +### Documentation + +* **contributing:** update references to rye-up.com ([dcc34a2](https://github.com/openai/openai-python/commit/dcc34a26d1a6a0debf440724fad658c77547048c)) + ## 1.30.2 (2024-05-23) Full Changelog: [v1.30.1...v1.30.2](https://github.com/openai/openai-python/compare/v1.30.1...v1.30.2) diff --git a/pyproject.toml b/pyproject.toml index 5c16d92b76..850cf8419b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.30.2" +version = "1.30.3" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index fc87a446a4..541680fae0 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.30.2" # x-release-please-version +__version__ = "1.30.3" # x-release-please-version From 59855b24b7d46a087d15bb9dfabce2ae3dfb1300 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Fri, 24 May 2024 15:37:45 +0100 Subject: [PATCH 357/816] chore(internal): fix lint issue --- src/openai/lib/azure.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/openai/lib/azure.py b/src/openai/lib/azure.py index b76b83c61c..165b9b82e2 100644 --- a/src/openai/lib/azure.py +++ b/src/openai/lib/azure.py @@ -2,7 +2,7 @@ import os import inspect -from typing import Any, Union, Mapping, TypeVar, Callable, Awaitable, overload +from typing import Any, Union, Mapping, TypeVar, Callable, Awaitable, cast, overload from typing_extensions import Self, override import httpx @@ -515,7 +515,7 @@ async def _get_azure_ad_token(self) -> str | None: token = provider() if inspect.isawaitable(token): token = await token - if not token or not isinstance(token, str): + if not token or not isinstance(cast(Any, token), str): raise ValueError( f"Expected `azure_ad_token_provider` argument to return a string but it returned {token}", ) From 379c6a36af4d2afb3df1fa18d112c654226af5b2 Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Tue, 28 May 2024 09:22:38 +0000 Subject: [PATCH 358/816] chore: add missing __all__ definitions --- src/openai/lib/azure.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/openai/lib/azure.py b/src/openai/lib/azure.py index 165b9b82e2..b76b83c61c 100644 --- a/src/openai/lib/azure.py +++ b/src/openai/lib/azure.py @@ -2,7 +2,7 @@ import os import inspect -from typing import Any, Union, Mapping, TypeVar, Callable, Awaitable, cast, overload +from typing import Any, Union, Mapping, TypeVar, Callable, Awaitable, overload from typing_extensions import Self, override import httpx @@ -515,7 +515,7 @@ async def _get_azure_ad_token(self) -> str | None: token = provider() if inspect.isawaitable(token): token = await token - if not token or not isinstance(cast(Any, token), str): + if not token or not isinstance(token, str): raise ValueError( f"Expected `azure_ad_token_provider` argument to return a string but it returned {token}", ) From bb0b38d9882745d51a32dc3fcc0d6a54cdd298cb Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Tue, 28 May 2024 05:23:07 -0400 Subject: [PATCH 359/816] release: 1.30.4 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 9 +++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 6c6045ba02..5d67d3563d 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.30.3" + ".": "1.30.4" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 7276bd8c03..b72dd9335d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 1.30.4 (2024-05-28) + +Full Changelog: [v1.30.3...v1.30.4](https://github.com/openai/openai-python/compare/v1.30.3...v1.30.4) + +### Chores + +* add missing __all__ definitions ([7fba60f](https://github.com/openai/openai-python/commit/7fba60f2e8adc26e83080aaf3e436eb9891e1253)) +* **internal:** fix lint issue ([f423cd0](https://github.com/openai/openai-python/commit/f423cd05d33b3e734eda7c0c008faac14ae96bb7)) + ## 1.30.3 (2024-05-24) Full Changelog: [v1.30.2...v1.30.3](https://github.com/openai/openai-python/compare/v1.30.2...v1.30.3) diff --git a/pyproject.toml b/pyproject.toml index 850cf8419b..3b6888a64d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.30.3" +version = "1.30.4" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 541680fae0..de2bb78a79 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.30.3" # x-release-please-version +__version__ = "1.30.4" # x-release-please-version From 6e7d8548899193d35b041a45d8e1b22cf2057481 Mon Sep 17 00:00:00 2001 From: Scott Addie <10702007+scottaddie@users.noreply.github.com> Date: Tue, 28 May 2024 21:26:47 -0500 Subject: [PATCH 360/816] Update Microsoft Azure OpenAI docs in README (#1439) * Update Microsoft Azure OpenAI docs in README * React to feedback --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index e566a2f8d0..5e351ba03c 100644 --- a/README.md +++ b/README.md @@ -581,7 +581,7 @@ By default the library closes underlying HTTP connections whenever the client is ## Microsoft Azure OpenAI -To use this library with [Azure OpenAI](https://learn.microsoft.com/en-us/azure/ai-services/openai/overview), use the `AzureOpenAI` +To use this library with [Azure OpenAI](https://learn.microsoft.com/azure/ai-services/openai/overview), use the `AzureOpenAI` class instead of the `OpenAI` class. > [!IMPORTANT] @@ -593,9 +593,9 @@ from openai import AzureOpenAI # gets the API Key from environment variable AZURE_OPENAI_API_KEY client = AzureOpenAI( - # https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#rest-api-versioning + # https://learn.microsoft.com/azure/ai-services/openai/reference#rest-api-versioning api_version="2023-07-01-preview", - # https://learn.microsoft.com/en-us/azure/cognitive-services/openai/how-to/create-resource?pivots=web-portal#create-a-resource + # https://learn.microsoft.com/azure/cognitive-services/openai/how-to/create-resource?pivots=web-portal#create-a-resource azure_endpoint="https://example-endpoint.openai.azure.com/", ) @@ -619,7 +619,7 @@ In addition to the options provided in the base `OpenAI` client, the following o - `azure_ad_token` (or the `AZURE_OPENAI_AD_TOKEN` environment variable) - `azure_ad_token_provider` -An example of using the client with Azure Active Directory can be found [here](https://github.com/openai/openai-python/blob/main/examples/azure_ad.py). +An example of using the client with Microsoft Entra ID (formerly known as Azure Active Directory) can be found [here](https://github.com/openai/openai-python/blob/main/examples/azure_ad.py). ## Versioning From e565c9425a58f90216b813883e018ceb42b9ca11 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Fri, 24 May 2024 15:37:45 +0100 Subject: [PATCH 361/816] chore(internal): fix lint issue --- src/openai/lib/azure.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/openai/lib/azure.py b/src/openai/lib/azure.py index b76b83c61c..165b9b82e2 100644 --- a/src/openai/lib/azure.py +++ b/src/openai/lib/azure.py @@ -2,7 +2,7 @@ import os import inspect -from typing import Any, Union, Mapping, TypeVar, Callable, Awaitable, overload +from typing import Any, Union, Mapping, TypeVar, Callable, Awaitable, cast, overload from typing_extensions import Self, override import httpx @@ -515,7 +515,7 @@ async def _get_azure_ad_token(self) -> str | None: token = provider() if inspect.isawaitable(token): token = await token - if not token or not isinstance(token, str): + if not token or not isinstance(cast(Any, token), str): raise ValueError( f"Expected `azure_ad_token_provider` argument to return a string but it returned {token}", ) From e872382c325eb0189432640a822980565290c19e Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 29 May 2024 17:29:14 +0000 Subject: [PATCH 362/816] release: 1.30.5 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 5d67d3563d..4449911fae 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.30.4" + ".": "1.30.5" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index b72dd9335d..8ae0f81ffc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.30.5 (2024-05-29) + +Full Changelog: [v1.30.4...v1.30.5](https://github.com/openai/openai-python/compare/v1.30.4...v1.30.5) + +### Chores + +* **internal:** fix lint issue ([35a1e80](https://github.com/openai/openai-python/commit/35a1e806891c34d5cc13ac8341751e5b15b52319)) + ## 1.30.4 (2024-05-28) Full Changelog: [v1.30.3...v1.30.4](https://github.com/openai/openai-python/compare/v1.30.3...v1.30.4) diff --git a/pyproject.toml b/pyproject.toml index 3b6888a64d..c09baa6d7d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.30.4" +version = "1.30.5" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index de2bb78a79..1a8a23bfa3 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.30.4" # x-release-please-version +__version__ = "1.30.5" # x-release-please-version From 89dee3f4c3444880cb359e7be2312f1f04caec4f Mon Sep 17 00:00:00 2001 From: Selim Waly Date: Sun, 2 Jun 2024 23:48:46 +0300 Subject: [PATCH 363/816] Fix Azure Ad Token Function's Return (#1460) Identify returned "token" as string. --- src/openai/lib/azure.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/openai/lib/azure.py b/src/openai/lib/azure.py index 165b9b82e2..cbe57b7b98 100644 --- a/src/openai/lib/azure.py +++ b/src/openai/lib/azure.py @@ -519,7 +519,7 @@ async def _get_azure_ad_token(self) -> str | None: raise ValueError( f"Expected `azure_ad_token_provider` argument to return a string but it returned {token}", ) - return token + return str(token) return None From 1ff30bf51858cb2ee8a89a4d7f6912f6ee98ff86 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 3 Jun 2024 23:55:27 +0100 Subject: [PATCH 364/816] feat(api): updates (#1461) --- .stats.yml | 2 +- src/openai/resources/batches.py | 18 ++++--- .../beta/vector_stores/file_batches.py | 24 ++++++++- .../resources/beta/vector_stores/files.py | 24 ++++++++- .../beta/vector_stores/vector_stores.py | 10 ++++ src/openai/resources/files.py | 24 ++++++--- src/openai/resources/fine_tuning/jobs/jobs.py | 10 ++++ src/openai/types/batch_create_params.py | 2 +- .../types/beta/assistant_create_params.py | 42 ++++++++++++++++ .../types/beta/assistant_stream_event.py | 12 +++++ src/openai/types/beta/file_search_tool.py | 20 +++++++- .../types/beta/file_search_tool_param.py | 19 ++++++- .../beta/thread_create_and_run_params.py | 43 ++++++++++++++++ src/openai/types/beta/thread_create_params.py | 42 ++++++++++++++++ .../types/beta/vector_store_create_params.py | 48 +++++++++++++++++- .../vector_stores/file_batch_create_params.py | 50 +++++++++++++++++-- .../beta/vector_stores/file_create_params.py | 49 +++++++++++++++++- .../beta/vector_stores/vector_store_file.py | 47 +++++++++++++++-- ...chat_completion_assistant_message_param.py | 2 +- .../types/chat/completion_create_params.py | 5 +- src/openai/types/file_create_params.py | 2 +- .../types/fine_tuning/job_create_params.py | 5 ++ .../types/shared/function_definition.py | 5 +- .../shared_params/function_definition.py | 5 +- tests/api_resources/beta/test_assistants.py | 2 + tests/api_resources/beta/test_threads.py | 6 +++ .../api_resources/beta/test_vector_stores.py | 2 + .../beta/vector_stores/test_file_batches.py | 18 +++++++ .../beta/vector_stores/test_files.py | 18 +++++++ 29 files changed, 515 insertions(+), 41 deletions(-) diff --git a/.stats.yml b/.stats.yml index 2e5c705a0d..11d2b0b181 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 64 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-363dd904e5d6e65b3a323fc88e6b502fb23a6aa319be219273e3ee47c7530993.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-0577fd0d08da6b867b002a5accd45f7116ef91c4940b41cf45dc479938c77163.yml diff --git a/src/openai/resources/batches.py b/src/openai/resources/batches.py index db4c4da235..7152fac622 100644 --- a/src/openai/resources/batches.py +++ b/src/openai/resources/batches.py @@ -68,7 +68,7 @@ def create( for how to upload a file. Your input file must be formatted as a - [JSONL file](https://platform.openai.com/docs/api-reference/batch/requestInput), + [JSONL file](https://platform.openai.com/docs/api-reference/batch/request-input), and must be uploaded with the purpose `batch`. The file can contain up to 50,000 requests, and can be up to 100 MB in size. @@ -195,8 +195,11 @@ def cancel( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Batch: - """ - Cancels an in-progress batch. + """Cancels an in-progress batch. + + The batch will be in status `cancelling` for up to + 10 minutes, before changing to `cancelled`, where it will have partial results + (if any) available in the output file. Args: extra_headers: Send extra headers @@ -259,7 +262,7 @@ async def create( for how to upload a file. Your input file must be formatted as a - [JSONL file](https://platform.openai.com/docs/api-reference/batch/requestInput), + [JSONL file](https://platform.openai.com/docs/api-reference/batch/request-input), and must be uploaded with the purpose `batch`. The file can contain up to 50,000 requests, and can be up to 100 MB in size. @@ -386,8 +389,11 @@ async def cancel( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Batch: - """ - Cancels an in-progress batch. + """Cancels an in-progress batch. + + The batch will be in status `cancelling` for up to + 10 minutes, before changing to `cancelled`, where it will have partial results + (if any) available in the output file. Args: extra_headers: Send extra headers diff --git a/src/openai/resources/beta/vector_stores/file_batches.py b/src/openai/resources/beta/vector_stores/file_batches.py index f1ced51700..21ac68f6de 100644 --- a/src/openai/resources/beta/vector_stores/file_batches.py +++ b/src/openai/resources/beta/vector_stores/file_batches.py @@ -47,6 +47,7 @@ def create( vector_store_id: str, *, file_ids: List[str], + chunking_strategy: file_batch_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -62,6 +63,9 @@ def create( the vector store should use. Useful for tools like `file_search` that can access files. + chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will use the `auto` + strategy. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -75,7 +79,13 @@ def create( extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._post( f"/vector_stores/{vector_store_id}/file_batches", - body=maybe_transform({"file_ids": file_ids}, file_batch_create_params.FileBatchCreateParams), + body=maybe_transform( + { + "file_ids": file_ids, + "chunking_strategy": chunking_strategy, + }, + file_batch_create_params.FileBatchCreateParams, + ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), @@ -351,6 +361,7 @@ async def create( vector_store_id: str, *, file_ids: List[str], + chunking_strategy: file_batch_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -366,6 +377,9 @@ async def create( the vector store should use. Useful for tools like `file_search` that can access files. + chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will use the `auto` + strategy. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -379,7 +393,13 @@ async def create( extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._post( f"/vector_stores/{vector_store_id}/file_batches", - body=await async_maybe_transform({"file_ids": file_ids}, file_batch_create_params.FileBatchCreateParams), + body=await async_maybe_transform( + { + "file_ids": file_ids, + "chunking_strategy": chunking_strategy, + }, + file_batch_create_params.FileBatchCreateParams, + ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), diff --git a/src/openai/resources/beta/vector_stores/files.py b/src/openai/resources/beta/vector_stores/files.py index 5c3db27619..30f19ef491 100644 --- a/src/openai/resources/beta/vector_stores/files.py +++ b/src/openai/resources/beta/vector_stores/files.py @@ -43,6 +43,7 @@ def create( vector_store_id: str, *, file_id: str, + chunking_strategy: file_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -60,6 +61,9 @@ def create( vector store should use. Useful for tools like `file_search` that can access files. + chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will use the `auto` + strategy. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -73,7 +77,13 @@ def create( extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._post( f"/vector_stores/{vector_store_id}/files", - body=maybe_transform({"file_id": file_id}, file_create_params.FileCreateParams), + body=maybe_transform( + { + "file_id": file_id, + "chunking_strategy": chunking_strategy, + }, + file_create_params.FileCreateParams, + ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), @@ -330,6 +340,7 @@ async def create( vector_store_id: str, *, file_id: str, + chunking_strategy: file_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -347,6 +358,9 @@ async def create( vector store should use. Useful for tools like `file_search` that can access files. + chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will use the `auto` + strategy. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -360,7 +374,13 @@ async def create( extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return await self._post( f"/vector_stores/{vector_store_id}/files", - body=await async_maybe_transform({"file_id": file_id}, file_create_params.FileCreateParams), + body=await async_maybe_transform( + { + "file_id": file_id, + "chunking_strategy": chunking_strategy, + }, + file_create_params.FileCreateParams, + ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), diff --git a/src/openai/resources/beta/vector_stores/vector_stores.py b/src/openai/resources/beta/vector_stores/vector_stores.py index 8a177c2864..cbd56a0693 100644 --- a/src/openai/resources/beta/vector_stores/vector_stores.py +++ b/src/openai/resources/beta/vector_stores/vector_stores.py @@ -64,6 +64,7 @@ def with_streaming_response(self) -> VectorStoresWithStreamingResponse: def create( self, *, + chunking_strategy: vector_store_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, expires_after: vector_store_create_params.ExpiresAfter | NotGiven = NOT_GIVEN, file_ids: List[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, @@ -79,6 +80,9 @@ def create( Create a vector store. Args: + chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will use the `auto` + strategy. Only applicable if `file_ids` is non-empty. + expires_after: The expiration policy for a vector store. file_ids: A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that @@ -105,6 +109,7 @@ def create( "/vector_stores", body=maybe_transform( { + "chunking_strategy": chunking_strategy, "expires_after": expires_after, "file_ids": file_ids, "metadata": metadata, @@ -326,6 +331,7 @@ def with_streaming_response(self) -> AsyncVectorStoresWithStreamingResponse: async def create( self, *, + chunking_strategy: vector_store_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, expires_after: vector_store_create_params.ExpiresAfter | NotGiven = NOT_GIVEN, file_ids: List[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, @@ -341,6 +347,9 @@ async def create( Create a vector store. Args: + chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will use the `auto` + strategy. Only applicable if `file_ids` is non-empty. + expires_after: The expiration policy for a vector store. file_ids: A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that @@ -367,6 +376,7 @@ async def create( "/vector_stores", body=await async_maybe_transform( { + "chunking_strategy": chunking_strategy, "expires_after": expires_after, "file_ids": file_ids, "metadata": metadata, diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index aed0829dfe..432ac30913 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -52,7 +52,7 @@ def create( self, *, file: FileTypes, - purpose: Literal["assistants", "batch", "fine-tune"], + purpose: Literal["assistants", "batch", "fine-tune", "vision"], # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -71,9 +71,15 @@ def create( [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for details. - The Fine-tuning API only supports `.jsonl` files. + The Fine-tuning API only supports `.jsonl` files. The input also has certain + required formats for fine-tuning + [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or + [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) + models. - The Batch API only supports `.jsonl` files up to 100 MB in size. + The Batch API only supports `.jsonl` files up to 100 MB in size. The input also + has a specific required + [format](https://platform.openai.com/docs/api-reference/batch/request-input). Please [contact us](https://help.openai.com/) if you need to increase these storage limits. @@ -329,7 +335,7 @@ async def create( self, *, file: FileTypes, - purpose: Literal["assistants", "batch", "fine-tune"], + purpose: Literal["assistants", "batch", "fine-tune", "vision"], # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -348,9 +354,15 @@ async def create( [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for details. - The Fine-tuning API only supports `.jsonl` files. + The Fine-tuning API only supports `.jsonl` files. The input also has certain + required formats for fine-tuning + [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or + [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) + models. - The Batch API only supports `.jsonl` files up to 100 MB in size. + The Batch API only supports `.jsonl` files up to 100 MB in size. The input also + has a specific required + [format](https://platform.openai.com/docs/api-reference/batch/request-input). Please [contact us](https://help.openai.com/) if you need to increase these storage limits. diff --git a/src/openai/resources/fine_tuning/jobs/jobs.py b/src/openai/resources/fine_tuning/jobs/jobs.py index f38956e6be..14b384a88d 100644 --- a/src/openai/resources/fine_tuning/jobs/jobs.py +++ b/src/openai/resources/fine_tuning/jobs/jobs.py @@ -87,6 +87,11 @@ def create( Your dataset must be formatted as a JSONL file. Additionally, you must upload your file with the purpose `fine-tune`. + The contents of the file should differ depending on if the model uses the + [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or + [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) + format. + See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) for more details. @@ -362,6 +367,11 @@ async def create( Your dataset must be formatted as a JSONL file. Additionally, you must upload your file with the purpose `fine-tune`. + The contents of the file should differ depending on if the model uses the + [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or + [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) + format. + See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) for more details. diff --git a/src/openai/types/batch_create_params.py b/src/openai/types/batch_create_params.py index 140380d417..55517d285b 100644 --- a/src/openai/types/batch_create_params.py +++ b/src/openai/types/batch_create_params.py @@ -30,7 +30,7 @@ class BatchCreateParams(TypedDict, total=False): for how to upload a file. Your input file must be formatted as a - [JSONL file](https://platform.openai.com/docs/api-reference/batch/requestInput), + [JSONL file](https://platform.openai.com/docs/api-reference/batch/request-input), and must be uploaded with the purpose `batch`. The file can contain up to 50,000 requests, and can be up to 100 MB in size. """ diff --git a/src/openai/types/beta/assistant_create_params.py b/src/openai/types/beta/assistant_create_params.py index 67e7f7e78c..c9b0317831 100644 --- a/src/openai/types/beta/assistant_create_params.py +++ b/src/openai/types/beta/assistant_create_params.py @@ -14,6 +14,10 @@ "ToolResourcesCodeInterpreter", "ToolResourcesFileSearch", "ToolResourcesFileSearchVectorStore", + "ToolResourcesFileSearchVectorStoreChunkingStrategy", + "ToolResourcesFileSearchVectorStoreChunkingStrategyAuto", + "ToolResourcesFileSearchVectorStoreChunkingStrategyStatic", + "ToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic", ] @@ -134,7 +138,45 @@ class ToolResourcesCodeInterpreter(TypedDict, total=False): """ +class ToolResourcesFileSearchVectorStoreChunkingStrategyAuto(TypedDict, total=False): + type: Required[Literal["auto"]] + """Always `auto`.""" + + +class ToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic(TypedDict, total=False): + chunk_overlap_tokens: Required[int] + """The number of tokens that overlap between chunks. The default value is `400`. + + Note that the overlap must not exceed half of `max_chunk_size_tokens`. + """ + + max_chunk_size_tokens: Required[int] + """The maximum number of tokens in each chunk. + + The default value is `800`. The minimum value is `100` and the maximum value is + `4096`. + """ + + +class ToolResourcesFileSearchVectorStoreChunkingStrategyStatic(TypedDict, total=False): + static: Required[ToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic] + + type: Required[Literal["static"]] + """Always `static`.""" + + +ToolResourcesFileSearchVectorStoreChunkingStrategy = Union[ + ToolResourcesFileSearchVectorStoreChunkingStrategyAuto, ToolResourcesFileSearchVectorStoreChunkingStrategyStatic +] + + class ToolResourcesFileSearchVectorStore(TypedDict, total=False): + chunking_strategy: ToolResourcesFileSearchVectorStoreChunkingStrategy + """The chunking strategy used to chunk the file(s). + + If not set, will use the `auto` strategy. + """ + file_ids: List[str] """ A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to diff --git a/src/openai/types/beta/assistant_stream_event.py b/src/openai/types/beta/assistant_stream_event.py index 91925e93b3..de66888403 100644 --- a/src/openai/types/beta/assistant_stream_event.py +++ b/src/openai/types/beta/assistant_stream_event.py @@ -21,6 +21,7 @@ "ThreadRunInProgress", "ThreadRunRequiresAction", "ThreadRunCompleted", + "ThreadRunIncomplete", "ThreadRunFailed", "ThreadRunCancelling", "ThreadRunCancelled", @@ -101,6 +102,16 @@ class ThreadRunCompleted(BaseModel): event: Literal["thread.run.completed"] +class ThreadRunIncomplete(BaseModel): + data: Run + """ + Represents an execution run on a + [thread](https://platform.openai.com/docs/api-reference/threads). + """ + + event: Literal["thread.run.incomplete"] + + class ThreadRunFailed(BaseModel): data: Run """ @@ -257,6 +268,7 @@ class ErrorEvent(BaseModel): ThreadRunInProgress, ThreadRunRequiresAction, ThreadRunCompleted, + ThreadRunIncomplete, ThreadRunFailed, ThreadRunCancelling, ThreadRunCancelled, diff --git a/src/openai/types/beta/file_search_tool.py b/src/openai/types/beta/file_search_tool.py index eea55ea6ac..e2711b9b3d 100644 --- a/src/openai/types/beta/file_search_tool.py +++ b/src/openai/types/beta/file_search_tool.py @@ -1,12 +1,30 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +from typing import Optional from typing_extensions import Literal from ..._models import BaseModel -__all__ = ["FileSearchTool"] +__all__ = ["FileSearchTool", "FileSearch"] + + +class FileSearch(BaseModel): + max_num_results: Optional[int] = None + """The maximum number of results the file search tool should output. + + The default is 20 for gpt-4\\** models and 5 for gpt-3.5-turbo. This number should + be between 1 and 50 inclusive. + + Note that the file search tool may output fewer than `max_num_results` results. + See the + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/number-of-chunks-returned) + for more information. + """ class FileSearchTool(BaseModel): type: Literal["file_search"] """The type of tool being defined: `file_search`""" + + file_search: Optional[FileSearch] = None + """Overrides for the file search tool.""" diff --git a/src/openai/types/beta/file_search_tool_param.py b/src/openai/types/beta/file_search_tool_param.py index d33fd06da4..115f86a444 100644 --- a/src/openai/types/beta/file_search_tool_param.py +++ b/src/openai/types/beta/file_search_tool_param.py @@ -4,9 +4,26 @@ from typing_extensions import Literal, Required, TypedDict -__all__ = ["FileSearchToolParam"] +__all__ = ["FileSearchToolParam", "FileSearch"] + + +class FileSearch(TypedDict, total=False): + max_num_results: int + """The maximum number of results the file search tool should output. + + The default is 20 for gpt-4\\** models and 5 for gpt-3.5-turbo. This number should + be between 1 and 50 inclusive. + + Note that the file search tool may output fewer than `max_num_results` results. + See the + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/number-of-chunks-returned) + for more information. + """ class FileSearchToolParam(TypedDict, total=False): type: Required[Literal["file_search"]] """The type of tool being defined: `file_search`""" + + file_search: FileSearch + """Overrides for the file search tool.""" diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index 6efe6e7aee..436c2daddf 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -22,6 +22,10 @@ "ThreadToolResourcesCodeInterpreter", "ThreadToolResourcesFileSearch", "ThreadToolResourcesFileSearchVectorStore", + "ThreadToolResourcesFileSearchVectorStoreChunkingStrategy", + "ThreadToolResourcesFileSearchVectorStoreChunkingStrategyAuto", + "ThreadToolResourcesFileSearchVectorStoreChunkingStrategyStatic", + "ThreadToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic", "ToolResources", "ToolResourcesCodeInterpreter", "ToolResourcesFileSearch", @@ -220,7 +224,46 @@ class ThreadToolResourcesCodeInterpreter(TypedDict, total=False): """ +class ThreadToolResourcesFileSearchVectorStoreChunkingStrategyAuto(TypedDict, total=False): + type: Required[Literal["auto"]] + """Always `auto`.""" + + +class ThreadToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic(TypedDict, total=False): + chunk_overlap_tokens: Required[int] + """The number of tokens that overlap between chunks. The default value is `400`. + + Note that the overlap must not exceed half of `max_chunk_size_tokens`. + """ + + max_chunk_size_tokens: Required[int] + """The maximum number of tokens in each chunk. + + The default value is `800`. The minimum value is `100` and the maximum value is + `4096`. + """ + + +class ThreadToolResourcesFileSearchVectorStoreChunkingStrategyStatic(TypedDict, total=False): + static: Required[ThreadToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic] + + type: Required[Literal["static"]] + """Always `static`.""" + + +ThreadToolResourcesFileSearchVectorStoreChunkingStrategy = Union[ + ThreadToolResourcesFileSearchVectorStoreChunkingStrategyAuto, + ThreadToolResourcesFileSearchVectorStoreChunkingStrategyStatic, +] + + class ThreadToolResourcesFileSearchVectorStore(TypedDict, total=False): + chunking_strategy: ThreadToolResourcesFileSearchVectorStoreChunkingStrategy + """The chunking strategy used to chunk the file(s). + + If not set, will use the `auto` strategy. + """ + file_ids: List[str] """ A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to diff --git a/src/openai/types/beta/thread_create_params.py b/src/openai/types/beta/thread_create_params.py index ccf50d58dc..5072ed12d9 100644 --- a/src/openai/types/beta/thread_create_params.py +++ b/src/openai/types/beta/thread_create_params.py @@ -18,6 +18,10 @@ "ToolResourcesCodeInterpreter", "ToolResourcesFileSearch", "ToolResourcesFileSearchVectorStore", + "ToolResourcesFileSearchVectorStoreChunkingStrategy", + "ToolResourcesFileSearchVectorStoreChunkingStrategyAuto", + "ToolResourcesFileSearchVectorStoreChunkingStrategyStatic", + "ToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic", ] @@ -90,7 +94,45 @@ class ToolResourcesCodeInterpreter(TypedDict, total=False): """ +class ToolResourcesFileSearchVectorStoreChunkingStrategyAuto(TypedDict, total=False): + type: Required[Literal["auto"]] + """Always `auto`.""" + + +class ToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic(TypedDict, total=False): + chunk_overlap_tokens: Required[int] + """The number of tokens that overlap between chunks. The default value is `400`. + + Note that the overlap must not exceed half of `max_chunk_size_tokens`. + """ + + max_chunk_size_tokens: Required[int] + """The maximum number of tokens in each chunk. + + The default value is `800`. The minimum value is `100` and the maximum value is + `4096`. + """ + + +class ToolResourcesFileSearchVectorStoreChunkingStrategyStatic(TypedDict, total=False): + static: Required[ToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic] + + type: Required[Literal["static"]] + """Always `static`.""" + + +ToolResourcesFileSearchVectorStoreChunkingStrategy = Union[ + ToolResourcesFileSearchVectorStoreChunkingStrategyAuto, ToolResourcesFileSearchVectorStoreChunkingStrategyStatic +] + + class ToolResourcesFileSearchVectorStore(TypedDict, total=False): + chunking_strategy: ToolResourcesFileSearchVectorStoreChunkingStrategy + """The chunking strategy used to chunk the file(s). + + If not set, will use the `auto` strategy. + """ + file_ids: List[str] """ A list of [file](https://platform.openai.com/docs/api-reference/files) IDs to diff --git a/src/openai/types/beta/vector_store_create_params.py b/src/openai/types/beta/vector_store_create_params.py index f1a3abcbdf..365d9923b8 100644 --- a/src/openai/types/beta/vector_store_create_params.py +++ b/src/openai/types/beta/vector_store_create_params.py @@ -2,13 +2,27 @@ from __future__ import annotations -from typing import List, Optional +from typing import List, Union, Optional from typing_extensions import Literal, Required, TypedDict -__all__ = ["VectorStoreCreateParams", "ExpiresAfter"] +__all__ = [ + "VectorStoreCreateParams", + "ChunkingStrategy", + "ChunkingStrategyAuto", + "ChunkingStrategyStatic", + "ChunkingStrategyStaticStatic", + "ExpiresAfter", +] class VectorStoreCreateParams(TypedDict, total=False): + chunking_strategy: ChunkingStrategy + """The chunking strategy used to chunk the file(s). + + If not set, will use the `auto` strategy. Only applicable if `file_ids` is + non-empty. + """ + expires_after: ExpiresAfter """The expiration policy for a vector store.""" @@ -31,6 +45,36 @@ class VectorStoreCreateParams(TypedDict, total=False): """The name of the vector store.""" +class ChunkingStrategyAuto(TypedDict, total=False): + type: Required[Literal["auto"]] + """Always `auto`.""" + + +class ChunkingStrategyStaticStatic(TypedDict, total=False): + chunk_overlap_tokens: Required[int] + """The number of tokens that overlap between chunks. The default value is `400`. + + Note that the overlap must not exceed half of `max_chunk_size_tokens`. + """ + + max_chunk_size_tokens: Required[int] + """The maximum number of tokens in each chunk. + + The default value is `800`. The minimum value is `100` and the maximum value is + `4096`. + """ + + +class ChunkingStrategyStatic(TypedDict, total=False): + static: Required[ChunkingStrategyStaticStatic] + + type: Required[Literal["static"]] + """Always `static`.""" + + +ChunkingStrategy = Union[ChunkingStrategyAuto, ChunkingStrategyStatic] + + class ExpiresAfter(TypedDict, total=False): anchor: Required[Literal["last_active_at"]] """Anchor timestamp after which the expiration policy applies. diff --git a/src/openai/types/beta/vector_stores/file_batch_create_params.py b/src/openai/types/beta/vector_stores/file_batch_create_params.py index 0882829732..9b98d0699e 100644 --- a/src/openai/types/beta/vector_stores/file_batch_create_params.py +++ b/src/openai/types/beta/vector_stores/file_batch_create_params.py @@ -2,10 +2,16 @@ from __future__ import annotations -from typing import List -from typing_extensions import Required, TypedDict +from typing import List, Union +from typing_extensions import Literal, Required, TypedDict -__all__ = ["FileBatchCreateParams"] +__all__ = [ + "FileBatchCreateParams", + "ChunkingStrategy", + "ChunkingStrategyAutoChunkingStrategyRequestParam", + "ChunkingStrategyStaticChunkingStrategyRequestParam", + "ChunkingStrategyStaticChunkingStrategyRequestParamStatic", +] class FileBatchCreateParams(TypedDict, total=False): @@ -15,3 +21,41 @@ class FileBatchCreateParams(TypedDict, total=False): the vector store should use. Useful for tools like `file_search` that can access files. """ + + chunking_strategy: ChunkingStrategy + """The chunking strategy used to chunk the file(s). + + If not set, will use the `auto` strategy. + """ + + +class ChunkingStrategyAutoChunkingStrategyRequestParam(TypedDict, total=False): + type: Required[Literal["auto"]] + """Always `auto`.""" + + +class ChunkingStrategyStaticChunkingStrategyRequestParamStatic(TypedDict, total=False): + chunk_overlap_tokens: Required[int] + """The number of tokens that overlap between chunks. The default value is `400`. + + Note that the overlap must not exceed half of `max_chunk_size_tokens`. + """ + + max_chunk_size_tokens: Required[int] + """The maximum number of tokens in each chunk. + + The default value is `800`. The minimum value is `100` and the maximum value is + `4096`. + """ + + +class ChunkingStrategyStaticChunkingStrategyRequestParam(TypedDict, total=False): + static: Required[ChunkingStrategyStaticChunkingStrategyRequestParamStatic] + + type: Required[Literal["static"]] + """Always `static`.""" + + +ChunkingStrategy = Union[ + ChunkingStrategyAutoChunkingStrategyRequestParam, ChunkingStrategyStaticChunkingStrategyRequestParam +] diff --git a/src/openai/types/beta/vector_stores/file_create_params.py b/src/openai/types/beta/vector_stores/file_create_params.py index 2fee588abf..2ae63f1462 100644 --- a/src/openai/types/beta/vector_stores/file_create_params.py +++ b/src/openai/types/beta/vector_stores/file_create_params.py @@ -2,9 +2,16 @@ from __future__ import annotations -from typing_extensions import Required, TypedDict +from typing import Union +from typing_extensions import Literal, Required, TypedDict -__all__ = ["FileCreateParams"] +__all__ = [ + "FileCreateParams", + "ChunkingStrategy", + "ChunkingStrategyAutoChunkingStrategyRequestParam", + "ChunkingStrategyStaticChunkingStrategyRequestParam", + "ChunkingStrategyStaticChunkingStrategyRequestParamStatic", +] class FileCreateParams(TypedDict, total=False): @@ -14,3 +21,41 @@ class FileCreateParams(TypedDict, total=False): vector store should use. Useful for tools like `file_search` that can access files. """ + + chunking_strategy: ChunkingStrategy + """The chunking strategy used to chunk the file(s). + + If not set, will use the `auto` strategy. + """ + + +class ChunkingStrategyAutoChunkingStrategyRequestParam(TypedDict, total=False): + type: Required[Literal["auto"]] + """Always `auto`.""" + + +class ChunkingStrategyStaticChunkingStrategyRequestParamStatic(TypedDict, total=False): + chunk_overlap_tokens: Required[int] + """The number of tokens that overlap between chunks. The default value is `400`. + + Note that the overlap must not exceed half of `max_chunk_size_tokens`. + """ + + max_chunk_size_tokens: Required[int] + """The maximum number of tokens in each chunk. + + The default value is `800`. The minimum value is `100` and the maximum value is + `4096`. + """ + + +class ChunkingStrategyStaticChunkingStrategyRequestParam(TypedDict, total=False): + static: Required[ChunkingStrategyStaticChunkingStrategyRequestParamStatic] + + type: Required[Literal["static"]] + """Always `static`.""" + + +ChunkingStrategy = Union[ + ChunkingStrategyAutoChunkingStrategyRequestParam, ChunkingStrategyStaticChunkingStrategyRequestParam +] diff --git a/src/openai/types/beta/vector_stores/vector_store_file.py b/src/openai/types/beta/vector_stores/vector_store_file.py index 3fab489602..d9d7625f86 100644 --- a/src/openai/types/beta/vector_stores/vector_store_file.py +++ b/src/openai/types/beta/vector_stores/vector_store_file.py @@ -1,11 +1,19 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing import Optional -from typing_extensions import Literal +from typing import Union, Optional +from typing_extensions import Literal, Annotated +from ...._utils import PropertyInfo from ...._models import BaseModel -__all__ = ["VectorStoreFile", "LastError"] +__all__ = [ + "VectorStoreFile", + "LastError", + "ChunkingStrategy", + "ChunkingStrategyStatic", + "ChunkingStrategyStaticStatic", + "ChunkingStrategyOther", +] class LastError(BaseModel): @@ -16,6 +24,36 @@ class LastError(BaseModel): """A human-readable description of the error.""" +class ChunkingStrategyStaticStatic(BaseModel): + chunk_overlap_tokens: int + """The number of tokens that overlap between chunks. The default value is `400`. + + Note that the overlap must not exceed half of `max_chunk_size_tokens`. + """ + + max_chunk_size_tokens: int + """The maximum number of tokens in each chunk. + + The default value is `800`. The minimum value is `100` and the maximum value is + `4096`. + """ + + +class ChunkingStrategyStatic(BaseModel): + static: ChunkingStrategyStaticStatic + + type: Literal["static"] + """Always `static`.""" + + +class ChunkingStrategyOther(BaseModel): + type: Literal["other"] + """Always `other`.""" + + +ChunkingStrategy = Annotated[Union[ChunkingStrategyStatic, ChunkingStrategyOther], PropertyInfo(discriminator="type")] + + class VectorStoreFile(BaseModel): id: str """The identifier, which can be referenced in API endpoints.""" @@ -52,3 +90,6 @@ class VectorStoreFile(BaseModel): that the [File](https://platform.openai.com/docs/api-reference/files) is attached to. """ + + chunking_strategy: Optional[ChunkingStrategy] = None + """The strategy used to chunk the file.""" diff --git a/src/openai/types/chat/chat_completion_assistant_message_param.py b/src/openai/types/chat/chat_completion_assistant_message_param.py index e1e399486e..8f7357b96c 100644 --- a/src/openai/types/chat/chat_completion_assistant_message_param.py +++ b/src/openai/types/chat/chat_completion_assistant_message_param.py @@ -33,7 +33,7 @@ class ChatCompletionAssistantMessageParam(TypedDict, total=False): Required unless `tool_calls` or `function_call` is specified. """ - function_call: FunctionCall + function_call: Optional[FunctionCall] """Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 226cf15882..a25f2fdd8f 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -219,9 +219,8 @@ class Function(TypedDict, total=False): parameters: shared_params.FunctionParameters """The parameters the functions accepts, described as a JSON Schema object. - See the - [guide](https://platform.openai.com/docs/guides/text-generation/function-calling) - for examples, and the + See the [guide](https://platform.openai.com/docs/guides/function-calling) for + examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format. diff --git a/src/openai/types/file_create_params.py b/src/openai/types/file_create_params.py index caa913d4d2..8b1c296f39 100644 --- a/src/openai/types/file_create_params.py +++ b/src/openai/types/file_create_params.py @@ -13,7 +13,7 @@ class FileCreateParams(TypedDict, total=False): file: Required[FileTypes] """The File object (not file name) to be uploaded.""" - purpose: Required[Literal["assistants", "batch", "fine-tune"]] + purpose: Required[Literal["assistants", "batch", "fine-tune", "vision"]] """The intended purpose of the uploaded file. Use "assistants" for diff --git a/src/openai/types/fine_tuning/job_create_params.py b/src/openai/types/fine_tuning/job_create_params.py index 1925f90d12..c5196e4406 100644 --- a/src/openai/types/fine_tuning/job_create_params.py +++ b/src/openai/types/fine_tuning/job_create_params.py @@ -25,6 +25,11 @@ class JobCreateParams(TypedDict, total=False): Your dataset must be formatted as a JSONL file. Additionally, you must upload your file with the purpose `fine-tune`. + The contents of the file should differ depending on if the model uses the + [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or + [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) + format. + See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) for more details. """ diff --git a/src/openai/types/shared/function_definition.py b/src/openai/types/shared/function_definition.py index a39116d6bd..49f5e67c50 100644 --- a/src/openai/types/shared/function_definition.py +++ b/src/openai/types/shared/function_definition.py @@ -25,9 +25,8 @@ class FunctionDefinition(BaseModel): parameters: Optional[FunctionParameters] = None """The parameters the functions accepts, described as a JSON Schema object. - See the - [guide](https://platform.openai.com/docs/guides/text-generation/function-calling) - for examples, and the + See the [guide](https://platform.openai.com/docs/guides/function-calling) for + examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format. diff --git a/src/openai/types/shared_params/function_definition.py b/src/openai/types/shared_params/function_definition.py index 58d0203b4f..29ccc548d4 100644 --- a/src/openai/types/shared_params/function_definition.py +++ b/src/openai/types/shared_params/function_definition.py @@ -26,9 +26,8 @@ class FunctionDefinition(TypedDict, total=False): parameters: shared_params.FunctionParameters """The parameters the functions accepts, described as a JSON Schema object. - See the - [guide](https://platform.openai.com/docs/guides/text-generation/function-calling) - for examples, and the + See the [guide](https://platform.openai.com/docs/guides/function-calling) for + examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format. diff --git a/tests/api_resources/beta/test_assistants.py b/tests/api_resources/beta/test_assistants.py index a92acb2ca5..dd0ce9266e 100644 --- a/tests/api_resources/beta/test_assistants.py +++ b/tests/api_resources/beta/test_assistants.py @@ -45,6 +45,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "vector_stores": [ { "file_ids": ["string", "string", "string"], + "chunking_strategy": {"type": "auto"}, "metadata": {}, } ], @@ -276,6 +277,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "vector_stores": [ { "file_ids": ["string", "string", "string"], + "chunking_strategy": {"type": "auto"}, "metadata": {}, } ], diff --git a/tests/api_resources/beta/test_threads.py b/tests/api_resources/beta/test_threads.py index 02c6e2586e..041562cb38 100644 --- a/tests/api_resources/beta/test_threads.py +++ b/tests/api_resources/beta/test_threads.py @@ -132,6 +132,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "vector_stores": [ { "file_ids": ["string", "string", "string"], + "chunking_strategy": {"type": "auto"}, "metadata": {}, } ], @@ -408,6 +409,7 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) "vector_stores": [ { "file_ids": ["string", "string", "string"], + "chunking_strategy": {"type": "auto"}, "metadata": {}, } ], @@ -576,6 +578,7 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) "vector_stores": [ { "file_ids": ["string", "string", "string"], + "chunking_strategy": {"type": "auto"}, "metadata": {}, } ], @@ -737,6 +740,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "vector_stores": [ { "file_ids": ["string", "string", "string"], + "chunking_strategy": {"type": "auto"}, "metadata": {}, } ], @@ -1013,6 +1017,7 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie "vector_stores": [ { "file_ids": ["string", "string", "string"], + "chunking_strategy": {"type": "auto"}, "metadata": {}, } ], @@ -1181,6 +1186,7 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie "vector_stores": [ { "file_ids": ["string", "string", "string"], + "chunking_strategy": {"type": "auto"}, "metadata": {}, } ], diff --git a/tests/api_resources/beta/test_vector_stores.py b/tests/api_resources/beta/test_vector_stores.py index e671c96a45..39fdb9d1d4 100644 --- a/tests/api_resources/beta/test_vector_stores.py +++ b/tests/api_resources/beta/test_vector_stores.py @@ -29,6 +29,7 @@ def test_method_create(self, client: OpenAI) -> None: @parametrize def test_method_create_with_all_params(self, client: OpenAI) -> None: vector_store = client.beta.vector_stores.create( + chunking_strategy={"type": "auto"}, expires_after={ "anchor": "last_active_at", "days": 1, @@ -233,6 +234,7 @@ async def test_method_create(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: vector_store = await async_client.beta.vector_stores.create( + chunking_strategy={"type": "auto"}, expires_after={ "anchor": "last_active_at", "days": 1, diff --git a/tests/api_resources/beta/vector_stores/test_file_batches.py b/tests/api_resources/beta/vector_stores/test_file_batches.py index 9854d1a138..631f2669ad 100644 --- a/tests/api_resources/beta/vector_stores/test_file_batches.py +++ b/tests/api_resources/beta/vector_stores/test_file_batches.py @@ -29,6 +29,15 @@ def test_method_create(self, client: OpenAI) -> None: ) assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) + @parametrize + def test_method_create_with_all_params(self, client: OpenAI) -> None: + file_batch = client.beta.vector_stores.file_batches.create( + "vs_abc123", + file_ids=["string"], + chunking_strategy={"type": "auto"}, + ) + assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) + @parametrize def test_raw_response_create(self, client: OpenAI) -> None: response = client.beta.vector_stores.file_batches.with_raw_response.create( @@ -232,6 +241,15 @@ async def test_method_create(self, async_client: AsyncOpenAI) -> None: ) assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) + @parametrize + async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: + file_batch = await async_client.beta.vector_stores.file_batches.create( + "vs_abc123", + file_ids=["string"], + chunking_strategy={"type": "auto"}, + ) + assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) + @parametrize async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: response = await async_client.beta.vector_stores.file_batches.with_raw_response.create( diff --git a/tests/api_resources/beta/vector_stores/test_files.py b/tests/api_resources/beta/vector_stores/test_files.py index 58301e2d37..36622e699b 100644 --- a/tests/api_resources/beta/vector_stores/test_files.py +++ b/tests/api_resources/beta/vector_stores/test_files.py @@ -29,6 +29,15 @@ def test_method_create(self, client: OpenAI) -> None: ) assert_matches_type(VectorStoreFile, file, path=["response"]) + @parametrize + def test_method_create_with_all_params(self, client: OpenAI) -> None: + file = client.beta.vector_stores.files.create( + "vs_abc123", + file_id="string", + chunking_strategy={"type": "auto"}, + ) + assert_matches_type(VectorStoreFile, file, path=["response"]) + @parametrize def test_raw_response_create(self, client: OpenAI) -> None: response = client.beta.vector_stores.files.with_raw_response.create( @@ -221,6 +230,15 @@ async def test_method_create(self, async_client: AsyncOpenAI) -> None: ) assert_matches_type(VectorStoreFile, file, path=["response"]) + @parametrize + async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: + file = await async_client.beta.vector_stores.files.create( + "vs_abc123", + file_id="string", + chunking_strategy={"type": "auto"}, + ) + assert_matches_type(VectorStoreFile, file, path=["response"]) + @parametrize async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: response = await async_client.beta.vector_stores.files.with_raw_response.create( From 14448b71b2c65c6e45b9bb4f01bbf9562061731b Mon Sep 17 00:00:00 2001 From: meorphis Date: Mon, 3 Jun 2024 19:01:39 -0400 Subject: [PATCH 365/816] chore: fix lint --- src/openai/lib/streaming/_assistants.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/openai/lib/streaming/_assistants.py b/src/openai/lib/streaming/_assistants.py index 03d97ec2eb..7445f9a96d 100644 --- a/src/openai/lib/streaming/_assistants.py +++ b/src/openai/lib/streaming/_assistants.py @@ -280,6 +280,7 @@ def _emit_sse_event(self, event: AssistantStreamEvent) -> None: or event.event == "thread.run.expired" or event.event == "thread.run.failed" or event.event == "thread.run.requires_action" + or event.event == "thread.run.incomplete" ): self.__current_run = event.data if self._current_tool_call: @@ -711,6 +712,7 @@ async def _emit_sse_event(self, event: AssistantStreamEvent) -> None: or event.event == "thread.run.expired" or event.event == "thread.run.failed" or event.event == "thread.run.requires_action" + or event.event == "thread.run.incomplete" ): self.__current_run = event.data if self._current_tool_call: From 4eff2db078dfa873b2a9301d62d04ca8f7fc36a4 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 3 Jun 2024 23:02:10 +0000 Subject: [PATCH 366/816] release: 1.31.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 4449911fae..81d2de2d26 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.30.5" + ".": "1.31.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ae0f81ffc..d6acfdd066 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.31.0 (2024-06-03) + +Full Changelog: [v1.30.5...v1.31.0](https://github.com/openai/openai-python/compare/v1.30.5...v1.31.0) + +### Features + +* **api:** updates ([#1461](https://github.com/openai/openai-python/issues/1461)) ([0d7cc5e](https://github.com/openai/openai-python/commit/0d7cc5e48c565fe10ee6e8ca4d050175eb543bcb)) + + +### Chores + +* fix lint ([1886dd4](https://github.com/openai/openai-python/commit/1886dd4c98d7a7b3a679bff739cb38badf5ae96c)) + ## 1.30.5 (2024-05-29) Full Changelog: [v1.30.4...v1.30.5](https://github.com/openai/openai-python/compare/v1.30.4...v1.30.5) diff --git a/pyproject.toml b/pyproject.toml index c09baa6d7d..7578ea718c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.30.5" +version = "1.31.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 1a8a23bfa3..e87d71b33a 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.30.5" # x-release-please-version +__version__ = "1.31.0" # x-release-please-version From 62069d2f3304c74374e8de99c69217f9f03e98c3 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 5 Jun 2024 05:33:56 -0400 Subject: [PATCH 367/816] chore(internal): minor change to tests (#1466) --- tests/api_resources/audio/test_speech.py | 16 ++++++------ tests/api_resources/test_completions.py | 32 ++++++++++++------------ 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/tests/api_resources/audio/test_speech.py b/tests/api_resources/audio/test_speech.py index 781ebeceb9..1f04a66435 100644 --- a/tests/api_resources/audio/test_speech.py +++ b/tests/api_resources/audio/test_speech.py @@ -27,7 +27,7 @@ def test_method_create(self, client: OpenAI, respx_mock: MockRouter) -> None: respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) speech = client.audio.speech.create( input="string", - model="string", + model="tts-1", voice="alloy", ) assert isinstance(speech, _legacy_response.HttpxBinaryResponseContent) @@ -39,7 +39,7 @@ def test_method_create_with_all_params(self, client: OpenAI, respx_mock: MockRou respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) speech = client.audio.speech.create( input="string", - model="string", + model="tts-1", voice="alloy", response_format="mp3", speed=0.25, @@ -54,7 +54,7 @@ def test_raw_response_create(self, client: OpenAI, respx_mock: MockRouter) -> No response = client.audio.speech.with_raw_response.create( input="string", - model="string", + model="tts-1", voice="alloy", ) @@ -69,7 +69,7 @@ def test_streaming_response_create(self, client: OpenAI, respx_mock: MockRouter) respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) with client.audio.speech.with_streaming_response.create( input="string", - model="string", + model="tts-1", voice="alloy", ) as response: assert not response.is_closed @@ -90,7 +90,7 @@ async def test_method_create(self, async_client: AsyncOpenAI, respx_mock: MockRo respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) speech = await async_client.audio.speech.create( input="string", - model="string", + model="tts-1", voice="alloy", ) assert isinstance(speech, _legacy_response.HttpxBinaryResponseContent) @@ -102,7 +102,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI, re respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) speech = await async_client.audio.speech.create( input="string", - model="string", + model="tts-1", voice="alloy", response_format="mp3", speed=0.25, @@ -117,7 +117,7 @@ async def test_raw_response_create(self, async_client: AsyncOpenAI, respx_mock: response = await async_client.audio.speech.with_raw_response.create( input="string", - model="string", + model="tts-1", voice="alloy", ) @@ -132,7 +132,7 @@ async def test_streaming_response_create(self, async_client: AsyncOpenAI, respx_ respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) async with async_client.audio.speech.with_streaming_response.create( input="string", - model="string", + model="tts-1", voice="alloy", ) as response: assert not response.is_closed diff --git a/tests/api_resources/test_completions.py b/tests/api_resources/test_completions.py index 69d914200f..fa7ae52131 100644 --- a/tests/api_resources/test_completions.py +++ b/tests/api_resources/test_completions.py @@ -20,7 +20,7 @@ class TestCompletions: @parametrize def test_method_create_overload_1(self, client: OpenAI) -> None: completion = client.completions.create( - model="string", + model="gpt-3.5-turbo-instruct", prompt="This is a test.", ) assert_matches_type(Completion, completion, path=["response"]) @@ -28,7 +28,7 @@ def test_method_create_overload_1(self, client: OpenAI) -> None: @parametrize def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: completion = client.completions.create( - model="string", + model="gpt-3.5-turbo-instruct", prompt="This is a test.", best_of=0, echo=True, @@ -52,7 +52,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: @parametrize def test_raw_response_create_overload_1(self, client: OpenAI) -> None: response = client.completions.with_raw_response.create( - model="string", + model="gpt-3.5-turbo-instruct", prompt="This is a test.", ) @@ -64,7 +64,7 @@ def test_raw_response_create_overload_1(self, client: OpenAI) -> None: @parametrize def test_streaming_response_create_overload_1(self, client: OpenAI) -> None: with client.completions.with_streaming_response.create( - model="string", + model="gpt-3.5-turbo-instruct", prompt="This is a test.", ) as response: assert not response.is_closed @@ -78,7 +78,7 @@ def test_streaming_response_create_overload_1(self, client: OpenAI) -> None: @parametrize def test_method_create_overload_2(self, client: OpenAI) -> None: completion_stream = client.completions.create( - model="string", + model="gpt-3.5-turbo-instruct", prompt="This is a test.", stream=True, ) @@ -87,7 +87,7 @@ def test_method_create_overload_2(self, client: OpenAI) -> None: @parametrize def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: completion_stream = client.completions.create( - model="string", + model="gpt-3.5-turbo-instruct", prompt="This is a test.", stream=True, best_of=0, @@ -111,7 +111,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: @parametrize def test_raw_response_create_overload_2(self, client: OpenAI) -> None: response = client.completions.with_raw_response.create( - model="string", + model="gpt-3.5-turbo-instruct", prompt="This is a test.", stream=True, ) @@ -123,7 +123,7 @@ def test_raw_response_create_overload_2(self, client: OpenAI) -> None: @parametrize def test_streaming_response_create_overload_2(self, client: OpenAI) -> None: with client.completions.with_streaming_response.create( - model="string", + model="gpt-3.5-turbo-instruct", prompt="This is a test.", stream=True, ) as response: @@ -142,7 +142,7 @@ class TestAsyncCompletions: @parametrize async def test_method_create_overload_1(self, async_client: AsyncOpenAI) -> None: completion = await async_client.completions.create( - model="string", + model="gpt-3.5-turbo-instruct", prompt="This is a test.", ) assert_matches_type(Completion, completion, path=["response"]) @@ -150,7 +150,7 @@ async def test_method_create_overload_1(self, async_client: AsyncOpenAI) -> None @parametrize async def test_method_create_with_all_params_overload_1(self, async_client: AsyncOpenAI) -> None: completion = await async_client.completions.create( - model="string", + model="gpt-3.5-turbo-instruct", prompt="This is a test.", best_of=0, echo=True, @@ -174,7 +174,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn @parametrize async def test_raw_response_create_overload_1(self, async_client: AsyncOpenAI) -> None: response = await async_client.completions.with_raw_response.create( - model="string", + model="gpt-3.5-turbo-instruct", prompt="This is a test.", ) @@ -186,7 +186,7 @@ async def test_raw_response_create_overload_1(self, async_client: AsyncOpenAI) - @parametrize async def test_streaming_response_create_overload_1(self, async_client: AsyncOpenAI) -> None: async with async_client.completions.with_streaming_response.create( - model="string", + model="gpt-3.5-turbo-instruct", prompt="This is a test.", ) as response: assert not response.is_closed @@ -200,7 +200,7 @@ async def test_streaming_response_create_overload_1(self, async_client: AsyncOpe @parametrize async def test_method_create_overload_2(self, async_client: AsyncOpenAI) -> None: completion_stream = await async_client.completions.create( - model="string", + model="gpt-3.5-turbo-instruct", prompt="This is a test.", stream=True, ) @@ -209,7 +209,7 @@ async def test_method_create_overload_2(self, async_client: AsyncOpenAI) -> None @parametrize async def test_method_create_with_all_params_overload_2(self, async_client: AsyncOpenAI) -> None: completion_stream = await async_client.completions.create( - model="string", + model="gpt-3.5-turbo-instruct", prompt="This is a test.", stream=True, best_of=0, @@ -233,7 +233,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn @parametrize async def test_raw_response_create_overload_2(self, async_client: AsyncOpenAI) -> None: response = await async_client.completions.with_raw_response.create( - model="string", + model="gpt-3.5-turbo-instruct", prompt="This is a test.", stream=True, ) @@ -245,7 +245,7 @@ async def test_raw_response_create_overload_2(self, async_client: AsyncOpenAI) - @parametrize async def test_streaming_response_create_overload_2(self, async_client: AsyncOpenAI) -> None: async with async_client.completions.with_streaming_response.create( - model="string", + model="gpt-3.5-turbo-instruct", prompt="This is a test.", stream=True, ) as response: From 2fcc0e428fbc10fdf1825f7f85bf384534173b4a Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 5 Jun 2024 09:34:25 +0000 Subject: [PATCH 368/816] release: 1.31.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 81d2de2d26..03537feab5 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.31.0" + ".": "1.31.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index d6acfdd066..dd23f9b017 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.31.1 (2024-06-05) + +Full Changelog: [v1.31.0...v1.31.1](https://github.com/openai/openai-python/compare/v1.31.0...v1.31.1) + +### Chores + +* **internal:** minor change to tests ([#1466](https://github.com/openai/openai-python/issues/1466)) ([cb33e71](https://github.com/openai/openai-python/commit/cb33e7152f25fb16cf4c39a6e4714169c62d6af8)) + ## 1.31.0 (2024-06-03) Full Changelog: [v1.30.5...v1.31.0](https://github.com/openai/openai-python/compare/v1.30.5...v1.31.0) diff --git a/pyproject.toml b/pyproject.toml index 7578ea718c..239960f0e1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.31.0" +version = "1.31.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index e87d71b33a..9fe77c14dc 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.31.0" # x-release-please-version +__version__ = "1.31.1" # x-release-please-version From 156d13e185bf5117bbec8e9778accda28fefb5dd Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 6 Jun 2024 03:39:46 -0400 Subject: [PATCH 369/816] chore(internal): minor refactor of tests (#1471) --- tests/api_resources/audio/test_speech.py | 16 ++++++------ tests/api_resources/test_completions.py | 32 ++++++++++++------------ 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/tests/api_resources/audio/test_speech.py b/tests/api_resources/audio/test_speech.py index 1f04a66435..781ebeceb9 100644 --- a/tests/api_resources/audio/test_speech.py +++ b/tests/api_resources/audio/test_speech.py @@ -27,7 +27,7 @@ def test_method_create(self, client: OpenAI, respx_mock: MockRouter) -> None: respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) speech = client.audio.speech.create( input="string", - model="tts-1", + model="string", voice="alloy", ) assert isinstance(speech, _legacy_response.HttpxBinaryResponseContent) @@ -39,7 +39,7 @@ def test_method_create_with_all_params(self, client: OpenAI, respx_mock: MockRou respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) speech = client.audio.speech.create( input="string", - model="tts-1", + model="string", voice="alloy", response_format="mp3", speed=0.25, @@ -54,7 +54,7 @@ def test_raw_response_create(self, client: OpenAI, respx_mock: MockRouter) -> No response = client.audio.speech.with_raw_response.create( input="string", - model="tts-1", + model="string", voice="alloy", ) @@ -69,7 +69,7 @@ def test_streaming_response_create(self, client: OpenAI, respx_mock: MockRouter) respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) with client.audio.speech.with_streaming_response.create( input="string", - model="tts-1", + model="string", voice="alloy", ) as response: assert not response.is_closed @@ -90,7 +90,7 @@ async def test_method_create(self, async_client: AsyncOpenAI, respx_mock: MockRo respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) speech = await async_client.audio.speech.create( input="string", - model="tts-1", + model="string", voice="alloy", ) assert isinstance(speech, _legacy_response.HttpxBinaryResponseContent) @@ -102,7 +102,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI, re respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) speech = await async_client.audio.speech.create( input="string", - model="tts-1", + model="string", voice="alloy", response_format="mp3", speed=0.25, @@ -117,7 +117,7 @@ async def test_raw_response_create(self, async_client: AsyncOpenAI, respx_mock: response = await async_client.audio.speech.with_raw_response.create( input="string", - model="tts-1", + model="string", voice="alloy", ) @@ -132,7 +132,7 @@ async def test_streaming_response_create(self, async_client: AsyncOpenAI, respx_ respx_mock.post("/audio/speech").mock(return_value=httpx.Response(200, json={"foo": "bar"})) async with async_client.audio.speech.with_streaming_response.create( input="string", - model="tts-1", + model="string", voice="alloy", ) as response: assert not response.is_closed diff --git a/tests/api_resources/test_completions.py b/tests/api_resources/test_completions.py index fa7ae52131..69d914200f 100644 --- a/tests/api_resources/test_completions.py +++ b/tests/api_resources/test_completions.py @@ -20,7 +20,7 @@ class TestCompletions: @parametrize def test_method_create_overload_1(self, client: OpenAI) -> None: completion = client.completions.create( - model="gpt-3.5-turbo-instruct", + model="string", prompt="This is a test.", ) assert_matches_type(Completion, completion, path=["response"]) @@ -28,7 +28,7 @@ def test_method_create_overload_1(self, client: OpenAI) -> None: @parametrize def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: completion = client.completions.create( - model="gpt-3.5-turbo-instruct", + model="string", prompt="This is a test.", best_of=0, echo=True, @@ -52,7 +52,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: @parametrize def test_raw_response_create_overload_1(self, client: OpenAI) -> None: response = client.completions.with_raw_response.create( - model="gpt-3.5-turbo-instruct", + model="string", prompt="This is a test.", ) @@ -64,7 +64,7 @@ def test_raw_response_create_overload_1(self, client: OpenAI) -> None: @parametrize def test_streaming_response_create_overload_1(self, client: OpenAI) -> None: with client.completions.with_streaming_response.create( - model="gpt-3.5-turbo-instruct", + model="string", prompt="This is a test.", ) as response: assert not response.is_closed @@ -78,7 +78,7 @@ def test_streaming_response_create_overload_1(self, client: OpenAI) -> None: @parametrize def test_method_create_overload_2(self, client: OpenAI) -> None: completion_stream = client.completions.create( - model="gpt-3.5-turbo-instruct", + model="string", prompt="This is a test.", stream=True, ) @@ -87,7 +87,7 @@ def test_method_create_overload_2(self, client: OpenAI) -> None: @parametrize def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: completion_stream = client.completions.create( - model="gpt-3.5-turbo-instruct", + model="string", prompt="This is a test.", stream=True, best_of=0, @@ -111,7 +111,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: @parametrize def test_raw_response_create_overload_2(self, client: OpenAI) -> None: response = client.completions.with_raw_response.create( - model="gpt-3.5-turbo-instruct", + model="string", prompt="This is a test.", stream=True, ) @@ -123,7 +123,7 @@ def test_raw_response_create_overload_2(self, client: OpenAI) -> None: @parametrize def test_streaming_response_create_overload_2(self, client: OpenAI) -> None: with client.completions.with_streaming_response.create( - model="gpt-3.5-turbo-instruct", + model="string", prompt="This is a test.", stream=True, ) as response: @@ -142,7 +142,7 @@ class TestAsyncCompletions: @parametrize async def test_method_create_overload_1(self, async_client: AsyncOpenAI) -> None: completion = await async_client.completions.create( - model="gpt-3.5-turbo-instruct", + model="string", prompt="This is a test.", ) assert_matches_type(Completion, completion, path=["response"]) @@ -150,7 +150,7 @@ async def test_method_create_overload_1(self, async_client: AsyncOpenAI) -> None @parametrize async def test_method_create_with_all_params_overload_1(self, async_client: AsyncOpenAI) -> None: completion = await async_client.completions.create( - model="gpt-3.5-turbo-instruct", + model="string", prompt="This is a test.", best_of=0, echo=True, @@ -174,7 +174,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn @parametrize async def test_raw_response_create_overload_1(self, async_client: AsyncOpenAI) -> None: response = await async_client.completions.with_raw_response.create( - model="gpt-3.5-turbo-instruct", + model="string", prompt="This is a test.", ) @@ -186,7 +186,7 @@ async def test_raw_response_create_overload_1(self, async_client: AsyncOpenAI) - @parametrize async def test_streaming_response_create_overload_1(self, async_client: AsyncOpenAI) -> None: async with async_client.completions.with_streaming_response.create( - model="gpt-3.5-turbo-instruct", + model="string", prompt="This is a test.", ) as response: assert not response.is_closed @@ -200,7 +200,7 @@ async def test_streaming_response_create_overload_1(self, async_client: AsyncOpe @parametrize async def test_method_create_overload_2(self, async_client: AsyncOpenAI) -> None: completion_stream = await async_client.completions.create( - model="gpt-3.5-turbo-instruct", + model="string", prompt="This is a test.", stream=True, ) @@ -209,7 +209,7 @@ async def test_method_create_overload_2(self, async_client: AsyncOpenAI) -> None @parametrize async def test_method_create_with_all_params_overload_2(self, async_client: AsyncOpenAI) -> None: completion_stream = await async_client.completions.create( - model="gpt-3.5-turbo-instruct", + model="string", prompt="This is a test.", stream=True, best_of=0, @@ -233,7 +233,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn @parametrize async def test_raw_response_create_overload_2(self, async_client: AsyncOpenAI) -> None: response = await async_client.completions.with_raw_response.create( - model="gpt-3.5-turbo-instruct", + model="string", prompt="This is a test.", stream=True, ) @@ -245,7 +245,7 @@ async def test_raw_response_create_overload_2(self, async_client: AsyncOpenAI) - @parametrize async def test_streaming_response_create_overload_2(self, async_client: AsyncOpenAI) -> None: async with async_client.completions.with_streaming_response.create( - model="gpt-3.5-turbo-instruct", + model="string", prompt="This is a test.", stream=True, ) as response: From a33712e161eacdcfead297da3f4a5bc491732e3f Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 6 Jun 2024 07:40:16 +0000 Subject: [PATCH 370/816] release: 1.31.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 03537feab5..dc28bf349b 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.31.1" + ".": "1.31.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index dd23f9b017..e8baa0d73d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.31.2 (2024-06-06) + +Full Changelog: [v1.31.1...v1.31.2](https://github.com/openai/openai-python/compare/v1.31.1...v1.31.2) + +### Chores + +* **internal:** minor refactor of tests ([#1471](https://github.com/openai/openai-python/issues/1471)) ([b7f2298](https://github.com/openai/openai-python/commit/b7f229866f249d16e995db361b923bb4c0b7f1d4)) + ## 1.31.1 (2024-06-05) Full Changelog: [v1.31.0...v1.31.1](https://github.com/openai/openai-python/compare/v1.31.0...v1.31.1) diff --git a/pyproject.toml b/pyproject.toml index 239960f0e1..31a8c5ce3c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.31.1" +version = "1.31.2" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 9fe77c14dc..f1befbacf9 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.31.1" # x-release-please-version +__version__ = "1.31.2" # x-release-please-version From 7399ffc8c4b5b0754358fc0467bddc2debec3d34 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 6 Jun 2024 14:55:43 -0400 Subject: [PATCH 371/816] feat(api): updates (#1474) --- .stats.yml | 2 +- .../resources/beta/threads/runs/runs.py | 34 +++++++++++++++++++ src/openai/resources/beta/threads/threads.py | 34 +++++++++++++++++++ src/openai/resources/chat/completions.py | 34 +++++++++++++++++++ .../beta/thread_create_and_run_params.py | 7 ++++ src/openai/types/beta/threads/run.py | 7 ++++ .../types/beta/threads/run_create_params.py | 7 ++++ .../types/chat/completion_create_params.py | 7 ++++ tests/api_resources/beta/test_threads.py | 4 +++ tests/api_resources/beta/threads/test_runs.py | 4 +++ tests/api_resources/chat/test_completions.py | 4 +++ 11 files changed, 143 insertions(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index 11d2b0b181..eb81a249f1 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 64 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-0577fd0d08da6b867b002a5accd45f7116ef91c4940b41cf45dc479938c77163.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-ff436357b12348b7c1c930469332a79cd23ac6ec537e645c411893c42de42e57.yml diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index c37071529c..5976ca4559 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -109,6 +109,7 @@ def create( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -163,6 +164,10 @@ def create( model associated with the assistant. If not, the model associated with the assistant will be used. + parallel_tool_calls: Whether to enable + [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + during tool use. + response_format: Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), @@ -257,6 +262,7 @@ def create( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -314,6 +320,10 @@ def create( model associated with the assistant. If not, the model associated with the assistant will be used. + parallel_tool_calls: Whether to enable + [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + during tool use. + response_format: Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), @@ -404,6 +414,7 @@ def create( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -461,6 +472,10 @@ def create( model associated with the assistant. If not, the model associated with the assistant will be used. + parallel_tool_calls: Whether to enable + [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + during tool use. + response_format: Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), @@ -550,6 +565,7 @@ def create( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -579,6 +595,7 @@ def create( "max_prompt_tokens": max_prompt_tokens, "metadata": metadata, "model": model, + "parallel_tool_calls": parallel_tool_calls, "response_format": response_format, "stream": stream, "temperature": temperature, @@ -1666,6 +1683,7 @@ async def create( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -1720,6 +1738,10 @@ async def create( model associated with the assistant. If not, the model associated with the assistant will be used. + parallel_tool_calls: Whether to enable + [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + during tool use. + response_format: Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), @@ -1814,6 +1836,7 @@ async def create( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -1871,6 +1894,10 @@ async def create( model associated with the assistant. If not, the model associated with the assistant will be used. + parallel_tool_calls: Whether to enable + [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + during tool use. + response_format: Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), @@ -1961,6 +1988,7 @@ async def create( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -2018,6 +2046,10 @@ async def create( model associated with the assistant. If not, the model associated with the assistant will be used. + parallel_tool_calls: Whether to enable + [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + during tool use. + response_format: Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), @@ -2107,6 +2139,7 @@ async def create( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -2136,6 +2169,7 @@ async def create( "max_prompt_tokens": max_prompt_tokens, "metadata": metadata, "model": model, + "parallel_tool_calls": parallel_tool_calls, "response_format": response_format, "stream": stream, "temperature": temperature, diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 36cdd03f91..05c06ff658 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -291,6 +291,7 @@ def create_and_run( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -340,6 +341,10 @@ def create_and_run( model associated with the assistant. If not, the model associated with the assistant will be used. + parallel_tool_calls: Whether to enable + [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + during tool use. + response_format: Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), @@ -438,6 +443,7 @@ def create_and_run( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, @@ -490,6 +496,10 @@ def create_and_run( model associated with the assistant. If not, the model associated with the assistant will be used. + parallel_tool_calls: Whether to enable + [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + during tool use. + response_format: Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), @@ -584,6 +594,7 @@ def create_and_run( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, @@ -636,6 +647,10 @@ def create_and_run( model associated with the assistant. If not, the model associated with the assistant will be used. + parallel_tool_calls: Whether to enable + [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + during tool use. + response_format: Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), @@ -729,6 +744,7 @@ def create_and_run( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -756,6 +772,7 @@ def create_and_run( "max_prompt_tokens": max_prompt_tokens, "metadata": metadata, "model": model, + "parallel_tool_calls": parallel_tool_calls, "response_format": response_format, "stream": stream, "temperature": temperature, @@ -1284,6 +1301,7 @@ async def create_and_run( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -1333,6 +1351,10 @@ async def create_and_run( model associated with the assistant. If not, the model associated with the assistant will be used. + parallel_tool_calls: Whether to enable + [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + during tool use. + response_format: Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), @@ -1431,6 +1453,7 @@ async def create_and_run( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, @@ -1483,6 +1506,10 @@ async def create_and_run( model associated with the assistant. If not, the model associated with the assistant will be used. + parallel_tool_calls: Whether to enable + [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + during tool use. + response_format: Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), @@ -1577,6 +1604,7 @@ async def create_and_run( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, @@ -1629,6 +1657,10 @@ async def create_and_run( model associated with the assistant. If not, the model associated with the assistant will be used. + parallel_tool_calls: Whether to enable + [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + during tool use. + response_format: Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), @@ -1722,6 +1754,7 @@ async def create_and_run( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -1749,6 +1782,7 @@ async def create_and_run( "max_prompt_tokens": max_prompt_tokens, "metadata": metadata, "model": model, + "parallel_tool_calls": parallel_tool_calls, "response_format": response_format, "stream": stream, "temperature": temperature, diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index aa25bc1858..ab35b03335 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -55,6 +55,7 @@ def create( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, @@ -131,6 +132,10 @@ def create( you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs. + parallel_tool_calls: Whether to enable + [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + during tool use. + presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. @@ -227,6 +232,7 @@ def create( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, @@ -309,6 +315,10 @@ def create( you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs. + parallel_tool_calls: Whether to enable + [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + during tool use. + presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. @@ -398,6 +408,7 @@ def create( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, @@ -480,6 +491,10 @@ def create( you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs. + parallel_tool_calls: Whether to enable + [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + during tool use. + presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. @@ -568,6 +583,7 @@ def create( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, @@ -600,6 +616,7 @@ def create( "logprobs": logprobs, "max_tokens": max_tokens, "n": n, + "parallel_tool_calls": parallel_tool_calls, "presence_penalty": presence_penalty, "response_format": response_format, "seed": seed, @@ -646,6 +663,7 @@ async def create( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, @@ -722,6 +740,10 @@ async def create( you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs. + parallel_tool_calls: Whether to enable + [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + during tool use. + presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. @@ -818,6 +840,7 @@ async def create( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, @@ -900,6 +923,10 @@ async def create( you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs. + parallel_tool_calls: Whether to enable + [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + during tool use. + presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. @@ -989,6 +1016,7 @@ async def create( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, @@ -1071,6 +1099,10 @@ async def create( you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs. + parallel_tool_calls: Whether to enable + [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + during tool use. + presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. @@ -1159,6 +1191,7 @@ async def create( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, @@ -1191,6 +1224,7 @@ async def create( "logprobs": logprobs, "max_tokens": max_tokens, "n": n, + "parallel_tool_calls": parallel_tool_calls, "presence_penalty": presence_penalty, "response_format": response_format, "seed": seed, diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index 436c2daddf..b8c69eb7ac 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -109,6 +109,13 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): assistant will be used. """ + parallel_tool_calls: bool + """ + Whether to enable + [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + during tool use. + """ + response_format: Optional[AssistantResponseFormatOptionParam] """Specifies the format that the model must output. diff --git a/src/openai/types/beta/threads/run.py b/src/openai/types/beta/threads/run.py index 8244ffd598..ea84f1e97c 100644 --- a/src/openai/types/beta/threads/run.py +++ b/src/openai/types/beta/threads/run.py @@ -151,6 +151,13 @@ class Run(BaseModel): object: Literal["thread.run"] """The object type, which is always `thread.run`.""" + parallel_tool_calls: bool + """ + Whether to enable + [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + during tool use. + """ + required_action: Optional[RequiredAction] = None """Details on the action required to continue the run. diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index 90c9708596..a7aa799e00 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -107,6 +107,13 @@ class RunCreateParamsBase(TypedDict, total=False): assistant will be used. """ + parallel_tool_calls: bool + """ + Whether to enable + [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + during tool use. + """ + response_format: Optional[AssistantResponseFormatOptionParam] """Specifies the format that the model must output. diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index a25f2fdd8f..47c2a5e24e 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -102,6 +102,13 @@ class CompletionCreateParamsBase(TypedDict, total=False): of the choices. Keep `n` as `1` to minimize costs. """ + parallel_tool_calls: bool + """ + Whether to enable + [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + during tool use. + """ + presence_penalty: Optional[float] """Number between -2.0 and 2.0. diff --git a/tests/api_resources/beta/test_threads.py b/tests/api_resources/beta/test_threads.py index 041562cb38..9e06b597ef 100644 --- a/tests/api_resources/beta/test_threads.py +++ b/tests/api_resources/beta/test_threads.py @@ -303,6 +303,7 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) max_prompt_tokens=256, metadata={}, model="gpt-4-turbo", + parallel_tool_calls=True, response_format="none", stream=False, temperature=1, @@ -473,6 +474,7 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) max_prompt_tokens=256, metadata={}, model="gpt-4-turbo", + parallel_tool_calls=True, response_format="none", temperature=1, thread={ @@ -911,6 +913,7 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie max_prompt_tokens=256, metadata={}, model="gpt-4-turbo", + parallel_tool_calls=True, response_format="none", stream=False, temperature=1, @@ -1081,6 +1084,7 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie max_prompt_tokens=256, metadata={}, model="gpt-4-turbo", + parallel_tool_calls=True, response_format="none", temperature=1, thread={ diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index 089dd1253e..26862ef1eb 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -136,6 +136,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: max_prompt_tokens=256, metadata={}, model="gpt-4-turbo", + parallel_tool_calls=True, response_format="none", stream=False, temperature=1, @@ -299,6 +300,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: max_prompt_tokens=256, metadata={}, model="gpt-4-turbo", + parallel_tool_calls=True, response_format="none", temperature=1, tool_choice="none", @@ -800,6 +802,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn max_prompt_tokens=256, metadata={}, model="gpt-4-turbo", + parallel_tool_calls=True, response_format="none", stream=False, temperature=1, @@ -963,6 +966,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn max_prompt_tokens=256, metadata={}, model="gpt-4-turbo", + parallel_tool_calls=True, response_format="none", temperature=1, tool_choice="none", diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index 1c195c4001..3099e16815 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -56,6 +56,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: logprobs=True, max_tokens=0, n=1, + parallel_tool_calls=True, presence_penalty=-2, response_format={"type": "json_object"}, seed=-9223372036854776000, @@ -171,6 +172,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: logprobs=True, max_tokens=0, n=1, + parallel_tool_calls=True, presence_penalty=-2, response_format={"type": "json_object"}, seed=-9223372036854776000, @@ -288,6 +290,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn logprobs=True, max_tokens=0, n=1, + parallel_tool_calls=True, presence_penalty=-2, response_format={"type": "json_object"}, seed=-9223372036854776000, @@ -403,6 +406,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn logprobs=True, max_tokens=0, n=1, + parallel_tool_calls=True, presence_penalty=-2, response_format={"type": "json_object"}, seed=-9223372036854776000, From 178afa0b04d233c89285e3fd90c9db226e030ef2 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 6 Jun 2024 18:56:15 +0000 Subject: [PATCH 372/816] release: 1.32.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index dc28bf349b..592b0e1529 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.31.2" + ".": "1.32.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index e8baa0d73d..17813558d2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.32.0 (2024-06-06) + +Full Changelog: [v1.31.2...v1.32.0](https://github.com/openai/openai-python/compare/v1.31.2...v1.32.0) + +### Features + +* **api:** updates ([#1474](https://github.com/openai/openai-python/issues/1474)) ([87ddff0](https://github.com/openai/openai-python/commit/87ddff0e6e64650691a8e32f7477b7a00e06ed23)) + ## 1.31.2 (2024-06-06) Full Changelog: [v1.31.1...v1.31.2](https://github.com/openai/openai-python/compare/v1.31.1...v1.31.2) diff --git a/pyproject.toml b/pyproject.toml index 31a8c5ce3c..0abca8c7ef 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.31.2" +version = "1.32.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index f1befbacf9..d7724070cf 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.31.2" # x-release-please-version +__version__ = "1.32.0" # x-release-please-version From bf8a453f11bacad19baece8f81829944a462f55c Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 7 Jun 2024 15:40:54 -0400 Subject: [PATCH 373/816] fix: remove erroneous thread create argument (#1476) --- .stats.yml | 2 +- src/openai/resources/beta/threads/runs/runs.py | 12 ++++++------ src/openai/resources/beta/threads/threads.py | 12 ++++++------ src/openai/resources/chat/completions.py | 12 ++++++------ .../types/beta/thread_create_and_run_params.py | 10 ++++++++-- src/openai/types/beta/thread_create_params.py | 9 +++++++-- src/openai/types/beta/threads/message.py | 17 ++++++++++++++--- .../types/beta/threads/message_create_params.py | 10 +++++++--- src/openai/types/beta/threads/run.py | 2 +- .../types/beta/threads/run_create_params.py | 11 ++++++++--- .../types/chat/completion_create_params.py | 2 +- 11 files changed, 65 insertions(+), 34 deletions(-) diff --git a/.stats.yml b/.stats.yml index eb81a249f1..a6c08f499b 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 64 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-ff436357b12348b7c1c930469332a79cd23ac6ec537e645c411893c42de42e57.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-c085faf70d6ff059fbe11b7b6b98123a612524cb9b8a6f649c99526e5b0b1bdb.yml diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 5976ca4559..43069dd1ae 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -165,7 +165,7 @@ def create( assistant will be used. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use. response_format: Specifies the format that the model must output. Compatible with @@ -321,7 +321,7 @@ def create( assistant will be used. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use. response_format: Specifies the format that the model must output. Compatible with @@ -473,7 +473,7 @@ def create( assistant will be used. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use. response_format: Specifies the format that the model must output. Compatible with @@ -1739,7 +1739,7 @@ async def create( assistant will be used. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use. response_format: Specifies the format that the model must output. Compatible with @@ -1895,7 +1895,7 @@ async def create( assistant will be used. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use. response_format: Specifies the format that the model must output. Compatible with @@ -2047,7 +2047,7 @@ async def create( assistant will be used. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use. response_format: Specifies the format that the model must output. Compatible with diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 05c06ff658..c0a908b7a2 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -342,7 +342,7 @@ def create_and_run( assistant will be used. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use. response_format: Specifies the format that the model must output. Compatible with @@ -497,7 +497,7 @@ def create_and_run( assistant will be used. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use. response_format: Specifies the format that the model must output. Compatible with @@ -648,7 +648,7 @@ def create_and_run( assistant will be used. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use. response_format: Specifies the format that the model must output. Compatible with @@ -1352,7 +1352,7 @@ async def create_and_run( assistant will be used. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use. response_format: Specifies the format that the model must output. Compatible with @@ -1507,7 +1507,7 @@ async def create_and_run( assistant will be used. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use. response_format: Specifies the format that the model must output. Compatible with @@ -1658,7 +1658,7 @@ async def create_and_run( assistant will be used. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use. response_format: Specifies the format that the model must output. Compatible with diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index ab35b03335..ed8e9373b0 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -133,7 +133,7 @@ def create( choices. Keep `n` as `1` to minimize costs. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use. presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on @@ -316,7 +316,7 @@ def create( choices. Keep `n` as `1` to minimize costs. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use. presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on @@ -492,7 +492,7 @@ def create( choices. Keep `n` as `1` to minimize costs. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use. presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on @@ -741,7 +741,7 @@ async def create( choices. Keep `n` as `1` to minimize costs. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use. presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on @@ -924,7 +924,7 @@ async def create( choices. Keep `n` as `1` to minimize costs. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use. presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on @@ -1100,7 +1100,7 @@ async def create( choices. Keep `n` as `1` to minimize costs. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use. presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index b8c69eb7ac..dbbff415ec 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -18,6 +18,7 @@ "ThreadMessage", "ThreadMessageAttachment", "ThreadMessageAttachmentTool", + "ThreadMessageAttachmentToolFileSearch", "ThreadToolResources", "ThreadToolResourcesCodeInterpreter", "ThreadToolResourcesFileSearch", @@ -112,7 +113,7 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): parallel_tool_calls: bool """ Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use. """ @@ -186,7 +187,12 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): """ -ThreadMessageAttachmentTool = Union[CodeInterpreterToolParam, FileSearchToolParam] +class ThreadMessageAttachmentToolFileSearch(TypedDict, total=False): + type: Required[Literal["file_search"]] + """The type of tool being defined: `file_search`""" + + +ThreadMessageAttachmentTool = Union[CodeInterpreterToolParam, ThreadMessageAttachmentToolFileSearch] class ThreadMessageAttachment(TypedDict, total=False): diff --git a/src/openai/types/beta/thread_create_params.py b/src/openai/types/beta/thread_create_params.py index 5072ed12d9..e5ea14a94d 100644 --- a/src/openai/types/beta/thread_create_params.py +++ b/src/openai/types/beta/thread_create_params.py @@ -5,7 +5,6 @@ from typing import List, Union, Iterable, Optional from typing_extensions import Literal, Required, TypedDict -from .file_search_tool_param import FileSearchToolParam from .code_interpreter_tool_param import CodeInterpreterToolParam from .threads.message_content_part_param import MessageContentPartParam @@ -14,6 +13,7 @@ "Message", "MessageAttachment", "MessageAttachmentTool", + "MessageAttachmentToolFileSearch", "ToolResources", "ToolResourcesCodeInterpreter", "ToolResourcesFileSearch", @@ -49,7 +49,12 @@ class ThreadCreateParams(TypedDict, total=False): """ -MessageAttachmentTool = Union[CodeInterpreterToolParam, FileSearchToolParam] +class MessageAttachmentToolFileSearch(TypedDict, total=False): + type: Required[Literal["file_search"]] + """The type of tool being defined: `file_search`""" + + +MessageAttachmentTool = Union[CodeInterpreterToolParam, MessageAttachmentToolFileSearch] class MessageAttachment(TypedDict, total=False): diff --git a/src/openai/types/beta/threads/message.py b/src/openai/types/beta/threads/message.py index ebaabdb0f5..90f083683d 100644 --- a/src/openai/types/beta/threads/message.py +++ b/src/openai/types/beta/threads/message.py @@ -5,12 +5,23 @@ from ...._models import BaseModel from .message_content import MessageContent -from ..file_search_tool import FileSearchTool from ..code_interpreter_tool import CodeInterpreterTool -__all__ = ["Message", "Attachment", "AttachmentTool", "IncompleteDetails"] +__all__ = [ + "Message", + "Attachment", + "AttachmentTool", + "AttachmentToolAssistantToolsFileSearchTypeOnly", + "IncompleteDetails", +] -AttachmentTool = Union[CodeInterpreterTool, FileSearchTool] + +class AttachmentToolAssistantToolsFileSearchTypeOnly(BaseModel): + type: Literal["file_search"] + """The type of tool being defined: `file_search`""" + + +AttachmentTool = Union[CodeInterpreterTool, AttachmentToolAssistantToolsFileSearchTypeOnly] class Attachment(BaseModel): diff --git a/src/openai/types/beta/threads/message_create_params.py b/src/openai/types/beta/threads/message_create_params.py index 3668df950d..b1b12293b7 100644 --- a/src/openai/types/beta/threads/message_create_params.py +++ b/src/openai/types/beta/threads/message_create_params.py @@ -5,11 +5,10 @@ from typing import Union, Iterable, Optional from typing_extensions import Literal, Required, TypedDict -from ..file_search_tool_param import FileSearchToolParam from .message_content_part_param import MessageContentPartParam from ..code_interpreter_tool_param import CodeInterpreterToolParam -__all__ = ["MessageCreateParams", "Attachment", "AttachmentTool"] +__all__ = ["MessageCreateParams", "Attachment", "AttachmentTool", "AttachmentToolFileSearch"] class MessageCreateParams(TypedDict, total=False): @@ -37,7 +36,12 @@ class MessageCreateParams(TypedDict, total=False): """ -AttachmentTool = Union[CodeInterpreterToolParam, FileSearchToolParam] +class AttachmentToolFileSearch(TypedDict, total=False): + type: Required[Literal["file_search"]] + """The type of tool being defined: `file_search`""" + + +AttachmentTool = Union[CodeInterpreterToolParam, AttachmentToolFileSearch] class Attachment(TypedDict, total=False): diff --git a/src/openai/types/beta/threads/run.py b/src/openai/types/beta/threads/run.py index ea84f1e97c..81d10d4a56 100644 --- a/src/openai/types/beta/threads/run.py +++ b/src/openai/types/beta/threads/run.py @@ -154,7 +154,7 @@ class Run(BaseModel): parallel_tool_calls: bool """ Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use. """ diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index a7aa799e00..89da241965 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -6,7 +6,6 @@ from typing_extensions import Literal, Required, TypedDict from ..assistant_tool_param import AssistantToolParam -from ..file_search_tool_param import FileSearchToolParam from .message_content_part_param import MessageContentPartParam from ..code_interpreter_tool_param import CodeInterpreterToolParam from ..assistant_tool_choice_option_param import AssistantToolChoiceOptionParam @@ -17,6 +16,7 @@ "AdditionalMessage", "AdditionalMessageAttachment", "AdditionalMessageAttachmentTool", + "AdditionalMessageAttachmentToolFileSearch", "TruncationStrategy", "RunCreateParamsNonStreaming", "RunCreateParamsStreaming", @@ -110,7 +110,7 @@ class RunCreateParamsBase(TypedDict, total=False): parallel_tool_calls: bool """ Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use. """ @@ -173,7 +173,12 @@ class RunCreateParamsBase(TypedDict, total=False): """ -AdditionalMessageAttachmentTool = Union[CodeInterpreterToolParam, FileSearchToolParam] +class AdditionalMessageAttachmentToolFileSearch(TypedDict, total=False): + type: Required[Literal["file_search"]] + """The type of tool being defined: `file_search`""" + + +AdditionalMessageAttachmentTool = Union[CodeInterpreterToolParam, AdditionalMessageAttachmentToolFileSearch] class AdditionalMessageAttachment(TypedDict, total=False): diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 47c2a5e24e..7dd7067f66 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -105,7 +105,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): parallel_tool_calls: bool """ Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) during tool use. """ From b8a85a0baa22e42d79d85fd42ebe44ef4d6cb80c Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 7 Jun 2024 19:41:22 +0000 Subject: [PATCH 374/816] release: 1.32.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 592b0e1529..cb8c32fee0 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.32.0" + ".": "1.32.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 17813558d2..ecfe0762a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.32.1 (2024-06-07) + +Full Changelog: [v1.32.0...v1.32.1](https://github.com/openai/openai-python/compare/v1.32.0...v1.32.1) + +### Bug Fixes + +* remove erroneous thread create argument ([#1476](https://github.com/openai/openai-python/issues/1476)) ([43175c4](https://github.com/openai/openai-python/commit/43175c40e607d626a77a151691778c35a0e60eec)) + ## 1.32.0 (2024-06-06) Full Changelog: [v1.31.2...v1.32.0](https://github.com/openai/openai-python/compare/v1.31.2...v1.32.0) diff --git a/pyproject.toml b/pyproject.toml index 0abca8c7ef..80b6bc0465 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.32.0" +version = "1.32.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index d7724070cf..aa58ad2d57 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.32.0" # x-release-please-version +__version__ = "1.32.1" # x-release-please-version From cc4e1b0021182f0bf4cb00246b23453a923fea76 Mon Sep 17 00:00:00 2001 From: pstern-sl <157847713+pstern-sl@users.noreply.github.com> Date: Fri, 7 Jun 2024 17:36:40 -0400 Subject: [PATCH 375/816] feat(api): adding chunking_strategy to polling helpers (#1478) --- .../resources/beta/vector_stores/file_batches.py | 8 ++++++++ src/openai/resources/beta/vector_stores/files.py | 16 ++++++++++++---- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/openai/resources/beta/vector_stores/file_batches.py b/src/openai/resources/beta/vector_stores/file_batches.py index 21ac68f6de..d6862c24ef 100644 --- a/src/openai/resources/beta/vector_stores/file_batches.py +++ b/src/openai/resources/beta/vector_stores/file_batches.py @@ -174,11 +174,13 @@ def create_and_poll( *, file_ids: List[str], poll_interval_ms: int | NotGiven = NOT_GIVEN, + chunking_strategy: file_batch_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, ) -> VectorStoreFileBatch: """Create a vector store batch and poll until all files have been processed.""" batch = self.create( vector_store_id=vector_store_id, file_ids=file_ids, + chunking_strategy=chunking_strategy, ) # TODO: don't poll unless necessary?? return self.poll( @@ -306,6 +308,7 @@ def upload_and_poll( max_concurrency: int = 5, file_ids: List[str] = [], poll_interval_ms: int | NotGiven = NOT_GIVEN, + chunking_strategy: file_batch_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, ) -> VectorStoreFileBatch: """Uploads the given files concurrently and then creates a vector store file batch. @@ -343,6 +346,7 @@ def upload_and_poll( vector_store_id=vector_store_id, file_ids=[*file_ids, *(f.id for f in results)], poll_interval_ms=poll_interval_ms, + chunking_strategy=chunking_strategy, ) return batch @@ -488,11 +492,13 @@ async def create_and_poll( *, file_ids: List[str], poll_interval_ms: int | NotGiven = NOT_GIVEN, + chunking_strategy: file_batch_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, ) -> VectorStoreFileBatch: """Create a vector store batch and poll until all files have been processed.""" batch = await self.create( vector_store_id=vector_store_id, file_ids=file_ids, + chunking_strategy=chunking_strategy, ) # TODO: don't poll unless necessary?? return await self.poll( @@ -620,6 +626,7 @@ async def upload_and_poll( max_concurrency: int = 5, file_ids: List[str] = [], poll_interval_ms: int | NotGiven = NOT_GIVEN, + chunking_strategy: file_batch_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, ) -> VectorStoreFileBatch: """Uploads the given files concurrently and then creates a vector store file batch. @@ -680,6 +687,7 @@ async def trio_upload_file(limiter: trio.CapacityLimiter, file: FileTypes) -> No vector_store_id=vector_store_id, file_ids=[*file_ids, *(f.id for f in uploaded_files)], poll_interval_ms=poll_interval_ms, + chunking_strategy=chunking_strategy, ) return batch diff --git a/src/openai/resources/beta/vector_stores/files.py b/src/openai/resources/beta/vector_stores/files.py index 30f19ef491..bc1655027c 100644 --- a/src/openai/resources/beta/vector_stores/files.py +++ b/src/openai/resources/beta/vector_stores/files.py @@ -245,9 +245,10 @@ def create_and_poll( *, vector_store_id: str, poll_interval_ms: int | NotGiven = NOT_GIVEN, + chunking_strategy: file_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, ) -> VectorStoreFile: """Attach a file to the given vector store and wait for it to be processed.""" - self.create(vector_store_id=vector_store_id, file_id=file_id) + self.create(vector_store_id=vector_store_id, file_id=file_id, chunking_strategy=chunking_strategy) return self.poll( file_id, @@ -301,6 +302,7 @@ def upload( *, vector_store_id: str, file: FileTypes, + chunking_strategy: file_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, ) -> VectorStoreFile: """Upload a file to the `files` API and then attach it to the given vector store. @@ -308,7 +310,7 @@ def upload( polling helper method to wait for processing to complete). """ file_obj = self._client.files.create(file=file, purpose="assistants") - return self.create(vector_store_id=vector_store_id, file_id=file_obj.id) + return self.create(vector_store_id=vector_store_id, file_id=file_obj.id, chunking_strategy=chunking_strategy) def upload_and_poll( self, @@ -316,12 +318,14 @@ def upload_and_poll( vector_store_id: str, file: FileTypes, poll_interval_ms: int | NotGiven = NOT_GIVEN, + chunking_strategy: file_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, ) -> VectorStoreFile: """Add a file to a vector store and poll until processing is complete.""" file_obj = self._client.files.create(file=file, purpose="assistants") return self.create_and_poll( vector_store_id=vector_store_id, file_id=file_obj.id, + chunking_strategy=chunking_strategy, poll_interval_ms=poll_interval_ms, ) @@ -542,9 +546,10 @@ async def create_and_poll( *, vector_store_id: str, poll_interval_ms: int | NotGiven = NOT_GIVEN, + chunking_strategy: file_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, ) -> VectorStoreFile: """Attach a file to the given vector store and wait for it to be processed.""" - await self.create(vector_store_id=vector_store_id, file_id=file_id) + await self.create(vector_store_id=vector_store_id, file_id=file_id, chunking_strategy=chunking_strategy) return await self.poll( file_id, @@ -598,6 +603,7 @@ async def upload( *, vector_store_id: str, file: FileTypes, + chunking_strategy: file_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, ) -> VectorStoreFile: """Upload a file to the `files` API and then attach it to the given vector store. @@ -605,7 +611,7 @@ async def upload( polling helper method to wait for processing to complete). """ file_obj = await self._client.files.create(file=file, purpose="assistants") - return await self.create(vector_store_id=vector_store_id, file_id=file_obj.id) + return await self.create(vector_store_id=vector_store_id, file_id=file_obj.id, chunking_strategy=chunking_strategy) async def upload_and_poll( self, @@ -613,6 +619,7 @@ async def upload_and_poll( vector_store_id: str, file: FileTypes, poll_interval_ms: int | NotGiven = NOT_GIVEN, + chunking_strategy: file_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, ) -> VectorStoreFile: """Add a file to a vector store and poll until processing is complete.""" file_obj = await self._client.files.create(file=file, purpose="assistants") @@ -620,6 +627,7 @@ async def upload_and_poll( vector_store_id=vector_store_id, file_id=file_obj.id, poll_interval_ms=poll_interval_ms, + chunking_strategy=chunking_strategy ) From 54a5911f5215148a0bdeb10e2bcfb84f635a75b9 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 7 Jun 2024 21:37:01 +0000 Subject: [PATCH 376/816] release: 1.33.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index cb8c32fee0..5334cb411c 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.32.1" + ".": "1.33.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index ecfe0762a1..236ef3ea4e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.33.0 (2024-06-07) + +Full Changelog: [v1.32.1...v1.33.0](https://github.com/openai/openai-python/compare/v1.32.1...v1.33.0) + +### Features + +* **api:** adding chunking_strategy to polling helpers ([#1478](https://github.com/openai/openai-python/issues/1478)) ([83be2a1](https://github.com/openai/openai-python/commit/83be2a13e0384d3de52190d86ccb1b5d7a197d84)) + ## 1.32.1 (2024-06-07) Full Changelog: [v1.32.0...v1.32.1](https://github.com/openai/openai-python/compare/v1.32.0...v1.32.1) diff --git a/pyproject.toml b/pyproject.toml index 80b6bc0465..873e52b8ff 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.32.1" +version = "1.33.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index aa58ad2d57..b4ef7ee2f3 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.32.1" # x-release-please-version +__version__ = "1.33.0" # x-release-please-version From 15c93bad5560b55bb6066db7514dfb1346ae2662 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 12 Jun 2024 14:45:02 -0400 Subject: [PATCH 377/816] feat(api): updates (#1481) --- .stats.yml | 2 +- src/openai/types/beta/threads/file_citation_annotation.py | 3 --- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/.stats.yml b/.stats.yml index a6c08f499b..c5ada3b5df 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 64 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-c085faf70d6ff059fbe11b7b6b98123a612524cb9b8a6f649c99526e5b0b1bdb.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-5cb1810135c35c5024698f3365626471a04796e26e393aefe1aa0ba3c0891919.yml diff --git a/src/openai/types/beta/threads/file_citation_annotation.py b/src/openai/types/beta/threads/file_citation_annotation.py index 68571cd477..c3085aed9b 100644 --- a/src/openai/types/beta/threads/file_citation_annotation.py +++ b/src/openai/types/beta/threads/file_citation_annotation.py @@ -11,9 +11,6 @@ class FileCitation(BaseModel): file_id: str """The ID of the specific File the citation is from.""" - quote: str - """The specific quote in the file.""" - class FileCitationAnnotation(BaseModel): end_index: int From 811f4e736b75a418fb9bc579861971b239e6cd0c Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 12 Jun 2024 18:45:34 +0000 Subject: [PATCH 378/816] release: 1.34.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 5334cb411c..257e308d6f 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.33.0" + ".": "1.34.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 236ef3ea4e..3295921654 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.34.0 (2024-06-12) + +Full Changelog: [v1.33.0...v1.34.0](https://github.com/openai/openai-python/compare/v1.33.0...v1.34.0) + +### Features + +* **api:** updates ([#1481](https://github.com/openai/openai-python/issues/1481)) ([b83db36](https://github.com/openai/openai-python/commit/b83db362f0c9a5a4d55588b954fb1df1a68c98e3)) + ## 1.33.0 (2024-06-07) Full Changelog: [v1.32.1...v1.33.0](https://github.com/openai/openai-python/compare/v1.32.1...v1.33.0) diff --git a/pyproject.toml b/pyproject.toml index 873e52b8ff..eb2da149b4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.33.0" +version = "1.34.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index b4ef7ee2f3..d0c1ef7e17 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.33.0" # x-release-please-version +__version__ = "1.34.0" # x-release-please-version From 6c8fcd541e45a83513123b68de60b25cdd623b07 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 18 Jun 2024 19:53:21 +0000 Subject: [PATCH 379/816] feat(api): add service tier argument for chat completions (#1486) --- .stats.yml | 2 +- src/openai/_base_client.py | 8 ++- src/openai/resources/chat/completions.py | 70 +++++++++++++++++++ src/openai/types/chat/chat_completion.py | 7 ++ .../types/chat/chat_completion_chunk.py | 7 ++ .../types/chat/completion_create_params.py | 13 ++++ tests/api_resources/chat/test_completions.py | 4 ++ 7 files changed, 109 insertions(+), 2 deletions(-) diff --git a/.stats.yml b/.stats.yml index c5ada3b5df..aa7e8427b0 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 64 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-5cb1810135c35c5024698f3365626471a04796e26e393aefe1aa0ba3c0891919.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-8fe357c6b5a425d810d731e4102a052d8e38c5e2d66950e6de1025415160bf88.yml diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 5d5d25fca9..1c9a1a03f2 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -457,7 +457,7 @@ def _build_request( raise RuntimeError(f"Unexpected JSON data type, {type(json_data)}, cannot merge with `extra_body`") headers = self._build_headers(options) - params = _merge_mappings(self._custom_query, options.params) + params = _merge_mappings(self.default_query, options.params) content_type = headers.get("Content-Type") # If the given Content-Type header is multipart/form-data then it @@ -593,6 +593,12 @@ def default_headers(self) -> dict[str, str | Omit]: **self._custom_headers, } + @property + def default_query(self) -> dict[str, object]: + return { + **self._custom_query, + } + def _validate_headers( self, headers: Headers, # noqa: ARG002 diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index ed8e9373b0..d50bce0757 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -59,6 +59,7 @@ def create( presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, @@ -163,6 +164,16 @@ def create( should refer to the `system_fingerprint` response parameter to monitor changes in the backend. + service_tier: Specifies the latency tier to use for processing the request. This parameter is + relevant for customers subscribed to the scale tier service: + + - If set to 'auto', the system will utilize scale tier credits until they are + exhausted. + - If set to 'default', the request will be processed in the shared cluster. + + When this parameter is set, the response body will include the `service_tier` + utilized. + stop: Up to 4 sequences where the API will stop generating further tokens. stream: If set, partial message deltas will be sent, like in ChatGPT. Tokens will be @@ -236,6 +247,7 @@ def create( presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -346,6 +358,16 @@ def create( should refer to the `system_fingerprint` response parameter to monitor changes in the backend. + service_tier: Specifies the latency tier to use for processing the request. This parameter is + relevant for customers subscribed to the scale tier service: + + - If set to 'auto', the system will utilize scale tier credits until they are + exhausted. + - If set to 'default', the request will be processed in the shared cluster. + + When this parameter is set, the response body will include the `service_tier` + utilized. + stop: Up to 4 sequences where the API will stop generating further tokens. stream_options: Options for streaming response. Only set this when you set `stream: true`. @@ -412,6 +434,7 @@ def create( presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -522,6 +545,16 @@ def create( should refer to the `system_fingerprint` response parameter to monitor changes in the backend. + service_tier: Specifies the latency tier to use for processing the request. This parameter is + relevant for customers subscribed to the scale tier service: + + - If set to 'auto', the system will utilize scale tier credits until they are + exhausted. + - If set to 'default', the request will be processed in the shared cluster. + + When this parameter is set, the response body will include the `service_tier` + utilized. + stop: Up to 4 sequences where the API will stop generating further tokens. stream_options: Options for streaming response. Only set this when you set `stream: true`. @@ -587,6 +620,7 @@ def create( presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, @@ -620,6 +654,7 @@ def create( "presence_penalty": presence_penalty, "response_format": response_format, "seed": seed, + "service_tier": service_tier, "stop": stop, "stream": stream, "stream_options": stream_options, @@ -667,6 +702,7 @@ async def create( presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, @@ -771,6 +807,16 @@ async def create( should refer to the `system_fingerprint` response parameter to monitor changes in the backend. + service_tier: Specifies the latency tier to use for processing the request. This parameter is + relevant for customers subscribed to the scale tier service: + + - If set to 'auto', the system will utilize scale tier credits until they are + exhausted. + - If set to 'default', the request will be processed in the shared cluster. + + When this parameter is set, the response body will include the `service_tier` + utilized. + stop: Up to 4 sequences where the API will stop generating further tokens. stream: If set, partial message deltas will be sent, like in ChatGPT. Tokens will be @@ -844,6 +890,7 @@ async def create( presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -954,6 +1001,16 @@ async def create( should refer to the `system_fingerprint` response parameter to monitor changes in the backend. + service_tier: Specifies the latency tier to use for processing the request. This parameter is + relevant for customers subscribed to the scale tier service: + + - If set to 'auto', the system will utilize scale tier credits until they are + exhausted. + - If set to 'default', the request will be processed in the shared cluster. + + When this parameter is set, the response body will include the `service_tier` + utilized. + stop: Up to 4 sequences where the API will stop generating further tokens. stream_options: Options for streaming response. Only set this when you set `stream: true`. @@ -1020,6 +1077,7 @@ async def create( presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -1130,6 +1188,16 @@ async def create( should refer to the `system_fingerprint` response parameter to monitor changes in the backend. + service_tier: Specifies the latency tier to use for processing the request. This parameter is + relevant for customers subscribed to the scale tier service: + + - If set to 'auto', the system will utilize scale tier credits until they are + exhausted. + - If set to 'default', the request will be processed in the shared cluster. + + When this parameter is set, the response body will include the `service_tier` + utilized. + stop: Up to 4 sequences where the API will stop generating further tokens. stream_options: Options for streaming response. Only set this when you set `stream: true`. @@ -1195,6 +1263,7 @@ async def create( presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, @@ -1228,6 +1297,7 @@ async def create( "presence_penalty": presence_penalty, "response_format": response_format, "seed": seed, + "service_tier": service_tier, "stop": stop, "stream": stream, "stream_options": stream_options, diff --git a/src/openai/types/chat/chat_completion.py b/src/openai/types/chat/chat_completion.py index 61a94a258e..5f4eaf3366 100644 --- a/src/openai/types/chat/chat_completion.py +++ b/src/openai/types/chat/chat_completion.py @@ -56,6 +56,13 @@ class ChatCompletion(BaseModel): object: Literal["chat.completion"] """The object type, which is always `chat.completion`.""" + service_tier: Optional[Literal["scale", "default"]] = None + """The service tier used for processing the request. + + This field is only included if the `service_tier` parameter is specified in the + request. + """ + system_fingerprint: Optional[str] = None """This fingerprint represents the backend configuration that the model runs with. diff --git a/src/openai/types/chat/chat_completion_chunk.py b/src/openai/types/chat/chat_completion_chunk.py index 084a5fcc07..65643c7e60 100644 --- a/src/openai/types/chat/chat_completion_chunk.py +++ b/src/openai/types/chat/chat_completion_chunk.py @@ -122,6 +122,13 @@ class ChatCompletionChunk(BaseModel): object: Literal["chat.completion.chunk"] """The object type, which is always `chat.completion.chunk`.""" + service_tier: Optional[Literal["scale", "default"]] = None + """The service tier used for processing the request. + + This field is only included if the `service_tier` parameter is specified in the + request. + """ + system_fingerprint: Optional[str] = None """ This fingerprint represents the backend configuration that the model runs with. diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 7dd7067f66..21187f3741 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -146,6 +146,19 @@ class CompletionCreateParamsBase(TypedDict, total=False): in the backend. """ + service_tier: Optional[Literal["auto", "default"]] + """Specifies the latency tier to use for processing the request. + + This parameter is relevant for customers subscribed to the scale tier service: + + - If set to 'auto', the system will utilize scale tier credits until they are + exhausted. + - If set to 'default', the request will be processed in the shared cluster. + + When this parameter is set, the response body will include the `service_tier` + utilized. + """ + stop: Union[Optional[str], List[str]] """Up to 4 sequences where the API will stop generating further tokens.""" diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index 3099e16815..87df11d1ee 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -60,6 +60,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: presence_penalty=-2, response_format={"type": "json_object"}, seed=-9223372036854776000, + service_tier="auto", stop="string", stream=False, stream_options={"include_usage": True}, @@ -176,6 +177,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: presence_penalty=-2, response_format={"type": "json_object"}, seed=-9223372036854776000, + service_tier="auto", stop="string", stream_options={"include_usage": True}, temperature=1, @@ -294,6 +296,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn presence_penalty=-2, response_format={"type": "json_object"}, seed=-9223372036854776000, + service_tier="auto", stop="string", stream=False, stream_options={"include_usage": True}, @@ -410,6 +413,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn presence_penalty=-2, response_format={"type": "json_object"}, seed=-9223372036854776000, + service_tier="auto", stop="string", stream_options={"include_usage": True}, temperature=1, From 6aa2a8030707e558ca08bf6992df2ad8926ed43a Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 18 Jun 2024 19:53:53 +0000 Subject: [PATCH 380/816] release: 1.35.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 257e308d6f..44959ac416 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.34.0" + ".": "1.35.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 3295921654..dc259c2ac8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.35.0 (2024-06-18) + +Full Changelog: [v1.34.0...v1.35.0](https://github.com/openai/openai-python/compare/v1.34.0...v1.35.0) + +### Features + +* **api:** add service tier argument for chat completions ([#1486](https://github.com/openai/openai-python/issues/1486)) ([b4b4e66](https://github.com/openai/openai-python/commit/b4b4e660b8bb7ae937787fcab9b40feaeba7f711)) + ## 1.34.0 (2024-06-12) Full Changelog: [v1.33.0...v1.34.0](https://github.com/openai/openai-python/compare/v1.33.0...v1.34.0) diff --git a/pyproject.toml b/pyproject.toml index eb2da149b4..5241598939 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.34.0" +version = "1.35.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index d0c1ef7e17..1f47c75093 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.34.0" # x-release-please-version +__version__ = "1.35.0" # x-release-please-version From dea7ee14780c9dc5456f20570e5c6d29a303c949 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 19 Jun 2024 11:18:26 +0000 Subject: [PATCH 381/816] fix(client/async): avoid blocking io call for platform headers (#1488) --- src/openai/_base_client.py | 17 +++++++++++++---- src/openai/_utils/__init__.py | 1 + src/openai/_utils/_reflection.py | 8 ++++++++ src/openai/_utils/_sync.py | 19 ++++++++++++++++++- 4 files changed, 40 insertions(+), 5 deletions(-) create mode 100644 src/openai/_utils/_reflection.py diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 1c9a1a03f2..84004ebba5 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -60,7 +60,7 @@ RequestOptions, ModelBuilderProtocol, ) -from ._utils import is_dict, is_list, is_given, lru_cache, is_mapping +from ._utils import is_dict, is_list, asyncify, is_given, lru_cache, is_mapping from ._compat import model_copy, model_dump from ._models import GenericModel, FinalRequestOptions, validate_type, construct_type from ._response import ( @@ -359,6 +359,7 @@ def __init__( self._custom_query = custom_query or {} self._strict_response_validation = _strict_response_validation self._idempotency_header = None + self._platform: Platform | None = None if max_retries is None: # pyright: ignore[reportUnnecessaryComparison] raise TypeError( @@ -623,7 +624,10 @@ def base_url(http://github.com/self,%20url:%20URL%20|%20str) -> None: self._base_url = self._enforce_trailing_slash(url if isinstance(url, URL) else URL(url)) def platform_headers(self) -> Dict[str, str]: - return platform_headers(self._version) + # the actual implementation is in a separate `lru_cache` decorated + # function because adding `lru_cache` to methods will leak memory + # https://github.com/python/cpython/issues/88476 + return platform_headers(self._version, platform=self._platform) def _parse_retry_after_header(self, response_headers: Optional[httpx.Headers] = None) -> float | None: """Returns a float of the number of seconds (not milliseconds) to wait after retrying, or None if unspecified. @@ -1513,6 +1517,11 @@ async def _request( stream_cls: type[_AsyncStreamT] | None, remaining_retries: int | None, ) -> ResponseT | _AsyncStreamT: + if self._platform is None: + # `get_platform` can make blocking IO calls so we + # execute it earlier while we are in an async context + self._platform = await asyncify(get_platform)() + cast_to = self._maybe_override_cast_to(cast_to, options) await self._prepare_options(options) @@ -1949,11 +1958,11 @@ def get_platform() -> Platform: @lru_cache(maxsize=None) -def platform_headers(version: str) -> Dict[str, str]: +def platform_headers(version: str, *, platform: Platform | None) -> Dict[str, str]: return { "X-Stainless-Lang": "python", "X-Stainless-Package-Version": version, - "X-Stainless-OS": str(get_platform()), + "X-Stainless-OS": str(platform or get_platform()), "X-Stainless-Arch": str(get_architecture()), "X-Stainless-Runtime": get_python_runtime(), "X-Stainless-Runtime-Version": get_python_version(), diff --git a/src/openai/_utils/__init__.py b/src/openai/_utils/__init__.py index 31b5b22799..667e2473f6 100644 --- a/src/openai/_utils/__init__.py +++ b/src/openai/_utils/__init__.py @@ -49,3 +49,4 @@ maybe_transform as maybe_transform, async_maybe_transform as async_maybe_transform, ) +from ._reflection import function_has_argument as function_has_argument diff --git a/src/openai/_utils/_reflection.py b/src/openai/_utils/_reflection.py new file mode 100644 index 0000000000..e134f58e08 --- /dev/null +++ b/src/openai/_utils/_reflection.py @@ -0,0 +1,8 @@ +import inspect +from typing import Any, Callable + + +def function_has_argument(func: Callable[..., Any], arg_name: str) -> bool: + """Returns whether or not the given function has a specific parameter""" + sig = inspect.signature(func) + return arg_name in sig.parameters diff --git a/src/openai/_utils/_sync.py b/src/openai/_utils/_sync.py index 595924e5b1..d0d810337e 100644 --- a/src/openai/_utils/_sync.py +++ b/src/openai/_utils/_sync.py @@ -7,6 +7,8 @@ import anyio import anyio.to_thread +from ._reflection import function_has_argument + T_Retval = TypeVar("T_Retval") T_ParamSpec = ParamSpec("T_ParamSpec") @@ -59,6 +61,21 @@ def do_work(arg1, arg2, kwarg1="", kwarg2="") -> str: async def wrapper(*args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs) -> T_Retval: partial_f = functools.partial(function, *args, **kwargs) - return await anyio.to_thread.run_sync(partial_f, cancellable=cancellable, limiter=limiter) + + # In `v4.1.0` anyio added the `abandon_on_cancel` argument and deprecated the old + # `cancellable` argument, so we need to use the new `abandon_on_cancel` to avoid + # surfacing deprecation warnings. + if function_has_argument(anyio.to_thread.run_sync, "abandon_on_cancel"): + return await anyio.to_thread.run_sync( + partial_f, + abandon_on_cancel=cancellable, + limiter=limiter, + ) + + return await anyio.to_thread.run_sync( + partial_f, + cancellable=cancellable, + limiter=limiter, + ) return wrapper From e005a8482d76a9939d88c71f13860ee3764fe2af Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 19 Jun 2024 16:48:49 +0000 Subject: [PATCH 382/816] release: 1.35.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 44959ac416..21b274b18a 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.35.0" + ".": "1.35.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index dc259c2ac8..f442ddd2ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.35.1 (2024-06-19) + +Full Changelog: [v1.35.0...v1.35.1](https://github.com/openai/openai-python/compare/v1.35.0...v1.35.1) + +### Bug Fixes + +* **client/async:** avoid blocking io call for platform headers ([#1488](https://github.com/openai/openai-python/issues/1488)) ([ae64c05](https://github.com/openai/openai-python/commit/ae64c05cbae76a58b592d913bee6ac1ef9611d4c)) + ## 1.35.0 (2024-06-18) Full Changelog: [v1.34.0...v1.35.0](https://github.com/openai/openai-python/compare/v1.34.0...v1.35.0) diff --git a/pyproject.toml b/pyproject.toml index 5241598939..270c21f4cf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.35.0" +version = "1.35.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 1f47c75093..ae8e3fb08d 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.35.0" # x-release-please-version +__version__ = "1.35.1" # x-release-please-version From a1203812c94812858f05d71c9b20a5865287b4fe Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Thu, 20 Jun 2024 18:47:34 +0100 Subject: [PATCH 383/816] fix(api): add missing parallel_tool_calls arguments --- src/openai/resources/beta/threads/threads.py | 12 ++++ tests/lib/test_assistants.py | 59 ++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 tests/lib/test_assistants.py diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index c0a908b7a2..a62ee8d1bb 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -828,6 +828,7 @@ def create_and_run_poll( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, @@ -856,6 +857,7 @@ def create_and_run_poll( max_prompt_tokens=max_prompt_tokens, metadata=metadata, model=model, + parallel_tool_calls=parallel_tool_calls, response_format=response_format, temperature=temperature, stream=False, @@ -908,6 +910,7 @@ def create_and_run_stream( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, @@ -962,6 +965,7 @@ def create_and_run_stream( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, @@ -1016,6 +1020,7 @@ def create_and_run_stream( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, @@ -1050,6 +1055,7 @@ def create_and_run_stream( "max_prompt_tokens": max_prompt_tokens, "metadata": metadata, "model": model, + "parallel_tool_calls": parallel_tool_calls, "response_format": response_format, "temperature": temperature, "tool_choice": tool_choice, @@ -1838,6 +1844,7 @@ async def create_and_run_poll( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, @@ -1866,6 +1873,7 @@ async def create_and_run_poll( max_prompt_tokens=max_prompt_tokens, metadata=metadata, model=model, + parallel_tool_calls=parallel_tool_calls, response_format=response_format, temperature=temperature, stream=False, @@ -1920,6 +1928,7 @@ def create_and_run_stream( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, @@ -1974,6 +1983,7 @@ def create_and_run_stream( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, @@ -2028,6 +2038,7 @@ def create_and_run_stream( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, @@ -2064,6 +2075,7 @@ def create_and_run_stream( "max_prompt_tokens": max_prompt_tokens, "metadata": metadata, "model": model, + "parallel_tool_calls": parallel_tool_calls, "response_format": response_format, "temperature": temperature, "tool_choice": tool_choice, diff --git a/tests/lib/test_assistants.py b/tests/lib/test_assistants.py new file mode 100644 index 0000000000..ac92f17ca3 --- /dev/null +++ b/tests/lib/test_assistants.py @@ -0,0 +1,59 @@ +from __future__ import annotations + +import inspect +from typing import Any, Callable + +import pytest + +from openai import OpenAI, AsyncOpenAI + + +def assert_signatures_in_sync( + source_func: Callable[..., Any], + check_func: Callable[..., Any], + *, + exclude_params: set[str] = set(), +) -> None: + check_sig = inspect.signature(check_func) + source_sig = inspect.signature(source_func) + + errors: list[str] = [] + + for name, generated_param in source_sig.parameters.items(): + if name in exclude_params: + continue + + custom_param = check_sig.parameters.get(name) + if not custom_param: + errors.append(f"the `{name}` param is missing") + continue + + if custom_param.annotation != generated_param.annotation: + errors.append( + f"types for the `{name}` param are do not match; generated={repr(generated_param.annotation)} custom={repr(generated_param.annotation)}" + ) + continue + + if errors: + raise AssertionError(f"{len(errors)} errors encountered when comparing signatures:\n\n" + "\n\n".join(errors)) + + +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +def test_create_and_run_poll_method_definition_in_sync(sync: bool, client: OpenAI, async_client: AsyncOpenAI) -> None: + checking_client = client if sync else async_client + + assert_signatures_in_sync( + checking_client.beta.threads.create_and_run, + checking_client.beta.threads.create_and_run_poll, + exclude_params={"stream"}, + ) + +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +def test_create_and_run_stream_method_definition_in_sync(sync: bool, client: OpenAI, async_client: AsyncOpenAI) -> None: + checking_client = client if sync else async_client + + assert_signatures_in_sync( + checking_client.beta.threads.create_and_run, + checking_client.beta.threads.create_and_run_stream, + exclude_params={"stream"}, + ) From 717e318d6e0c652721c6e7081acd6db226f77820 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 20 Jun 2024 17:48:10 +0000 Subject: [PATCH 384/816] release: 1.35.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 21b274b18a..5554412dd2 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.35.1" + ".": "1.35.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index f442ddd2ce..5eede818c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.35.2 (2024-06-20) + +Full Changelog: [v1.35.1...v1.35.2](https://github.com/openai/openai-python/compare/v1.35.1...v1.35.2) + +### Bug Fixes + +* **api:** add missing parallel_tool_calls arguments ([4041e4f](https://github.com/openai/openai-python/commit/4041e4f6ea1e2316179a82031001308be23a2524)) + ## 1.35.1 (2024-06-19) Full Changelog: [v1.35.0...v1.35.1](https://github.com/openai/openai-python/compare/v1.35.0...v1.35.1) diff --git a/pyproject.toml b/pyproject.toml index 270c21f4cf..91a3f5d19d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.35.1" +version = "1.35.2" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index ae8e3fb08d..f053bcea86 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.35.1" # x-release-please-version +__version__ = "1.35.2" # x-release-please-version From 203f094b2338bff01b2bd513113845a07ded630d Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Thu, 20 Jun 2024 18:52:48 +0100 Subject: [PATCH 385/816] fix(tests): add explicit type annotation --- tests/lib/test_assistants.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/lib/test_assistants.py b/tests/lib/test_assistants.py index ac92f17ca3..487b9938c7 100644 --- a/tests/lib/test_assistants.py +++ b/tests/lib/test_assistants.py @@ -40,7 +40,7 @@ def assert_signatures_in_sync( @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) def test_create_and_run_poll_method_definition_in_sync(sync: bool, client: OpenAI, async_client: AsyncOpenAI) -> None: - checking_client = client if sync else async_client + checking_client: OpenAI | AsyncOpenAI = client if sync else async_client assert_signatures_in_sync( checking_client.beta.threads.create_and_run, @@ -50,7 +50,7 @@ def test_create_and_run_poll_method_definition_in_sync(sync: bool, client: OpenA @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) def test_create_and_run_stream_method_definition_in_sync(sync: bool, client: OpenAI, async_client: AsyncOpenAI) -> None: - checking_client = client if sync else async_client + checking_client: OpenAI | AsyncOpenAI = client if sync else async_client assert_signatures_in_sync( checking_client.beta.threads.create_and_run, From f3e6e634a86d5789ab1274ae27f43adc842f4ba8 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 20 Jun 2024 17:53:33 +0000 Subject: [PATCH 386/816] release: 1.35.3 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 5554412dd2..7d2dc6aa83 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.35.2" + ".": "1.35.3" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 5eede818c4..4dcfe237ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.35.3 (2024-06-20) + +Full Changelog: [v1.35.2...v1.35.3](https://github.com/openai/openai-python/compare/v1.35.2...v1.35.3) + +### Bug Fixes + +* **tests:** add explicit type annotation ([9345f10](https://github.com/openai/openai-python/commit/9345f104889056b2ef6646d65375925a0a3bae03)) + ## 1.35.2 (2024-06-20) Full Changelog: [v1.35.1...v1.35.2](https://github.com/openai/openai-python/compare/v1.35.1...v1.35.2) diff --git a/pyproject.toml b/pyproject.toml index 91a3f5d19d..dfe148cc51 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.35.2" +version = "1.35.3" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index f053bcea86..1bba5023e0 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.35.2" # x-release-please-version +__version__ = "1.35.3" # x-release-please-version From 293c02d0cb095679579b79e2996bc3f830f682e1 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 21 Jun 2024 10:16:40 +0000 Subject: [PATCH 387/816] chore(doc): clarify service tier default value (#1496) --- .stats.yml | 2 +- src/openai/resources/chat/completions.py | 18 ++++++++++++------ .../types/chat/completion_create_params.py | 3 ++- 3 files changed, 15 insertions(+), 8 deletions(-) diff --git a/.stats.yml b/.stats.yml index aa7e8427b0..04682ea0a6 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 64 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-8fe357c6b5a425d810d731e4102a052d8e38c5e2d66950e6de1025415160bf88.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-3a69e1cc9e1efda3fb82d0fb35961749f886a87594dae9d8d2aa5c60f157f5d2.yml diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index d50bce0757..d73ece2109 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -169,7 +169,8 @@ def create( - If set to 'auto', the system will utilize scale tier credits until they are exhausted. - - If set to 'default', the request will be processed in the shared cluster. + - If set to 'default', the request will be processed using the default service + tier with a lower uptime SLA and no latency guarentee. When this parameter is set, the response body will include the `service_tier` utilized. @@ -363,7 +364,8 @@ def create( - If set to 'auto', the system will utilize scale tier credits until they are exhausted. - - If set to 'default', the request will be processed in the shared cluster. + - If set to 'default', the request will be processed using the default service + tier with a lower uptime SLA and no latency guarentee. When this parameter is set, the response body will include the `service_tier` utilized. @@ -550,7 +552,8 @@ def create( - If set to 'auto', the system will utilize scale tier credits until they are exhausted. - - If set to 'default', the request will be processed in the shared cluster. + - If set to 'default', the request will be processed using the default service + tier with a lower uptime SLA and no latency guarentee. When this parameter is set, the response body will include the `service_tier` utilized. @@ -812,7 +815,8 @@ async def create( - If set to 'auto', the system will utilize scale tier credits until they are exhausted. - - If set to 'default', the request will be processed in the shared cluster. + - If set to 'default', the request will be processed using the default service + tier with a lower uptime SLA and no latency guarentee. When this parameter is set, the response body will include the `service_tier` utilized. @@ -1006,7 +1010,8 @@ async def create( - If set to 'auto', the system will utilize scale tier credits until they are exhausted. - - If set to 'default', the request will be processed in the shared cluster. + - If set to 'default', the request will be processed using the default service + tier with a lower uptime SLA and no latency guarentee. When this parameter is set, the response body will include the `service_tier` utilized. @@ -1193,7 +1198,8 @@ async def create( - If set to 'auto', the system will utilize scale tier credits until they are exhausted. - - If set to 'default', the request will be processed in the shared cluster. + - If set to 'default', the request will be processed using the default service + tier with a lower uptime SLA and no latency guarentee. When this parameter is set, the response body will include the `service_tier` utilized. diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 21187f3741..85157653f2 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -153,7 +153,8 @@ class CompletionCreateParamsBase(TypedDict, total=False): - If set to 'auto', the system will utilize scale tier credits until they are exhausted. - - If set to 'default', the request will be processed in the shared cluster. + - If set to 'default', the request will be processed using the default service + tier with a lower uptime SLA and no latency guarentee. When this parameter is set, the response body will include the `service_tier` utilized. From d3254d12f9ae9178dfb471aa963a4ebc670e7b8a Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 25 Jun 2024 13:56:05 +0000 Subject: [PATCH 388/816] fix(docs): fix link to advanced python httpx docs (#1499) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5e351ba03c..1ea79f8d80 100644 --- a/README.md +++ b/README.md @@ -560,7 +560,7 @@ You can directly override the [httpx client](https://www.python-httpx.org/api/#c - Support for proxies - Custom transports -- Additional [advanced](https://www.python-httpx.org/advanced/#client-instances) functionality +- Additional [advanced](https://www.python-httpx.org/advanced/clients/) functionality ```python from openai import OpenAI, DefaultHttpxClient From 8061d18dd8bb1f9f17a46ac0d90edb2592a132a0 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 26 Jun 2024 01:12:25 +0000 Subject: [PATCH 389/816] fix: temporarily patch upstream version to fix broken release flow (#1500) --- bin/publish-pypi | 3 +++ 1 file changed, 3 insertions(+) diff --git a/bin/publish-pypi b/bin/publish-pypi index 826054e924..05bfccbb71 100644 --- a/bin/publish-pypi +++ b/bin/publish-pypi @@ -3,4 +3,7 @@ set -eux mkdir -p dist rye build --clean +# Patching importlib-metadata version until upstream library version is updated +# https://github.com/pypa/twine/issues/977#issuecomment-2189800841 +"$HOME/.rye/self/bin/python3" -m pip install 'importlib-metadata==7.2.1' rye publish --yes --token=$PYPI_TOKEN From 254937a733b95366d21f5bda45b2f84693488e42 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 26 Jun 2024 01:13:13 +0000 Subject: [PATCH 390/816] release: 1.35.4 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 14 ++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 17 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 7d2dc6aa83..994b53c2bf 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.35.3" + ".": "1.35.4" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 4dcfe237ea..f04a26588e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,19 @@ # Changelog +## 1.35.4 (2024-06-26) + +Full Changelog: [v1.35.3...v1.35.4](https://github.com/openai/openai-python/compare/v1.35.3...v1.35.4) + +### Bug Fixes + +* **docs:** fix link to advanced python httpx docs ([#1499](https://github.com/openai/openai-python/issues/1499)) ([cf45cd5](https://github.com/openai/openai-python/commit/cf45cd5942cecec569072146673ddfc0e0ec108e)) +* temporarily patch upstream version to fix broken release flow ([#1500](https://github.com/openai/openai-python/issues/1500)) ([4f10470](https://github.com/openai/openai-python/commit/4f10470f5f74fc258a78fa6d897d8ab5b70dcf52)) + + +### Chores + +* **doc:** clarify service tier default value ([#1496](https://github.com/openai/openai-python/issues/1496)) ([ba39667](https://github.com/openai/openai-python/commit/ba39667c4faa8e10457347be41334ca9639186d4)) + ## 1.35.3 (2024-06-20) Full Changelog: [v1.35.2...v1.35.3](https://github.com/openai/openai-python/compare/v1.35.2...v1.35.3) diff --git a/pyproject.toml b/pyproject.toml index dfe148cc51..afbc56485e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.35.3" +version = "1.35.4" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 1bba5023e0..6439aacf1d 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.35.3" # x-release-please-version +__version__ = "1.35.4" # x-release-please-version From 612135773016d61b4e064600694cbdf4bd73284d Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Wed, 26 Jun 2024 11:09:28 +0100 Subject: [PATCH 391/816] fix(cli/migrate): avoid reliance on Python 3.12 argument --- src/openai/cli/_tools/migrate.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/openai/cli/_tools/migrate.py b/src/openai/cli/_tools/migrate.py index 53073b866f..7c10bb7f85 100644 --- a/src/openai/cli/_tools/migrate.py +++ b/src/openai/cli/_tools/migrate.py @@ -138,7 +138,10 @@ def install() -> Path: unpacked_dir.mkdir(parents=True, exist_ok=True) with tarfile.open(temp_file, "r:gz") as archive: - archive.extractall(unpacked_dir, filter="data") + if sys.version_info >= (3, 12): + archive.extractall(unpacked_dir, filter="data") + else: + archive.extractall(unpacked_dir) for item in unpacked_dir.iterdir(): item.rename(target_dir / item.name) From c34cb641b1334d5a780e45488ad07e3abe1251ee Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 26 Jun 2024 10:09:53 +0000 Subject: [PATCH 392/816] release: 1.35.5 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 994b53c2bf..940027a677 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.35.4" + ".": "1.35.5" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index f04a26588e..39672b081b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.35.5 (2024-06-26) + +Full Changelog: [v1.35.4...v1.35.5](https://github.com/openai/openai-python/compare/v1.35.4...v1.35.5) + +### Bug Fixes + +* **cli/migrate:** avoid reliance on Python 3.12 argument ([be7a06b](https://github.com/openai/openai-python/commit/be7a06b3875e3ecb9229d67a41e290ca218f092d)) + ## 1.35.4 (2024-06-26) Full Changelog: [v1.35.3...v1.35.4](https://github.com/openai/openai-python/compare/v1.35.3...v1.35.4) diff --git a/pyproject.toml b/pyproject.toml index afbc56485e..d2cf1d0b5e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.35.4" +version = "1.35.5" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 6439aacf1d..4e8d735687 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.35.4" # x-release-please-version +__version__ = "1.35.5" # x-release-please-version From 137f38bab43fe41435c4045c668d749726aac393 Mon Sep 17 00:00:00 2001 From: Nino Risteski <95188570+NinoRisteski@users.noreply.github.com> Date: Thu, 27 Jun 2024 14:57:19 +0200 Subject: [PATCH 393/816] docs(readme): improve some wording (#1392) fixed a few typos --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 1ea79f8d80..15853f27c6 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ so that your API Key is not stored in source control. When interacting with the API some actions such as starting a Run and adding files to vector stores are asynchronous and take time to complete. The SDK includes helper functions which will poll the status until it reaches a terminal state and then return the resulting object. -If an API method results in an action which could benefit from polling there will be a corresponding version of the +If an API method results in an action that could benefit from polling there will be a corresponding version of the method ending in '\_and_poll'. For instance to create a Run and poll until it reaches a terminal state you can run: @@ -71,7 +71,7 @@ More information on the lifecycle of a Run can be found in the [Run Lifecycle Do ### Bulk Upload Helpers -When creating an interacting with vector stores, you can use the polling helpers to monitor the status of operations. +When creating and interacting with vector stores, you can use polling helpers to monitor the status of operations. For convenience, we also provide a bulk upload helper to allow you to simultaneously upload several files at once. ```python @@ -85,7 +85,7 @@ batch = await client.vector_stores.file_batches.upload_and_poll( ### Streaming Helpers -The SDK also includes helpers to process streams and handle the incoming events. +The SDK also includes helpers to process streams and handle incoming events. ```python with client.beta.threads.runs.stream( @@ -201,7 +201,7 @@ completion = openai.chat.completions.create( print(completion.choices[0].message.content) ``` -The API is the exact same as the standard client instance based API. +The API is the exact same as the standard client instance-based API. This is intended to be used within REPLs or notebooks for faster iteration, **not** in application code. From 7f067717a0cc0bc371a1ae43d5e69905cdbe32c0 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 27 Jun 2024 12:57:42 +0000 Subject: [PATCH 394/816] release: 1.35.6 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 940027a677..964fe0a6ee 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.35.5" + ".": "1.35.6" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 39672b081b..6cb68a071c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.35.6 (2024-06-27) + +Full Changelog: [v1.35.5...v1.35.6](https://github.com/openai/openai-python/compare/v1.35.5...v1.35.6) + +### Documentation + +* **readme:** improve some wording ([#1392](https://github.com/openai/openai-python/issues/1392)) ([a58a052](https://github.com/openai/openai-python/commit/a58a05215b560ebcf3ff3eb1dd997259720a48f3)) + ## 1.35.5 (2024-06-26) Full Changelog: [v1.35.4...v1.35.5](https://github.com/openai/openai-python/compare/v1.35.4...v1.35.5) diff --git a/pyproject.toml b/pyproject.toml index d2cf1d0b5e..452f4dc6d1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.35.5" +version = "1.35.6" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 4e8d735687..b93ac747f6 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.35.5" # x-release-please-version +__version__ = "1.35.6" # x-release-please-version From 42fb72fd6b0886d19cf58d358f99187b5113ea34 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 27 Jun 2024 16:32:04 +0000 Subject: [PATCH 395/816] fix(build): include more files in sdist builds (#1504) --- pyproject.toml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index 452f4dc6d1..e645db6772 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -105,6 +105,21 @@ include = [ [tool.hatch.build.targets.wheel] packages = ["src/openai"] +[tool.hatch.build.targets.sdist] +# Basically everything except hidden files/directories (such as .github, .devcontainers, .python-version, etc) +include = [ + "/*.toml", + "/*.json", + "/*.lock", + "/*.md", + "/mypy.ini", + "/noxfile.py", + "bin/*", + "examples/*", + "src/*", + "tests/*", +] + [tool.hatch.metadata.hooks.fancy-pypi-readme] content-type = "text/markdown" From 6316b7c0f182877e578a3dbed2fd129b63538af5 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 27 Jun 2024 16:32:30 +0000 Subject: [PATCH 396/816] release: 1.35.7 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 964fe0a6ee..873dd128c1 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.35.6" + ".": "1.35.7" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 6cb68a071c..37f920b3a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.35.7 (2024-06-27) + +Full Changelog: [v1.35.6...v1.35.7](https://github.com/openai/openai-python/compare/v1.35.6...v1.35.7) + +### Bug Fixes + +* **build:** include more files in sdist builds ([#1504](https://github.com/openai/openai-python/issues/1504)) ([730c1b5](https://github.com/openai/openai-python/commit/730c1b53b1a61e218a85aa2d1cf3ba4775618755)) + ## 1.35.6 (2024-06-27) Full Changelog: [v1.35.5...v1.35.6](https://github.com/openai/openai-python/compare/v1.35.5...v1.35.6) diff --git a/pyproject.toml b/pyproject.toml index e645db6772..658d5a412b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.35.6" +version = "1.35.7" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index b93ac747f6..b9f757681a 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.35.6" # x-release-please-version +__version__ = "1.35.7" # x-release-please-version From 2dd44460d35dc4d79057d0c27d2324a39048885e Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 28 Jun 2024 12:41:56 +0000 Subject: [PATCH 397/816] chore(internal): add reflection helper function (#1508) --- src/openai/_utils/__init__.py | 5 ++++- src/openai/_utils/_reflection.py | 34 ++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/openai/_utils/__init__.py b/src/openai/_utils/__init__.py index 667e2473f6..3efe66c8e8 100644 --- a/src/openai/_utils/__init__.py +++ b/src/openai/_utils/__init__.py @@ -49,4 +49,7 @@ maybe_transform as maybe_transform, async_maybe_transform as async_maybe_transform, ) -from ._reflection import function_has_argument as function_has_argument +from ._reflection import ( + function_has_argument as function_has_argument, + assert_signatures_in_sync as assert_signatures_in_sync, +) diff --git a/src/openai/_utils/_reflection.py b/src/openai/_utils/_reflection.py index e134f58e08..9a53c7bd21 100644 --- a/src/openai/_utils/_reflection.py +++ b/src/openai/_utils/_reflection.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import inspect from typing import Any, Callable @@ -6,3 +8,35 @@ def function_has_argument(func: Callable[..., Any], arg_name: str) -> bool: """Returns whether or not the given function has a specific parameter""" sig = inspect.signature(func) return arg_name in sig.parameters + + +def assert_signatures_in_sync( + source_func: Callable[..., Any], + check_func: Callable[..., Any], + *, + exclude_params: set[str] = set(), +) -> None: + """Ensure that the signature of the second function matches the first.""" + + check_sig = inspect.signature(check_func) + source_sig = inspect.signature(source_func) + + errors: list[str] = [] + + for name, source_param in source_sig.parameters.items(): + if name in exclude_params: + continue + + custom_param = check_sig.parameters.get(name) + if not custom_param: + errors.append(f"the `{name}` param is missing") + continue + + if custom_param.annotation != source_param.annotation: + errors.append( + f"types for the `{name}` param are do not match; source={repr(source_param.annotation)} checking={repr(source_param.annotation)}" + ) + continue + + if errors: + raise AssertionError(f"{len(errors)} errors encountered when comparing signatures:\n\n" + "\n\n".join(errors)) From 24347efc6d94faddb10b773b04c2b5afa38b2ea6 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 28 Jun 2024 14:11:37 +0000 Subject: [PATCH 398/816] chore: gitignore test server logs (#1509) --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 0f9a66a976..8779740800 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +.prism.log .vscode _dev From edf8d80bea56ee1d530e582f57a75600230e52ab Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 2 Jul 2024 11:20:52 +0000 Subject: [PATCH 399/816] chore(internal): add helper method for constructing `BaseModel`s (#1517) --- src/openai/_models.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/openai/_models.py b/src/openai/_models.py index 75c68cc730..5d95bb4b2b 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -10,6 +10,7 @@ ClassVar, Protocol, Required, + ParamSpec, TypedDict, TypeGuard, final, @@ -67,6 +68,9 @@ __all__ = ["BaseModel", "GenericModel"] _T = TypeVar("_T") +_BaseModelT = TypeVar("_BaseModelT", bound="BaseModel") + +P = ParamSpec("P") @runtime_checkable @@ -379,6 +383,29 @@ def is_basemodel_type(type_: type) -> TypeGuard[type[BaseModel] | type[GenericMo return issubclass(origin, BaseModel) or issubclass(origin, GenericModel) +def build( + base_model_cls: Callable[P, _BaseModelT], + *args: P.args, + **kwargs: P.kwargs, +) -> _BaseModelT: + """Construct a BaseModel class without validation. + + This is useful for cases where you need to instantiate a `BaseModel` + from an API response as this provides type-safe params which isn't supported + by helpers like `construct_type()`. + + ```py + build(MyModel, my_field_a="foo", my_field_b=123) + ``` + """ + if args: + raise TypeError( + "Received positional arguments which are not supported; Keyword arguments must be used instead", + ) + + return cast(_BaseModelT, construct_type(type_=base_model_cls, value=kwargs)) + + def construct_type(*, value: object, type_: object) -> object: """Loose coercion to the expected type with construction of nested values. From d9540b4da9c87e229fc53b39288748ab3adce44e Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 1 Jul 2024 13:36:44 +0000 Subject: [PATCH 400/816] chore(internal): add rich as a dev dependency (#1514) it's often very helpful when writing demo scripts --- pyproject.toml | 1 + requirements-dev.lock | 15 +++++++++++---- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 658d5a412b..d1bd9c19fb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -60,6 +60,7 @@ dev-dependencies = [ "nox", "dirty-equals>=0.6.0", "importlib-metadata>=6.7.0", + "rich>=13.7.1", "inline-snapshot >=0.7.0", "azure-identity >=1.14.1", "types-tqdm > 4", diff --git a/requirements-dev.lock b/requirements-dev.lock index c5416cd4db..3e3284cebc 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -70,11 +70,15 @@ idna==3.4 importlib-metadata==7.0.0 iniconfig==2.0.0 # via pytest -inline-snapshot==0.7.0 -msal==1.28.0 +inline-snapshot==0.10.2 +markdown-it-py==3.0.0 + # via rich +mdurl==0.1.2 + # via markdown-it-py +msal==1.29.0 # via azure-identity # via msal-extensions -msal-extensions==1.1.0 +msal-extensions==1.2.0 # via azure-identity mypy==1.7.1 mypy-extensions==1.0.0 @@ -91,7 +95,6 @@ outcome==1.3.0.post0 # via trio packaging==23.2 # via black - # via msal-extensions # via nox # via pytest pandas==2.1.4 @@ -115,6 +118,8 @@ pydantic==2.7.1 # via openai pydantic-core==2.18.2 # via pydantic +pygments==2.18.0 + # via rich pyjwt==2.8.0 # via msal pyright==1.1.364 @@ -131,6 +136,8 @@ requests==2.31.0 # via azure-core # via msal respx==0.20.2 +rich==13.7.1 + # via inline-snapshot ruff==0.1.9 setuptools==68.2.2 # via nodeenv From fee32a0b23fb8ae4e963c1ce8593d387a02a4b3d Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 2 Jul 2024 11:26:45 +0000 Subject: [PATCH 401/816] release: 1.35.8 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 11 +++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 14 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 873dd128c1..1ef8c632ae 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.35.7" + ".": "1.35.8" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 37f920b3a9..1e40cafda7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## 1.35.8 (2024-07-02) + +Full Changelog: [v1.35.7...v1.35.8](https://github.com/openai/openai-python/compare/v1.35.7...v1.35.8) + +### Chores + +* gitignore test server logs ([#1509](https://github.com/openai/openai-python/issues/1509)) ([936d840](https://github.com/openai/openai-python/commit/936d84094a28ad0a2b4a20e2b3bbf1674048223e)) +* **internal:** add helper method for constructing `BaseModel`s ([#1517](https://github.com/openai/openai-python/issues/1517)) ([e5ddbf5](https://github.com/openai/openai-python/commit/e5ddbf554ce4b6be4b59114a36e69f02ca724acf)) +* **internal:** add reflection helper function ([#1508](https://github.com/openai/openai-python/issues/1508)) ([6044e1b](https://github.com/openai/openai-python/commit/6044e1bbfa9e46a01faf5a9edf198f86fa4c6dd0)) +* **internal:** add rich as a dev dependency ([#1514](https://github.com/openai/openai-python/issues/1514)) ([8a2b4e4](https://github.com/openai/openai-python/commit/8a2b4e4c1233dca916531ebc65d65a8d35fa7b7b)) + ## 1.35.7 (2024-06-27) Full Changelog: [v1.35.6...v1.35.7](https://github.com/openai/openai-python/compare/v1.35.6...v1.35.7) diff --git a/pyproject.toml b/pyproject.toml index d1bd9c19fb..ea1f76bf42 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.35.7" +version = "1.35.8" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index b9f757681a..c612421e90 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.35.7" # x-release-please-version +__version__ = "1.35.8" # x-release-please-version From 1c59013ad29de370a96b44fcd14da2956cc2a03d Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 2 Jul 2024 19:13:30 +0000 Subject: [PATCH 402/816] fix(client): always respect content-type multipart/form-data if provided (#1519) --- src/openai/_base_client.py | 20 +++++++++-- src/openai/resources/audio/transcriptions.py | 18 +++++----- src/openai/resources/audio/translations.py | 18 +++++----- src/openai/resources/files.py | 18 +++++----- src/openai/resources/images.py | 36 +++++++++----------- 5 files changed, 58 insertions(+), 52 deletions(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 84004ebba5..2f4b0c7fbd 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -58,6 +58,7 @@ HttpxSendArgs, AsyncTransport, RequestOptions, + HttpxRequestFiles, ModelBuilderProtocol, ) from ._utils import is_dict, is_list, asyncify, is_given, lru_cache, is_mapping @@ -460,6 +461,7 @@ def _build_request( headers = self._build_headers(options) params = _merge_mappings(self.default_query, options.params) content_type = headers.get("Content-Type") + files = options.files # If the given Content-Type header is multipart/form-data then it # has to be removed so that httpx can generate the header with @@ -473,7 +475,7 @@ def _build_request( headers.pop("Content-Type") # As we are now sending multipart/form-data instead of application/json - # we need to tell httpx to use it, https://www.python-httpx.org/advanced/#multipart-file-encoding + # we need to tell httpx to use it, https://www.python-httpx.org/advanced/clients/#multipart-file-encoding if json_data: if not is_dict(json_data): raise TypeError( @@ -481,6 +483,15 @@ def _build_request( ) kwargs["data"] = self._serialize_multipartform(json_data) + # httpx determines whether or not to send a "multipart/form-data" + # request based on the truthiness of the "files" argument. + # This gets around that issue by generating a dict value that + # evaluates to true. + # + # https://github.com/encode/httpx/discussions/2399#discussioncomment-3814186 + if not files: + files = cast(HttpxRequestFiles, ForceMultipartDict()) + # TODO: report this error to httpx return self._client.build_request( # pyright: ignore[reportUnknownMemberType] headers=headers, @@ -493,7 +504,7 @@ def _build_request( # https://github.com/microsoft/pyright/issues/3526#event-6715453066 params=self.qs.stringify(cast(Mapping[str, Any], params)) if params else None, json=json_data, - files=options.files, + files=files, **kwargs, ) @@ -1891,6 +1902,11 @@ def make_request_options( return options +class ForceMultipartDict(Dict[str, None]): + def __bool__(self) -> bool: + return True + + class OtherPlatform: def __init__(self, name: str) -> None: self.name = name diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index 995680186b..c03137dbfd 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -108,11 +108,10 @@ def create( } ) files = extract_files(cast(Mapping[str, object], body), paths=[["file"]]) - if files: - # It should be noted that the actual Content-Type header that will be - # sent to the server will contain a `boundary` parameter, e.g. - # multipart/form-data; boundary=---abc-- - extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} + # It should be noted that the actual Content-Type header that will be + # sent to the server will contain a `boundary` parameter, e.g. + # multipart/form-data; boundary=---abc-- + extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} return self._post( "/audio/transcriptions", body=maybe_transform(body, transcription_create_params.TranscriptionCreateParams), @@ -205,11 +204,10 @@ async def create( } ) files = extract_files(cast(Mapping[str, object], body), paths=[["file"]]) - if files: - # It should be noted that the actual Content-Type header that will be - # sent to the server will contain a `boundary` parameter, e.g. - # multipart/form-data; boundary=---abc-- - extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} + # It should be noted that the actual Content-Type header that will be + # sent to the server will contain a `boundary` parameter, e.g. + # multipart/form-data; boundary=---abc-- + extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} return await self._post( "/audio/transcriptions", body=await async_maybe_transform(body, transcription_create_params.TranscriptionCreateParams), diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index d711ee2fbd..485e1a33df 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -93,11 +93,10 @@ def create( } ) files = extract_files(cast(Mapping[str, object], body), paths=[["file"]]) - if files: - # It should be noted that the actual Content-Type header that will be - # sent to the server will contain a `boundary` parameter, e.g. - # multipart/form-data; boundary=---abc-- - extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} + # It should be noted that the actual Content-Type header that will be + # sent to the server will contain a `boundary` parameter, e.g. + # multipart/form-data; boundary=---abc-- + extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} return self._post( "/audio/translations", body=maybe_transform(body, translation_create_params.TranslationCreateParams), @@ -175,11 +174,10 @@ async def create( } ) files = extract_files(cast(Mapping[str, object], body), paths=[["file"]]) - if files: - # It should be noted that the actual Content-Type header that will be - # sent to the server will contain a `boundary` parameter, e.g. - # multipart/form-data; boundary=---abc-- - extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} + # It should be noted that the actual Content-Type header that will be + # sent to the server will contain a `boundary` parameter, e.g. + # multipart/form-data; boundary=---abc-- + extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} return await self._post( "/audio/translations", body=await async_maybe_transform(body, translation_create_params.TranslationCreateParams), diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index 432ac30913..75c971a8bc 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -111,11 +111,10 @@ def create( } ) files = extract_files(cast(Mapping[str, object], body), paths=[["file"]]) - if files: - # It should be noted that the actual Content-Type header that will be - # sent to the server will contain a `boundary` parameter, e.g. - # multipart/form-data; boundary=---abc-- - extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} + # It should be noted that the actual Content-Type header that will be + # sent to the server will contain a `boundary` parameter, e.g. + # multipart/form-data; boundary=---abc-- + extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} return self._post( "/files", body=maybe_transform(body, file_create_params.FileCreateParams), @@ -394,11 +393,10 @@ async def create( } ) files = extract_files(cast(Mapping[str, object], body), paths=[["file"]]) - if files: - # It should be noted that the actual Content-Type header that will be - # sent to the server will contain a `boundary` parameter, e.g. - # multipart/form-data; boundary=---abc-- - extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} + # It should be noted that the actual Content-Type header that will be + # sent to the server will contain a `boundary` parameter, e.g. + # multipart/form-data; boundary=---abc-- + extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} return await self._post( "/files", body=await async_maybe_transform(body, file_create_params.FileCreateParams), diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py index 74b2a46a3f..3728392f93 100644 --- a/src/openai/resources/images.py +++ b/src/openai/resources/images.py @@ -95,11 +95,10 @@ def create_variation( } ) files = extract_files(cast(Mapping[str, object], body), paths=[["image"]]) - if files: - # It should be noted that the actual Content-Type header that will be - # sent to the server will contain a `boundary` parameter, e.g. - # multipart/form-data; boundary=---abc-- - extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} + # It should be noted that the actual Content-Type header that will be + # sent to the server will contain a `boundary` parameter, e.g. + # multipart/form-data; boundary=---abc-- + extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} return self._post( "/images/variations", body=maybe_transform(body, image_create_variation_params.ImageCreateVariationParams), @@ -179,11 +178,10 @@ def edit( } ) files = extract_files(cast(Mapping[str, object], body), paths=[["image"], ["mask"]]) - if files: - # It should be noted that the actual Content-Type header that will be - # sent to the server will contain a `boundary` parameter, e.g. - # multipart/form-data; boundary=---abc-- - extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} + # It should be noted that the actual Content-Type header that will be + # sent to the server will contain a `boundary` parameter, e.g. + # multipart/form-data; boundary=---abc-- + extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} return self._post( "/images/edits", body=maybe_transform(body, image_edit_params.ImageEditParams), @@ -343,11 +341,10 @@ async def create_variation( } ) files = extract_files(cast(Mapping[str, object], body), paths=[["image"]]) - if files: - # It should be noted that the actual Content-Type header that will be - # sent to the server will contain a `boundary` parameter, e.g. - # multipart/form-data; boundary=---abc-- - extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} + # It should be noted that the actual Content-Type header that will be + # sent to the server will contain a `boundary` parameter, e.g. + # multipart/form-data; boundary=---abc-- + extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} return await self._post( "/images/variations", body=await async_maybe_transform(body, image_create_variation_params.ImageCreateVariationParams), @@ -427,11 +424,10 @@ async def edit( } ) files = extract_files(cast(Mapping[str, object], body), paths=[["image"], ["mask"]]) - if files: - # It should be noted that the actual Content-Type header that will be - # sent to the server will contain a `boundary` parameter, e.g. - # multipart/form-data; boundary=---abc-- - extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} + # It should be noted that the actual Content-Type header that will be + # sent to the server will contain a `boundary` parameter, e.g. + # multipart/form-data; boundary=---abc-- + extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} return await self._post( "/images/edits", body=await async_maybe_transform(body, image_edit_params.ImageEditParams), From 4826fe9dace2765bd79749c3c45dbd4cc2381e34 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 2 Jul 2024 19:50:24 +0000 Subject: [PATCH 403/816] chore: minor change to tests (#1521) --- .stats.yml | 2 +- tests/api_resources/chat/test_completions.py | 8 ++++---- tests/api_resources/test_completions.py | 8 ++++---- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.stats.yml b/.stats.yml index 04682ea0a6..57f5afaffe 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 64 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-3a69e1cc9e1efda3fb82d0fb35961749f886a87594dae9d8d2aa5c60f157f5d2.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-27d8d6da893c1cdd53b491ec05153df22b1e113965f253a1d6eb8d75b628173f.yml diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index 87df11d1ee..5cb2a8c717 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -59,7 +59,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: parallel_tool_calls=True, presence_penalty=-2, response_format={"type": "json_object"}, - seed=-9223372036854776000, + seed=-9007199254740991, service_tier="auto", stop="string", stream=False, @@ -176,7 +176,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: parallel_tool_calls=True, presence_penalty=-2, response_format={"type": "json_object"}, - seed=-9223372036854776000, + seed=-9007199254740991, service_tier="auto", stop="string", stream_options={"include_usage": True}, @@ -295,7 +295,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn parallel_tool_calls=True, presence_penalty=-2, response_format={"type": "json_object"}, - seed=-9223372036854776000, + seed=-9007199254740991, service_tier="auto", stop="string", stream=False, @@ -412,7 +412,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn parallel_tool_calls=True, presence_penalty=-2, response_format={"type": "json_object"}, - seed=-9223372036854776000, + seed=-9007199254740991, service_tier="auto", stop="string", stream_options={"include_usage": True}, diff --git a/tests/api_resources/test_completions.py b/tests/api_resources/test_completions.py index 69d914200f..ad2679cabe 100644 --- a/tests/api_resources/test_completions.py +++ b/tests/api_resources/test_completions.py @@ -38,7 +38,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: max_tokens=16, n=1, presence_penalty=-2, - seed=-9223372036854776000, + seed=-9007199254740991, stop="\n", stream=False, stream_options={"include_usage": True}, @@ -98,7 +98,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: max_tokens=16, n=1, presence_penalty=-2, - seed=-9223372036854776000, + seed=-9007199254740991, stop="\n", stream_options={"include_usage": True}, suffix="test.", @@ -160,7 +160,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn max_tokens=16, n=1, presence_penalty=-2, - seed=-9223372036854776000, + seed=-9007199254740991, stop="\n", stream=False, stream_options={"include_usage": True}, @@ -220,7 +220,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn max_tokens=16, n=1, presence_penalty=-2, - seed=-9223372036854776000, + seed=-9007199254740991, stop="\n", stream_options={"include_usage": True}, suffix="test.", From 58bec2ffe5274b37fed3adad8da188f0cbc5406c Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 2 Jul 2024 19:50:51 +0000 Subject: [PATCH 404/816] release: 1.35.9 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 1ef8c632ae..84be15d4a5 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.35.8" + ".": "1.35.9" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e40cafda7..03aa28e2fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.35.9 (2024-07-02) + +Full Changelog: [v1.35.8...v1.35.9](https://github.com/openai/openai-python/compare/v1.35.8...v1.35.9) + +### Bug Fixes + +* **client:** always respect content-type multipart/form-data if provided ([#1519](https://github.com/openai/openai-python/issues/1519)) ([6da55e1](https://github.com/openai/openai-python/commit/6da55e10c4ba8c78687baedc68d5599ea120d05c)) + + +### Chores + +* minor change to tests ([#1521](https://github.com/openai/openai-python/issues/1521)) ([a679c0b](https://github.com/openai/openai-python/commit/a679c0bd1e041434440174daa7a64289746856d1)) + ## 1.35.8 (2024-07-02) Full Changelog: [v1.35.7...v1.35.8](https://github.com/openai/openai-python/compare/v1.35.7...v1.35.8) diff --git a/pyproject.toml b/pyproject.toml index ea1f76bf42..be7a95dd69 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.35.8" +version = "1.35.9" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index c612421e90..0a534db76c 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.35.8" # x-release-please-version +__version__ = "1.35.9" # x-release-please-version From 94fc49d8b198b4b9fe98bf22883ed82b060e865b Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 3 Jul 2024 17:37:28 +0000 Subject: [PATCH 405/816] chore(ci): update rye to v0.35.0 (#1523) --- .devcontainer/Dockerfile | 2 +- .github/workflows/ci.yml | 4 ++-- .github/workflows/create-releases.yml | 4 ++-- .github/workflows/publish-pypi.yml | 4 ++-- requirements-dev.lock | 1 + requirements.lock | 1 + 6 files changed, 9 insertions(+), 7 deletions(-) diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index 83bca8f716..ac9a2e7521 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -3,7 +3,7 @@ FROM mcr.microsoft.com/vscode/devcontainers/python:0-${VARIANT} USER vscode -RUN curl -sSf https://rye.astral.sh/get | RYE_VERSION="0.24.0" RYE_INSTALL_OPTION="--yes" bash +RUN curl -sSf https://rye.astral.sh/get | RYE_VERSION="0.35.0" RYE_INSTALL_OPTION="--yes" bash ENV PATH=/home/vscode/.rye/shims:$PATH RUN echo "[[ -d .venv ]] && source .venv/bin/activate" >> /home/vscode/.bashrc diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6fc5b36597..7e58412065 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,7 +21,7 @@ jobs: curl -sSf https://rye.astral.sh/get | bash echo "$HOME/.rye/shims" >> $GITHUB_PATH env: - RYE_VERSION: 0.24.0 + RYE_VERSION: '0.35.0' RYE_INSTALL_OPTION: '--yes' - name: Install dependencies @@ -42,7 +42,7 @@ jobs: curl -sSf https://rye.astral.sh/get | bash echo "$HOME/.rye/shims" >> $GITHUB_PATH env: - RYE_VERSION: 0.24.0 + RYE_VERSION: '0.35.0' RYE_INSTALL_OPTION: '--yes' - name: Bootstrap diff --git a/.github/workflows/create-releases.yml b/.github/workflows/create-releases.yml index 1ac03ede3f..2a97049033 100644 --- a/.github/workflows/create-releases.yml +++ b/.github/workflows/create-releases.yml @@ -28,8 +28,8 @@ jobs: curl -sSf https://rye.astral.sh/get | bash echo "$HOME/.rye/shims" >> $GITHUB_PATH env: - RYE_VERSION: 0.24.0 - RYE_INSTALL_OPTION: "--yes" + RYE_VERSION: '0.35.0' + RYE_INSTALL_OPTION: '--yes' - name: Publish to PyPI if: ${{ steps.release.outputs.releases_created }} diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml index aae985b27e..44027a3c4c 100644 --- a/.github/workflows/publish-pypi.yml +++ b/.github/workflows/publish-pypi.yml @@ -17,8 +17,8 @@ jobs: curl -sSf https://rye.astral.sh/get | bash echo "$HOME/.rye/shims" >> $GITHUB_PATH env: - RYE_VERSION: 0.24.0 - RYE_INSTALL_OPTION: "--yes" + RYE_VERSION: '0.35.0' + RYE_INSTALL_OPTION: '--yes' - name: Publish to PyPI run: | diff --git a/requirements-dev.lock b/requirements-dev.lock index 3e3284cebc..21a6b8d20c 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -6,6 +6,7 @@ # features: [] # all-features: true # with-sources: false +# generate-hashes: false -e file:. annotated-types==0.6.0 diff --git a/requirements.lock b/requirements.lock index 47cf8a40e9..3c3d6ae702 100644 --- a/requirements.lock +++ b/requirements.lock @@ -6,6 +6,7 @@ # features: [] # all-features: true # with-sources: false +# generate-hashes: false -e file:. annotated-types==0.6.0 From 50371bf3151ebb1a43017abfe205d4d9b2e5faac Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 3 Jul 2024 17:37:56 +0000 Subject: [PATCH 406/816] release: 1.35.10 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 84be15d4a5..cb142b301b 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.35.9" + ".": "1.35.10" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 03aa28e2fd..bd9eebd658 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.35.10 (2024-07-03) + +Full Changelog: [v1.35.9...v1.35.10](https://github.com/openai/openai-python/compare/v1.35.9...v1.35.10) + +### Chores + +* **ci:** update rye to v0.35.0 ([#1523](https://github.com/openai/openai-python/issues/1523)) ([dd118c4](https://github.com/openai/openai-python/commit/dd118c422019df00b153104b7bddf892c2ec7417)) + ## 1.35.9 (2024-07-02) Full Changelog: [v1.35.8...v1.35.9](https://github.com/openai/openai-python/compare/v1.35.8...v1.35.9) diff --git a/pyproject.toml b/pyproject.toml index be7a95dd69..348abf87a7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.35.9" +version = "1.35.10" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 0a534db76c..6765e6c941 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.35.9" # x-release-please-version +__version__ = "1.35.10" # x-release-please-version From 665f4dcb9da63f2f88f189e05a1c531830e52155 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 9 Jul 2024 15:52:07 +0000 Subject: [PATCH 407/816] chore(internal): minor request options handling changes (#1534) --- src/openai/_base_client.py | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 2f4b0c7fbd..7ab2a56169 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -956,6 +956,11 @@ def _request( stream: bool, stream_cls: type[_StreamT] | None, ) -> ResponseT | _StreamT: + # create a copy of the options we were given so that if the + # options are mutated later & we then retry, the retries are + # given the original options + input_options = model_copy(options) + cast_to = self._maybe_override_cast_to(cast_to, options) self._prepare_options(options) @@ -980,7 +985,7 @@ def _request( if retries > 0: return self._retry_request( - options, + input_options, cast_to, retries, stream=stream, @@ -995,7 +1000,7 @@ def _request( if retries > 0: return self._retry_request( - options, + input_options, cast_to, retries, stream=stream, @@ -1024,7 +1029,7 @@ def _request( if retries > 0 and self._should_retry(err.response): err.response.close() return self._retry_request( - options, + input_options, cast_to, retries, err.response.headers, @@ -1533,6 +1538,11 @@ async def _request( # execute it earlier while we are in an async context self._platform = await asyncify(get_platform)() + # create a copy of the options we were given so that if the + # options are mutated later & we then retry, the retries are + # given the original options + input_options = model_copy(options) + cast_to = self._maybe_override_cast_to(cast_to, options) await self._prepare_options(options) @@ -1555,7 +1565,7 @@ async def _request( if retries > 0: return await self._retry_request( - options, + input_options, cast_to, retries, stream=stream, @@ -1570,7 +1580,7 @@ async def _request( if retries > 0: return await self._retry_request( - options, + input_options, cast_to, retries, stream=stream, @@ -1593,7 +1603,7 @@ async def _request( if retries > 0 and self._should_retry(err.response): await err.response.aclose() return await self._retry_request( - options, + input_options, cast_to, retries, err.response.headers, From 41f682bc055de55350f025ef4e664949cbf31eb6 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 9 Jul 2024 15:52:35 +0000 Subject: [PATCH 408/816] release: 1.35.11 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index cb142b301b..f0ed4549e0 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.35.10" + ".": "1.35.11" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index bd9eebd658..52c8216f28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.35.11 (2024-07-09) + +Full Changelog: [v1.35.10...v1.35.11](https://github.com/openai/openai-python/compare/v1.35.10...v1.35.11) + +### Chores + +* **internal:** minor request options handling changes ([#1534](https://github.com/openai/openai-python/issues/1534)) ([8b0e493](https://github.com/openai/openai-python/commit/8b0e49302b3fcc32cf02393bf28354c577188904)) + ## 1.35.10 (2024-07-03) Full Changelog: [v1.35.9...v1.35.10](https://github.com/openai/openai-python/compare/v1.35.9...v1.35.10) diff --git a/pyproject.toml b/pyproject.toml index 348abf87a7..3098d4c24f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.35.10" +version = "1.35.11" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 6765e6c941..237442ec47 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.35.10" # x-release-please-version +__version__ = "1.35.11" # x-release-please-version From 6b01ba6af35c3b1fae0cbf4a012c5dcfa97ae10f Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Tue, 9 Jul 2024 19:03:49 +0100 Subject: [PATCH 409/816] fix(azure): refresh auth token during retries (#1533) --- tests/lib/test_azure.py | 88 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 86 insertions(+), 2 deletions(-) diff --git a/tests/lib/test_azure.py b/tests/lib/test_azure.py index 9360b2925a..a9d3478350 100644 --- a/tests/lib/test_azure.py +++ b/tests/lib/test_azure.py @@ -1,7 +1,9 @@ -from typing import Union -from typing_extensions import Literal +from typing import Union, cast +from typing_extensions import Literal, Protocol +import httpx import pytest +from respx import MockRouter from openai._models import FinalRequestOptions from openai.lib.azure import AzureOpenAI, AsyncAzureOpenAI @@ -22,6 +24,10 @@ ) +class MockRequestCall(Protocol): + request: httpx.Request + + @pytest.mark.parametrize("client", [sync_client, async_client]) def test_implicit_deployment_path(client: Client) -> None: req = client._build_request( @@ -64,3 +70,81 @@ def test_client_copying_override_options(client: Client) -> None: api_version="2022-05-01", ) assert copied._custom_query == {"api-version": "2022-05-01"} + + +@pytest.mark.respx() +def test_client_token_provider_refresh_sync(respx_mock: MockRouter) -> None: + respx_mock.post( + "https://example-resource.azure.openai.com/openai/deployments/gpt-4/chat/completions?api-version=2024-02-01" + ).mock( + side_effect=[ + httpx.Response(500, json={"error": "server error"}), + httpx.Response(200, json={"foo": "bar"}), + ] + ) + + counter = 0 + + def token_provider() -> str: + nonlocal counter + + counter += 1 + + if counter == 1: + return "first" + + return "second" + + client = AzureOpenAI( + api_version="2024-02-01", + azure_ad_token_provider=token_provider, + azure_endpoint="https://example-resource.azure.openai.com/", + ) + client.chat.completions.create(messages=[], model="gpt-4") + + calls = cast("list[MockRequestCall]", respx_mock.calls) + + assert len(calls) == 2 + + assert calls[0].request.headers.get("Authorization") == "Bearer first" + assert calls[1].request.headers.get("Authorization") == "Bearer second" + + +@pytest.mark.asyncio +@pytest.mark.respx() +async def test_client_token_provider_refresh_async(respx_mock: MockRouter) -> None: + respx_mock.post( + "https://example-resource.azure.openai.com/openai/deployments/gpt-4/chat/completions?api-version=2024-02-01" + ).mock( + side_effect=[ + httpx.Response(500, json={"error": "server error"}), + httpx.Response(200, json={"foo": "bar"}), + ] + ) + + counter = 0 + + def token_provider() -> str: + nonlocal counter + + counter += 1 + + if counter == 1: + return "first" + + return "second" + + client = AsyncAzureOpenAI( + api_version="2024-02-01", + azure_ad_token_provider=token_provider, + azure_endpoint="https://example-resource.azure.openai.com/", + ) + + await client.chat.completions.create(messages=[], model="gpt-4") + + calls = cast("list[MockRequestCall]", respx_mock.calls) + + assert len(calls) == 2 + + assert calls[0].request.headers.get("Authorization") == "Bearer first" + assert calls[1].request.headers.get("Authorization") == "Bearer second" From 8cccea6df6174e6eecb3674b474a1da1add94290 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Tue, 9 Jul 2024 19:13:30 +0100 Subject: [PATCH 410/816] fix(tests): fresh_env() now resets new environment values --- tests/test_module_client.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/test_module_client.py b/tests/test_module_client.py index 05b5f81111..6bab33a1d7 100644 --- a/tests/test_module_client.py +++ b/tests/test_module_client.py @@ -110,6 +110,7 @@ def fresh_env() -> Iterator[None]: _os.environ.clear() yield finally: + _os.environ.clear() _os.environ.update(old) From e0ed37c19a99462db73ada4ba40ae185442b6cbb Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 9 Jul 2024 18:13:54 +0000 Subject: [PATCH 411/816] release: 1.35.12 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 9 +++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index f0ed4549e0..7ac9c7d661 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.35.11" + ".": "1.35.12" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 52c8216f28..7e0be66b84 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 1.35.12 (2024-07-09) + +Full Changelog: [v1.35.11...v1.35.12](https://github.com/openai/openai-python/compare/v1.35.11...v1.35.12) + +### Bug Fixes + +* **azure:** refresh auth token during retries ([#1533](https://github.com/openai/openai-python/issues/1533)) ([287926e](https://github.com/openai/openai-python/commit/287926e4c0920b930af2b9d3d8b46a24e78e2979)) +* **tests:** fresh_env() now resets new environment values ([64da888](https://github.com/openai/openai-python/commit/64da888ca4d13f0b4b6d9e22ec93a897b2d6bb24)) + ## 1.35.11 (2024-07-09) Full Changelog: [v1.35.10...v1.35.11](https://github.com/openai/openai-python/compare/v1.35.10...v1.35.11) diff --git a/pyproject.toml b/pyproject.toml index 3098d4c24f..b81031b1fa 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.35.11" +version = "1.35.12" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 237442ec47..d7cdffe676 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.35.11" # x-release-please-version +__version__ = "1.35.12" # x-release-please-version From c80fe33638956852af890f0358d272620b17212f Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Wed, 10 Jul 2024 10:55:35 +0100 Subject: [PATCH 412/816] fix(threads/runs/create_and_run_stream): correct tool_resources param --- src/openai/resources/beta/threads/threads.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index a62ee8d1bb..8d3289658d 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -1062,7 +1062,7 @@ def create_and_run_stream( "stream": True, "thread": thread, "tools": tools, - "tool": tool_resources, + "tool_resources": tool_resources, "truncation_strategy": truncation_strategy, "top_p": top_p, }, @@ -2082,7 +2082,7 @@ def create_and_run_stream( "stream": True, "thread": thread, "tools": tools, - "tool": tool_resources, + "tool_resources": tool_resources, "truncation_strategy": truncation_strategy, "top_p": top_p, }, From 2df8aa3d15b42708bdf7e23da7411946c4f40da2 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 10 Jul 2024 11:38:16 +0000 Subject: [PATCH 413/816] chore(internal): add helper function (#1538) --- src/openai/_models.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/openai/_models.py b/src/openai/_models.py index 5d95bb4b2b..eb7ce3bde9 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -643,6 +643,14 @@ def validate_type(*, type_: type[_T], value: object) -> _T: return cast(_T, _validate_non_model_type(type_=type_, value=value)) +def set_pydantic_config(typ: Any, config: pydantic.ConfigDict) -> None: + """Add a pydantic config for the given type. + + Note: this is a no-op on Pydantic v1. + """ + setattr(typ, "__pydantic_config__", config) # noqa: B010 + + # our use of subclasssing here causes weirdness for type checkers, # so we just pretend that we don't subclass if TYPE_CHECKING: From ec4511a6fa4862770cf14b2b58d3493e9bacb062 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 10 Jul 2024 11:38:47 +0000 Subject: [PATCH 414/816] release: 1.35.13 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 7ac9c7d661..cbc88f07a5 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.35.12" + ".": "1.35.13" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e0be66b84..ea823dcd66 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.35.13 (2024-07-10) + +Full Changelog: [v1.35.12...v1.35.13](https://github.com/openai/openai-python/compare/v1.35.12...v1.35.13) + +### Bug Fixes + +* **threads/runs/create_and_run_stream:** correct tool_resources param ([8effd08](https://github.com/openai/openai-python/commit/8effd08be3ab1cf509bdbfd9f174f9186fdbf71f)) + + +### Chores + +* **internal:** add helper function ([#1538](https://github.com/openai/openai-python/issues/1538)) ([81655a0](https://github.com/openai/openai-python/commit/81655a012e28c0240e71cf74b77ad1f9ac630906)) + ## 1.35.12 (2024-07-09) Full Changelog: [v1.35.11...v1.35.12](https://github.com/openai/openai-python/compare/v1.35.11...v1.35.12) diff --git a/pyproject.toml b/pyproject.toml index b81031b1fa..24fee167ff 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.35.12" +version = "1.35.13" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index d7cdffe676..40d6e8e31d 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.35.12" # x-release-please-version +__version__ = "1.35.13" # x-release-please-version From f14f859370ac4545e5b46fba3cb4a1fafacfdd15 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 15 Jul 2024 10:42:17 +0100 Subject: [PATCH 415/816] chore(internal): minor formatting changes --- examples/assistant.py | 1 - src/openai/resources/beta/vector_stores/files.py | 6 ++++-- src/openai/types/audio/transcription.py | 1 - src/openai/types/audio/translation.py | 1 - src/openai/types/batch_request_counts.py | 1 - src/openai/types/beta/assistant_tool_choice_function.py | 1 - src/openai/types/completion_usage.py | 1 - src/openai/types/fine_tuning/fine_tuning_job_integration.py | 1 - src/openai/types/model_deleted.py | 1 - tests/lib/test_assistants.py | 1 + 10 files changed, 5 insertions(+), 10 deletions(-) diff --git a/examples/assistant.py b/examples/assistant.py index 0631494ecc..f6924a0c7d 100644 --- a/examples/assistant.py +++ b/examples/assistant.py @@ -1,4 +1,3 @@ - import openai # gets API Key from environment variable OPENAI_API_KEY diff --git a/src/openai/resources/beta/vector_stores/files.py b/src/openai/resources/beta/vector_stores/files.py index bc1655027c..35ca331cc0 100644 --- a/src/openai/resources/beta/vector_stores/files.py +++ b/src/openai/resources/beta/vector_stores/files.py @@ -611,7 +611,9 @@ async def upload( polling helper method to wait for processing to complete). """ file_obj = await self._client.files.create(file=file, purpose="assistants") - return await self.create(vector_store_id=vector_store_id, file_id=file_obj.id, chunking_strategy=chunking_strategy) + return await self.create( + vector_store_id=vector_store_id, file_id=file_obj.id, chunking_strategy=chunking_strategy + ) async def upload_and_poll( self, @@ -627,7 +629,7 @@ async def upload_and_poll( vector_store_id=vector_store_id, file_id=file_obj.id, poll_interval_ms=poll_interval_ms, - chunking_strategy=chunking_strategy + chunking_strategy=chunking_strategy, ) diff --git a/src/openai/types/audio/transcription.py b/src/openai/types/audio/transcription.py index 0b6ab39e78..edb5f227fc 100644 --- a/src/openai/types/audio/transcription.py +++ b/src/openai/types/audio/transcription.py @@ -1,7 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from ..._models import BaseModel __all__ = ["Transcription"] diff --git a/src/openai/types/audio/translation.py b/src/openai/types/audio/translation.py index 3d9ede2939..7c0e905189 100644 --- a/src/openai/types/audio/translation.py +++ b/src/openai/types/audio/translation.py @@ -1,7 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from ..._models import BaseModel __all__ = ["Translation"] diff --git a/src/openai/types/batch_request_counts.py b/src/openai/types/batch_request_counts.py index ef6c84a0a1..7e1d49fb88 100644 --- a/src/openai/types/batch_request_counts.py +++ b/src/openai/types/batch_request_counts.py @@ -1,7 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from .._models import BaseModel __all__ = ["BatchRequestCounts"] diff --git a/src/openai/types/beta/assistant_tool_choice_function.py b/src/openai/types/beta/assistant_tool_choice_function.py index d0d4255357..0c896d8087 100644 --- a/src/openai/types/beta/assistant_tool_choice_function.py +++ b/src/openai/types/beta/assistant_tool_choice_function.py @@ -1,7 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from ..._models import BaseModel __all__ = ["AssistantToolChoiceFunction"] diff --git a/src/openai/types/completion_usage.py b/src/openai/types/completion_usage.py index 0d57b96595..ac09afd479 100644 --- a/src/openai/types/completion_usage.py +++ b/src/openai/types/completion_usage.py @@ -1,7 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from .._models import BaseModel __all__ = ["CompletionUsage"] diff --git a/src/openai/types/fine_tuning/fine_tuning_job_integration.py b/src/openai/types/fine_tuning/fine_tuning_job_integration.py index 8076313cae..9a66aa4f17 100644 --- a/src/openai/types/fine_tuning/fine_tuning_job_integration.py +++ b/src/openai/types/fine_tuning/fine_tuning_job_integration.py @@ -1,7 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from .fine_tuning_job_wandb_integration_object import FineTuningJobWandbIntegrationObject FineTuningJobIntegration = FineTuningJobWandbIntegrationObject diff --git a/src/openai/types/model_deleted.py b/src/openai/types/model_deleted.py index d9a48bb1b5..7f81e1b380 100644 --- a/src/openai/types/model_deleted.py +++ b/src/openai/types/model_deleted.py @@ -1,7 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from .._models import BaseModel __all__ = ["ModelDeleted"] diff --git a/tests/lib/test_assistants.py b/tests/lib/test_assistants.py index 487b9938c7..38a47d4d12 100644 --- a/tests/lib/test_assistants.py +++ b/tests/lib/test_assistants.py @@ -48,6 +48,7 @@ def test_create_and_run_poll_method_definition_in_sync(sync: bool, client: OpenA exclude_params={"stream"}, ) + @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) def test_create_and_run_stream_method_definition_in_sync(sync: bool, client: OpenAI, async_client: AsyncOpenAI) -> None: checking_client: OpenAI | AsyncOpenAI = client if sync else async_client From 83ebf66f16b1664977e01fec0885f29c3588ecc4 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 15 Jul 2024 09:57:42 +0100 Subject: [PATCH 416/816] chore(internal): minor options / compat functions updates (#1549) --- src/openai/_base_client.py | 12 ++++++------ src/openai/_compat.py | 6 +++--- src/openai/lib/azure.py | 13 +++++++++---- 3 files changed, 18 insertions(+), 13 deletions(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 7ab2a56169..4b93ab298c 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -880,9 +880,9 @@ def __exit__( def _prepare_options( self, options: FinalRequestOptions, # noqa: ARG002 - ) -> None: + ) -> FinalRequestOptions: """Hook for mutating the given options""" - return None + return options def _prepare_request( self, @@ -962,7 +962,7 @@ def _request( input_options = model_copy(options) cast_to = self._maybe_override_cast_to(cast_to, options) - self._prepare_options(options) + options = self._prepare_options(options) retries = self._remaining_retries(remaining_retries, options) request = self._build_request(options) @@ -1457,9 +1457,9 @@ async def __aexit__( async def _prepare_options( self, options: FinalRequestOptions, # noqa: ARG002 - ) -> None: + ) -> FinalRequestOptions: """Hook for mutating the given options""" - return None + return options async def _prepare_request( self, @@ -1544,7 +1544,7 @@ async def _request( input_options = model_copy(options) cast_to = self._maybe_override_cast_to(cast_to, options) - await self._prepare_options(options) + options = await self._prepare_options(options) retries = self._remaining_retries(remaining_retries, options) request = self._build_request(options) diff --git a/src/openai/_compat.py b/src/openai/_compat.py index 74c7639b4c..c919b5adb3 100644 --- a/src/openai/_compat.py +++ b/src/openai/_compat.py @@ -118,10 +118,10 @@ def get_model_fields(model: type[pydantic.BaseModel]) -> dict[str, FieldInfo]: return model.__fields__ # type: ignore -def model_copy(model: _ModelT) -> _ModelT: +def model_copy(model: _ModelT, *, deep: bool = False) -> _ModelT: if PYDANTIC_V2: - return model.model_copy() - return model.copy() # type: ignore + return model.model_copy(deep=deep) + return model.copy(deep=deep) # type: ignore def model_json(model: pydantic.BaseModel, *, indent: int | None = None) -> str: diff --git a/src/openai/lib/azure.py b/src/openai/lib/azure.py index cbe57b7b98..433486fded 100644 --- a/src/openai/lib/azure.py +++ b/src/openai/lib/azure.py @@ -10,6 +10,7 @@ from .._types import NOT_GIVEN, Omit, Timeout, NotGiven from .._utils import is_given, is_mapping from .._client import OpenAI, AsyncOpenAI +from .._compat import model_copy from .._models import FinalRequestOptions from .._streaming import Stream, AsyncStream from .._exceptions import OpenAIError @@ -281,8 +282,10 @@ def _get_azure_ad_token(self) -> str | None: return None @override - def _prepare_options(self, options: FinalRequestOptions) -> None: + def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions: headers: dict[str, str | Omit] = {**options.headers} if is_given(options.headers) else {} + + options = model_copy(options) options.headers = headers azure_ad_token = self._get_azure_ad_token() @@ -296,7 +299,7 @@ def _prepare_options(self, options: FinalRequestOptions) -> None: # should never be hit raise ValueError("Unable to handle auth") - return super()._prepare_options(options) + return options class AsyncAzureOpenAI(BaseAzureClient[httpx.AsyncClient, AsyncStream[Any]], AsyncOpenAI): @@ -524,8 +527,10 @@ async def _get_azure_ad_token(self) -> str | None: return None @override - async def _prepare_options(self, options: FinalRequestOptions) -> None: + async def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions: headers: dict[str, str | Omit] = {**options.headers} if is_given(options.headers) else {} + + options = model_copy(options) options.headers = headers azure_ad_token = await self._get_azure_ad_token() @@ -539,4 +544,4 @@ async def _prepare_options(self, options: FinalRequestOptions) -> None: # should never be hit raise ValueError("Unable to handle auth") - return await super()._prepare_options(options) + return options From 2e8ea52b08a74a06d227d35586c6250814958ecb Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 15 Jul 2024 18:20:46 +0000 Subject: [PATCH 417/816] chore(docs): minor update to formatting of API link in README (#1550) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 15853f27c6..38d10899ae 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ It is generated from our [OpenAPI specification](https://github.com/openai/opena ## Documentation -The REST API documentation can be found [on platform.openai.com](https://platform.openai.com/docs). The full API of this library can be found in [api.md](api.md). +The REST API documentation can be found on [platform.openai.com](https://platform.openai.com/docs). The full API of this library can be found in [api.md](api.md). ## Installation From 435a5805ccbd5939a68f7f359ab72e937ef86e59 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 15 Jul 2024 18:21:14 +0000 Subject: [PATCH 418/816] release: 1.35.14 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 10 ++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 13 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index cbc88f07a5..968573fdbe 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.35.13" + ".": "1.35.14" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index ea823dcd66..134e36c1ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## 1.35.14 (2024-07-15) + +Full Changelog: [v1.35.13...v1.35.14](https://github.com/openai/openai-python/compare/v1.35.13...v1.35.14) + +### Chores + +* **docs:** minor update to formatting of API link in README ([#1550](https://github.com/openai/openai-python/issues/1550)) ([a6e59c6](https://github.com/openai/openai-python/commit/a6e59c6bbff9e1132aa323c0ecb3be7f0692ae42)) +* **internal:** minor formatting changes ([ee1c62e](https://github.com/openai/openai-python/commit/ee1c62ede01872e76156d886af4aab5f8eb1cc64)) +* **internal:** minor options / compat functions updates ([#1549](https://github.com/openai/openai-python/issues/1549)) ([a0701b5](https://github.com/openai/openai-python/commit/a0701b5dbeda4ac2d8a4b093aee4bdad9d674ee2)) + ## 1.35.13 (2024-07-10) Full Changelog: [v1.35.12...v1.35.13](https://github.com/openai/openai-python/compare/v1.35.12...v1.35.13) diff --git a/pyproject.toml b/pyproject.toml index 24fee167ff..c958c63478 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.35.13" +version = "1.35.14" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 40d6e8e31d..34da91ad4b 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.35.13" # x-release-please-version +__version__ = "1.35.14" # x-release-please-version From 8ce46febbba6d35b4b7bf2568e2c2b819d9edf99 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 16 Jul 2024 22:33:58 +0000 Subject: [PATCH 419/816] chore(internal): update formatting (#1553) --- src/openai/types/audio/transcription.py | 1 + src/openai/types/audio/translation.py | 1 + src/openai/types/batch_request_counts.py | 1 + src/openai/types/beta/assistant_tool_choice_function.py | 1 + src/openai/types/completion_usage.py | 1 + src/openai/types/fine_tuning/fine_tuning_job_integration.py | 1 + src/openai/types/model_deleted.py | 1 + 7 files changed, 7 insertions(+) diff --git a/src/openai/types/audio/transcription.py b/src/openai/types/audio/transcription.py index edb5f227fc..0b6ab39e78 100644 --- a/src/openai/types/audio/transcription.py +++ b/src/openai/types/audio/transcription.py @@ -1,6 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + from ..._models import BaseModel __all__ = ["Transcription"] diff --git a/src/openai/types/audio/translation.py b/src/openai/types/audio/translation.py index 7c0e905189..3d9ede2939 100644 --- a/src/openai/types/audio/translation.py +++ b/src/openai/types/audio/translation.py @@ -1,6 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + from ..._models import BaseModel __all__ = ["Translation"] diff --git a/src/openai/types/batch_request_counts.py b/src/openai/types/batch_request_counts.py index 7e1d49fb88..ef6c84a0a1 100644 --- a/src/openai/types/batch_request_counts.py +++ b/src/openai/types/batch_request_counts.py @@ -1,6 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + from .._models import BaseModel __all__ = ["BatchRequestCounts"] diff --git a/src/openai/types/beta/assistant_tool_choice_function.py b/src/openai/types/beta/assistant_tool_choice_function.py index 0c896d8087..d0d4255357 100644 --- a/src/openai/types/beta/assistant_tool_choice_function.py +++ b/src/openai/types/beta/assistant_tool_choice_function.py @@ -1,6 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + from ..._models import BaseModel __all__ = ["AssistantToolChoiceFunction"] diff --git a/src/openai/types/completion_usage.py b/src/openai/types/completion_usage.py index ac09afd479..0d57b96595 100644 --- a/src/openai/types/completion_usage.py +++ b/src/openai/types/completion_usage.py @@ -1,6 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + from .._models import BaseModel __all__ = ["CompletionUsage"] diff --git a/src/openai/types/fine_tuning/fine_tuning_job_integration.py b/src/openai/types/fine_tuning/fine_tuning_job_integration.py index 9a66aa4f17..8076313cae 100644 --- a/src/openai/types/fine_tuning/fine_tuning_job_integration.py +++ b/src/openai/types/fine_tuning/fine_tuning_job_integration.py @@ -1,6 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + from .fine_tuning_job_wandb_integration_object import FineTuningJobWandbIntegrationObject FineTuningJobIntegration = FineTuningJobWandbIntegrationObject diff --git a/src/openai/types/model_deleted.py b/src/openai/types/model_deleted.py index 7f81e1b380..d9a48bb1b5 100644 --- a/src/openai/types/model_deleted.py +++ b/src/openai/types/model_deleted.py @@ -1,6 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + from .._models import BaseModel __all__ = ["ModelDeleted"] From f8f01a6100997d55bf48599d3d766b7249fb65b5 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 18 Jul 2024 16:53:49 +0000 Subject: [PATCH 420/816] chore(docs): document how to do per-request http client customization (#1560) --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 38d10899ae..653fb9a2c3 100644 --- a/README.md +++ b/README.md @@ -575,6 +575,12 @@ client = OpenAI( ) ``` +You can also customize the client on a per-request basis by using `with_options()`: + +```python +client.with_options(http_client=DefaultHttpxClient(...)) +``` + ### Managing HTTP resources By default the library closes underlying HTTP connections whenever the client is [garbage collected](https://docs.python.org/3/reference/datamodel.html#object.__del__). You can manually close the client using the `.close()` method if desired, or with a context manager that closes when exiting. From 0de7419c962805bbe9db18d99524b66673f7f8e9 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 18 Jul 2024 16:54:21 +0000 Subject: [PATCH 421/816] release: 1.35.15 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 9 +++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 968573fdbe..1441c27096 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.35.14" + ".": "1.35.15" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 134e36c1ba..580daadf44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 1.35.15 (2024-07-18) + +Full Changelog: [v1.35.14...v1.35.15](https://github.com/openai/openai-python/compare/v1.35.14...v1.35.15) + +### Chores + +* **docs:** document how to do per-request http client customization ([#1560](https://github.com/openai/openai-python/issues/1560)) ([24c0768](https://github.com/openai/openai-python/commit/24c076873c5cb2abe0d3e285b99aa110451b0f19)) +* **internal:** update formatting ([#1553](https://github.com/openai/openai-python/issues/1553)) ([e1389bc](https://github.com/openai/openai-python/commit/e1389bcc26f3aac63fc6bc9bb151c9a330d95b4e)) + ## 1.35.14 (2024-07-15) Full Changelog: [v1.35.13...v1.35.14](https://github.com/openai/openai-python/compare/v1.35.13...v1.35.14) diff --git a/pyproject.toml b/pyproject.toml index c958c63478..a43bfd89d7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.35.14" +version = "1.35.15" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 34da91ad4b..eed4227390 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.35.14" # x-release-please-version +__version__ = "1.35.15" # x-release-please-version From 38fe1a63795946079649b1b85e7335ca94f7a6c3 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 19 Jul 2024 14:54:42 +0000 Subject: [PATCH 422/816] feat(api): add new gpt-4o-mini models (#1561) --- .stats.yml | 2 +- src/openai/resources/beta/assistants.py | 4 ++++ src/openai/resources/beta/threads/runs/runs.py | 16 ++++++++++++++++ src/openai/resources/beta/threads/threads.py | 16 ++++++++++++++++ src/openai/types/beta/assistant_create_params.py | 2 ++ .../types/beta/thread_create_and_run_params.py | 2 ++ .../types/beta/threads/run_create_params.py | 2 ++ src/openai/types/chat_model.py | 2 ++ 8 files changed, 45 insertions(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index 57f5afaffe..27e2ce5ede 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 64 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-27d8d6da893c1cdd53b491ec05153df22b1e113965f253a1d6eb8d75b628173f.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-518ca6c60061d3e8bc0971facf40d752f2aea62e3522cc168ad29a1f29cab3dd.yml diff --git a/src/openai/resources/beta/assistants.py b/src/openai/resources/beta/assistants.py index 5912aff77a..066db66913 100644 --- a/src/openai/resources/beta/assistants.py +++ b/src/openai/resources/beta/assistants.py @@ -51,6 +51,8 @@ def create( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -440,6 +442,8 @@ async def create( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 43069dd1ae..1759120bfe 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -87,6 +87,8 @@ def create( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -240,6 +242,8 @@ def create( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -392,6 +396,8 @@ def create( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -543,6 +549,8 @@ def create( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -1661,6 +1669,8 @@ async def create( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -1814,6 +1824,8 @@ async def create( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -1966,6 +1978,8 @@ async def create( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -2117,6 +2131,8 @@ async def create( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 8d3289658d..3720ab9a25 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -269,6 +269,8 @@ def create_and_run( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -421,6 +423,8 @@ def create_and_run( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -572,6 +576,8 @@ def create_and_run( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -722,6 +728,8 @@ def create_and_run( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -1285,6 +1293,8 @@ async def create_and_run( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -1437,6 +1447,8 @@ async def create_and_run( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -1588,6 +1600,8 @@ async def create_and_run( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -1738,6 +1752,8 @@ async def create_and_run( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", diff --git a/src/openai/types/beta/assistant_create_params.py b/src/openai/types/beta/assistant_create_params.py index c9b0317831..754752ae65 100644 --- a/src/openai/types/beta/assistant_create_params.py +++ b/src/openai/types/beta/assistant_create_params.py @@ -28,6 +28,8 @@ class AssistantCreateParams(TypedDict, total=False): Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index dbbff415ec..9421a894d9 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -82,6 +82,8 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index 89da241965..81cd85188b 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -79,6 +79,8 @@ class RunCreateParamsBase(TypedDict, total=False): Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", diff --git a/src/openai/types/chat_model.py b/src/openai/types/chat_model.py index 0d2937ea32..87b2acb90a 100644 --- a/src/openai/types/chat_model.py +++ b/src/openai/types/chat_model.py @@ -7,6 +7,8 @@ ChatModel = Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", From 4c6a5ed71775e82a0bbff28bea3d401ec066238e Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 19 Jul 2024 14:55:14 +0000 Subject: [PATCH 423/816] release: 1.36.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 1441c27096..f29e96b89e 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.35.15" + ".": "1.36.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 580daadf44..92703a485f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.36.0 (2024-07-19) + +Full Changelog: [v1.35.15...v1.36.0](https://github.com/openai/openai-python/compare/v1.35.15...v1.36.0) + +### Features + +* **api:** add new gpt-4o-mini models ([#1561](https://github.com/openai/openai-python/issues/1561)) ([5672ad4](https://github.com/openai/openai-python/commit/5672ad40aaa3498f6143baa48fc22bb1a3475bea)) + ## 1.35.15 (2024-07-18) Full Changelog: [v1.35.14...v1.35.15](https://github.com/openai/openai-python/compare/v1.35.14...v1.35.15) diff --git a/pyproject.toml b/pyproject.toml index a43bfd89d7..0ec0fe5ce3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.35.15" +version = "1.36.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index eed4227390..f3975de68c 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.35.15" # x-release-please-version +__version__ = "1.36.0" # x-release-please-version From 1a9124bf89fce69fc3c51a4bbf2f4fedb1749823 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Fri, 19 Jul 2024 15:39:29 +0100 Subject: [PATCH 424/816] fix(types): add gpt-4o-mini to more assistants methods --- src/openai/resources/beta/threads/threads.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 3720ab9a25..ff7fa70cf8 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -814,6 +814,8 @@ def create_and_run_poll( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -896,6 +898,8 @@ def create_and_run_stream( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -951,6 +955,8 @@ def create_and_run_stream( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -1006,6 +1012,8 @@ def create_and_run_stream( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -1838,6 +1846,8 @@ async def create_and_run_poll( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -1922,6 +1932,8 @@ def create_and_run_stream( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -1977,6 +1989,8 @@ def create_and_run_stream( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -2032,6 +2046,8 @@ def create_and_run_stream( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", From af8f606b3eef1af99f98929847f1b5baf19171ae Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Sat, 20 Jul 2024 05:04:03 +0000 Subject: [PATCH 425/816] release: 1.36.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index f29e96b89e..46ea083269 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.36.0" + ".": "1.36.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 92703a485f..c7cac5a9a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.36.1 (2024-07-20) + +Full Changelog: [v1.36.0...v1.36.1](https://github.com/openai/openai-python/compare/v1.36.0...v1.36.1) + +### Bug Fixes + +* **types:** add gpt-4o-mini to more assistants methods ([39a8a37](https://github.com/openai/openai-python/commit/39a8a372eb3f2d75fd4310d42294d05175a59fd8)) + ## 1.36.0 (2024-07-19) Full Changelog: [v1.35.15...v1.36.0](https://github.com/openai/openai-python/compare/v1.35.15...v1.36.0) diff --git a/pyproject.toml b/pyproject.toml index 0ec0fe5ce3..03a4a77f56 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.36.0" +version = "1.36.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index f3975de68c..6021f184f8 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.36.0" # x-release-please-version +__version__ = "1.36.1" # x-release-please-version From c814354fd769aaa3f387d3d1cdcccca3b90b7a2c Mon Sep 17 00:00:00 2001 From: Aurish Hammad Hafeez Date: Mon, 22 Jul 2024 15:30:24 +0500 Subject: [PATCH 426/816] fix(cli/audio): handle non-json response format (#1557) * Fix handling of --response-format in audio transcriptions create command * handle the string case in audio directly --------- Co-authored-by: Robert Craigie --- src/openai/cli/_api/audio.py | 52 +++++++++++++++++++++++------------- 1 file changed, 33 insertions(+), 19 deletions(-) diff --git a/src/openai/cli/_api/audio.py b/src/openai/cli/_api/audio.py index 90d21b9932..269c67df28 100644 --- a/src/openai/cli/_api/audio.py +++ b/src/openai/cli/_api/audio.py @@ -1,5 +1,6 @@ from __future__ import annotations +import sys from typing import TYPE_CHECKING, Any, Optional, cast from argparse import ArgumentParser @@ -7,6 +8,7 @@ from ..._types import NOT_GIVEN from .._models import BaseModel from .._progress import BufferReader +from ...types.audio import Transcription if TYPE_CHECKING: from argparse import _SubParsersAction @@ -65,30 +67,42 @@ def transcribe(args: CLITranscribeArgs) -> None: with open(args.file, "rb") as file_reader: buffer_reader = BufferReader(file_reader.read(), desc="Upload progress") - model = get_client().audio.transcriptions.create( - file=(args.file, buffer_reader), - model=args.model, - language=args.language or NOT_GIVEN, - temperature=args.temperature or NOT_GIVEN, - prompt=args.prompt or NOT_GIVEN, - # casts required because the API is typed for enums - # but we don't want to validate that here for forwards-compat - response_format=cast(Any, args.response_format), + model = cast( + "Transcription | str", + get_client().audio.transcriptions.create( + file=(args.file, buffer_reader), + model=args.model, + language=args.language or NOT_GIVEN, + temperature=args.temperature or NOT_GIVEN, + prompt=args.prompt or NOT_GIVEN, + # casts required because the API is typed for enums + # but we don't want to validate that here for forwards-compat + response_format=cast(Any, args.response_format), + ), ) - print_model(model) + if isinstance(model, str): + sys.stdout.write(model + "\n") + else: + print_model(model) @staticmethod def translate(args: CLITranslationArgs) -> None: with open(args.file, "rb") as file_reader: buffer_reader = BufferReader(file_reader.read(), desc="Upload progress") - model = get_client().audio.translations.create( - file=(args.file, buffer_reader), - model=args.model, - temperature=args.temperature or NOT_GIVEN, - prompt=args.prompt or NOT_GIVEN, - # casts required because the API is typed for enums - # but we don't want to validate that here for forwards-compat - response_format=cast(Any, args.response_format), + model = cast( + "Transcription | str", + get_client().audio.translations.create( + file=(args.file, buffer_reader), + model=args.model, + temperature=args.temperature or NOT_GIVEN, + prompt=args.prompt or NOT_GIVEN, + # casts required because the API is typed for enums + # but we don't want to validate that here for forwards-compat + response_format=cast(Any, args.response_format), + ), ) - print_model(model) + if isinstance(model, str): + sys.stdout.write(model + "\n") + else: + print_model(model) From 24ab406b410633d9df46cc5b0239e66f2e8f69ba Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 22 Jul 2024 11:10:52 +0000 Subject: [PATCH 427/816] feat(api): add uploads endpoints (#1568) --- .stats.yml | 4 +- api.md | 26 + src/openai/_client.py | 8 + src/openai/resources/__init__.py | 14 + src/openai/resources/chat/completions.py | 6 + src/openai/resources/uploads/__init__.py | 33 ++ src/openai/resources/uploads/parts.py | 188 +++++++ src/openai/resources/uploads/uploads.py | 473 ++++++++++++++++++ src/openai/types/__init__.py | 3 + .../types/chat/completion_create_params.py | 1 + src/openai/types/upload.py | 42 ++ src/openai/types/upload_complete_params.py | 19 + src/openai/types/upload_create_params.py | 29 ++ src/openai/types/uploads/__init__.py | 6 + .../types/uploads/part_create_params.py | 14 + src/openai/types/uploads/upload_part.py | 21 + tests/api_resources/test_uploads.py | 280 +++++++++++ tests/api_resources/uploads/__init__.py | 1 + tests/api_resources/uploads/test_parts.py | 106 ++++ 19 files changed, 1272 insertions(+), 2 deletions(-) create mode 100644 src/openai/resources/uploads/__init__.py create mode 100644 src/openai/resources/uploads/parts.py create mode 100644 src/openai/resources/uploads/uploads.py create mode 100644 src/openai/types/upload.py create mode 100644 src/openai/types/upload_complete_params.py create mode 100644 src/openai/types/upload_create_params.py create mode 100644 src/openai/types/uploads/__init__.py create mode 100644 src/openai/types/uploads/part_create_params.py create mode 100644 src/openai/types/uploads/upload_part.py create mode 100644 tests/api_resources/test_uploads.py create mode 100644 tests/api_resources/uploads/__init__.py create mode 100644 tests/api_resources/uploads/test_parts.py diff --git a/.stats.yml b/.stats.yml index 27e2ce5ede..4e4cb5509c 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ -configured_endpoints: 64 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-518ca6c60061d3e8bc0971facf40d752f2aea62e3522cc168ad29a1f29cab3dd.yml +configured_endpoints: 68 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-77cfff37114bc9f141c7e6107eb5f1b38d8cc99bc3d4ce03a066db2b6b649c69.yml diff --git a/api.md b/api.md index de69f11dca..82a5360edd 100644 --- a/api.md +++ b/api.md @@ -415,3 +415,29 @@ Methods: - client.batches.retrieve(batch_id) -> Batch - client.batches.list(\*\*params) -> SyncCursorPage[Batch] - client.batches.cancel(batch_id) -> Batch + +# Uploads + +Types: + +```python +from openai.types import Upload +``` + +Methods: + +- client.uploads.create(\*\*params) -> Upload +- client.uploads.cancel(upload_id) -> Upload +- client.uploads.complete(upload_id, \*\*params) -> Upload + +## Parts + +Types: + +```python +from openai.types.uploads import UploadPart +``` + +Methods: + +- client.uploads.parts.create(upload_id, \*\*params) -> UploadPart diff --git a/src/openai/_client.py b/src/openai/_client.py index 8f3060c6f6..8b404e234d 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -58,6 +58,7 @@ class OpenAI(SyncAPIClient): fine_tuning: resources.FineTuning beta: resources.Beta batches: resources.Batches + uploads: resources.Uploads with_raw_response: OpenAIWithRawResponse with_streaming_response: OpenAIWithStreamedResponse @@ -143,6 +144,7 @@ def __init__( self.fine_tuning = resources.FineTuning(self) self.beta = resources.Beta(self) self.batches = resources.Batches(self) + self.uploads = resources.Uploads(self) self.with_raw_response = OpenAIWithRawResponse(self) self.with_streaming_response = OpenAIWithStreamedResponse(self) @@ -270,6 +272,7 @@ class AsyncOpenAI(AsyncAPIClient): fine_tuning: resources.AsyncFineTuning beta: resources.AsyncBeta batches: resources.AsyncBatches + uploads: resources.AsyncUploads with_raw_response: AsyncOpenAIWithRawResponse with_streaming_response: AsyncOpenAIWithStreamedResponse @@ -355,6 +358,7 @@ def __init__( self.fine_tuning = resources.AsyncFineTuning(self) self.beta = resources.AsyncBeta(self) self.batches = resources.AsyncBatches(self) + self.uploads = resources.AsyncUploads(self) self.with_raw_response = AsyncOpenAIWithRawResponse(self) self.with_streaming_response = AsyncOpenAIWithStreamedResponse(self) @@ -483,6 +487,7 @@ def __init__(self, client: OpenAI) -> None: self.fine_tuning = resources.FineTuningWithRawResponse(client.fine_tuning) self.beta = resources.BetaWithRawResponse(client.beta) self.batches = resources.BatchesWithRawResponse(client.batches) + self.uploads = resources.UploadsWithRawResponse(client.uploads) class AsyncOpenAIWithRawResponse: @@ -498,6 +503,7 @@ def __init__(self, client: AsyncOpenAI) -> None: self.fine_tuning = resources.AsyncFineTuningWithRawResponse(client.fine_tuning) self.beta = resources.AsyncBetaWithRawResponse(client.beta) self.batches = resources.AsyncBatchesWithRawResponse(client.batches) + self.uploads = resources.AsyncUploadsWithRawResponse(client.uploads) class OpenAIWithStreamedResponse: @@ -513,6 +519,7 @@ def __init__(self, client: OpenAI) -> None: self.fine_tuning = resources.FineTuningWithStreamingResponse(client.fine_tuning) self.beta = resources.BetaWithStreamingResponse(client.beta) self.batches = resources.BatchesWithStreamingResponse(client.batches) + self.uploads = resources.UploadsWithStreamingResponse(client.uploads) class AsyncOpenAIWithStreamedResponse: @@ -528,6 +535,7 @@ def __init__(self, client: AsyncOpenAI) -> None: self.fine_tuning = resources.AsyncFineTuningWithStreamingResponse(client.fine_tuning) self.beta = resources.AsyncBetaWithStreamingResponse(client.beta) self.batches = resources.AsyncBatchesWithStreamingResponse(client.batches) + self.uploads = resources.AsyncUploadsWithStreamingResponse(client.uploads) Client = OpenAI diff --git a/src/openai/resources/__init__.py b/src/openai/resources/__init__.py index ecae4243fc..e2cc1c4b0c 100644 --- a/src/openai/resources/__init__.py +++ b/src/openai/resources/__init__.py @@ -56,6 +56,14 @@ BatchesWithStreamingResponse, AsyncBatchesWithStreamingResponse, ) +from .uploads import ( + Uploads, + AsyncUploads, + UploadsWithRawResponse, + AsyncUploadsWithRawResponse, + UploadsWithStreamingResponse, + AsyncUploadsWithStreamingResponse, +) from .embeddings import ( Embeddings, AsyncEmbeddings, @@ -156,4 +164,10 @@ "AsyncBatchesWithRawResponse", "BatchesWithStreamingResponse", "AsyncBatchesWithStreamingResponse", + "Uploads", + "AsyncUploads", + "UploadsWithRawResponse", + "AsyncUploadsWithRawResponse", + "UploadsWithStreamingResponse", + "AsyncUploadsWithStreamingResponse", ] diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index d73ece2109..88892d1d64 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -171,6 +171,7 @@ def create( exhausted. - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. + - When not set, the default behavior is 'auto'. When this parameter is set, the response body will include the `service_tier` utilized. @@ -366,6 +367,7 @@ def create( exhausted. - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. + - When not set, the default behavior is 'auto'. When this parameter is set, the response body will include the `service_tier` utilized. @@ -554,6 +556,7 @@ def create( exhausted. - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. + - When not set, the default behavior is 'auto'. When this parameter is set, the response body will include the `service_tier` utilized. @@ -817,6 +820,7 @@ async def create( exhausted. - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. + - When not set, the default behavior is 'auto'. When this parameter is set, the response body will include the `service_tier` utilized. @@ -1012,6 +1016,7 @@ async def create( exhausted. - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. + - When not set, the default behavior is 'auto'. When this parameter is set, the response body will include the `service_tier` utilized. @@ -1200,6 +1205,7 @@ async def create( exhausted. - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. + - When not set, the default behavior is 'auto'. When this parameter is set, the response body will include the `service_tier` utilized. diff --git a/src/openai/resources/uploads/__init__.py b/src/openai/resources/uploads/__init__.py new file mode 100644 index 0000000000..12d1056f9e --- /dev/null +++ b/src/openai/resources/uploads/__init__.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .parts import ( + Parts, + AsyncParts, + PartsWithRawResponse, + AsyncPartsWithRawResponse, + PartsWithStreamingResponse, + AsyncPartsWithStreamingResponse, +) +from .uploads import ( + Uploads, + AsyncUploads, + UploadsWithRawResponse, + AsyncUploadsWithRawResponse, + UploadsWithStreamingResponse, + AsyncUploadsWithStreamingResponse, +) + +__all__ = [ + "Parts", + "AsyncParts", + "PartsWithRawResponse", + "AsyncPartsWithRawResponse", + "PartsWithStreamingResponse", + "AsyncPartsWithStreamingResponse", + "Uploads", + "AsyncUploads", + "UploadsWithRawResponse", + "AsyncUploadsWithRawResponse", + "UploadsWithStreamingResponse", + "AsyncUploadsWithStreamingResponse", +] diff --git a/src/openai/resources/uploads/parts.py b/src/openai/resources/uploads/parts.py new file mode 100644 index 0000000000..3ec2592b1e --- /dev/null +++ b/src/openai/resources/uploads/parts.py @@ -0,0 +1,188 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Mapping, cast + +import httpx + +from ... import _legacy_response +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes +from ..._utils import ( + extract_files, + maybe_transform, + deepcopy_minimal, + async_maybe_transform, +) +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ..._base_client import make_request_options +from ...types.uploads import part_create_params +from ...types.uploads.upload_part import UploadPart + +__all__ = ["Parts", "AsyncParts"] + + +class Parts(SyncAPIResource): + @cached_property + def with_raw_response(self) -> PartsWithRawResponse: + return PartsWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> PartsWithStreamingResponse: + return PartsWithStreamingResponse(self) + + def create( + self, + upload_id: str, + *, + data: FileTypes, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> UploadPart: + """ + Adds a + [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an + [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object. + A Part represents a chunk of bytes from the file you are trying to upload. + + Each Part can be at most 64 MB, and you can add Parts until you hit the Upload + maximum of 8 GB. + + It is possible to add multiple Parts in parallel. You can decide the intended + order of the Parts when you + [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete). + + Args: + data: The chunk of bytes for this Part. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not upload_id: + raise ValueError(f"Expected a non-empty value for `upload_id` but received {upload_id!r}") + body = deepcopy_minimal({"data": data}) + files = extract_files(cast(Mapping[str, object], body), paths=[["data"]]) + # It should be noted that the actual Content-Type header that will be + # sent to the server will contain a `boundary` parameter, e.g. + # multipart/form-data; boundary=---abc-- + extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} + return self._post( + f"/uploads/{upload_id}/parts", + body=maybe_transform(body, part_create_params.PartCreateParams), + files=files, + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=UploadPart, + ) + + +class AsyncParts(AsyncAPIResource): + @cached_property + def with_raw_response(self) -> AsyncPartsWithRawResponse: + return AsyncPartsWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncPartsWithStreamingResponse: + return AsyncPartsWithStreamingResponse(self) + + async def create( + self, + upload_id: str, + *, + data: FileTypes, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> UploadPart: + """ + Adds a + [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an + [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object. + A Part represents a chunk of bytes from the file you are trying to upload. + + Each Part can be at most 64 MB, and you can add Parts until you hit the Upload + maximum of 8 GB. + + It is possible to add multiple Parts in parallel. You can decide the intended + order of the Parts when you + [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete). + + Args: + data: The chunk of bytes for this Part. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not upload_id: + raise ValueError(f"Expected a non-empty value for `upload_id` but received {upload_id!r}") + body = deepcopy_minimal({"data": data}) + files = extract_files(cast(Mapping[str, object], body), paths=[["data"]]) + # It should be noted that the actual Content-Type header that will be + # sent to the server will contain a `boundary` parameter, e.g. + # multipart/form-data; boundary=---abc-- + extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} + return await self._post( + f"/uploads/{upload_id}/parts", + body=await async_maybe_transform(body, part_create_params.PartCreateParams), + files=files, + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=UploadPart, + ) + + +class PartsWithRawResponse: + def __init__(self, parts: Parts) -> None: + self._parts = parts + + self.create = _legacy_response.to_raw_response_wrapper( + parts.create, + ) + + +class AsyncPartsWithRawResponse: + def __init__(self, parts: AsyncParts) -> None: + self._parts = parts + + self.create = _legacy_response.async_to_raw_response_wrapper( + parts.create, + ) + + +class PartsWithStreamingResponse: + def __init__(self, parts: Parts) -> None: + self._parts = parts + + self.create = to_streamed_response_wrapper( + parts.create, + ) + + +class AsyncPartsWithStreamingResponse: + def __init__(self, parts: AsyncParts) -> None: + self._parts = parts + + self.create = async_to_streamed_response_wrapper( + parts.create, + ) diff --git a/src/openai/resources/uploads/uploads.py b/src/openai/resources/uploads/uploads.py new file mode 100644 index 0000000000..4100423d3e --- /dev/null +++ b/src/openai/resources/uploads/uploads.py @@ -0,0 +1,473 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List +from typing_extensions import Literal + +import httpx + +from ... import _legacy_response +from .parts import ( + Parts, + AsyncParts, + PartsWithRawResponse, + AsyncPartsWithRawResponse, + PartsWithStreamingResponse, + AsyncPartsWithStreamingResponse, +) +from ...types import upload_create_params, upload_complete_params +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ..._utils import ( + maybe_transform, + async_maybe_transform, +) +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ..._base_client import make_request_options +from ...types.upload import Upload + +__all__ = ["Uploads", "AsyncUploads"] + + +class Uploads(SyncAPIResource): + @cached_property + def parts(self) -> Parts: + return Parts(self._client) + + @cached_property + def with_raw_response(self) -> UploadsWithRawResponse: + return UploadsWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> UploadsWithStreamingResponse: + return UploadsWithStreamingResponse(self) + + def create( + self, + *, + bytes: int, + filename: str, + mime_type: str, + purpose: Literal["assistants", "batch", "fine-tune", "vision"], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Upload: + """ + Creates an intermediate + [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object + that you can add + [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to. + Currently, an Upload can accept at most 8 GB in total and expires after an hour + after you create it. + + Once you complete the Upload, we will create a + [File](https://platform.openai.com/docs/api-reference/files/object) object that + contains all the parts you uploaded. This File is usable in the rest of our + platform as a regular File object. + + For certain `purpose`s, the correct `mime_type` must be specified. Please refer + to documentation for the supported MIME types for your use case: + + - [Assistants](https://platform.openai.com/docs/assistants/tools/file-search/supported-files) + + For guidance on the proper filename extensions for each purpose, please follow + the documentation on + [creating a File](https://platform.openai.com/docs/api-reference/files/create). + + Args: + bytes: The number of bytes in the file you are uploading. + + filename: The name of the file to upload. + + mime_type: The MIME type of the file. + + This must fall within the supported MIME types for your file purpose. See the + supported MIME types for assistants and vision. + + purpose: The intended purpose of the uploaded file. + + See the + [documentation on File purposes](https://platform.openai.com/docs/api-reference/files/create#files-create-purpose). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._post( + "/uploads", + body=maybe_transform( + { + "bytes": bytes, + "filename": filename, + "mime_type": mime_type, + "purpose": purpose, + }, + upload_create_params.UploadCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Upload, + ) + + def cancel( + self, + upload_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Upload: + """Cancels the Upload. + + No Parts may be added after an Upload is cancelled. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not upload_id: + raise ValueError(f"Expected a non-empty value for `upload_id` but received {upload_id!r}") + return self._post( + f"/uploads/{upload_id}/cancel", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Upload, + ) + + def complete( + self, + upload_id: str, + *, + part_ids: List[str], + md5: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Upload: + """ + Completes the + [Upload](https://platform.openai.com/docs/api-reference/uploads/object). + + Within the returned Upload object, there is a nested + [File](https://platform.openai.com/docs/api-reference/files/object) object that + is ready to use in the rest of the platform. + + You can specify the order of the Parts by passing in an ordered list of the Part + IDs. + + The number of bytes uploaded upon completion must match the number of bytes + initially specified when creating the Upload object. No Parts may be added after + an Upload is completed. + + Args: + part_ids: The ordered list of Part IDs. + + md5: The optional md5 checksum for the file contents to verify if the bytes uploaded + matches what you expect. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not upload_id: + raise ValueError(f"Expected a non-empty value for `upload_id` but received {upload_id!r}") + return self._post( + f"/uploads/{upload_id}/complete", + body=maybe_transform( + { + "part_ids": part_ids, + "md5": md5, + }, + upload_complete_params.UploadCompleteParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Upload, + ) + + +class AsyncUploads(AsyncAPIResource): + @cached_property + def parts(self) -> AsyncParts: + return AsyncParts(self._client) + + @cached_property + def with_raw_response(self) -> AsyncUploadsWithRawResponse: + return AsyncUploadsWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncUploadsWithStreamingResponse: + return AsyncUploadsWithStreamingResponse(self) + + async def create( + self, + *, + bytes: int, + filename: str, + mime_type: str, + purpose: Literal["assistants", "batch", "fine-tune", "vision"], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Upload: + """ + Creates an intermediate + [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object + that you can add + [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to. + Currently, an Upload can accept at most 8 GB in total and expires after an hour + after you create it. + + Once you complete the Upload, we will create a + [File](https://platform.openai.com/docs/api-reference/files/object) object that + contains all the parts you uploaded. This File is usable in the rest of our + platform as a regular File object. + + For certain `purpose`s, the correct `mime_type` must be specified. Please refer + to documentation for the supported MIME types for your use case: + + - [Assistants](https://platform.openai.com/docs/assistants/tools/file-search/supported-files) + + For guidance on the proper filename extensions for each purpose, please follow + the documentation on + [creating a File](https://platform.openai.com/docs/api-reference/files/create). + + Args: + bytes: The number of bytes in the file you are uploading. + + filename: The name of the file to upload. + + mime_type: The MIME type of the file. + + This must fall within the supported MIME types for your file purpose. See the + supported MIME types for assistants and vision. + + purpose: The intended purpose of the uploaded file. + + See the + [documentation on File purposes](https://platform.openai.com/docs/api-reference/files/create#files-create-purpose). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._post( + "/uploads", + body=await async_maybe_transform( + { + "bytes": bytes, + "filename": filename, + "mime_type": mime_type, + "purpose": purpose, + }, + upload_create_params.UploadCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Upload, + ) + + async def cancel( + self, + upload_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Upload: + """Cancels the Upload. + + No Parts may be added after an Upload is cancelled. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not upload_id: + raise ValueError(f"Expected a non-empty value for `upload_id` but received {upload_id!r}") + return await self._post( + f"/uploads/{upload_id}/cancel", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Upload, + ) + + async def complete( + self, + upload_id: str, + *, + part_ids: List[str], + md5: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Upload: + """ + Completes the + [Upload](https://platform.openai.com/docs/api-reference/uploads/object). + + Within the returned Upload object, there is a nested + [File](https://platform.openai.com/docs/api-reference/files/object) object that + is ready to use in the rest of the platform. + + You can specify the order of the Parts by passing in an ordered list of the Part + IDs. + + The number of bytes uploaded upon completion must match the number of bytes + initially specified when creating the Upload object. No Parts may be added after + an Upload is completed. + + Args: + part_ids: The ordered list of Part IDs. + + md5: The optional md5 checksum for the file contents to verify if the bytes uploaded + matches what you expect. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not upload_id: + raise ValueError(f"Expected a non-empty value for `upload_id` but received {upload_id!r}") + return await self._post( + f"/uploads/{upload_id}/complete", + body=await async_maybe_transform( + { + "part_ids": part_ids, + "md5": md5, + }, + upload_complete_params.UploadCompleteParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Upload, + ) + + +class UploadsWithRawResponse: + def __init__(self, uploads: Uploads) -> None: + self._uploads = uploads + + self.create = _legacy_response.to_raw_response_wrapper( + uploads.create, + ) + self.cancel = _legacy_response.to_raw_response_wrapper( + uploads.cancel, + ) + self.complete = _legacy_response.to_raw_response_wrapper( + uploads.complete, + ) + + @cached_property + def parts(self) -> PartsWithRawResponse: + return PartsWithRawResponse(self._uploads.parts) + + +class AsyncUploadsWithRawResponse: + def __init__(self, uploads: AsyncUploads) -> None: + self._uploads = uploads + + self.create = _legacy_response.async_to_raw_response_wrapper( + uploads.create, + ) + self.cancel = _legacy_response.async_to_raw_response_wrapper( + uploads.cancel, + ) + self.complete = _legacy_response.async_to_raw_response_wrapper( + uploads.complete, + ) + + @cached_property + def parts(self) -> AsyncPartsWithRawResponse: + return AsyncPartsWithRawResponse(self._uploads.parts) + + +class UploadsWithStreamingResponse: + def __init__(self, uploads: Uploads) -> None: + self._uploads = uploads + + self.create = to_streamed_response_wrapper( + uploads.create, + ) + self.cancel = to_streamed_response_wrapper( + uploads.cancel, + ) + self.complete = to_streamed_response_wrapper( + uploads.complete, + ) + + @cached_property + def parts(self) -> PartsWithStreamingResponse: + return PartsWithStreamingResponse(self._uploads.parts) + + +class AsyncUploadsWithStreamingResponse: + def __init__(self, uploads: AsyncUploads) -> None: + self._uploads = uploads + + self.create = async_to_streamed_response_wrapper( + uploads.create, + ) + self.cancel = async_to_streamed_response_wrapper( + uploads.cancel, + ) + self.complete = async_to_streamed_response_wrapper( + uploads.complete, + ) + + @cached_property + def parts(self) -> AsyncPartsWithStreamingResponse: + return AsyncPartsWithStreamingResponse(self._uploads.parts) diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index 7873efb34f..71f4a59b9e 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -10,6 +10,7 @@ FunctionDefinition as FunctionDefinition, FunctionParameters as FunctionParameters, ) +from .upload import Upload as Upload from .embedding import Embedding as Embedding from .chat_model import ChatModel as ChatModel from .completion import Completion as Completion @@ -28,7 +29,9 @@ from .file_create_params import FileCreateParams as FileCreateParams from .batch_create_params import BatchCreateParams as BatchCreateParams from .batch_request_counts import BatchRequestCounts as BatchRequestCounts +from .upload_create_params import UploadCreateParams as UploadCreateParams from .image_generate_params import ImageGenerateParams as ImageGenerateParams +from .upload_complete_params import UploadCompleteParams as UploadCompleteParams from .embedding_create_params import EmbeddingCreateParams as EmbeddingCreateParams from .completion_create_params import CompletionCreateParams as CompletionCreateParams from .moderation_create_params import ModerationCreateParams as ModerationCreateParams diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 85157653f2..783922539f 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -155,6 +155,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): exhausted. - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. + - When not set, the default behavior is 'auto'. When this parameter is set, the response body will include the `service_tier` utilized. diff --git a/src/openai/types/upload.py b/src/openai/types/upload.py new file mode 100644 index 0000000000..1cf8ee97f8 --- /dev/null +++ b/src/openai/types/upload.py @@ -0,0 +1,42 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel +from .file_object import FileObject + +__all__ = ["Upload"] + + +class Upload(BaseModel): + id: str + """The Upload unique identifier, which can be referenced in API endpoints.""" + + bytes: int + """The intended number of bytes to be uploaded.""" + + created_at: int + """The Unix timestamp (in seconds) for when the Upload was created.""" + + expires_at: int + """The Unix timestamp (in seconds) for when the Upload was created.""" + + filename: str + """The name of the file to be uploaded.""" + + object: Literal["upload"] + """The object type, which is always "upload".""" + + purpose: str + """The intended purpose of the file. + + [Please refer here](https://platform.openai.com/docs/api-reference/files/object#files/object-purpose) + for acceptable values. + """ + + status: Literal["pending", "completed", "cancelled", "expired"] + """The status of the Upload.""" + + file: Optional[FileObject] = None + """The ready File object after the Upload is completed.""" diff --git a/src/openai/types/upload_complete_params.py b/src/openai/types/upload_complete_params.py new file mode 100644 index 0000000000..cce568d5c6 --- /dev/null +++ b/src/openai/types/upload_complete_params.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List +from typing_extensions import Required, TypedDict + +__all__ = ["UploadCompleteParams"] + + +class UploadCompleteParams(TypedDict, total=False): + part_ids: Required[List[str]] + """The ordered list of Part IDs.""" + + md5: str + """ + The optional md5 checksum for the file contents to verify if the bytes uploaded + matches what you expect. + """ diff --git a/src/openai/types/upload_create_params.py b/src/openai/types/upload_create_params.py new file mode 100644 index 0000000000..3165ebcc7a --- /dev/null +++ b/src/openai/types/upload_create_params.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["UploadCreateParams"] + + +class UploadCreateParams(TypedDict, total=False): + bytes: Required[int] + """The number of bytes in the file you are uploading.""" + + filename: Required[str] + """The name of the file to upload.""" + + mime_type: Required[str] + """The MIME type of the file. + + This must fall within the supported MIME types for your file purpose. See the + supported MIME types for assistants and vision. + """ + + purpose: Required[Literal["assistants", "batch", "fine-tune", "vision"]] + """The intended purpose of the uploaded file. + + See the + [documentation on File purposes](https://platform.openai.com/docs/api-reference/files/create#files-create-purpose). + """ diff --git a/src/openai/types/uploads/__init__.py b/src/openai/types/uploads/__init__.py new file mode 100644 index 0000000000..41deb0ab4b --- /dev/null +++ b/src/openai/types/uploads/__init__.py @@ -0,0 +1,6 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .upload_part import UploadPart as UploadPart +from .part_create_params import PartCreateParams as PartCreateParams diff --git a/src/openai/types/uploads/part_create_params.py b/src/openai/types/uploads/part_create_params.py new file mode 100644 index 0000000000..9851ca41e9 --- /dev/null +++ b/src/openai/types/uploads/part_create_params.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +from ..._types import FileTypes + +__all__ = ["PartCreateParams"] + + +class PartCreateParams(TypedDict, total=False): + data: Required[FileTypes] + """The chunk of bytes for this Part.""" diff --git a/src/openai/types/uploads/upload_part.py b/src/openai/types/uploads/upload_part.py new file mode 100644 index 0000000000..e09621d8f9 --- /dev/null +++ b/src/openai/types/uploads/upload_part.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["UploadPart"] + + +class UploadPart(BaseModel): + id: str + """The upload Part unique identifier, which can be referenced in API endpoints.""" + + created_at: int + """The Unix timestamp (in seconds) for when the Part was created.""" + + object: Literal["upload.part"] + """The object type, which is always `upload.part`.""" + + upload_id: str + """The ID of the Upload object that this Part was added to.""" diff --git a/tests/api_resources/test_uploads.py b/tests/api_resources/test_uploads.py new file mode 100644 index 0000000000..cb62df6b51 --- /dev/null +++ b/tests/api_resources/test_uploads.py @@ -0,0 +1,280 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai.types import Upload + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") + + +class TestUploads: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + def test_method_create(self, client: OpenAI) -> None: + upload = client.uploads.create( + bytes=0, + filename="filename", + mime_type="mime_type", + purpose="assistants", + ) + assert_matches_type(Upload, upload, path=["response"]) + + @parametrize + def test_raw_response_create(self, client: OpenAI) -> None: + response = client.uploads.with_raw_response.create( + bytes=0, + filename="filename", + mime_type="mime_type", + purpose="assistants", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + upload = response.parse() + assert_matches_type(Upload, upload, path=["response"]) + + @parametrize + def test_streaming_response_create(self, client: OpenAI) -> None: + with client.uploads.with_streaming_response.create( + bytes=0, + filename="filename", + mime_type="mime_type", + purpose="assistants", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + upload = response.parse() + assert_matches_type(Upload, upload, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_method_cancel(self, client: OpenAI) -> None: + upload = client.uploads.cancel( + "upload_abc123", + ) + assert_matches_type(Upload, upload, path=["response"]) + + @parametrize + def test_raw_response_cancel(self, client: OpenAI) -> None: + response = client.uploads.with_raw_response.cancel( + "upload_abc123", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + upload = response.parse() + assert_matches_type(Upload, upload, path=["response"]) + + @parametrize + def test_streaming_response_cancel(self, client: OpenAI) -> None: + with client.uploads.with_streaming_response.cancel( + "upload_abc123", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + upload = response.parse() + assert_matches_type(Upload, upload, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_cancel(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `upload_id` but received ''"): + client.uploads.with_raw_response.cancel( + "", + ) + + @parametrize + def test_method_complete(self, client: OpenAI) -> None: + upload = client.uploads.complete( + upload_id="upload_abc123", + part_ids=["string", "string", "string"], + ) + assert_matches_type(Upload, upload, path=["response"]) + + @parametrize + def test_method_complete_with_all_params(self, client: OpenAI) -> None: + upload = client.uploads.complete( + upload_id="upload_abc123", + part_ids=["string", "string", "string"], + md5="md5", + ) + assert_matches_type(Upload, upload, path=["response"]) + + @parametrize + def test_raw_response_complete(self, client: OpenAI) -> None: + response = client.uploads.with_raw_response.complete( + upload_id="upload_abc123", + part_ids=["string", "string", "string"], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + upload = response.parse() + assert_matches_type(Upload, upload, path=["response"]) + + @parametrize + def test_streaming_response_complete(self, client: OpenAI) -> None: + with client.uploads.with_streaming_response.complete( + upload_id="upload_abc123", + part_ids=["string", "string", "string"], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + upload = response.parse() + assert_matches_type(Upload, upload, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_complete(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `upload_id` but received ''"): + client.uploads.with_raw_response.complete( + upload_id="", + part_ids=["string", "string", "string"], + ) + + +class TestAsyncUploads: + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + async def test_method_create(self, async_client: AsyncOpenAI) -> None: + upload = await async_client.uploads.create( + bytes=0, + filename="filename", + mime_type="mime_type", + purpose="assistants", + ) + assert_matches_type(Upload, upload, path=["response"]) + + @parametrize + async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: + response = await async_client.uploads.with_raw_response.create( + bytes=0, + filename="filename", + mime_type="mime_type", + purpose="assistants", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + upload = response.parse() + assert_matches_type(Upload, upload, path=["response"]) + + @parametrize + async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: + async with async_client.uploads.with_streaming_response.create( + bytes=0, + filename="filename", + mime_type="mime_type", + purpose="assistants", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + upload = await response.parse() + assert_matches_type(Upload, upload, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_method_cancel(self, async_client: AsyncOpenAI) -> None: + upload = await async_client.uploads.cancel( + "upload_abc123", + ) + assert_matches_type(Upload, upload, path=["response"]) + + @parametrize + async def test_raw_response_cancel(self, async_client: AsyncOpenAI) -> None: + response = await async_client.uploads.with_raw_response.cancel( + "upload_abc123", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + upload = response.parse() + assert_matches_type(Upload, upload, path=["response"]) + + @parametrize + async def test_streaming_response_cancel(self, async_client: AsyncOpenAI) -> None: + async with async_client.uploads.with_streaming_response.cancel( + "upload_abc123", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + upload = await response.parse() + assert_matches_type(Upload, upload, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_cancel(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `upload_id` but received ''"): + await async_client.uploads.with_raw_response.cancel( + "", + ) + + @parametrize + async def test_method_complete(self, async_client: AsyncOpenAI) -> None: + upload = await async_client.uploads.complete( + upload_id="upload_abc123", + part_ids=["string", "string", "string"], + ) + assert_matches_type(Upload, upload, path=["response"]) + + @parametrize + async def test_method_complete_with_all_params(self, async_client: AsyncOpenAI) -> None: + upload = await async_client.uploads.complete( + upload_id="upload_abc123", + part_ids=["string", "string", "string"], + md5="md5", + ) + assert_matches_type(Upload, upload, path=["response"]) + + @parametrize + async def test_raw_response_complete(self, async_client: AsyncOpenAI) -> None: + response = await async_client.uploads.with_raw_response.complete( + upload_id="upload_abc123", + part_ids=["string", "string", "string"], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + upload = response.parse() + assert_matches_type(Upload, upload, path=["response"]) + + @parametrize + async def test_streaming_response_complete(self, async_client: AsyncOpenAI) -> None: + async with async_client.uploads.with_streaming_response.complete( + upload_id="upload_abc123", + part_ids=["string", "string", "string"], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + upload = await response.parse() + assert_matches_type(Upload, upload, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_complete(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `upload_id` but received ''"): + await async_client.uploads.with_raw_response.complete( + upload_id="", + part_ids=["string", "string", "string"], + ) diff --git a/tests/api_resources/uploads/__init__.py b/tests/api_resources/uploads/__init__.py new file mode 100644 index 0000000000..fd8019a9a1 --- /dev/null +++ b/tests/api_resources/uploads/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/uploads/test_parts.py b/tests/api_resources/uploads/test_parts.py new file mode 100644 index 0000000000..2bba241a6d --- /dev/null +++ b/tests/api_resources/uploads/test_parts.py @@ -0,0 +1,106 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai.types.uploads import UploadPart + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") + + +class TestParts: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + def test_method_create(self, client: OpenAI) -> None: + part = client.uploads.parts.create( + upload_id="upload_abc123", + data=b"raw file contents", + ) + assert_matches_type(UploadPart, part, path=["response"]) + + @parametrize + def test_raw_response_create(self, client: OpenAI) -> None: + response = client.uploads.parts.with_raw_response.create( + upload_id="upload_abc123", + data=b"raw file contents", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + part = response.parse() + assert_matches_type(UploadPart, part, path=["response"]) + + @parametrize + def test_streaming_response_create(self, client: OpenAI) -> None: + with client.uploads.parts.with_streaming_response.create( + upload_id="upload_abc123", + data=b"raw file contents", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + part = response.parse() + assert_matches_type(UploadPart, part, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_create(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `upload_id` but received ''"): + client.uploads.parts.with_raw_response.create( + upload_id="", + data=b"raw file contents", + ) + + +class TestAsyncParts: + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + async def test_method_create(self, async_client: AsyncOpenAI) -> None: + part = await async_client.uploads.parts.create( + upload_id="upload_abc123", + data=b"raw file contents", + ) + assert_matches_type(UploadPart, part, path=["response"]) + + @parametrize + async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: + response = await async_client.uploads.parts.with_raw_response.create( + upload_id="upload_abc123", + data=b"raw file contents", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + part = response.parse() + assert_matches_type(UploadPart, part, path=["response"]) + + @parametrize + async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: + async with async_client.uploads.parts.with_streaming_response.create( + upload_id="upload_abc123", + data=b"raw file contents", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + part = await response.parse() + assert_matches_type(UploadPart, part, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_create(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `upload_id` but received ''"): + await async_client.uploads.parts.with_raw_response.create( + upload_id="", + data=b"raw file contents", + ) From ff5add01c7a6129d1977f3d831d02d818a3cbac3 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 22 Jul 2024 11:36:03 +0000 Subject: [PATCH 428/816] docs(readme): fix example snippet imports (#1569) --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 653fb9a2c3..525c1b5aaf 100644 --- a/README.md +++ b/README.md @@ -228,7 +228,7 @@ List methods in the OpenAI API are paginated. This library provides auto-paginating iterators with each list response, so you do not have to request successive pages manually: ```python -import openai +from openai import OpenAI client = OpenAI() @@ -246,7 +246,7 @@ Or, asynchronously: ```python import asyncio -import openai +from openai import AsyncOpenAI client = AsyncOpenAI() From 1ed0e35679438cc7409f2e3aeb36d637b3c579c0 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 22 Jul 2024 11:36:30 +0000 Subject: [PATCH 429/816] release: 1.37.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 18 ++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 21 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 46ea083269..36116e176b 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.36.1" + ".": "1.37.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index c7cac5a9a0..77acf5f5df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,23 @@ # Changelog +## 1.37.0 (2024-07-22) + +Full Changelog: [v1.36.1...v1.37.0](https://github.com/openai/openai-python/compare/v1.36.1...v1.37.0) + +### Features + +* **api:** add uploads endpoints ([#1568](https://github.com/openai/openai-python/issues/1568)) ([d877b6d](https://github.com/openai/openai-python/commit/d877b6dabb9b3e8da6ff2f46de1120af54de398d)) + + +### Bug Fixes + +* **cli/audio:** handle non-json response format ([#1557](https://github.com/openai/openai-python/issues/1557)) ([bb7431f](https://github.com/openai/openai-python/commit/bb7431f602602d4c74d75809c6934a7fd192972d)) + + +### Documentation + +* **readme:** fix example snippet imports ([#1569](https://github.com/openai/openai-python/issues/1569)) ([0c90af6](https://github.com/openai/openai-python/commit/0c90af6412b3314c2257b9b8eb7fabd767f32ef6)) + ## 1.36.1 (2024-07-20) Full Changelog: [v1.36.0...v1.36.1](https://github.com/openai/openai-python/compare/v1.36.0...v1.36.1) diff --git a/pyproject.toml b/pyproject.toml index 03a4a77f56..299e40d2a1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.36.1" +version = "1.37.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 6021f184f8..1fca52e377 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.36.1" # x-release-please-version +__version__ = "1.37.0" # x-release-please-version From edf0fb0f63adea2d0a6f75d94fa4b1b1f7e91851 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 23 Jul 2024 10:34:47 +0000 Subject: [PATCH 430/816] chore(tests): update prism version (#1572) --- scripts/mock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/mock b/scripts/mock index fe89a1d084..f586157699 100755 --- a/scripts/mock +++ b/scripts/mock @@ -21,7 +21,7 @@ echo "==> Starting mock server with URL ${URL}" # Run prism mock on the given spec if [ "$1" == "--daemon" ]; then - npm exec --package=@stoplight/prism-cli@~5.8 -- prism mock "$URL" &> .prism.log & + npm exec --package=@stainless-api/prism-cli@5.8.4 -- prism mock "$URL" &> .prism.log & # Wait for server to come online echo -n "Waiting for server" @@ -37,5 +37,5 @@ if [ "$1" == "--daemon" ]; then echo else - npm exec --package=@stoplight/prism-cli@~5.8 -- prism mock "$URL" + npm exec --package=@stainless-api/prism-cli@5.8.4 -- prism mock "$URL" fi From 195c05a64d39c87b2dfdf1eca2d339597f1fce03 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 25 Jul 2024 05:03:57 +0000 Subject: [PATCH 431/816] release: 1.37.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 36116e176b..6fc89ad7bc 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.37.0" + ".": "1.37.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 77acf5f5df..138180cf6b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.37.1 (2024-07-25) + +Full Changelog: [v1.37.0...v1.37.1](https://github.com/openai/openai-python/compare/v1.37.0...v1.37.1) + +### Chores + +* **tests:** update prism version ([#1572](https://github.com/openai/openai-python/issues/1572)) ([af82593](https://github.com/openai/openai-python/commit/af8259393673af1ef6ec711da6297eb4ad55b66e)) + ## 1.37.0 (2024-07-22) Full Changelog: [v1.36.1...v1.37.0](https://github.com/openai/openai-python/compare/v1.36.1...v1.37.0) diff --git a/pyproject.toml b/pyproject.toml index 299e40d2a1..c4d5bbd1aa 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.37.0" +version = "1.37.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 1fca52e377..5e58cb3c83 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.37.0" # x-release-please-version +__version__ = "1.37.1" # x-release-please-version From 1d2288562d3c65c8b07189b0570ca6bf512111b1 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 29 Jul 2024 09:53:24 +0100 Subject: [PATCH 432/816] chore(runs/create_and_poll): add parallel_tool_calls request param --- .../resources/beta/threads/runs/runs.py | 8 ++++ tests/lib/test_assistants.py | 45 +++++-------------- 2 files changed, 20 insertions(+), 33 deletions(-) diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 1759120bfe..7db8b120f9 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -822,6 +822,8 @@ def create_and_poll( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -844,6 +846,7 @@ def create_and_poll( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -877,6 +880,7 @@ def create_and_poll( response_format=response_format, temperature=temperature, tool_choice=tool_choice, + parallel_tool_calls=parallel_tool_calls, # We assume we are not streaming when polling stream=False, tools=tools, @@ -2404,6 +2408,8 @@ async def create_and_poll( Literal[ "gpt-4o", "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -2426,6 +2432,7 @@ async def create_and_poll( None, ] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -2459,6 +2466,7 @@ async def create_and_poll( response_format=response_format, temperature=temperature, tool_choice=tool_choice, + parallel_tool_calls=parallel_tool_calls, # We assume we are not streaming when polling stream=False, tools=tools, diff --git a/tests/lib/test_assistants.py b/tests/lib/test_assistants.py index 38a47d4d12..b9d4e8927c 100644 --- a/tests/lib/test_assistants.py +++ b/tests/lib/test_assistants.py @@ -1,41 +1,9 @@ from __future__ import annotations -import inspect -from typing import Any, Callable - import pytest from openai import OpenAI, AsyncOpenAI - - -def assert_signatures_in_sync( - source_func: Callable[..., Any], - check_func: Callable[..., Any], - *, - exclude_params: set[str] = set(), -) -> None: - check_sig = inspect.signature(check_func) - source_sig = inspect.signature(source_func) - - errors: list[str] = [] - - for name, generated_param in source_sig.parameters.items(): - if name in exclude_params: - continue - - custom_param = check_sig.parameters.get(name) - if not custom_param: - errors.append(f"the `{name}` param is missing") - continue - - if custom_param.annotation != generated_param.annotation: - errors.append( - f"types for the `{name}` param are do not match; generated={repr(generated_param.annotation)} custom={repr(generated_param.annotation)}" - ) - continue - - if errors: - raise AssertionError(f"{len(errors)} errors encountered when comparing signatures:\n\n" + "\n\n".join(errors)) +from openai._utils import assert_signatures_in_sync @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) @@ -58,3 +26,14 @@ def test_create_and_run_stream_method_definition_in_sync(sync: bool, client: Ope checking_client.beta.threads.create_and_run_stream, exclude_params={"stream"}, ) + + +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +def test_create_and_poll_method_definition_in_sync(sync: bool, client: OpenAI, async_client: AsyncOpenAI) -> None: + checking_client: OpenAI | AsyncOpenAI = client if sync else async_client + + assert_signatures_in_sync( + checking_client.beta.threads.runs.create, + checking_client.beta.threads.runs.create_and_poll, + exclude_params={"stream"}, + ) From 88e61191c06f8523cbf56fee50a5ad3dd1dad646 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 29 Jul 2024 14:56:54 +0000 Subject: [PATCH 433/816] chore(internal): add type construction helper (#1584) --- src/openai/_models.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/openai/_models.py b/src/openai/_models.py index eb7ce3bde9..5148d5a7b3 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -406,6 +406,15 @@ def build( return cast(_BaseModelT, construct_type(type_=base_model_cls, value=kwargs)) +def construct_type_unchecked(*, value: object, type_: type[_T]) -> _T: + """Loose coercion to the expected type with construction of nested values. + + Note: the returned value from this function is not guaranteed to match the + given type. + """ + return cast(_T, construct_type(value=value, type_=type_)) + + def construct_type(*, value: object, type_: object) -> object: """Loose coercion to the expected type with construction of nested values. From 5f177dcdb1f455ededa2a9c121436ba72ba7409f Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 1 Aug 2024 05:03:59 +0000 Subject: [PATCH 434/816] release: 1.37.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 9 +++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 6fc89ad7bc..9baafa1759 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.37.1" + ".": "1.37.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 138180cf6b..824d4d83b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 1.37.2 (2024-08-01) + +Full Changelog: [v1.37.1...v1.37.2](https://github.com/openai/openai-python/compare/v1.37.1...v1.37.2) + +### Chores + +* **internal:** add type construction helper ([#1584](https://github.com/openai/openai-python/issues/1584)) ([cbb186a](https://github.com/openai/openai-python/commit/cbb186a534b520fa5b11a9b371b175e3f6a6482b)) +* **runs/create_and_poll:** add parallel_tool_calls request param ([04b3e6c](https://github.com/openai/openai-python/commit/04b3e6c39ee5a7088e0e4dfa4c06f3dcce901a57)) + ## 1.37.1 (2024-07-25) Full Changelog: [v1.37.0...v1.37.1](https://github.com/openai/openai-python/compare/v1.37.0...v1.37.1) diff --git a/pyproject.toml b/pyproject.toml index c4d5bbd1aa..3c6dcd409a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.37.1" +version = "1.37.2" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 5e58cb3c83..e36be4473a 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.37.1" # x-release-please-version +__version__ = "1.37.2" # x-release-please-version From ece795f0c2dde3f483f9af9126d4c98adf789a8a Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Fri, 2 Aug 2024 09:32:24 +0000 Subject: [PATCH 435/816] feat: extract out `ImageModel`, `AudioModel`, `SpeechModel` (#1586) --- api.md | 16 +- src/openai/resources/audio/speech.py | 9 +- src/openai/resources/audio/transcriptions.py | 9 +- src/openai/resources/audio/translations.py | 10 +- src/openai/resources/beta/assistants.py | 62 +- .../resources/beta/threads/runs/runs.py | 650 +----------------- src/openai/resources/beta/threads/threads.py | 485 +------------ src/openai/resources/images.py | 17 +- src/openai/resources/moderations.py | 10 +- src/openai/types/__init__.py | 3 + src/openai/types/audio/__init__.py | 1 + .../types/audio/speech_create_params.py | 4 +- src/openai/types/audio/speech_model.py | 7 + src/openai/types/audio/transcription.py | 1 - .../audio/transcription_create_params.py | 3 +- src/openai/types/audio/translation.py | 1 - .../types/audio/translation_create_params.py | 5 +- src/openai/types/audio_model.py | 7 + src/openai/types/batch_request_counts.py | 1 - .../types/beta/assistant_create_params.py | 31 +- .../beta/assistant_tool_choice_function.py | 1 - .../beta/thread_create_and_run_params.py | 30 +- .../types/beta/threads/run_create_params.py | 30 +- src/openai/types/completion_usage.py | 1 - .../fine_tuning_job_integration.py | 1 - .../types/image_create_variation_params.py | 3 +- src/openai/types/image_edit_params.py | 3 +- src/openai/types/image_generate_params.py | 4 +- src/openai/types/image_model.py | 7 + src/openai/types/model_deleted.py | 1 - src/openai/types/moderation_create_params.py | 6 +- src/openai/types/moderation_model.py | 7 + 32 files changed, 149 insertions(+), 1277 deletions(-) create mode 100644 src/openai/types/audio/speech_model.py create mode 100644 src/openai/types/audio_model.py create mode 100644 src/openai/types/image_model.py create mode 100644 src/openai/types/moderation_model.py diff --git a/api.md b/api.md index 82a5360edd..85e81467dc 100644 --- a/api.md +++ b/api.md @@ -92,7 +92,7 @@ Methods: Types: ```python -from openai.types import Image, ImagesResponse +from openai.types import Image, ImageModel, ImagesResponse ``` Methods: @@ -103,6 +103,12 @@ Methods: # Audio +Types: + +```python +from openai.types import AudioModel +``` + ## Transcriptions Types: @@ -129,6 +135,12 @@ Methods: ## Speech +Types: + +```python +from openai.types.audio import SpeechModel +``` + Methods: - client.audio.speech.create(\*\*params) -> HttpxBinaryResponseContent @@ -138,7 +150,7 @@ Methods: Types: ```python -from openai.types import Moderation, ModerationCreateResponse +from openai.types import Moderation, ModerationModel, ModerationCreateResponse ``` Methods: diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index e26c58051e..a0df9ec487 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -22,9 +22,8 @@ async_to_custom_streamed_response_wrapper, ) from ...types.audio import speech_create_params -from ..._base_client import ( - make_request_options, -) +from ..._base_client import make_request_options +from ...types.audio.speech_model import SpeechModel __all__ = ["Speech", "AsyncSpeech"] @@ -42,7 +41,7 @@ def create( self, *, input: str, - model: Union[str, Literal["tts-1", "tts-1-hd"]], + model: Union[str, SpeechModel], voice: Literal["alloy", "echo", "fable", "onyx", "nova", "shimmer"], response_format: Literal["mp3", "opus", "aac", "flac", "wav", "pcm"] | NotGiven = NOT_GIVEN, speed: float | NotGiven = NOT_GIVEN, @@ -115,7 +114,7 @@ async def create( self, *, input: str, - model: Union[str, Literal["tts-1", "tts-1-hd"]], + model: Union[str, SpeechModel], voice: Literal["alloy", "echo", "fable", "onyx", "nova", "shimmer"], response_format: Literal["mp3", "opus", "aac", "flac", "wav", "pcm"] | NotGiven = NOT_GIVEN, speed: float | NotGiven = NOT_GIVEN, diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index c03137dbfd..1ee962411c 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -19,9 +19,8 @@ from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ...types.audio import transcription_create_params -from ..._base_client import ( - make_request_options, -) +from ..._base_client import make_request_options +from ...types.audio_model import AudioModel from ...types.audio.transcription import Transcription __all__ = ["Transcriptions", "AsyncTranscriptions"] @@ -40,7 +39,7 @@ def create( self, *, file: FileTypes, - model: Union[str, Literal["whisper-1"]], + model: Union[str, AudioModel], language: str | NotGiven = NOT_GIVEN, prompt: str | NotGiven = NOT_GIVEN, response_format: Literal["json", "text", "srt", "verbose_json", "vtt"] | NotGiven = NOT_GIVEN, @@ -136,7 +135,7 @@ async def create( self, *, file: FileTypes, - model: Union[str, Literal["whisper-1"]], + model: Union[str, AudioModel], language: str | NotGiven = NOT_GIVEN, prompt: str | NotGiven = NOT_GIVEN, response_format: Literal["json", "text", "srt", "verbose_json", "vtt"] | NotGiven = NOT_GIVEN, diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index 485e1a33df..ed97ccf840 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -3,7 +3,6 @@ from __future__ import annotations from typing import Union, Mapping, cast -from typing_extensions import Literal import httpx @@ -19,9 +18,8 @@ from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ...types.audio import translation_create_params -from ..._base_client import ( - make_request_options, -) +from ..._base_client import make_request_options +from ...types.audio_model import AudioModel from ...types.audio.translation import Translation __all__ = ["Translations", "AsyncTranslations"] @@ -40,7 +38,7 @@ def create( self, *, file: FileTypes, - model: Union[str, Literal["whisper-1"]], + model: Union[str, AudioModel], prompt: str | NotGiven = NOT_GIVEN, response_format: str | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, @@ -121,7 +119,7 @@ async def create( self, *, file: FileTypes, - model: Union[str, Literal["whisper-1"]], + model: Union[str, AudioModel], prompt: str | NotGiven = NOT_GIVEN, response_format: str | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, diff --git a/src/openai/resources/beta/assistants.py b/src/openai/resources/beta/assistants.py index 066db66913..b4dc3cfdd6 100644 --- a/src/openai/resources/beta/assistants.py +++ b/src/openai/resources/beta/assistants.py @@ -22,10 +22,8 @@ assistant_create_params, assistant_update_params, ) -from ..._base_client import ( - AsyncPaginator, - make_request_options, -) +from ..._base_client import AsyncPaginator, make_request_options +from ...types.chat_model import ChatModel from ...types.beta.assistant import Assistant from ...types.beta.assistant_deleted import AssistantDeleted from ...types.beta.assistant_tool_param import AssistantToolParam @@ -46,33 +44,7 @@ def with_streaming_response(self) -> AssistantsWithStreamingResponse: def create( self, *, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - ], + model: Union[str, ChatModel], description: Optional[str] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, @@ -437,33 +409,7 @@ def with_streaming_response(self) -> AsyncAssistantsWithStreamingResponse: async def create( self, *, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - ], + model: Union[str, ChatModel], description: Optional[str] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 7db8b120f9..61c6bb486f 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -30,10 +30,7 @@ from ....._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ....._streaming import Stream, AsyncStream from .....pagination import SyncCursorPage, AsyncCursorPage -from ....._base_client import ( - AsyncPaginator, - make_request_options, -) +from ....._base_client import AsyncPaginator, make_request_options from .....lib.streaming import ( AssistantEventHandler, AssistantEventHandlerT, @@ -42,6 +39,7 @@ AsyncAssistantEventHandlerT, AsyncAssistantStreamManager, ) +from .....types.chat_model import ChatModel from .....types.beta.threads import ( run_list_params, run_create_params, @@ -82,35 +80,7 @@ def create( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, @@ -237,35 +207,7 @@ def create( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -391,35 +333,7 @@ def create( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -544,35 +458,7 @@ def create( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, @@ -817,35 +703,7 @@ def create_and_poll( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -913,33 +771,8 @@ def create_and_stream( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -969,33 +802,8 @@ def create_and_stream( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -1025,33 +833,8 @@ def create_and_stream( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -1096,6 +879,7 @@ def create_and_stream( "stream": True, "tools": tools, "truncation_strategy": truncation_strategy, + "parallel_tool_calls": parallel_tool_calls, "top_p": top_p, }, run_create_params.RunCreateParams, @@ -1165,33 +949,7 @@ def stream( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -1220,33 +978,7 @@ def stream( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -1275,33 +1007,7 @@ def stream( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -1668,35 +1374,7 @@ async def create( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, @@ -1823,35 +1501,7 @@ async def create( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -1977,35 +1627,7 @@ async def create( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -2130,35 +1752,7 @@ async def create( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, @@ -2403,35 +1997,7 @@ async def create_and_poll( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -2499,33 +2065,8 @@ def create_and_stream( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -2555,33 +2096,8 @@ def create_and_stream( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -2611,33 +2127,8 @@ def create_and_stream( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -2685,6 +2176,7 @@ def create_and_stream( "tools": tools, "truncation_strategy": truncation_strategy, "top_p": top_p, + "parallel_tool_calls": parallel_tool_calls, }, run_create_params.RunCreateParams, ), @@ -2753,33 +2245,7 @@ def stream( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -2808,33 +2274,7 @@ def stream( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -2863,33 +2303,7 @@ def stream( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index ff7fa70cf8..f40e164180 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -41,9 +41,7 @@ thread_update_params, thread_create_and_run_params, ) -from ...._base_client import ( - make_request_options, -) +from ...._base_client import make_request_options from ....lib.streaming import ( AssistantEventHandler, AssistantEventHandlerT, @@ -52,6 +50,7 @@ AsyncAssistantEventHandlerT, AsyncAssistantStreamManager, ) +from ....types.chat_model import ChatModel from ....types.beta.thread import Thread from ....types.beta.threads.run import Run from ....types.beta.thread_deleted import ThreadDeleted @@ -264,35 +263,7 @@ def create_and_run( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, @@ -418,35 +389,7 @@ def create_and_run( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -571,35 +514,7 @@ def create_and_run( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -723,35 +638,7 @@ def create_and_run( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, @@ -809,35 +696,7 @@ def create_and_run_poll( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -893,35 +752,7 @@ def create_and_run_stream( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -950,35 +781,7 @@ def create_and_run_stream( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -1007,35 +810,7 @@ def create_and_run_stream( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -1296,35 +1071,7 @@ async def create_and_run( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, @@ -1450,35 +1197,7 @@ async def create_and_run( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -1603,35 +1322,7 @@ async def create_and_run( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -1755,35 +1446,7 @@ async def create_and_run( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, @@ -1841,35 +1504,7 @@ async def create_and_run_poll( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -1927,35 +1562,7 @@ def create_and_run_stream( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -1984,35 +1591,7 @@ def create_and_run_stream( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -2041,35 +1620,7 @@ def create_and_run_stream( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] - | NotGiven = NOT_GIVEN, + model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py index 3728392f93..0913b572cb 100644 --- a/src/openai/resources/images.py +++ b/src/openai/resources/images.py @@ -19,9 +19,8 @@ from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper -from .._base_client import ( - make_request_options, -) +from .._base_client import make_request_options +from ..types.image_model import ImageModel from ..types.images_response import ImagesResponse __all__ = ["Images", "AsyncImages"] @@ -40,7 +39,7 @@ def create_variation( self, *, image: FileTypes, - model: Union[str, Literal["dall-e-2"], None] | NotGiven = NOT_GIVEN, + model: Union[str, ImageModel, None] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN, size: Optional[Literal["256x256", "512x512", "1024x1024"]] | NotGiven = NOT_GIVEN, @@ -115,7 +114,7 @@ def edit( image: FileTypes, prompt: str, mask: FileTypes | NotGiven = NOT_GIVEN, - model: Union[str, Literal["dall-e-2"], None] | NotGiven = NOT_GIVEN, + model: Union[str, ImageModel, None] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN, size: Optional[Literal["256x256", "512x512", "1024x1024"]] | NotGiven = NOT_GIVEN, @@ -196,7 +195,7 @@ def generate( self, *, prompt: str, - model: Union[str, Literal["dall-e-2", "dall-e-3"], None] | NotGiven = NOT_GIVEN, + model: Union[str, ImageModel, None] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, quality: Literal["standard", "hd"] | NotGiven = NOT_GIVEN, response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN, @@ -286,7 +285,7 @@ async def create_variation( self, *, image: FileTypes, - model: Union[str, Literal["dall-e-2"], None] | NotGiven = NOT_GIVEN, + model: Union[str, ImageModel, None] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN, size: Optional[Literal["256x256", "512x512", "1024x1024"]] | NotGiven = NOT_GIVEN, @@ -361,7 +360,7 @@ async def edit( image: FileTypes, prompt: str, mask: FileTypes | NotGiven = NOT_GIVEN, - model: Union[str, Literal["dall-e-2"], None] | NotGiven = NOT_GIVEN, + model: Union[str, ImageModel, None] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN, size: Optional[Literal["256x256", "512x512", "1024x1024"]] | NotGiven = NOT_GIVEN, @@ -442,7 +441,7 @@ async def generate( self, *, prompt: str, - model: Union[str, Literal["dall-e-2", "dall-e-3"], None] | NotGiven = NOT_GIVEN, + model: Union[str, ImageModel, None] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, quality: Literal["standard", "hd"] | NotGiven = NOT_GIVEN, response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN, diff --git a/src/openai/resources/moderations.py b/src/openai/resources/moderations.py index 9386e50dae..b9ad9972f0 100644 --- a/src/openai/resources/moderations.py +++ b/src/openai/resources/moderations.py @@ -3,7 +3,6 @@ from __future__ import annotations from typing import List, Union -from typing_extensions import Literal import httpx @@ -17,9 +16,8 @@ from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper -from .._base_client import ( - make_request_options, -) +from .._base_client import make_request_options +from ..types.moderation_model import ModerationModel from ..types.moderation_create_response import ModerationCreateResponse __all__ = ["Moderations", "AsyncModerations"] @@ -38,7 +36,7 @@ def create( self, *, input: Union[str, List[str]], - model: Union[str, Literal["text-moderation-latest", "text-moderation-stable"]] | NotGiven = NOT_GIVEN, + model: Union[str, ModerationModel] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -98,7 +96,7 @@ async def create( self, *, input: Union[str, List[str]], - model: Union[str, Literal["text-moderation-latest", "text-moderation-stable"]] | NotGiven = NOT_GIVEN, + model: Union[str, ModerationModel] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index 71f4a59b9e..84916962cc 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -15,14 +15,17 @@ from .chat_model import ChatModel as ChatModel from .completion import Completion as Completion from .moderation import Moderation as Moderation +from .audio_model import AudioModel as AudioModel from .batch_error import BatchError as BatchError from .file_object import FileObject as FileObject +from .image_model import ImageModel as ImageModel from .file_content import FileContent as FileContent from .file_deleted import FileDeleted as FileDeleted from .model_deleted import ModelDeleted as ModelDeleted from .images_response import ImagesResponse as ImagesResponse from .completion_usage import CompletionUsage as CompletionUsage from .file_list_params import FileListParams as FileListParams +from .moderation_model import ModerationModel as ModerationModel from .batch_list_params import BatchListParams as BatchListParams from .completion_choice import CompletionChoice as CompletionChoice from .image_edit_params import ImageEditParams as ImageEditParams diff --git a/src/openai/types/audio/__init__.py b/src/openai/types/audio/__init__.py index 8d2c44c86a..1de5c0ff82 100644 --- a/src/openai/types/audio/__init__.py +++ b/src/openai/types/audio/__init__.py @@ -3,6 +3,7 @@ from __future__ import annotations from .translation import Translation as Translation +from .speech_model import SpeechModel as SpeechModel from .transcription import Transcription as Transcription from .speech_create_params import SpeechCreateParams as SpeechCreateParams from .translation_create_params import TranslationCreateParams as TranslationCreateParams diff --git a/src/openai/types/audio/speech_create_params.py b/src/openai/types/audio/speech_create_params.py index 8d75ec4ccc..dff66e49c7 100644 --- a/src/openai/types/audio/speech_create_params.py +++ b/src/openai/types/audio/speech_create_params.py @@ -5,6 +5,8 @@ from typing import Union from typing_extensions import Literal, Required, TypedDict +from .speech_model import SpeechModel + __all__ = ["SpeechCreateParams"] @@ -12,7 +14,7 @@ class SpeechCreateParams(TypedDict, total=False): input: Required[str] """The text to generate audio for. The maximum length is 4096 characters.""" - model: Required[Union[str, Literal["tts-1", "tts-1-hd"]]] + model: Required[Union[str, SpeechModel]] """ One of the available [TTS models](https://platform.openai.com/docs/models/tts): `tts-1` or `tts-1-hd` diff --git a/src/openai/types/audio/speech_model.py b/src/openai/types/audio/speech_model.py new file mode 100644 index 0000000000..e92b898b99 --- /dev/null +++ b/src/openai/types/audio/speech_model.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +__all__ = ["SpeechModel"] + +SpeechModel = Literal["tts-1", "tts-1-hd"] diff --git a/src/openai/types/audio/transcription.py b/src/openai/types/audio/transcription.py index 0b6ab39e78..edb5f227fc 100644 --- a/src/openai/types/audio/transcription.py +++ b/src/openai/types/audio/transcription.py @@ -1,7 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from ..._models import BaseModel __all__ = ["Transcription"] diff --git a/src/openai/types/audio/transcription_create_params.py b/src/openai/types/audio/transcription_create_params.py index 6b2d5bae79..a825fefecb 100644 --- a/src/openai/types/audio/transcription_create_params.py +++ b/src/openai/types/audio/transcription_create_params.py @@ -6,6 +6,7 @@ from typing_extensions import Literal, Required, TypedDict from ..._types import FileTypes +from ..audio_model import AudioModel __all__ = ["TranscriptionCreateParams"] @@ -17,7 +18,7 @@ class TranscriptionCreateParams(TypedDict, total=False): flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. """ - model: Required[Union[str, Literal["whisper-1"]]] + model: Required[Union[str, AudioModel]] """ID of the model to use. Only `whisper-1` (which is powered by our open source Whisper V2 model) is diff --git a/src/openai/types/audio/translation.py b/src/openai/types/audio/translation.py index 3d9ede2939..7c0e905189 100644 --- a/src/openai/types/audio/translation.py +++ b/src/openai/types/audio/translation.py @@ -1,7 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from ..._models import BaseModel __all__ = ["Translation"] diff --git a/src/openai/types/audio/translation_create_params.py b/src/openai/types/audio/translation_create_params.py index f23a41ed5c..054996a134 100644 --- a/src/openai/types/audio/translation_create_params.py +++ b/src/openai/types/audio/translation_create_params.py @@ -3,9 +3,10 @@ from __future__ import annotations from typing import Union -from typing_extensions import Literal, Required, TypedDict +from typing_extensions import Required, TypedDict from ..._types import FileTypes +from ..audio_model import AudioModel __all__ = ["TranslationCreateParams"] @@ -17,7 +18,7 @@ class TranslationCreateParams(TypedDict, total=False): mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. """ - model: Required[Union[str, Literal["whisper-1"]]] + model: Required[Union[str, AudioModel]] """ID of the model to use. Only `whisper-1` (which is powered by our open source Whisper V2 model) is diff --git a/src/openai/types/audio_model.py b/src/openai/types/audio_model.py new file mode 100644 index 0000000000..d48e1c06d3 --- /dev/null +++ b/src/openai/types/audio_model.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +__all__ = ["AudioModel"] + +AudioModel = Literal["whisper-1"] diff --git a/src/openai/types/batch_request_counts.py b/src/openai/types/batch_request_counts.py index ef6c84a0a1..7e1d49fb88 100644 --- a/src/openai/types/batch_request_counts.py +++ b/src/openai/types/batch_request_counts.py @@ -1,7 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from .._models import BaseModel __all__ = ["BatchRequestCounts"] diff --git a/src/openai/types/beta/assistant_create_params.py b/src/openai/types/beta/assistant_create_params.py index 754752ae65..42a42ae04e 100644 --- a/src/openai/types/beta/assistant_create_params.py +++ b/src/openai/types/beta/assistant_create_params.py @@ -5,6 +5,7 @@ from typing import List, Union, Iterable, Optional from typing_extensions import Literal, Required, TypedDict +from ..chat_model import ChatModel from .assistant_tool_param import AssistantToolParam from .assistant_response_format_option_param import AssistantResponseFormatOptionParam @@ -22,35 +23,7 @@ class AssistantCreateParams(TypedDict, total=False): - model: Required[ - Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - ] - ] + model: Required[Union[str, ChatModel]] """ID of the model to use. You can use the diff --git a/src/openai/types/beta/assistant_tool_choice_function.py b/src/openai/types/beta/assistant_tool_choice_function.py index d0d4255357..0c896d8087 100644 --- a/src/openai/types/beta/assistant_tool_choice_function.py +++ b/src/openai/types/beta/assistant_tool_choice_function.py @@ -1,7 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from ..._models import BaseModel __all__ = ["AssistantToolChoiceFunction"] diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index 9421a894d9..c3edf34813 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -5,6 +5,7 @@ from typing import List, Union, Iterable, Optional from typing_extensions import Literal, Required, TypedDict +from ..chat_model import ChatModel from .function_tool_param import FunctionToolParam from .file_search_tool_param import FileSearchToolParam from .code_interpreter_tool_param import CodeInterpreterToolParam @@ -77,34 +78,7 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): a maxium of 512 characters long. """ - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] + model: Union[str, ChatModel, None] """ The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index 81cd85188b..dca757ab5f 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -5,6 +5,7 @@ from typing import Union, Iterable, Optional from typing_extensions import Literal, Required, TypedDict +from ...chat_model import ChatModel from ..assistant_tool_param import AssistantToolParam from .message_content_part_param import MessageContentPartParam from ..code_interpreter_tool_param import CodeInterpreterToolParam @@ -74,34 +75,7 @@ class RunCreateParamsBase(TypedDict, total=False): a maxium of 512 characters long. """ - model: Union[ - str, - Literal[ - "gpt-4o", - "gpt-4o-2024-05-13", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", - ], - None, - ] + model: Union[str, ChatModel, None] """ The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the diff --git a/src/openai/types/completion_usage.py b/src/openai/types/completion_usage.py index 0d57b96595..ac09afd479 100644 --- a/src/openai/types/completion_usage.py +++ b/src/openai/types/completion_usage.py @@ -1,7 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from .._models import BaseModel __all__ = ["CompletionUsage"] diff --git a/src/openai/types/fine_tuning/fine_tuning_job_integration.py b/src/openai/types/fine_tuning/fine_tuning_job_integration.py index 8076313cae..9a66aa4f17 100644 --- a/src/openai/types/fine_tuning/fine_tuning_job_integration.py +++ b/src/openai/types/fine_tuning/fine_tuning_job_integration.py @@ -1,7 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from .fine_tuning_job_wandb_integration_object import FineTuningJobWandbIntegrationObject FineTuningJobIntegration = FineTuningJobWandbIntegrationObject diff --git a/src/openai/types/image_create_variation_params.py b/src/openai/types/image_create_variation_params.py index 2549307372..d6ecf0f1ae 100644 --- a/src/openai/types/image_create_variation_params.py +++ b/src/openai/types/image_create_variation_params.py @@ -6,6 +6,7 @@ from typing_extensions import Literal, Required, TypedDict from .._types import FileTypes +from .image_model import ImageModel __all__ = ["ImageCreateVariationParams"] @@ -17,7 +18,7 @@ class ImageCreateVariationParams(TypedDict, total=False): Must be a valid PNG file, less than 4MB, and square. """ - model: Union[str, Literal["dall-e-2"], None] + model: Union[str, ImageModel, None] """The model to use for image generation. Only `dall-e-2` is supported at this time. diff --git a/src/openai/types/image_edit_params.py b/src/openai/types/image_edit_params.py index 073456e349..a596a8692b 100644 --- a/src/openai/types/image_edit_params.py +++ b/src/openai/types/image_edit_params.py @@ -6,6 +6,7 @@ from typing_extensions import Literal, Required, TypedDict from .._types import FileTypes +from .image_model import ImageModel __all__ = ["ImageEditParams"] @@ -31,7 +32,7 @@ class ImageEditParams(TypedDict, total=False): PNG file, less than 4MB, and have the same dimensions as `image`. """ - model: Union[str, Literal["dall-e-2"], None] + model: Union[str, ImageModel, None] """The model to use for image generation. Only `dall-e-2` is supported at this time. diff --git a/src/openai/types/image_generate_params.py b/src/openai/types/image_generate_params.py index 18c56f8ed6..307adeb3da 100644 --- a/src/openai/types/image_generate_params.py +++ b/src/openai/types/image_generate_params.py @@ -5,6 +5,8 @@ from typing import Union, Optional from typing_extensions import Literal, Required, TypedDict +from .image_model import ImageModel + __all__ = ["ImageGenerateParams"] @@ -16,7 +18,7 @@ class ImageGenerateParams(TypedDict, total=False): `dall-e-3`. """ - model: Union[str, Literal["dall-e-2", "dall-e-3"], None] + model: Union[str, ImageModel, None] """The model to use for image generation.""" n: Optional[int] diff --git a/src/openai/types/image_model.py b/src/openai/types/image_model.py new file mode 100644 index 0000000000..ce6535ff2c --- /dev/null +++ b/src/openai/types/image_model.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +__all__ = ["ImageModel"] + +ImageModel = Literal["dall-e-2", "dall-e-3"] diff --git a/src/openai/types/model_deleted.py b/src/openai/types/model_deleted.py index d9a48bb1b5..7f81e1b380 100644 --- a/src/openai/types/model_deleted.py +++ b/src/openai/types/model_deleted.py @@ -1,7 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from .._models import BaseModel __all__ = ["ModelDeleted"] diff --git a/src/openai/types/moderation_create_params.py b/src/openai/types/moderation_create_params.py index d4608def54..337682194d 100644 --- a/src/openai/types/moderation_create_params.py +++ b/src/openai/types/moderation_create_params.py @@ -3,7 +3,9 @@ from __future__ import annotations from typing import List, Union -from typing_extensions import Literal, Required, TypedDict +from typing_extensions import Required, TypedDict + +from .moderation_model import ModerationModel __all__ = ["ModerationCreateParams"] @@ -12,7 +14,7 @@ class ModerationCreateParams(TypedDict, total=False): input: Required[Union[str, List[str]]] """The input text to classify""" - model: Union[str, Literal["text-moderation-latest", "text-moderation-stable"]] + model: Union[str, ModerationModel] """ Two content moderations models are available: `text-moderation-stable` and `text-moderation-latest`. diff --git a/src/openai/types/moderation_model.py b/src/openai/types/moderation_model.py new file mode 100644 index 0000000000..73362596f3 --- /dev/null +++ b/src/openai/types/moderation_model.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +__all__ = ["ModerationModel"] + +ModerationModel = Literal["text-moderation-latest", "text-moderation-stable"] From 08943dfdb1caf2d3fa67fcb2afb6ca5502da08f4 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 2 Aug 2024 04:04:44 +0000 Subject: [PATCH 436/816] feat: make enums not nominal (#1588) --- .stats.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index 4e4cb5509c..6cc7757636 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-77cfff37114bc9f141c7e6107eb5f1b38d8cc99bc3d4ce03a066db2b6b649c69.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-b04761ffd2adad3cc19a6dc6fc696ac445878219972f891881a967340fa9a6b0.yml From da48e4cac78d1d4ac749e2aa5cfd619fde1e6c68 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 2 Aug 2024 09:32:49 +0000 Subject: [PATCH 437/816] release: 1.38.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 9 +++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 9baafa1759..b90a705e63 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.37.2" + ".": "1.38.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 824d4d83b7..0f62f6689d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 1.38.0 (2024-08-02) + +Full Changelog: [v1.37.2...v1.38.0](https://github.com/openai/openai-python/compare/v1.37.2...v1.38.0) + +### Features + +* extract out `ImageModel`, `AudioModel`, `SpeechModel` ([#1586](https://github.com/openai/openai-python/issues/1586)) ([b800316](https://github.com/openai/openai-python/commit/b800316aee6c8b2aeb609ca4c41972adccd2fa7a)) +* make enums not nominal ([#1588](https://github.com/openai/openai-python/issues/1588)) ([ab4519b](https://github.com/openai/openai-python/commit/ab4519bc45f5512c8c5165641c217385d999809c)) + ## 1.37.2 (2024-08-01) Full Changelog: [v1.37.1...v1.37.2](https://github.com/openai/openai-python/compare/v1.37.1...v1.37.2) diff --git a/pyproject.toml b/pyproject.toml index 3c6dcd409a..0d736aa444 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.37.2" +version = "1.38.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index e36be4473a..ea1c039fab 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.37.2" # x-release-please-version +__version__ = "1.38.0" # x-release-please-version From d4a998e8501d15c5dd990b1914a056044ff5f8f6 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 5 Aug 2024 11:02:33 +0000 Subject: [PATCH 438/816] chore(internal): use `TypeAlias` marker for type assignments (#1597) --- src/openai/types/audio/speech_model.py | 4 ++-- src/openai/types/audio_model.py | 4 ++-- src/openai/types/beta/assistant_create_params.py | 4 ++-- src/openai/types/beta/assistant_response_format_option.py | 4 ++-- .../types/beta/assistant_response_format_option_param.py | 4 ++-- src/openai/types/beta/assistant_stream_event.py | 4 ++-- src/openai/types/beta/assistant_tool.py | 6 ++++-- src/openai/types/beta/assistant_tool_choice_option.py | 4 ++-- .../types/beta/assistant_tool_choice_option_param.py | 4 ++-- src/openai/types/beta/assistant_tool_param.py | 3 ++- src/openai/types/beta/thread_create_and_run_params.py | 8 ++++---- src/openai/types/beta/thread_create_params.py | 6 +++--- src/openai/types/beta/threads/annotation.py | 4 ++-- src/openai/types/beta/threads/annotation_delta.py | 4 ++-- src/openai/types/beta/threads/message.py | 4 ++-- src/openai/types/beta/threads/message_content.py | 4 ++-- src/openai/types/beta/threads/message_content_delta.py | 4 ++-- .../types/beta/threads/message_content_part_param.py | 3 ++- src/openai/types/beta/threads/message_create_params.py | 4 ++-- src/openai/types/beta/threads/run_create_params.py | 4 ++-- src/openai/types/beta/threads/run_status.py | 4 ++-- .../types/beta/threads/runs/code_interpreter_tool_call.py | 4 ++-- .../beta/threads/runs/code_interpreter_tool_call_delta.py | 4 ++-- src/openai/types/beta/threads/runs/run_step.py | 6 ++++-- src/openai/types/beta/threads/runs/run_step_delta.py | 6 ++++-- src/openai/types/beta/threads/runs/tool_call.py | 4 ++-- src/openai/types/beta/threads/runs/tool_call_delta.py | 4 ++-- src/openai/types/beta/vector_store_create_params.py | 4 ++-- .../types/beta/vector_stores/file_batch_create_params.py | 4 ++-- src/openai/types/beta/vector_stores/file_create_params.py | 4 ++-- src/openai/types/beta/vector_stores/vector_store_file.py | 6 ++++-- .../types/chat/chat_completion_content_part_param.py | 5 ++++- src/openai/types/chat/chat_completion_message_param.py | 3 ++- src/openai/types/chat/chat_completion_role.py | 4 ++-- .../chat/chat_completion_tool_choice_option_param.py | 6 ++++-- src/openai/types/chat/completion_create_params.py | 4 ++-- src/openai/types/chat_model.py | 4 ++-- src/openai/types/file_content.py | 3 ++- src/openai/types/image_model.py | 4 ++-- src/openai/types/moderation_model.py | 4 ++-- src/openai/types/shared/function_parameters.py | 3 ++- src/openai/types/shared_params/function_parameters.py | 3 ++- 42 files changed, 99 insertions(+), 80 deletions(-) diff --git a/src/openai/types/audio/speech_model.py b/src/openai/types/audio/speech_model.py index e92b898b99..bd685ab34d 100644 --- a/src/openai/types/audio/speech_model.py +++ b/src/openai/types/audio/speech_model.py @@ -1,7 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias __all__ = ["SpeechModel"] -SpeechModel = Literal["tts-1", "tts-1-hd"] +SpeechModel: TypeAlias = Literal["tts-1", "tts-1-hd"] diff --git a/src/openai/types/audio_model.py b/src/openai/types/audio_model.py index d48e1c06d3..94ae84c015 100644 --- a/src/openai/types/audio_model.py +++ b/src/openai/types/audio_model.py @@ -1,7 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias __all__ = ["AudioModel"] -AudioModel = Literal["whisper-1"] +AudioModel: TypeAlias = Literal["whisper-1"] diff --git a/src/openai/types/beta/assistant_create_params.py b/src/openai/types/beta/assistant_create_params.py index 42a42ae04e..c10f7f57ad 100644 --- a/src/openai/types/beta/assistant_create_params.py +++ b/src/openai/types/beta/assistant_create_params.py @@ -3,7 +3,7 @@ from __future__ import annotations from typing import List, Union, Iterable, Optional -from typing_extensions import Literal, Required, TypedDict +from typing_extensions import Literal, Required, TypeAlias, TypedDict from ..chat_model import ChatModel from .assistant_tool_param import AssistantToolParam @@ -140,7 +140,7 @@ class ToolResourcesFileSearchVectorStoreChunkingStrategyStatic(TypedDict, total= """Always `static`.""" -ToolResourcesFileSearchVectorStoreChunkingStrategy = Union[ +ToolResourcesFileSearchVectorStoreChunkingStrategy: TypeAlias = Union[ ToolResourcesFileSearchVectorStoreChunkingStrategyAuto, ToolResourcesFileSearchVectorStoreChunkingStrategyStatic ] diff --git a/src/openai/types/beta/assistant_response_format_option.py b/src/openai/types/beta/assistant_response_format_option.py index d4e05e0ea9..6ce390f6d6 100644 --- a/src/openai/types/beta/assistant_response_format_option.py +++ b/src/openai/types/beta/assistant_response_format_option.py @@ -1,10 +1,10 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Union -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias from .assistant_response_format import AssistantResponseFormat __all__ = ["AssistantResponseFormatOption"] -AssistantResponseFormatOption = Union[Literal["none", "auto"], AssistantResponseFormat] +AssistantResponseFormatOption: TypeAlias = Union[Literal["none", "auto"], AssistantResponseFormat] diff --git a/src/openai/types/beta/assistant_response_format_option_param.py b/src/openai/types/beta/assistant_response_format_option_param.py index 46e04125d1..8100088723 100644 --- a/src/openai/types/beta/assistant_response_format_option_param.py +++ b/src/openai/types/beta/assistant_response_format_option_param.py @@ -3,10 +3,10 @@ from __future__ import annotations from typing import Union -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias from .assistant_response_format_param import AssistantResponseFormatParam __all__ = ["AssistantResponseFormatOptionParam"] -AssistantResponseFormatOptionParam = Union[Literal["none", "auto"], AssistantResponseFormatParam] +AssistantResponseFormatOptionParam: TypeAlias = Union[Literal["none", "auto"], AssistantResponseFormatParam] diff --git a/src/openai/types/beta/assistant_stream_event.py b/src/openai/types/beta/assistant_stream_event.py index de66888403..f1d8898ff2 100644 --- a/src/openai/types/beta/assistant_stream_event.py +++ b/src/openai/types/beta/assistant_stream_event.py @@ -1,7 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Union -from typing_extensions import Literal, Annotated +from typing_extensions import Literal, Annotated, TypeAlias from .thread import Thread from ..._utils import PropertyInfo @@ -260,7 +260,7 @@ class ErrorEvent(BaseModel): event: Literal["error"] -AssistantStreamEvent = Annotated[ +AssistantStreamEvent: TypeAlias = Annotated[ Union[ ThreadCreated, ThreadRunCreated, diff --git a/src/openai/types/beta/assistant_tool.py b/src/openai/types/beta/assistant_tool.py index 7832da48cc..1bde6858b1 100644 --- a/src/openai/types/beta/assistant_tool.py +++ b/src/openai/types/beta/assistant_tool.py @@ -1,7 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Union -from typing_extensions import Annotated +from typing_extensions import Annotated, TypeAlias from ..._utils import PropertyInfo from .function_tool import FunctionTool @@ -10,4 +10,6 @@ __all__ = ["AssistantTool"] -AssistantTool = Annotated[Union[CodeInterpreterTool, FileSearchTool, FunctionTool], PropertyInfo(discriminator="type")] +AssistantTool: TypeAlias = Annotated[ + Union[CodeInterpreterTool, FileSearchTool, FunctionTool], PropertyInfo(discriminator="type") +] diff --git a/src/openai/types/beta/assistant_tool_choice_option.py b/src/openai/types/beta/assistant_tool_choice_option.py index 8958bc8fb0..e57c3278fb 100644 --- a/src/openai/types/beta/assistant_tool_choice_option.py +++ b/src/openai/types/beta/assistant_tool_choice_option.py @@ -1,10 +1,10 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Union -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias from .assistant_tool_choice import AssistantToolChoice __all__ = ["AssistantToolChoiceOption"] -AssistantToolChoiceOption = Union[Literal["none", "auto", "required"], AssistantToolChoice] +AssistantToolChoiceOption: TypeAlias = Union[Literal["none", "auto", "required"], AssistantToolChoice] diff --git a/src/openai/types/beta/assistant_tool_choice_option_param.py b/src/openai/types/beta/assistant_tool_choice_option_param.py index 81b7f15136..cc0053d37e 100644 --- a/src/openai/types/beta/assistant_tool_choice_option_param.py +++ b/src/openai/types/beta/assistant_tool_choice_option_param.py @@ -3,10 +3,10 @@ from __future__ import annotations from typing import Union -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias from .assistant_tool_choice_param import AssistantToolChoiceParam __all__ = ["AssistantToolChoiceOptionParam"] -AssistantToolChoiceOptionParam = Union[Literal["none", "auto", "required"], AssistantToolChoiceParam] +AssistantToolChoiceOptionParam: TypeAlias = Union[Literal["none", "auto", "required"], AssistantToolChoiceParam] diff --git a/src/openai/types/beta/assistant_tool_param.py b/src/openai/types/beta/assistant_tool_param.py index 5b1d30ba2f..321c4b1ddb 100644 --- a/src/openai/types/beta/assistant_tool_param.py +++ b/src/openai/types/beta/assistant_tool_param.py @@ -3,6 +3,7 @@ from __future__ import annotations from typing import Union +from typing_extensions import TypeAlias from .function_tool_param import FunctionToolParam from .file_search_tool_param import FileSearchToolParam @@ -10,4 +11,4 @@ __all__ = ["AssistantToolParam"] -AssistantToolParam = Union[CodeInterpreterToolParam, FileSearchToolParam, FunctionToolParam] +AssistantToolParam: TypeAlias = Union[CodeInterpreterToolParam, FileSearchToolParam, FunctionToolParam] diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index c3edf34813..62cff921e2 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -3,7 +3,7 @@ from __future__ import annotations from typing import List, Union, Iterable, Optional -from typing_extensions import Literal, Required, TypedDict +from typing_extensions import Literal, Required, TypeAlias, TypedDict from ..chat_model import ChatModel from .function_tool_param import FunctionToolParam @@ -168,7 +168,7 @@ class ThreadMessageAttachmentToolFileSearch(TypedDict, total=False): """The type of tool being defined: `file_search`""" -ThreadMessageAttachmentTool = Union[CodeInterpreterToolParam, ThreadMessageAttachmentToolFileSearch] +ThreadMessageAttachmentTool: TypeAlias = Union[CodeInterpreterToolParam, ThreadMessageAttachmentToolFileSearch] class ThreadMessageAttachment(TypedDict, total=False): @@ -240,7 +240,7 @@ class ThreadToolResourcesFileSearchVectorStoreChunkingStrategyStatic(TypedDict, """Always `static`.""" -ThreadToolResourcesFileSearchVectorStoreChunkingStrategy = Union[ +ThreadToolResourcesFileSearchVectorStoreChunkingStrategy: TypeAlias = Union[ ThreadToolResourcesFileSearchVectorStoreChunkingStrategyAuto, ThreadToolResourcesFileSearchVectorStoreChunkingStrategyStatic, ] @@ -342,7 +342,7 @@ class ToolResources(TypedDict, total=False): file_search: ToolResourcesFileSearch -Tool = Union[CodeInterpreterToolParam, FileSearchToolParam, FunctionToolParam] +Tool: TypeAlias = Union[CodeInterpreterToolParam, FileSearchToolParam, FunctionToolParam] class TruncationStrategy(TypedDict, total=False): diff --git a/src/openai/types/beta/thread_create_params.py b/src/openai/types/beta/thread_create_params.py index e5ea14a94d..f9561aa48c 100644 --- a/src/openai/types/beta/thread_create_params.py +++ b/src/openai/types/beta/thread_create_params.py @@ -3,7 +3,7 @@ from __future__ import annotations from typing import List, Union, Iterable, Optional -from typing_extensions import Literal, Required, TypedDict +from typing_extensions import Literal, Required, TypeAlias, TypedDict from .code_interpreter_tool_param import CodeInterpreterToolParam from .threads.message_content_part_param import MessageContentPartParam @@ -54,7 +54,7 @@ class MessageAttachmentToolFileSearch(TypedDict, total=False): """The type of tool being defined: `file_search`""" -MessageAttachmentTool = Union[CodeInterpreterToolParam, MessageAttachmentToolFileSearch] +MessageAttachmentTool: TypeAlias = Union[CodeInterpreterToolParam, MessageAttachmentToolFileSearch] class MessageAttachment(TypedDict, total=False): @@ -126,7 +126,7 @@ class ToolResourcesFileSearchVectorStoreChunkingStrategyStatic(TypedDict, total= """Always `static`.""" -ToolResourcesFileSearchVectorStoreChunkingStrategy = Union[ +ToolResourcesFileSearchVectorStoreChunkingStrategy: TypeAlias = Union[ ToolResourcesFileSearchVectorStoreChunkingStrategyAuto, ToolResourcesFileSearchVectorStoreChunkingStrategyStatic ] diff --git a/src/openai/types/beta/threads/annotation.py b/src/openai/types/beta/threads/annotation.py index 31e228c831..13c10abf4d 100644 --- a/src/openai/types/beta/threads/annotation.py +++ b/src/openai/types/beta/threads/annotation.py @@ -1,7 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Union -from typing_extensions import Annotated +from typing_extensions import Annotated, TypeAlias from ...._utils import PropertyInfo from .file_path_annotation import FilePathAnnotation @@ -9,4 +9,4 @@ __all__ = ["Annotation"] -Annotation = Annotated[Union[FileCitationAnnotation, FilePathAnnotation], PropertyInfo(discriminator="type")] +Annotation: TypeAlias = Annotated[Union[FileCitationAnnotation, FilePathAnnotation], PropertyInfo(discriminator="type")] diff --git a/src/openai/types/beta/threads/annotation_delta.py b/src/openai/types/beta/threads/annotation_delta.py index 912429672f..c7c6c89837 100644 --- a/src/openai/types/beta/threads/annotation_delta.py +++ b/src/openai/types/beta/threads/annotation_delta.py @@ -1,7 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Union -from typing_extensions import Annotated +from typing_extensions import Annotated, TypeAlias from ...._utils import PropertyInfo from .file_path_delta_annotation import FilePathDeltaAnnotation @@ -9,6 +9,6 @@ __all__ = ["AnnotationDelta"] -AnnotationDelta = Annotated[ +AnnotationDelta: TypeAlias = Annotated[ Union[FileCitationDeltaAnnotation, FilePathDeltaAnnotation], PropertyInfo(discriminator="type") ] diff --git a/src/openai/types/beta/threads/message.py b/src/openai/types/beta/threads/message.py index 90f083683d..298a1d4273 100644 --- a/src/openai/types/beta/threads/message.py +++ b/src/openai/types/beta/threads/message.py @@ -1,7 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import List, Union, Optional -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias from ...._models import BaseModel from .message_content import MessageContent @@ -21,7 +21,7 @@ class AttachmentToolAssistantToolsFileSearchTypeOnly(BaseModel): """The type of tool being defined: `file_search`""" -AttachmentTool = Union[CodeInterpreterTool, AttachmentToolAssistantToolsFileSearchTypeOnly] +AttachmentTool: TypeAlias = Union[CodeInterpreterTool, AttachmentToolAssistantToolsFileSearchTypeOnly] class Attachment(BaseModel): diff --git a/src/openai/types/beta/threads/message_content.py b/src/openai/types/beta/threads/message_content.py index 4f17d14786..7b718c3ca9 100644 --- a/src/openai/types/beta/threads/message_content.py +++ b/src/openai/types/beta/threads/message_content.py @@ -1,7 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Union -from typing_extensions import Annotated +from typing_extensions import Annotated, TypeAlias from ...._utils import PropertyInfo from .text_content_block import TextContentBlock @@ -10,6 +10,6 @@ __all__ = ["MessageContent"] -MessageContent = Annotated[ +MessageContent: TypeAlias = Annotated[ Union[ImageFileContentBlock, ImageURLContentBlock, TextContentBlock], PropertyInfo(discriminator="type") ] diff --git a/src/openai/types/beta/threads/message_content_delta.py b/src/openai/types/beta/threads/message_content_delta.py index 6c5f732b12..667172c08f 100644 --- a/src/openai/types/beta/threads/message_content_delta.py +++ b/src/openai/types/beta/threads/message_content_delta.py @@ -1,7 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Union -from typing_extensions import Annotated +from typing_extensions import Annotated, TypeAlias from ...._utils import PropertyInfo from .text_delta_block import TextDeltaBlock @@ -10,6 +10,6 @@ __all__ = ["MessageContentDelta"] -MessageContentDelta = Annotated[ +MessageContentDelta: TypeAlias = Annotated[ Union[ImageFileDeltaBlock, TextDeltaBlock, ImageURLDeltaBlock], PropertyInfo(discriminator="type") ] diff --git a/src/openai/types/beta/threads/message_content_part_param.py b/src/openai/types/beta/threads/message_content_part_param.py index d11442a3a9..dc09a01c27 100644 --- a/src/openai/types/beta/threads/message_content_part_param.py +++ b/src/openai/types/beta/threads/message_content_part_param.py @@ -3,6 +3,7 @@ from __future__ import annotations from typing import Union +from typing_extensions import TypeAlias from .text_content_block_param import TextContentBlockParam from .image_url_content_block_param import ImageURLContentBlockParam @@ -10,4 +11,4 @@ __all__ = ["MessageContentPartParam"] -MessageContentPartParam = Union[ImageFileContentBlockParam, ImageURLContentBlockParam, TextContentBlockParam] +MessageContentPartParam: TypeAlias = Union[ImageFileContentBlockParam, ImageURLContentBlockParam, TextContentBlockParam] diff --git a/src/openai/types/beta/threads/message_create_params.py b/src/openai/types/beta/threads/message_create_params.py index b1b12293b7..2b450deb5d 100644 --- a/src/openai/types/beta/threads/message_create_params.py +++ b/src/openai/types/beta/threads/message_create_params.py @@ -3,7 +3,7 @@ from __future__ import annotations from typing import Union, Iterable, Optional -from typing_extensions import Literal, Required, TypedDict +from typing_extensions import Literal, Required, TypeAlias, TypedDict from .message_content_part_param import MessageContentPartParam from ..code_interpreter_tool_param import CodeInterpreterToolParam @@ -41,7 +41,7 @@ class AttachmentToolFileSearch(TypedDict, total=False): """The type of tool being defined: `file_search`""" -AttachmentTool = Union[CodeInterpreterToolParam, AttachmentToolFileSearch] +AttachmentTool: TypeAlias = Union[CodeInterpreterToolParam, AttachmentToolFileSearch] class Attachment(TypedDict, total=False): diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index dca757ab5f..e0c42fd23f 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -3,7 +3,7 @@ from __future__ import annotations from typing import Union, Iterable, Optional -from typing_extensions import Literal, Required, TypedDict +from typing_extensions import Literal, Required, TypeAlias, TypedDict from ...chat_model import ChatModel from ..assistant_tool_param import AssistantToolParam @@ -154,7 +154,7 @@ class AdditionalMessageAttachmentToolFileSearch(TypedDict, total=False): """The type of tool being defined: `file_search`""" -AdditionalMessageAttachmentTool = Union[CodeInterpreterToolParam, AdditionalMessageAttachmentToolFileSearch] +AdditionalMessageAttachmentTool: TypeAlias = Union[CodeInterpreterToolParam, AdditionalMessageAttachmentToolFileSearch] class AdditionalMessageAttachment(TypedDict, total=False): diff --git a/src/openai/types/beta/threads/run_status.py b/src/openai/types/beta/threads/run_status.py index 6666d00e5a..47c7cbd007 100644 --- a/src/openai/types/beta/threads/run_status.py +++ b/src/openai/types/beta/threads/run_status.py @@ -1,10 +1,10 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias __all__ = ["RunStatus"] -RunStatus = Literal[ +RunStatus: TypeAlias = Literal[ "queued", "in_progress", "requires_action", diff --git a/src/openai/types/beta/threads/runs/code_interpreter_tool_call.py b/src/openai/types/beta/threads/runs/code_interpreter_tool_call.py index 2f07243684..e7df4e19c4 100644 --- a/src/openai/types/beta/threads/runs/code_interpreter_tool_call.py +++ b/src/openai/types/beta/threads/runs/code_interpreter_tool_call.py @@ -1,7 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import List, Union -from typing_extensions import Literal, Annotated +from typing_extensions import Literal, Annotated, TypeAlias from ....._utils import PropertyInfo from ....._models import BaseModel @@ -39,7 +39,7 @@ class CodeInterpreterOutputImage(BaseModel): """Always `image`.""" -CodeInterpreterOutput = Annotated[ +CodeInterpreterOutput: TypeAlias = Annotated[ Union[CodeInterpreterOutputLogs, CodeInterpreterOutputImage], PropertyInfo(discriminator="type") ] diff --git a/src/openai/types/beta/threads/runs/code_interpreter_tool_call_delta.py b/src/openai/types/beta/threads/runs/code_interpreter_tool_call_delta.py index eff76355b3..9d7a1563cd 100644 --- a/src/openai/types/beta/threads/runs/code_interpreter_tool_call_delta.py +++ b/src/openai/types/beta/threads/runs/code_interpreter_tool_call_delta.py @@ -1,7 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import List, Union, Optional -from typing_extensions import Literal, Annotated +from typing_extensions import Literal, Annotated, TypeAlias from ....._utils import PropertyInfo from ....._models import BaseModel @@ -10,7 +10,7 @@ __all__ = ["CodeInterpreterToolCallDelta", "CodeInterpreter", "CodeInterpreterOutput"] -CodeInterpreterOutput = Annotated[ +CodeInterpreterOutput: TypeAlias = Annotated[ Union[CodeInterpreterLogs, CodeInterpreterOutputImage], PropertyInfo(discriminator="type") ] diff --git a/src/openai/types/beta/threads/runs/run_step.py b/src/openai/types/beta/threads/runs/run_step.py index 7c81dcac2b..e3163c508b 100644 --- a/src/openai/types/beta/threads/runs/run_step.py +++ b/src/openai/types/beta/threads/runs/run_step.py @@ -1,7 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Union, Optional -from typing_extensions import Literal, Annotated +from typing_extensions import Literal, Annotated, TypeAlias from ....._utils import PropertyInfo from ....._models import BaseModel @@ -19,7 +19,9 @@ class LastError(BaseModel): """A human-readable description of the error.""" -StepDetails = Annotated[Union[MessageCreationStepDetails, ToolCallsStepDetails], PropertyInfo(discriminator="type")] +StepDetails: TypeAlias = Annotated[ + Union[MessageCreationStepDetails, ToolCallsStepDetails], PropertyInfo(discriminator="type") +] class Usage(BaseModel): diff --git a/src/openai/types/beta/threads/runs/run_step_delta.py b/src/openai/types/beta/threads/runs/run_step_delta.py index d6b4aefeb9..1139088fb4 100644 --- a/src/openai/types/beta/threads/runs/run_step_delta.py +++ b/src/openai/types/beta/threads/runs/run_step_delta.py @@ -1,7 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Union, Optional -from typing_extensions import Annotated +from typing_extensions import Annotated, TypeAlias from ....._utils import PropertyInfo from ....._models import BaseModel @@ -10,7 +10,9 @@ __all__ = ["RunStepDelta", "StepDetails"] -StepDetails = Annotated[Union[RunStepDeltaMessageDelta, ToolCallDeltaObject], PropertyInfo(discriminator="type")] +StepDetails: TypeAlias = Annotated[ + Union[RunStepDeltaMessageDelta, ToolCallDeltaObject], PropertyInfo(discriminator="type") +] class RunStepDelta(BaseModel): diff --git a/src/openai/types/beta/threads/runs/tool_call.py b/src/openai/types/beta/threads/runs/tool_call.py index 77d86b46d9..565e3109be 100644 --- a/src/openai/types/beta/threads/runs/tool_call.py +++ b/src/openai/types/beta/threads/runs/tool_call.py @@ -1,7 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Union -from typing_extensions import Annotated +from typing_extensions import Annotated, TypeAlias from ....._utils import PropertyInfo from .function_tool_call import FunctionToolCall @@ -10,6 +10,6 @@ __all__ = ["ToolCall"] -ToolCall = Annotated[ +ToolCall: TypeAlias = Annotated[ Union[CodeInterpreterToolCall, FileSearchToolCall, FunctionToolCall], PropertyInfo(discriminator="type") ] diff --git a/src/openai/types/beta/threads/runs/tool_call_delta.py b/src/openai/types/beta/threads/runs/tool_call_delta.py index 90cfe0657e..f0b8070c97 100644 --- a/src/openai/types/beta/threads/runs/tool_call_delta.py +++ b/src/openai/types/beta/threads/runs/tool_call_delta.py @@ -1,7 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Union -from typing_extensions import Annotated +from typing_extensions import Annotated, TypeAlias from ....._utils import PropertyInfo from .function_tool_call_delta import FunctionToolCallDelta @@ -10,7 +10,7 @@ __all__ = ["ToolCallDelta"] -ToolCallDelta = Annotated[ +ToolCallDelta: TypeAlias = Annotated[ Union[CodeInterpreterToolCallDelta, FileSearchToolCallDelta, FunctionToolCallDelta], PropertyInfo(discriminator="type"), ] diff --git a/src/openai/types/beta/vector_store_create_params.py b/src/openai/types/beta/vector_store_create_params.py index 365d9923b8..4f74af49f8 100644 --- a/src/openai/types/beta/vector_store_create_params.py +++ b/src/openai/types/beta/vector_store_create_params.py @@ -3,7 +3,7 @@ from __future__ import annotations from typing import List, Union, Optional -from typing_extensions import Literal, Required, TypedDict +from typing_extensions import Literal, Required, TypeAlias, TypedDict __all__ = [ "VectorStoreCreateParams", @@ -72,7 +72,7 @@ class ChunkingStrategyStatic(TypedDict, total=False): """Always `static`.""" -ChunkingStrategy = Union[ChunkingStrategyAuto, ChunkingStrategyStatic] +ChunkingStrategy: TypeAlias = Union[ChunkingStrategyAuto, ChunkingStrategyStatic] class ExpiresAfter(TypedDict, total=False): diff --git a/src/openai/types/beta/vector_stores/file_batch_create_params.py b/src/openai/types/beta/vector_stores/file_batch_create_params.py index 9b98d0699e..e1c3303cf3 100644 --- a/src/openai/types/beta/vector_stores/file_batch_create_params.py +++ b/src/openai/types/beta/vector_stores/file_batch_create_params.py @@ -3,7 +3,7 @@ from __future__ import annotations from typing import List, Union -from typing_extensions import Literal, Required, TypedDict +from typing_extensions import Literal, Required, TypeAlias, TypedDict __all__ = [ "FileBatchCreateParams", @@ -56,6 +56,6 @@ class ChunkingStrategyStaticChunkingStrategyRequestParam(TypedDict, total=False) """Always `static`.""" -ChunkingStrategy = Union[ +ChunkingStrategy: TypeAlias = Union[ ChunkingStrategyAutoChunkingStrategyRequestParam, ChunkingStrategyStaticChunkingStrategyRequestParam ] diff --git a/src/openai/types/beta/vector_stores/file_create_params.py b/src/openai/types/beta/vector_stores/file_create_params.py index 2ae63f1462..cfb80657c6 100644 --- a/src/openai/types/beta/vector_stores/file_create_params.py +++ b/src/openai/types/beta/vector_stores/file_create_params.py @@ -3,7 +3,7 @@ from __future__ import annotations from typing import Union -from typing_extensions import Literal, Required, TypedDict +from typing_extensions import Literal, Required, TypeAlias, TypedDict __all__ = [ "FileCreateParams", @@ -56,6 +56,6 @@ class ChunkingStrategyStaticChunkingStrategyRequestParam(TypedDict, total=False) """Always `static`.""" -ChunkingStrategy = Union[ +ChunkingStrategy: TypeAlias = Union[ ChunkingStrategyAutoChunkingStrategyRequestParam, ChunkingStrategyStaticChunkingStrategyRequestParam ] diff --git a/src/openai/types/beta/vector_stores/vector_store_file.py b/src/openai/types/beta/vector_stores/vector_store_file.py index d9d7625f86..4762de0ebd 100644 --- a/src/openai/types/beta/vector_stores/vector_store_file.py +++ b/src/openai/types/beta/vector_stores/vector_store_file.py @@ -1,7 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Union, Optional -from typing_extensions import Literal, Annotated +from typing_extensions import Literal, Annotated, TypeAlias from ...._utils import PropertyInfo from ...._models import BaseModel @@ -51,7 +51,9 @@ class ChunkingStrategyOther(BaseModel): """Always `other`.""" -ChunkingStrategy = Annotated[Union[ChunkingStrategyStatic, ChunkingStrategyOther], PropertyInfo(discriminator="type")] +ChunkingStrategy: TypeAlias = Annotated[ + Union[ChunkingStrategyStatic, ChunkingStrategyOther], PropertyInfo(discriminator="type") +] class VectorStoreFile(BaseModel): diff --git a/src/openai/types/chat/chat_completion_content_part_param.py b/src/openai/types/chat/chat_completion_content_part_param.py index f9b5f71e43..e0c6e480f2 100644 --- a/src/openai/types/chat/chat_completion_content_part_param.py +++ b/src/openai/types/chat/chat_completion_content_part_param.py @@ -3,10 +3,13 @@ from __future__ import annotations from typing import Union +from typing_extensions import TypeAlias from .chat_completion_content_part_text_param import ChatCompletionContentPartTextParam from .chat_completion_content_part_image_param import ChatCompletionContentPartImageParam __all__ = ["ChatCompletionContentPartParam"] -ChatCompletionContentPartParam = Union[ChatCompletionContentPartTextParam, ChatCompletionContentPartImageParam] +ChatCompletionContentPartParam: TypeAlias = Union[ + ChatCompletionContentPartTextParam, ChatCompletionContentPartImageParam +] diff --git a/src/openai/types/chat/chat_completion_message_param.py b/src/openai/types/chat/chat_completion_message_param.py index a3644a5310..ec65d94cae 100644 --- a/src/openai/types/chat/chat_completion_message_param.py +++ b/src/openai/types/chat/chat_completion_message_param.py @@ -3,6 +3,7 @@ from __future__ import annotations from typing import Union +from typing_extensions import TypeAlias from .chat_completion_tool_message_param import ChatCompletionToolMessageParam from .chat_completion_user_message_param import ChatCompletionUserMessageParam @@ -12,7 +13,7 @@ __all__ = ["ChatCompletionMessageParam"] -ChatCompletionMessageParam = Union[ +ChatCompletionMessageParam: TypeAlias = Union[ ChatCompletionSystemMessageParam, ChatCompletionUserMessageParam, ChatCompletionAssistantMessageParam, diff --git a/src/openai/types/chat/chat_completion_role.py b/src/openai/types/chat/chat_completion_role.py index 1fd83888d3..c2ebef74c8 100644 --- a/src/openai/types/chat/chat_completion_role.py +++ b/src/openai/types/chat/chat_completion_role.py @@ -1,7 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias __all__ = ["ChatCompletionRole"] -ChatCompletionRole = Literal["system", "user", "assistant", "tool", "function"] +ChatCompletionRole: TypeAlias = Literal["system", "user", "assistant", "tool", "function"] diff --git a/src/openai/types/chat/chat_completion_tool_choice_option_param.py b/src/openai/types/chat/chat_completion_tool_choice_option_param.py index 1d3c2506ab..7dedf041b7 100644 --- a/src/openai/types/chat/chat_completion_tool_choice_option_param.py +++ b/src/openai/types/chat/chat_completion_tool_choice_option_param.py @@ -3,10 +3,12 @@ from __future__ import annotations from typing import Union -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias from .chat_completion_named_tool_choice_param import ChatCompletionNamedToolChoiceParam __all__ = ["ChatCompletionToolChoiceOptionParam"] -ChatCompletionToolChoiceOptionParam = Union[Literal["none", "auto", "required"], ChatCompletionNamedToolChoiceParam] +ChatCompletionToolChoiceOptionParam: TypeAlias = Union[ + Literal["none", "auto", "required"], ChatCompletionNamedToolChoiceParam +] diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 783922539f..9e81881b9e 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -3,7 +3,7 @@ from __future__ import annotations from typing import Dict, List, Union, Iterable, Optional -from typing_extensions import Literal, Required, TypedDict +from typing_extensions import Literal, Required, TypeAlias, TypedDict from ...types import shared_params from ..chat_model import ChatModel @@ -221,7 +221,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): """ -FunctionCall = Union[Literal["none", "auto"], ChatCompletionFunctionCallOptionParam] +FunctionCall: TypeAlias = Union[Literal["none", "auto"], ChatCompletionFunctionCallOptionParam] class Function(TypedDict, total=False): diff --git a/src/openai/types/chat_model.py b/src/openai/types/chat_model.py index 87b2acb90a..edb7b732bf 100644 --- a/src/openai/types/chat_model.py +++ b/src/openai/types/chat_model.py @@ -1,10 +1,10 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias __all__ = ["ChatModel"] -ChatModel = Literal[ +ChatModel: TypeAlias = Literal[ "gpt-4o", "gpt-4o-2024-05-13", "gpt-4o-mini", diff --git a/src/openai/types/file_content.py b/src/openai/types/file_content.py index b4aa08a9a3..d89eee623e 100644 --- a/src/openai/types/file_content.py +++ b/src/openai/types/file_content.py @@ -1,6 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +from typing_extensions import TypeAlias __all__ = ["FileContent"] -FileContent = str +FileContent: TypeAlias = str diff --git a/src/openai/types/image_model.py b/src/openai/types/image_model.py index ce6535ff2c..1672369bea 100644 --- a/src/openai/types/image_model.py +++ b/src/openai/types/image_model.py @@ -1,7 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias __all__ = ["ImageModel"] -ImageModel = Literal["dall-e-2", "dall-e-3"] +ImageModel: TypeAlias = Literal["dall-e-2", "dall-e-3"] diff --git a/src/openai/types/moderation_model.py b/src/openai/types/moderation_model.py index 73362596f3..f549aeeb7a 100644 --- a/src/openai/types/moderation_model.py +++ b/src/openai/types/moderation_model.py @@ -1,7 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias __all__ = ["ModerationModel"] -ModerationModel = Literal["text-moderation-latest", "text-moderation-stable"] +ModerationModel: TypeAlias = Literal["text-moderation-latest", "text-moderation-stable"] diff --git a/src/openai/types/shared/function_parameters.py b/src/openai/types/shared/function_parameters.py index c9524e4cb8..a3d83e3496 100644 --- a/src/openai/types/shared/function_parameters.py +++ b/src/openai/types/shared/function_parameters.py @@ -1,7 +1,8 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Dict +from typing_extensions import TypeAlias __all__ = ["FunctionParameters"] -FunctionParameters = Dict[str, object] +FunctionParameters: TypeAlias = Dict[str, object] diff --git a/src/openai/types/shared_params/function_parameters.py b/src/openai/types/shared_params/function_parameters.py index 5b40efb78f..45fc742d3b 100644 --- a/src/openai/types/shared_params/function_parameters.py +++ b/src/openai/types/shared_params/function_parameters.py @@ -3,7 +3,8 @@ from __future__ import annotations from typing import Dict +from typing_extensions import TypeAlias __all__ = ["FunctionParameters"] -FunctionParameters = Dict[str, object] +FunctionParameters: TypeAlias = Dict[str, object] From 5c7030ed6622f1f10000816a1bc0f98b719afdd7 Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Mon, 5 Aug 2024 11:51:22 +0000 Subject: [PATCH 439/816] chore(internal): bump pyright (#1599) --- requirements-dev.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.lock b/requirements-dev.lock index 21a6b8d20c..3ad6b88f68 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -123,7 +123,7 @@ pygments==2.18.0 # via rich pyjwt==2.8.0 # via msal -pyright==1.1.364 +pyright==1.1.374 pytest==7.1.1 # via pytest-asyncio pytest-asyncio==0.21.1 From 98d8b2ac13ce7b22fd9ce237157bc1be593c7362 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 5 Aug 2024 13:20:50 +0000 Subject: [PATCH 440/816] feat(client): add `retries_taken` to raw response class (#1601) --- src/openai/_base_client.py | 10 +++ src/openai/_legacy_response.py | 18 ++++- src/openai/_response.py | 5 ++ tests/test_client.py | 122 +++++++++++++++++++++++++++++++++ 4 files changed, 154 insertions(+), 1 deletion(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 4b93ab298c..c8fce0bea4 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -1051,6 +1051,7 @@ def _request( response=response, stream=stream, stream_cls=stream_cls, + retries_taken=options.get_max_retries(self.max_retries) - retries, ) def _retry_request( @@ -1092,6 +1093,7 @@ def _process_response( response: httpx.Response, stream: bool, stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None, + retries_taken: int = 0, ) -> ResponseT: if response.request.headers.get(RAW_RESPONSE_HEADER) == "true": return cast( @@ -1103,6 +1105,7 @@ def _process_response( stream=stream, stream_cls=stream_cls, options=options, + retries_taken=retries_taken, ), ) @@ -1122,6 +1125,7 @@ def _process_response( stream=stream, stream_cls=stream_cls, options=options, + retries_taken=retries_taken, ), ) @@ -1135,6 +1139,7 @@ def _process_response( stream=stream, stream_cls=stream_cls, options=options, + retries_taken=retries_taken, ) if bool(response.request.headers.get(RAW_RESPONSE_HEADER)): return cast(ResponseT, api_response) @@ -1625,6 +1630,7 @@ async def _request( response=response, stream=stream, stream_cls=stream_cls, + retries_taken=options.get_max_retries(self.max_retries) - retries, ) async def _retry_request( @@ -1664,6 +1670,7 @@ async def _process_response( response: httpx.Response, stream: bool, stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None, + retries_taken: int = 0, ) -> ResponseT: if response.request.headers.get(RAW_RESPONSE_HEADER) == "true": return cast( @@ -1675,6 +1682,7 @@ async def _process_response( stream=stream, stream_cls=stream_cls, options=options, + retries_taken=retries_taken, ), ) @@ -1694,6 +1702,7 @@ async def _process_response( stream=stream, stream_cls=stream_cls, options=options, + retries_taken=retries_taken, ), ) @@ -1707,6 +1716,7 @@ async def _process_response( stream=stream, stream_cls=stream_cls, options=options, + retries_taken=retries_taken, ) if bool(response.request.headers.get(RAW_RESPONSE_HEADER)): return cast(ResponseT, api_response) diff --git a/src/openai/_legacy_response.py b/src/openai/_legacy_response.py index 1de906b167..66d7606a60 100644 --- a/src/openai/_legacy_response.py +++ b/src/openai/_legacy_response.py @@ -5,7 +5,18 @@ import logging import datetime import functools -from typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, Iterator, AsyncIterator, cast, overload +from typing import ( + TYPE_CHECKING, + Any, + Union, + Generic, + TypeVar, + Callable, + Iterator, + AsyncIterator, + cast, + overload, +) from typing_extensions import Awaitable, ParamSpec, override, deprecated, get_origin import anyio @@ -53,6 +64,9 @@ class LegacyAPIResponse(Generic[R]): http_response: httpx.Response + retries_taken: int + """The number of retries made. If no retries happened this will be `0`""" + def __init__( self, *, @@ -62,6 +76,7 @@ def __init__( stream: bool, stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None, options: FinalRequestOptions, + retries_taken: int = 0, ) -> None: self._cast_to = cast_to self._client = client @@ -70,6 +85,7 @@ def __init__( self._stream_cls = stream_cls self._options = options self.http_response = raw + self.retries_taken = retries_taken @property def request_id(self) -> str | None: diff --git a/src/openai/_response.py b/src/openai/_response.py index 4ba2ae681c..3bf4de4287 100644 --- a/src/openai/_response.py +++ b/src/openai/_response.py @@ -55,6 +55,9 @@ class BaseAPIResponse(Generic[R]): http_response: httpx.Response + retries_taken: int + """The number of retries made. If no retries happened this will be `0`""" + def __init__( self, *, @@ -64,6 +67,7 @@ def __init__( stream: bool, stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None, options: FinalRequestOptions, + retries_taken: int = 0, ) -> None: self._cast_to = cast_to self._client = client @@ -72,6 +76,7 @@ def __init__( self._stream_cls = stream_cls self._options = options self.http_response = raw + self.retries_taken = retries_taken @property def headers(self) -> httpx.Headers: diff --git a/tests/test_client.py b/tests/test_client.py index c1e545e66f..49e71653c5 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -758,6 +758,65 @@ def test_retrying_status_errors_doesnt_leak(self, respx_mock: MockRouter) -> Non assert _get_open_connections(self.client) == 0 + @pytest.mark.parametrize("failures_before_success", [0, 2, 4]) + @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) + @pytest.mark.respx(base_url=base_url) + def test_retries_taken(self, client: OpenAI, failures_before_success: int, respx_mock: MockRouter) -> None: + client = client.with_options(max_retries=4) + + nb_retries = 0 + + def retry_handler(_request: httpx.Request) -> httpx.Response: + nonlocal nb_retries + if nb_retries < failures_before_success: + nb_retries += 1 + return httpx.Response(500) + return httpx.Response(200) + + respx_mock.post("/chat/completions").mock(side_effect=retry_handler) + + response = client.chat.completions.with_raw_response.create( + messages=[ + { + "content": "content", + "role": "system", + } + ], + model="gpt-4-turbo", + ) + + assert response.retries_taken == failures_before_success + + @pytest.mark.parametrize("failures_before_success", [0, 2, 4]) + @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) + @pytest.mark.respx(base_url=base_url) + def test_retries_taken_new_response_class( + self, client: OpenAI, failures_before_success: int, respx_mock: MockRouter + ) -> None: + client = client.with_options(max_retries=4) + + nb_retries = 0 + + def retry_handler(_request: httpx.Request) -> httpx.Response: + nonlocal nb_retries + if nb_retries < failures_before_success: + nb_retries += 1 + return httpx.Response(500) + return httpx.Response(200) + + respx_mock.post("/chat/completions").mock(side_effect=retry_handler) + + with client.chat.completions.with_streaming_response.create( + messages=[ + { + "content": "content", + "role": "system", + } + ], + model="gpt-4-turbo", + ) as response: + assert response.retries_taken == failures_before_success + class TestAsyncOpenAI: client = AsyncOpenAI(base_url=base_url, api_key=api_key, _strict_response_validation=True) @@ -1488,3 +1547,66 @@ async def test_retrying_status_errors_doesnt_leak(self, respx_mock: MockRouter) ) assert _get_open_connections(self.client) == 0 + + @pytest.mark.parametrize("failures_before_success", [0, 2, 4]) + @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) + @pytest.mark.respx(base_url=base_url) + @pytest.mark.asyncio + async def test_retries_taken( + self, async_client: AsyncOpenAI, failures_before_success: int, respx_mock: MockRouter + ) -> None: + client = async_client.with_options(max_retries=4) + + nb_retries = 0 + + def retry_handler(_request: httpx.Request) -> httpx.Response: + nonlocal nb_retries + if nb_retries < failures_before_success: + nb_retries += 1 + return httpx.Response(500) + return httpx.Response(200) + + respx_mock.post("/chat/completions").mock(side_effect=retry_handler) + + response = await client.chat.completions.with_raw_response.create( + messages=[ + { + "content": "content", + "role": "system", + } + ], + model="gpt-4-turbo", + ) + + assert response.retries_taken == failures_before_success + + @pytest.mark.parametrize("failures_before_success", [0, 2, 4]) + @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) + @pytest.mark.respx(base_url=base_url) + @pytest.mark.asyncio + async def test_retries_taken_new_response_class( + self, async_client: AsyncOpenAI, failures_before_success: int, respx_mock: MockRouter + ) -> None: + client = async_client.with_options(max_retries=4) + + nb_retries = 0 + + def retry_handler(_request: httpx.Request) -> httpx.Response: + nonlocal nb_retries + if nb_retries < failures_before_success: + nb_retries += 1 + return httpx.Response(500) + return httpx.Response(200) + + respx_mock.post("/chat/completions").mock(side_effect=retry_handler) + + async with client.chat.completions.with_streaming_response.create( + messages=[ + { + "content": "content", + "role": "system", + } + ], + model="gpt-4-turbo", + ) as response: + assert response.retries_taken == failures_before_success From d50550bd5b4b6b4385b6327dc2cbc679b8dd29fd Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 5 Aug 2024 15:21:01 +0100 Subject: [PATCH 441/816] fix(assistants): add parallel_tool_calls param to runs.stream --- src/openai/resources/beta/threads/runs/runs.py | 8 ++++++++ tests/lib/test_assistants.py | 11 +++++++++++ 2 files changed, 19 insertions(+) diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 61c6bb486f..23a09d30ce 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -950,6 +950,7 @@ def stream( max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -979,6 +980,7 @@ def stream( max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -1008,6 +1010,7 @@ def stream( max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -1051,6 +1054,7 @@ def stream( "tool_choice": tool_choice, "stream": True, "tools": tools, + "parallel_tool_calls": parallel_tool_calls, "truncation_strategy": truncation_strategy, "top_p": top_p, }, @@ -2246,6 +2250,7 @@ def stream( max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -2275,6 +2280,7 @@ def stream( max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -2304,6 +2310,7 @@ def stream( max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -2349,6 +2356,7 @@ def stream( "tool_choice": tool_choice, "stream": True, "tools": tools, + "parallel_tool_calls": parallel_tool_calls, "truncation_strategy": truncation_strategy, "top_p": top_p, }, diff --git a/tests/lib/test_assistants.py b/tests/lib/test_assistants.py index b9d4e8927c..67d021ec35 100644 --- a/tests/lib/test_assistants.py +++ b/tests/lib/test_assistants.py @@ -28,6 +28,17 @@ def test_create_and_run_stream_method_definition_in_sync(sync: bool, client: Ope ) +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +def test_run_stream_method_definition_in_sync(sync: bool, client: OpenAI, async_client: AsyncOpenAI) -> None: + checking_client: OpenAI | AsyncOpenAI = client if sync else async_client + + assert_signatures_in_sync( + checking_client.beta.threads.runs.create, + checking_client.beta.threads.runs.stream, + exclude_params={"stream"}, + ) + + @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) def test_create_and_poll_method_definition_in_sync(sync: bool, client: OpenAI, async_client: AsyncOpenAI) -> None: checking_client: OpenAI | AsyncOpenAI = client if sync else async_client From 30194f1955f2272e7af8b54fba3732d7a7e60307 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 5 Aug 2024 14:31:39 +0000 Subject: [PATCH 442/816] chore(internal): test updates (#1602) --- src/openai/_utils/_reflection.py | 2 +- tests/test_client.py | 7 +++++-- tests/utils.py | 10 +++++++--- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/openai/_utils/_reflection.py b/src/openai/_utils/_reflection.py index 9a53c7bd21..89aa712ac4 100644 --- a/src/openai/_utils/_reflection.py +++ b/src/openai/_utils/_reflection.py @@ -34,7 +34,7 @@ def assert_signatures_in_sync( if custom_param.annotation != source_param.annotation: errors.append( - f"types for the `{name}` param are do not match; source={repr(source_param.annotation)} checking={repr(source_param.annotation)}" + f"types for the `{name}` param are do not match; source={repr(source_param.annotation)} checking={repr(custom_param.annotation)}" ) continue diff --git a/tests/test_client.py b/tests/test_client.py index 49e71653c5..2402ffa82f 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -17,6 +17,7 @@ from pydantic import ValidationError from openai import OpenAI, AsyncOpenAI, APIResponseValidationError +from openai._types import Omit from openai._models import BaseModel, FinalRequestOptions from openai._constants import RAW_RESPONSE_HEADER from openai._streaming import Stream, AsyncStream @@ -328,7 +329,8 @@ def test_validate_headers(self) -> None: assert request.headers.get("Authorization") == f"Bearer {api_key}" with pytest.raises(OpenAIError): - client2 = OpenAI(base_url=base_url, api_key=None, _strict_response_validation=True) + with update_env(**{"OPENAI_API_KEY": Omit()}): + client2 = OpenAI(base_url=base_url, api_key=None, _strict_response_validation=True) _ = client2 def test_default_query_option(self) -> None: @@ -1103,7 +1105,8 @@ def test_validate_headers(self) -> None: assert request.headers.get("Authorization") == f"Bearer {api_key}" with pytest.raises(OpenAIError): - client2 = AsyncOpenAI(base_url=base_url, api_key=None, _strict_response_validation=True) + with update_env(**{"OPENAI_API_KEY": Omit()}): + client2 = AsyncOpenAI(base_url=base_url, api_key=None, _strict_response_validation=True) _ = client2 def test_default_query_option(self) -> None: diff --git a/tests/utils.py b/tests/utils.py index 060b99339f..165f4e5bfd 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -8,7 +8,7 @@ from datetime import date, datetime from typing_extensions import Literal, get_args, get_origin, assert_type -from openai._types import NoneType +from openai._types import Omit, NoneType from openai._utils import ( is_dict, is_list, @@ -139,11 +139,15 @@ def _assert_list_type(type_: type[object], value: object) -> None: @contextlib.contextmanager -def update_env(**new_env: str) -> Iterator[None]: +def update_env(**new_env: str | Omit) -> Iterator[None]: old = os.environ.copy() try: - os.environ.update(new_env) + for name, value in new_env.items(): + if isinstance(value, Omit): + os.environ.pop(name, None) + else: + os.environ[name] = value yield None finally: From a5f5c8ed9a0f2658214525011507e3091c186bdf Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 5 Aug 2024 14:32:09 +0000 Subject: [PATCH 443/816] release: 1.39.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 20 ++++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 23 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index b90a705e63..4d14a67e1c 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.38.0" + ".": "1.39.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f62f6689d..b9cc30e307 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,25 @@ # Changelog +## 1.39.0 (2024-08-05) + +Full Changelog: [v1.38.0...v1.39.0](https://github.com/openai/openai-python/compare/v1.38.0...v1.39.0) + +### Features + +* **client:** add `retries_taken` to raw response class ([#1601](https://github.com/openai/openai-python/issues/1601)) ([777822b](https://github.com/openai/openai-python/commit/777822b39b7f9ebd6272d0af8fc04f9d657bd886)) + + +### Bug Fixes + +* **assistants:** add parallel_tool_calls param to runs.stream ([113e82a](https://github.com/openai/openai-python/commit/113e82a82c7390660ad3324fa8f9842f83b27571)) + + +### Chores + +* **internal:** bump pyright ([#1599](https://github.com/openai/openai-python/issues/1599)) ([27f0f10](https://github.com/openai/openai-python/commit/27f0f107e39d16adc0d5a50ffe4c687e0e3c42e5)) +* **internal:** test updates ([#1602](https://github.com/openai/openai-python/issues/1602)) ([af22d80](https://github.com/openai/openai-python/commit/af22d8079cf44cde5f03a206e78b900f8413dc43)) +* **internal:** use `TypeAlias` marker for type assignments ([#1597](https://github.com/openai/openai-python/issues/1597)) ([5907ea0](https://github.com/openai/openai-python/commit/5907ea04d6f5e0ffd17c38ad6a644a720ece8abe)) + ## 1.38.0 (2024-08-02) Full Changelog: [v1.37.2...v1.38.0](https://github.com/openai/openai-python/compare/v1.37.2...v1.38.0) diff --git a/pyproject.toml b/pyproject.toml index 0d736aa444..d0527bd84e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.38.0" +version = "1.39.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index ea1c039fab..aed8ee29b2 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.38.0" # x-release-please-version +__version__ = "1.39.0" # x-release-please-version From 1d8a28e39a9389b36b93770da248926b052b3e28 Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Tue, 6 Aug 2024 10:28:23 +0000 Subject: [PATCH 444/816] chore(internal): bump ruff version (#1604) --- pyproject.toml | 12 ++++--- requirements-dev.lock | 2 +- src/openai/_base_client.py | 63 +++++++++++---------------------- src/openai/_compat.py | 24 +++++-------- src/openai/_files.py | 12 +++---- src/openai/_legacy_response.py | 6 ++-- src/openai/_response.py | 12 +++---- src/openai/_types.py | 9 ++--- src/openai/_utils/_proxy.py | 3 +- src/openai/_utils/_utils.py | 18 ++++------ src/openai/cli/_errors.py | 6 ++-- src/openai/lib/azure.py | 18 ++++------ tests/test_deepcopy.py | 3 +- tests/test_legacy_response.py | 3 +- tests/test_response.py | 12 +++---- tests/test_utils/test_typing.py | 15 +++----- 16 files changed, 76 insertions(+), 142 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index d0527bd84e..99e0fc6591 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -83,8 +83,8 @@ format = { chain = [ "check:ruff", "typecheck", ]} -"check:ruff" = "ruff ." -"fix:ruff" = "ruff --fix ." +"check:ruff" = "ruff check ." +"fix:ruff" = "ruff check --fix ." typecheck = { chain = [ "typecheck:pyright", @@ -168,6 +168,11 @@ reportPrivateUsage = false line-length = 120 output-format = "grouped" target-version = "py37" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] select = [ # isort "I", @@ -198,9 +203,6 @@ unfixable = [ ] ignore-init-module-imports = true -[tool.ruff.format] -docstring-code-format = true - [tool.ruff.lint.flake8-tidy-imports.banned-api] "functools.lru_cache".msg = "This function does not retain type information for the wrapped function's arguments; The `lru_cache` function from `_utils` should be used instead" diff --git a/requirements-dev.lock b/requirements-dev.lock index 3ad6b88f68..d2ad945343 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -139,7 +139,7 @@ requests==2.31.0 respx==0.20.2 rich==13.7.1 # via inline-snapshot -ruff==0.1.9 +ruff==0.5.6 setuptools==68.2.2 # via nodeenv six==1.16.0 diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index c8fce0bea4..3388d69fab 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -125,16 +125,14 @@ def __init__( self, *, url: URL, - ) -> None: - ... + ) -> None: ... @overload def __init__( self, *, params: Query, - ) -> None: - ... + ) -> None: ... def __init__( self, @@ -167,8 +165,7 @@ def has_next_page(self) -> bool: return False return self.next_page_info() is not None - def next_page_info(self) -> Optional[PageInfo]: - ... + def next_page_info(self) -> Optional[PageInfo]: ... def _get_page_items(self) -> Iterable[_T]: # type: ignore[empty-body] ... @@ -904,8 +901,7 @@ def request( *, stream: Literal[True], stream_cls: Type[_StreamT], - ) -> _StreamT: - ... + ) -> _StreamT: ... @overload def request( @@ -915,8 +911,7 @@ def request( remaining_retries: Optional[int] = None, *, stream: Literal[False] = False, - ) -> ResponseT: - ... + ) -> ResponseT: ... @overload def request( @@ -927,8 +922,7 @@ def request( *, stream: bool = False, stream_cls: Type[_StreamT] | None = None, - ) -> ResponseT | _StreamT: - ... + ) -> ResponseT | _StreamT: ... def request( self, @@ -1172,8 +1166,7 @@ def get( cast_to: Type[ResponseT], options: RequestOptions = {}, stream: Literal[False] = False, - ) -> ResponseT: - ... + ) -> ResponseT: ... @overload def get( @@ -1184,8 +1177,7 @@ def get( options: RequestOptions = {}, stream: Literal[True], stream_cls: type[_StreamT], - ) -> _StreamT: - ... + ) -> _StreamT: ... @overload def get( @@ -1196,8 +1188,7 @@ def get( options: RequestOptions = {}, stream: bool, stream_cls: type[_StreamT] | None = None, - ) -> ResponseT | _StreamT: - ... + ) -> ResponseT | _StreamT: ... def get( self, @@ -1223,8 +1214,7 @@ def post( options: RequestOptions = {}, files: RequestFiles | None = None, stream: Literal[False] = False, - ) -> ResponseT: - ... + ) -> ResponseT: ... @overload def post( @@ -1237,8 +1227,7 @@ def post( files: RequestFiles | None = None, stream: Literal[True], stream_cls: type[_StreamT], - ) -> _StreamT: - ... + ) -> _StreamT: ... @overload def post( @@ -1251,8 +1240,7 @@ def post( files: RequestFiles | None = None, stream: bool, stream_cls: type[_StreamT] | None = None, - ) -> ResponseT | _StreamT: - ... + ) -> ResponseT | _StreamT: ... def post( self, @@ -1485,8 +1473,7 @@ async def request( *, stream: Literal[False] = False, remaining_retries: Optional[int] = None, - ) -> ResponseT: - ... + ) -> ResponseT: ... @overload async def request( @@ -1497,8 +1484,7 @@ async def request( stream: Literal[True], stream_cls: type[_AsyncStreamT], remaining_retries: Optional[int] = None, - ) -> _AsyncStreamT: - ... + ) -> _AsyncStreamT: ... @overload async def request( @@ -1509,8 +1495,7 @@ async def request( stream: bool, stream_cls: type[_AsyncStreamT] | None = None, remaining_retries: Optional[int] = None, - ) -> ResponseT | _AsyncStreamT: - ... + ) -> ResponseT | _AsyncStreamT: ... async def request( self, @@ -1739,8 +1724,7 @@ async def get( cast_to: Type[ResponseT], options: RequestOptions = {}, stream: Literal[False] = False, - ) -> ResponseT: - ... + ) -> ResponseT: ... @overload async def get( @@ -1751,8 +1735,7 @@ async def get( options: RequestOptions = {}, stream: Literal[True], stream_cls: type[_AsyncStreamT], - ) -> _AsyncStreamT: - ... + ) -> _AsyncStreamT: ... @overload async def get( @@ -1763,8 +1746,7 @@ async def get( options: RequestOptions = {}, stream: bool, stream_cls: type[_AsyncStreamT] | None = None, - ) -> ResponseT | _AsyncStreamT: - ... + ) -> ResponseT | _AsyncStreamT: ... async def get( self, @@ -1788,8 +1770,7 @@ async def post( files: RequestFiles | None = None, options: RequestOptions = {}, stream: Literal[False] = False, - ) -> ResponseT: - ... + ) -> ResponseT: ... @overload async def post( @@ -1802,8 +1783,7 @@ async def post( options: RequestOptions = {}, stream: Literal[True], stream_cls: type[_AsyncStreamT], - ) -> _AsyncStreamT: - ... + ) -> _AsyncStreamT: ... @overload async def post( @@ -1816,8 +1796,7 @@ async def post( options: RequestOptions = {}, stream: bool, stream_cls: type[_AsyncStreamT] | None = None, - ) -> ResponseT | _AsyncStreamT: - ... + ) -> ResponseT | _AsyncStreamT: ... async def post( self, diff --git a/src/openai/_compat.py b/src/openai/_compat.py index c919b5adb3..7c6f91a870 100644 --- a/src/openai/_compat.py +++ b/src/openai/_compat.py @@ -159,22 +159,19 @@ def model_parse(model: type[_ModelT], data: Any) -> _ModelT: # generic models if TYPE_CHECKING: - class GenericModel(pydantic.BaseModel): - ... + class GenericModel(pydantic.BaseModel): ... else: if PYDANTIC_V2: # there no longer needs to be a distinction in v2 but # we still have to create our own subclass to avoid # inconsistent MRO ordering errors - class GenericModel(pydantic.BaseModel): - ... + class GenericModel(pydantic.BaseModel): ... else: import pydantic.generics - class GenericModel(pydantic.generics.GenericModel, pydantic.BaseModel): - ... + class GenericModel(pydantic.generics.GenericModel, pydantic.BaseModel): ... # cached properties @@ -193,26 +190,21 @@ class typed_cached_property(Generic[_T]): func: Callable[[Any], _T] attrname: str | None - def __init__(self, func: Callable[[Any], _T]) -> None: - ... + def __init__(self, func: Callable[[Any], _T]) -> None: ... @overload - def __get__(self, instance: None, owner: type[Any] | None = None) -> Self: - ... + def __get__(self, instance: None, owner: type[Any] | None = None) -> Self: ... @overload - def __get__(self, instance: object, owner: type[Any] | None = None) -> _T: - ... + def __get__(self, instance: object, owner: type[Any] | None = None) -> _T: ... def __get__(self, instance: object, owner: type[Any] | None = None) -> _T | Self: raise NotImplementedError() - def __set_name__(self, owner: type[Any], name: str) -> None: - ... + def __set_name__(self, owner: type[Any], name: str) -> None: ... # __set__ is not defined at runtime, but @cached_property is designed to be settable - def __set__(self, instance: object, value: _T) -> None: - ... + def __set__(self, instance: object, value: _T) -> None: ... else: try: from functools import cached_property as cached_property diff --git a/src/openai/_files.py b/src/openai/_files.py index ad7b668b4b..801a0d2928 100644 --- a/src/openai/_files.py +++ b/src/openai/_files.py @@ -39,13 +39,11 @@ def assert_is_file_content(obj: object, *, key: str | None = None) -> None: @overload -def to_httpx_files(files: None) -> None: - ... +def to_httpx_files(files: None) -> None: ... @overload -def to_httpx_files(files: RequestFiles) -> HttpxRequestFiles: - ... +def to_httpx_files(files: RequestFiles) -> HttpxRequestFiles: ... def to_httpx_files(files: RequestFiles | None) -> HttpxRequestFiles | None: @@ -83,13 +81,11 @@ def _read_file_content(file: FileContent) -> HttpxFileContent: @overload -async def async_to_httpx_files(files: None) -> None: - ... +async def async_to_httpx_files(files: None) -> None: ... @overload -async def async_to_httpx_files(files: RequestFiles) -> HttpxRequestFiles: - ... +async def async_to_httpx_files(files: RequestFiles) -> HttpxRequestFiles: ... async def async_to_httpx_files(files: RequestFiles | None) -> HttpxRequestFiles | None: diff --git a/src/openai/_legacy_response.py b/src/openai/_legacy_response.py index 66d7606a60..c42fb8b83e 100644 --- a/src/openai/_legacy_response.py +++ b/src/openai/_legacy_response.py @@ -92,12 +92,10 @@ def request_id(self) -> str | None: return self.http_response.headers.get("x-request-id") # type: ignore[no-any-return] @overload - def parse(self, *, to: type[_T]) -> _T: - ... + def parse(self, *, to: type[_T]) -> _T: ... @overload - def parse(self) -> R: - ... + def parse(self) -> R: ... def parse(self, *, to: type[_T] | None = None) -> R | _T: """Returns the rich python representation of this response's data. diff --git a/src/openai/_response.py b/src/openai/_response.py index 3bf4de4287..f9d91786f6 100644 --- a/src/openai/_response.py +++ b/src/openai/_response.py @@ -268,12 +268,10 @@ def request_id(self) -> str | None: return self.http_response.headers.get("x-request-id") # type: ignore[no-any-return] @overload - def parse(self, *, to: type[_T]) -> _T: - ... + def parse(self, *, to: type[_T]) -> _T: ... @overload - def parse(self) -> R: - ... + def parse(self) -> R: ... def parse(self, *, to: type[_T] | None = None) -> R | _T: """Returns the rich python representation of this response's data. @@ -376,12 +374,10 @@ def request_id(self) -> str | None: return self.http_response.headers.get("x-request-id") # type: ignore[no-any-return] @overload - async def parse(self, *, to: type[_T]) -> _T: - ... + async def parse(self, *, to: type[_T]) -> _T: ... @overload - async def parse(self) -> R: - ... + async def parse(self) -> R: ... async def parse(self, *, to: type[_T] | None = None) -> R | _T: """Returns the rich python representation of this response's data. diff --git a/src/openai/_types.py b/src/openai/_types.py index de9b1dd48b..5611b2d38f 100644 --- a/src/openai/_types.py +++ b/src/openai/_types.py @@ -112,8 +112,7 @@ class NotGiven: For example: ```py - def get(timeout: Union[int, NotGiven, None] = NotGiven()) -> Response: - ... + def get(timeout: Union[int, NotGiven, None] = NotGiven()) -> Response: ... get(timeout=1) # 1s timeout @@ -163,16 +162,14 @@ def build( *, response: Response, data: object, - ) -> _T: - ... + ) -> _T: ... Headers = Mapping[str, Union[str, Omit]] class HeadersLikeProtocol(Protocol): - def get(self, __key: str) -> str | None: - ... + def get(self, __key: str) -> str | None: ... HeadersLike = Union[Headers, HeadersLikeProtocol] diff --git a/src/openai/_utils/_proxy.py b/src/openai/_utils/_proxy.py index c46a62a698..ffd883e9dd 100644 --- a/src/openai/_utils/_proxy.py +++ b/src/openai/_utils/_proxy.py @@ -59,5 +59,4 @@ def __as_proxied__(self) -> T: return cast(T, self) @abstractmethod - def __load__(self) -> T: - ... + def __load__(self) -> T: ... diff --git a/src/openai/_utils/_utils.py b/src/openai/_utils/_utils.py index 34797c2905..2fc5a1c65a 100644 --- a/src/openai/_utils/_utils.py +++ b/src/openai/_utils/_utils.py @@ -211,20 +211,17 @@ def required_args(*variants: Sequence[str]) -> Callable[[CallableT], CallableT]: Example usage: ```py @overload - def foo(*, a: str) -> str: - ... + def foo(*, a: str) -> str: ... @overload - def foo(*, b: bool) -> str: - ... + def foo(*, b: bool) -> str: ... # This enforces the same constraints that a static type checker would # i.e. that either a or b must be passed to the function @required_args(["a"], ["b"]) - def foo(*, a: str | None = None, b: bool | None = None) -> str: - ... + def foo(*, a: str | None = None, b: bool | None = None) -> str: ... ``` """ @@ -286,18 +283,15 @@ def wrapper(*args: object, **kwargs: object) -> object: @overload -def strip_not_given(obj: None) -> None: - ... +def strip_not_given(obj: None) -> None: ... @overload -def strip_not_given(obj: Mapping[_K, _V | NotGiven]) -> dict[_K, _V]: - ... +def strip_not_given(obj: Mapping[_K, _V | NotGiven]) -> dict[_K, _V]: ... @overload -def strip_not_given(obj: object) -> object: - ... +def strip_not_given(obj: object) -> object: ... def strip_not_given(obj: object | None) -> object: diff --git a/src/openai/cli/_errors.py b/src/openai/cli/_errors.py index 2bf06070d6..7d0292dab2 100644 --- a/src/openai/cli/_errors.py +++ b/src/openai/cli/_errors.py @@ -8,12 +8,10 @@ from .._exceptions import APIError, OpenAIError -class CLIError(OpenAIError): - ... +class CLIError(OpenAIError): ... -class SilentCLIError(CLIError): - ... +class SilentCLIError(CLIError): ... def display_error(err: CLIError | APIError | pydantic.ValidationError) -> None: diff --git a/src/openai/lib/azure.py b/src/openai/lib/azure.py index 433486fded..ef64137de4 100644 --- a/src/openai/lib/azure.py +++ b/src/openai/lib/azure.py @@ -80,8 +80,7 @@ def __init__( default_query: Mapping[str, object] | None = None, http_client: httpx.Client | None = None, _strict_response_validation: bool = False, - ) -> None: - ... + ) -> None: ... @overload def __init__( @@ -99,8 +98,7 @@ def __init__( default_query: Mapping[str, object] | None = None, http_client: httpx.Client | None = None, _strict_response_validation: bool = False, - ) -> None: - ... + ) -> None: ... @overload def __init__( @@ -118,8 +116,7 @@ def __init__( default_query: Mapping[str, object] | None = None, http_client: httpx.Client | None = None, _strict_response_validation: bool = False, - ) -> None: - ... + ) -> None: ... def __init__( self, @@ -321,8 +318,7 @@ def __init__( default_query: Mapping[str, object] | None = None, http_client: httpx.AsyncClient | None = None, _strict_response_validation: bool = False, - ) -> None: - ... + ) -> None: ... @overload def __init__( @@ -341,8 +337,7 @@ def __init__( default_query: Mapping[str, object] | None = None, http_client: httpx.AsyncClient | None = None, _strict_response_validation: bool = False, - ) -> None: - ... + ) -> None: ... @overload def __init__( @@ -361,8 +356,7 @@ def __init__( default_query: Mapping[str, object] | None = None, http_client: httpx.AsyncClient | None = None, _strict_response_validation: bool = False, - ) -> None: - ... + ) -> None: ... def __init__( self, diff --git a/tests/test_deepcopy.py b/tests/test_deepcopy.py index 8cf65ce94e..86a2adb1a2 100644 --- a/tests/test_deepcopy.py +++ b/tests/test_deepcopy.py @@ -41,8 +41,7 @@ def test_nested_list() -> None: assert_different_identities(obj1[1], obj2[1]) -class MyObject: - ... +class MyObject: ... def test_ignores_other_types() -> None: diff --git a/tests/test_legacy_response.py b/tests/test_legacy_response.py index 45025f81d0..3659ee12c1 100644 --- a/tests/test_legacy_response.py +++ b/tests/test_legacy_response.py @@ -12,8 +12,7 @@ from openai._legacy_response import LegacyAPIResponse -class PydanticModel(pydantic.BaseModel): - ... +class PydanticModel(pydantic.BaseModel): ... def test_response_parse_mismatched_basemodel(client: OpenAI) -> None: diff --git a/tests/test_response.py b/tests/test_response.py index af153b67c4..6ea1be1a1a 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -19,16 +19,13 @@ from openai._base_client import FinalRequestOptions -class ConcreteBaseAPIResponse(APIResponse[bytes]): - ... +class ConcreteBaseAPIResponse(APIResponse[bytes]): ... -class ConcreteAPIResponse(APIResponse[List[str]]): - ... +class ConcreteAPIResponse(APIResponse[List[str]]): ... -class ConcreteAsyncAPIResponse(APIResponse[httpx.Response]): - ... +class ConcreteAsyncAPIResponse(APIResponse[httpx.Response]): ... def test_extract_response_type_direct_classes() -> None: @@ -56,8 +53,7 @@ def test_extract_response_type_binary_response() -> None: assert extract_response_type(AsyncBinaryAPIResponse) == bytes -class PydanticModel(pydantic.BaseModel): - ... +class PydanticModel(pydantic.BaseModel): ... def test_response_parse_mismatched_basemodel(client: OpenAI) -> None: diff --git a/tests/test_utils/test_typing.py b/tests/test_utils/test_typing.py index 690960802a..535935b9e1 100644 --- a/tests/test_utils/test_typing.py +++ b/tests/test_utils/test_typing.py @@ -9,24 +9,19 @@ _T3 = TypeVar("_T3") -class BaseGeneric(Generic[_T]): - ... +class BaseGeneric(Generic[_T]): ... -class SubclassGeneric(BaseGeneric[_T]): - ... +class SubclassGeneric(BaseGeneric[_T]): ... -class BaseGenericMultipleTypeArgs(Generic[_T, _T2, _T3]): - ... +class BaseGenericMultipleTypeArgs(Generic[_T, _T2, _T3]): ... -class SubclassGenericMultipleTypeArgs(BaseGenericMultipleTypeArgs[_T, _T2, _T3]): - ... +class SubclassGenericMultipleTypeArgs(BaseGenericMultipleTypeArgs[_T, _T2, _T3]): ... -class SubclassDifferentOrderGenericMultipleTypeArgs(BaseGenericMultipleTypeArgs[_T2, _T, _T3]): - ... +class SubclassDifferentOrderGenericMultipleTypeArgs(BaseGenericMultipleTypeArgs[_T2, _T, _T3]): ... def test_extract_type_var() -> None: From 762b9058a89235653dd538cfc03b847f6e5b1907 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 6 Aug 2024 15:02:40 +0000 Subject: [PATCH 445/816] chore(internal): update pydantic compat helper function (#1607) --- src/openai/_compat.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/openai/_compat.py b/src/openai/_compat.py index 7c6f91a870..21fe6941ce 100644 --- a/src/openai/_compat.py +++ b/src/openai/_compat.py @@ -7,7 +7,7 @@ import pydantic from pydantic.fields import FieldInfo -from ._types import StrBytesIntFloat +from ._types import IncEx, StrBytesIntFloat _T = TypeVar("_T") _ModelT = TypeVar("_ModelT", bound=pydantic.BaseModel) @@ -133,17 +133,20 @@ def model_json(model: pydantic.BaseModel, *, indent: int | None = None) -> str: def model_dump( model: pydantic.BaseModel, *, + exclude: IncEx = None, exclude_unset: bool = False, exclude_defaults: bool = False, ) -> dict[str, Any]: if PYDANTIC_V2: return model.model_dump( + exclude=exclude, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, ) return cast( "dict[str, Any]", model.dict( # pyright: ignore[reportDeprecated, reportUnnecessaryCast] + exclude=exclude, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, ), From bf1ca86cf392eb0ffed1e146937c5d73d8a568f0 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Tue, 6 Aug 2024 18:11:32 +0100 Subject: [PATCH 446/816] feat(api): add structured outputs support This commit adds support for JSON schema response format & adds a separate `.beta.chat.completions.parse()` method to automatically deserialise the response content into a Pydantic model. For more details on structured outputs, see this guide https://platform.openai.com/docs/guides/structured-outputs --- .github/workflows/ci.yml | 1 - .inline-snapshot/external/.gitignore | 2 + ...9cda31e5a0af80decdbddd21c056545c6d4616.bin | 100 ++ ...8ab9141d709b770a74dc025fb8770a42aabee9.bin | 180 +++ ...c4861e696495d9a45c19be02cf479e28c31316.bin | 12 + ...ec5f581ea9de2524599f06b0d405db8997b826.bin | 8 + ...0e08ddfad221d6632fdb200a95ca6c996238e2.bin | 52 + ...4b7ca16b9fadc5c4551ea066d305eb1607e1c6.bin | 28 + ...abc40785d712248f65c8595c99879080d0eeb9.bin | 36 + ...5521e0258cc2cef0528a17fbdadb9cc76695f0.bin | 72 ++ ...f05bd963fe093622e5bf9a95a3ebede64714bc.bin | 30 + ...194b58fc759adc3685170e0a61033241d2eda5.bin | 32 + ...ca00f3a963d785c6fe78c35d60d038cd7a8ba0.bin | 36 + ...13a82f959a175ec05ce3c07412bbc9fd436234.bin | 22 + .stats.yml | 2 +- api.md | 13 +- examples/parsing.py | 36 + examples/parsing_stream.py | 42 + examples/parsing_tools.py | 80 ++ examples/parsing_tools_stream.py | 38 + helpers.md | 276 ++++- pyproject.toml | 5 +- requirements-dev.lock | 4 +- requirements.lock | 4 +- src/openai/__init__.py | 6 +- src/openai/_client.py | 4 +- src/openai/_compat.py | 12 + src/openai/_exceptions.py | 16 + src/openai/lib/__init__.py | 2 + src/openai/lib/_parsing/__init__.py | 12 + src/openai/lib/_parsing/_completions.py | 254 ++++ src/openai/lib/_pydantic.py | 71 ++ src/openai/lib/_tools.py | 54 + src/openai/lib/streaming/_deltas.py | 64 + src/openai/lib/streaming/chat/__init__.py | 26 + src/openai/lib/streaming/chat/_completions.py | 724 ++++++++++++ src/openai/lib/streaming/chat/_events.py | 123 ++ src/openai/lib/streaming/chat/_types.py | 20 + src/openai/resources/beta/assistants.py | 20 + src/openai/resources/beta/beta.py | 9 + src/openai/resources/beta/chat/__init__.py | 11 + src/openai/resources/beta/chat/chat.py | 21 + src/openai/resources/beta/chat/completions.py | 449 +++++++ .../resources/beta/threads/runs/runs.py | 30 + src/openai/resources/beta/threads/threads.py | 30 + src/openai/resources/chat/completions.py | 16 +- src/openai/resources/fine_tuning/jobs/jobs.py | 12 +- src/openai/types/__init__.py | 3 + src/openai/types/beta/__init__.py | 2 - src/openai/types/beta/assistant.py | 5 + .../types/beta/assistant_create_params.py | 5 + .../types/beta/assistant_response_format.py | 13 - .../beta/assistant_response_format_option.py | 8 +- .../assistant_response_format_option_param.py | 9 +- .../beta/assistant_response_format_param.py | 12 - .../types/beta/assistant_update_params.py | 5 + src/openai/types/beta/file_search_tool.py | 4 +- .../types/beta/file_search_tool_param.py | 4 +- .../beta/thread_create_and_run_params.py | 5 + src/openai/types/beta/threads/__init__.py | 2 + .../types/beta/threads/message_content.py | 5 +- .../beta/threads/message_content_delta.py | 4 +- .../beta/threads/refusal_content_block.py | 14 + .../types/beta/threads/refusal_delta_block.py | 18 + src/openai/types/beta/threads/run.py | 5 + .../types/beta/threads/run_create_params.py | 5 + .../beta/vector_stores/vector_store_file.py | 2 +- src/openai/types/chat/__init__.py | 12 + src/openai/types/chat/chat_completion.py | 3 + ...chat_completion_assistant_message_param.py | 15 +- .../types/chat/chat_completion_chunk.py | 6 + ...t_completion_content_part_refusal_param.py | 15 + .../types/chat/chat_completion_message.py | 3 + .../chat_completion_system_message_param.py | 5 +- .../chat_completion_tool_message_param.py | 5 +- .../types/chat/completion_create_params.py | 9 +- .../types/chat/parsed_chat_completion.py | 40 + .../types/chat/parsed_function_tool_call.py | 29 + src/openai/types/chat_model.py | 1 + .../types/fine_tuning/job_create_params.py | 6 +- src/openai/types/shared/__init__.py | 3 + .../types/shared/function_definition.py | 9 + .../shared/response_format_json_object.py | 12 + .../shared/response_format_json_schema.py | 44 + .../types/shared/response_format_text.py | 12 + src/openai/types/shared_params/__init__.py | 3 + .../shared_params/function_definition.py | 10 + .../response_format_json_object.py | 12 + .../response_format_json_schema.py | 42 + .../shared_params/response_format_text.py | 12 + tests/api_resources/beta/test_assistants.py | 104 +- tests/api_resources/beta/test_threads.py | 16 +- tests/api_resources/beta/threads/test_runs.py | 16 +- tests/api_resources/chat/test_completions.py | 52 +- tests/api_resources/fine_tuning/test_jobs.py | 16 +- tests/api_resources/test_models.py | 24 +- tests/lib/__init__.py | 0 tests/lib/chat/__init__.py | 0 tests/lib/chat/_utils.py | 59 + tests/lib/chat/test_completions.py | 633 ++++++++++ tests/lib/chat/test_completions_streaming.py | 1047 +++++++++++++++++ tests/lib/schema_types/query.py | 51 + tests/lib/test_pydantic.py | 161 +++ tests/test_client.py | 16 +- 104 files changed, 5542 insertions(+), 188 deletions(-) create mode 100644 .inline-snapshot/external/.gitignore create mode 100644 .inline-snapshot/external/1437bd06a9d5c414e56fd0840b9cda31e5a0af80decdbddd21c056545c6d4616.bin create mode 100644 .inline-snapshot/external/3e0df46f250db854eacb34e3258ab9141d709b770a74dc025fb8770a42aabee9.bin create mode 100644 .inline-snapshot/external/70c7df71ce729e178fc5e54f0cc4861e696495d9a45c19be02cf479e28c31316.bin create mode 100644 .inline-snapshot/external/7ae6c1a2631bf7444b8f70b592ec5f581ea9de2524599f06b0d405db8997b826.bin create mode 100644 .inline-snapshot/external/a346213bec7a572810bd1ffe290e08ddfad221d6632fdb200a95ca6c996238e2.bin create mode 100644 .inline-snapshot/external/a7097cae6a1f8dea453977a1784b7ca16b9fadc5c4551ea066d305eb1607e1c6.bin create mode 100644 .inline-snapshot/external/ae070a447e1ded1ad4819f7608abc40785d712248f65c8595c99879080d0eeb9.bin create mode 100644 .inline-snapshot/external/b9d6bee9f9b8ee5bdea06cd6955521e0258cc2cef0528a17fbdadb9cc76695f0.bin create mode 100644 .inline-snapshot/external/cb77dc69b6c8289a6f1e88fa24f05bd963fe093622e5bf9a95a3ebede64714bc.bin create mode 100644 .inline-snapshot/external/d79326933c1586e731a8235998194b58fc759adc3685170e0a61033241d2eda5.bin create mode 100644 .inline-snapshot/external/ea9a417d533b9adfece02608f2ca00f3a963d785c6fe78c35d60d038cd7a8ba0.bin create mode 100644 .inline-snapshot/external/fb75060ede89cac360ce8baf1513a82f959a175ec05ce3c07412bbc9fd436234.bin create mode 100644 examples/parsing.py create mode 100644 examples/parsing_stream.py create mode 100644 examples/parsing_tools.py create mode 100644 examples/parsing_tools_stream.py create mode 100644 src/openai/lib/__init__.py create mode 100644 src/openai/lib/_parsing/__init__.py create mode 100644 src/openai/lib/_parsing/_completions.py create mode 100644 src/openai/lib/_pydantic.py create mode 100644 src/openai/lib/_tools.py create mode 100644 src/openai/lib/streaming/_deltas.py create mode 100644 src/openai/lib/streaming/chat/__init__.py create mode 100644 src/openai/lib/streaming/chat/_completions.py create mode 100644 src/openai/lib/streaming/chat/_events.py create mode 100644 src/openai/lib/streaming/chat/_types.py create mode 100644 src/openai/resources/beta/chat/__init__.py create mode 100644 src/openai/resources/beta/chat/chat.py create mode 100644 src/openai/resources/beta/chat/completions.py delete mode 100644 src/openai/types/beta/assistant_response_format.py delete mode 100644 src/openai/types/beta/assistant_response_format_param.py create mode 100644 src/openai/types/beta/threads/refusal_content_block.py create mode 100644 src/openai/types/beta/threads/refusal_delta_block.py create mode 100644 src/openai/types/chat/chat_completion_content_part_refusal_param.py create mode 100644 src/openai/types/chat/parsed_chat_completion.py create mode 100644 src/openai/types/chat/parsed_function_tool_call.py create mode 100644 src/openai/types/shared/response_format_json_object.py create mode 100644 src/openai/types/shared/response_format_json_schema.py create mode 100644 src/openai/types/shared/response_format_text.py create mode 100644 src/openai/types/shared_params/response_format_json_object.py create mode 100644 src/openai/types/shared_params/response_format_json_schema.py create mode 100644 src/openai/types/shared_params/response_format_text.py create mode 100644 tests/lib/__init__.py create mode 100644 tests/lib/chat/__init__.py create mode 100644 tests/lib/chat/_utils.py create mode 100644 tests/lib/chat/test_completions.py create mode 100644 tests/lib/chat/test_completions_streaming.py create mode 100644 tests/lib/schema_types/query.py create mode 100644 tests/lib/test_pydantic.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7e58412065..de70348b9c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -50,4 +50,3 @@ jobs: - name: Run tests run: ./scripts/test - diff --git a/.inline-snapshot/external/.gitignore b/.inline-snapshot/external/.gitignore new file mode 100644 index 0000000000..45bef68be1 --- /dev/null +++ b/.inline-snapshot/external/.gitignore @@ -0,0 +1,2 @@ +# ignore all snapshots which are not refered in the source +*-new.* diff --git a/.inline-snapshot/external/1437bd06a9d5c414e56fd0840b9cda31e5a0af80decdbddd21c056545c6d4616.bin b/.inline-snapshot/external/1437bd06a9d5c414e56fd0840b9cda31e5a0af80decdbddd21c056545c6d4616.bin new file mode 100644 index 0000000000..f96745e385 --- /dev/null +++ b/.inline-snapshot/external/1437bd06a9d5c414e56fd0840b9cda31e5a0af80decdbddd21c056545c6d4616.bin @@ -0,0 +1,100 @@ +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"{\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":"{\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":"{\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"city"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":"city"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":"city"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"San"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":"San"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":"San"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\",\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":"\",\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":"\",\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"temperature"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":"temperature"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":"temperature"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"64"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":",\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":"68"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":",\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":"64"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":",\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"units"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":"units"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":"units"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"f"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":"f"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":"f"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\"}"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":"\"}"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":"\"}"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[],"usage":{"prompt_tokens":17,"completion_tokens":42,"total_tokens":59}} + +data: [DONE] + diff --git a/.inline-snapshot/external/3e0df46f250db854eacb34e3258ab9141d709b770a74dc025fb8770a42aabee9.bin b/.inline-snapshot/external/3e0df46f250db854eacb34e3258ab9141d709b770a74dc025fb8770a42aabee9.bin new file mode 100644 index 0000000000..eb1cf9e733 --- /dev/null +++ b/.inline-snapshot/external/3e0df46f250db854eacb34e3258ab9141d709b770a74dc025fb8770a42aabee9.bin @@ -0,0 +1,180 @@ +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"{\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"location"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"San"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":","},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" CA"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"temperature"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"N"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"/A"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"conditions"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"N"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"/A"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"humidity"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"N"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"/A"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"wind"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"_speed"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"N"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"/A"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"timestamp"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"N"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"/A"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"note"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"Real"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"-time"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" data"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" is"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" not"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" available"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" Please"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" check"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" a"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" reliable"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" service"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" for"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" the"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" most"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" up"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"-to"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"-date"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" information"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" on"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" San"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"'s"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" conditions"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":".\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"}"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[],"usage":{"prompt_tokens":19,"completion_tokens":86,"total_tokens":105}} + +data: [DONE] + diff --git a/.inline-snapshot/external/70c7df71ce729e178fc5e54f0cc4861e696495d9a45c19be02cf479e28c31316.bin b/.inline-snapshot/external/70c7df71ce729e178fc5e54f0cc4861e696495d9a45c19be02cf479e28c31316.bin new file mode 100644 index 0000000000..21c41d3958 --- /dev/null +++ b/.inline-snapshot/external/70c7df71ce729e178fc5e54f0cc4861e696495d9a45c19be02cf479e28c31316.bin @@ -0,0 +1,12 @@ +data: {"id":"chatcmpl-9tDU7wVJ0lzoNjC1aNIjnP99zMW2C","object":"chat.completion.chunk","created":1722946903,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":{"content":[],"refusal":null},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tDU7wVJ0lzoNjC1aNIjnP99zMW2C","object":"chat.completion.chunk","created":1722946903,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"Foo"},"logprobs":{"content":[{"token":"Foo","logprob":-0.006764991,"bytes":[70,111,111],"top_logprobs":[]}],"refusal":null},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tDU7wVJ0lzoNjC1aNIjnP99zMW2C","object":"chat.completion.chunk","created":1722946903,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"!"},"logprobs":{"content":[{"token":"!","logprob":-0.31380808,"bytes":[33],"top_logprobs":[]}],"refusal":null},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tDU7wVJ0lzoNjC1aNIjnP99zMW2C","object":"chat.completion.chunk","created":1722946903,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-9tDU7wVJ0lzoNjC1aNIjnP99zMW2C","object":"chat.completion.chunk","created":1722946903,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[],"usage":{"prompt_tokens":9,"completion_tokens":2,"total_tokens":11}} + +data: [DONE] + diff --git a/.inline-snapshot/external/7ae6c1a2631bf7444b8f70b592ec5f581ea9de2524599f06b0d405db8997b826.bin b/.inline-snapshot/external/7ae6c1a2631bf7444b8f70b592ec5f581ea9de2524599f06b0d405db8997b826.bin new file mode 100644 index 0000000000..d261ccd0d0 --- /dev/null +++ b/.inline-snapshot/external/7ae6c1a2631bf7444b8f70b592ec5f581ea9de2524599f06b0d405db8997b826.bin @@ -0,0 +1,8 @@ +data: {"id":"chatcmpl-9tAC6v0rUCOp8tty9cizBsGmRcVIx","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"role":"assistant","content":null,"refusal":""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC6v0rUCOp8tty9cizBsGmRcVIx","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"length"}]} + +data: {"id":"chatcmpl-9tAC6v0rUCOp8tty9cizBsGmRcVIx","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[],"usage":{"prompt_tokens":17,"completion_tokens":1,"total_tokens":18}} + +data: [DONE] + diff --git a/.inline-snapshot/external/a346213bec7a572810bd1ffe290e08ddfad221d6632fdb200a95ca6c996238e2.bin b/.inline-snapshot/external/a346213bec7a572810bd1ffe290e08ddfad221d6632fdb200a95ca6c996238e2.bin new file mode 100644 index 0000000000..2ceced2f1c --- /dev/null +++ b/.inline-snapshot/external/a346213bec7a572810bd1ffe290e08ddfad221d6632fdb200a95ca6c996238e2.bin @@ -0,0 +1,52 @@ +data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"role":"assistant","content":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_g4Q1vRbE0CaHGOs5if8mHsBq","type":"function","function":{"name":"GetWeatherArgs","arguments":""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"ci"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"ty\": "}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"Edinb"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"urgh"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\", \"c"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"ountry"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\": \""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"UK\", "}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"units"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\": \""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"c\"}"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"id":"call_gWj3HQxZEHnFvyJLEHIiJKBV","type":"function","function":{"name":"get_stock_price","arguments":""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"{\"ti"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"cker\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":": \"AAP"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"L\", "}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"\"exch"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"ange\":"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":" \"NA"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"SDAQ\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"}"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"tool_calls"}]} + +data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[],"usage":{"prompt_tokens":149,"completion_tokens":60,"total_tokens":209}} + +data: [DONE] + diff --git a/.inline-snapshot/external/a7097cae6a1f8dea453977a1784b7ca16b9fadc5c4551ea066d305eb1607e1c6.bin b/.inline-snapshot/external/a7097cae6a1f8dea453977a1784b7ca16b9fadc5c4551ea066d305eb1607e1c6.bin new file mode 100644 index 0000000000..de0efe6bab --- /dev/null +++ b/.inline-snapshot/external/a7097cae6a1f8dea453977a1784b7ca16b9fadc5c4551ea066d305eb1607e1c6.bin @@ -0,0 +1,28 @@ +data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"role":"assistant","content":null,"tool_calls":[{"index":0,"id":"call_rQe3kzGnTr2epjx8HREg3F2a","type":"function","function":{"name":"get_weather","arguments":""}}],"refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"city"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"San"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":" Francisco"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\",\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"state"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"CA"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"}"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"tool_calls"}]} + +data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[],"usage":{"prompt_tokens":48,"completion_tokens":19,"total_tokens":67}} + +data: [DONE] + diff --git a/.inline-snapshot/external/ae070a447e1ded1ad4819f7608abc40785d712248f65c8595c99879080d0eeb9.bin b/.inline-snapshot/external/ae070a447e1ded1ad4819f7608abc40785d712248f65c8595c99879080d0eeb9.bin new file mode 100644 index 0000000000..af003a8120 --- /dev/null +++ b/.inline-snapshot/external/ae070a447e1ded1ad4819f7608abc40785d712248f65c8595c99879080d0eeb9.bin @@ -0,0 +1,36 @@ +data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"role":"assistant","content":null,"tool_calls":[{"index":0,"id":"call_Vz6ZXciy6Y0PYfT4d9W7fYB4","type":"function","function":{"name":"GetWeatherArgs","arguments":""}}],"refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"city"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"Ed"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"inburgh"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\",\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"country"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"UK"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\",\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"units"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"c"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"}"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"tool_calls"}]} + +data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[],"usage":{"prompt_tokens":76,"completion_tokens":24,"total_tokens":100}} + +data: [DONE] + diff --git a/.inline-snapshot/external/b9d6bee9f9b8ee5bdea06cd6955521e0258cc2cef0528a17fbdadb9cc76695f0.bin b/.inline-snapshot/external/b9d6bee9f9b8ee5bdea06cd6955521e0258cc2cef0528a17fbdadb9cc76695f0.bin new file mode 100644 index 0000000000..b4337f886a --- /dev/null +++ b/.inline-snapshot/external/b9d6bee9f9b8ee5bdea06cd6955521e0258cc2cef0528a17fbdadb9cc76695f0.bin @@ -0,0 +1,72 @@ +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"I'm"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" unable"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" to"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" provide"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" real"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"-time"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" updates"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" To"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" get"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" the"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" latest"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" information"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" for"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" San"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":","},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" I"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" recommend"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" checking"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" a"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" reliable"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" website"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" or"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" using"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" a"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" app"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":32,"total_tokens":46}} + +data: [DONE] + diff --git a/.inline-snapshot/external/cb77dc69b6c8289a6f1e88fa24f05bd963fe093622e5bf9a95a3ebede64714bc.bin b/.inline-snapshot/external/cb77dc69b6c8289a6f1e88fa24f05bd963fe093622e5bf9a95a3ebede64714bc.bin new file mode 100644 index 0000000000..a95f28a54b --- /dev/null +++ b/.inline-snapshot/external/cb77dc69b6c8289a6f1e88fa24f05bd963fe093622e5bf9a95a3ebede64714bc.bin @@ -0,0 +1,30 @@ +data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"role":"assistant","content":null,"refusal":""},"logprobs":{"content":null,"refusal":[]},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":"I'm"},"logprobs":{"content":null,"refusal":[{"token":"I'm","logprob":-0.0010472201,"bytes":[73,39,109],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" very"},"logprobs":{"content":null,"refusal":[{"token":" very","logprob":-0.7292482,"bytes":[32,118,101,114,121],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" sorry"},"logprobs":{"content":null,"refusal":[{"token":" sorry","logprob":-5.080963e-6,"bytes":[32,115,111,114,114,121],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":","},"logprobs":{"content":null,"refusal":[{"token":",","logprob":-0.00004048445,"bytes":[44],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" but"},"logprobs":{"content":null,"refusal":[{"token":" but","logprob":-0.038046427,"bytes":[32,98,117,116],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" I"},"logprobs":{"content":null,"refusal":[{"token":" I","logprob":-0.0019351852,"bytes":[32,73],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" can't"},"logprobs":{"content":null,"refusal":[{"token":" can't","logprob":-0.008995773,"bytes":[32,99,97,110,39,116],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" assist"},"logprobs":{"content":null,"refusal":[{"token":" assist","logprob":-0.0033510819,"bytes":[32,97,115,115,105,115,116],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" with"},"logprobs":{"content":null,"refusal":[{"token":" with","logprob":-0.0036033941,"bytes":[32,119,105,116,104],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" that"},"logprobs":{"content":null,"refusal":[{"token":" that","logprob":-0.0015974608,"bytes":[32,116,104,97,116],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":"."},"logprobs":{"content":null,"refusal":[{"token":".","logprob":-0.6339823,"bytes":[46],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[],"usage":{"prompt_tokens":17,"completion_tokens":12,"total_tokens":29}} + +data: [DONE] + diff --git a/.inline-snapshot/external/d79326933c1586e731a8235998194b58fc759adc3685170e0a61033241d2eda5.bin b/.inline-snapshot/external/d79326933c1586e731a8235998194b58fc759adc3685170e0a61033241d2eda5.bin new file mode 100644 index 0000000000..895e4828ef --- /dev/null +++ b/.inline-snapshot/external/d79326933c1586e731a8235998194b58fc759adc3685170e0a61033241d2eda5.bin @@ -0,0 +1,32 @@ +data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"role":"assistant","content":null,"refusal":""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":"I'm"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" very"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" sorry"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":","},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" but"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" I"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" can't"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" assist"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" with"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" that"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" request"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":"."},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[],"usage":{"prompt_tokens":17,"completion_tokens":13,"total_tokens":30}} + +data: [DONE] + diff --git a/.inline-snapshot/external/ea9a417d533b9adfece02608f2ca00f3a963d785c6fe78c35d60d038cd7a8ba0.bin b/.inline-snapshot/external/ea9a417d533b9adfece02608f2ca00f3a963d785c6fe78c35d60d038cd7a8ba0.bin new file mode 100644 index 0000000000..869b94de1a --- /dev/null +++ b/.inline-snapshot/external/ea9a417d533b9adfece02608f2ca00f3a963d785c6fe78c35d60d038cd7a8ba0.bin @@ -0,0 +1,36 @@ +data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"{\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"city"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"San"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\",\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"temperature"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"63"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":",\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"units"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"f"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\"}"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[],"usage":{"prompt_tokens":17,"completion_tokens":14,"total_tokens":31}} + +data: [DONE] + diff --git a/.inline-snapshot/external/fb75060ede89cac360ce8baf1513a82f959a175ec05ce3c07412bbc9fd436234.bin b/.inline-snapshot/external/fb75060ede89cac360ce8baf1513a82f959a175ec05ce3c07412bbc9fd436234.bin new file mode 100644 index 0000000000..970b1adf80 --- /dev/null +++ b/.inline-snapshot/external/fb75060ede89cac360ce8baf1513a82f959a175ec05ce3c07412bbc9fd436234.bin @@ -0,0 +1,22 @@ +data: {"id":"chatcmpl-9tACC99384oWbk9upfFD1gITJehjE","object":"chat.completion.chunk","created":1722934260,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"role":"assistant","content":null,"tool_calls":[{"index":0,"id":"call_9rqjEc1DQRADTYGVV45LbZwL","type":"function","function":{"name":"get_weather","arguments":""}}],"refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACC99384oWbk9upfFD1gITJehjE","object":"chat.completion.chunk","created":1722934260,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACC99384oWbk9upfFD1gITJehjE","object":"chat.completion.chunk","created":1722934260,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"city"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACC99384oWbk9upfFD1gITJehjE","object":"chat.completion.chunk","created":1722934260,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACC99384oWbk9upfFD1gITJehjE","object":"chat.completion.chunk","created":1722934260,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"New"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACC99384oWbk9upfFD1gITJehjE","object":"chat.completion.chunk","created":1722934260,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":" York"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACC99384oWbk9upfFD1gITJehjE","object":"chat.completion.chunk","created":1722934260,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":" City"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACC99384oWbk9upfFD1gITJehjE","object":"chat.completion.chunk","created":1722934260,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"}"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tACC99384oWbk9upfFD1gITJehjE","object":"chat.completion.chunk","created":1722934260,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-9tACC99384oWbk9upfFD1gITJehjE","object":"chat.completion.chunk","created":1722934260,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[],"usage":{"prompt_tokens":44,"completion_tokens":16,"total_tokens":60}} + +data: [DONE] + diff --git a/.stats.yml b/.stats.yml index 6cc7757636..da26758316 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-b04761ffd2adad3cc19a6dc6fc696ac445878219972f891881a967340fa9a6b0.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-c36d30a94622922f83d56a025cdf0095ff7cb18a5138838c698c8443f21fb3a8.yml diff --git a/api.md b/api.md index 85e81467dc..1687476d86 100644 --- a/api.md +++ b/api.md @@ -1,7 +1,14 @@ # Shared Types ```python -from openai.types import ErrorObject, FunctionDefinition, FunctionParameters +from openai.types import ( + ErrorObject, + FunctionDefinition, + FunctionParameters, + ResponseFormatJSONObject, + ResponseFormatJSONSchema, + ResponseFormatText, +) ``` # Completions @@ -35,6 +42,7 @@ from openai.types.chat import ( ChatCompletionChunk, ChatCompletionContentPart, ChatCompletionContentPartImage, + ChatCompletionContentPartRefusal, ChatCompletionContentPartText, ChatCompletionFunctionCallOption, ChatCompletionFunctionMessageParam, @@ -296,7 +304,6 @@ Types: ```python from openai.types.beta import ( - AssistantResponseFormat, AssistantResponseFormatOption, AssistantToolChoice, AssistantToolChoiceFunction, @@ -397,6 +404,8 @@ from openai.types.beta.threads import ( MessageDeleted, MessageDelta, MessageDeltaEvent, + RefusalContentBlock, + RefusalDeltaBlock, Text, TextContentBlock, TextContentBlockParam, diff --git a/examples/parsing.py b/examples/parsing.py new file mode 100644 index 0000000000..17e5db52ec --- /dev/null +++ b/examples/parsing.py @@ -0,0 +1,36 @@ +from typing import List + +import rich +from pydantic import BaseModel + +from openai import OpenAI + + +class Step(BaseModel): + explanation: str + output: str + + +class MathResponse(BaseModel): + steps: List[Step] + final_answer: str + + +client = OpenAI() + +completion = client.beta.chat.completions.parse( + model="gpt-4o-2024-08-06", + messages=[ + {"role": "system", "content": "You are a helpful math tutor."}, + {"role": "user", "content": "solve 8x + 31 = 2"}, + ], + response_format=MathResponse, +) + +message = completion.choices[0].message +if message.parsed: + rich.print(message.parsed.steps) + + print("answer: ", message.parsed.final_answer) +else: + print(message.refusal) diff --git a/examples/parsing_stream.py b/examples/parsing_stream.py new file mode 100644 index 0000000000..6c6f078f77 --- /dev/null +++ b/examples/parsing_stream.py @@ -0,0 +1,42 @@ +from typing import List + +import rich +from pydantic import BaseModel + +from openai import OpenAI + + +class Step(BaseModel): + explanation: str + output: str + + +class MathResponse(BaseModel): + steps: List[Step] + final_answer: str + + +client = OpenAI() + +with client.beta.chat.completions.stream( + model="gpt-4o-2024-08-06", + messages=[ + {"role": "system", "content": "You are a helpful math tutor."}, + {"role": "user", "content": "solve 8x + 31 = 2"}, + ], + response_format=MathResponse, +) as stream: + for event in stream: + if event.type == "content.delta": + print(event.delta, end="", flush=True) + elif event.type == "content.done": + print("\n") + if event.parsed is not None: + print(f"answer: {event.parsed.final_answer}") + elif event.type == "refusal.delta": + print(event.delta, end="", flush=True) + elif event.type == "refusal.done": + print() + +print("---------------") +rich.print(stream.get_final_completion()) diff --git a/examples/parsing_tools.py b/examples/parsing_tools.py new file mode 100644 index 0000000000..c6065eeb7a --- /dev/null +++ b/examples/parsing_tools.py @@ -0,0 +1,80 @@ +from enum import Enum +from typing import List, Union + +import rich +from pydantic import BaseModel + +import openai +from openai import OpenAI + + +class Table(str, Enum): + orders = "orders" + customers = "customers" + products = "products" + + +class Column(str, Enum): + id = "id" + status = "status" + expected_delivery_date = "expected_delivery_date" + delivered_at = "delivered_at" + shipped_at = "shipped_at" + ordered_at = "ordered_at" + canceled_at = "canceled_at" + + +class Operator(str, Enum): + eq = "=" + gt = ">" + lt = "<" + le = "<=" + ge = ">=" + ne = "!=" + + +class OrderBy(str, Enum): + asc = "asc" + desc = "desc" + + +class DynamicValue(BaseModel): + column_name: str + + +class Condition(BaseModel): + column: str + operator: Operator + value: Union[str, int, DynamicValue] + + +class Query(BaseModel): + table_name: Table + columns: List[Column] + conditions: List[Condition] + order_by: OrderBy + + +client = OpenAI() + +completion = client.beta.chat.completions.parse( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "system", + "content": "You are a helpful assistant. The current date is August 6, 2024. You help users query for the data they are looking for by calling the query function.", + }, + { + "role": "user", + "content": "look up all my orders in november of last year that were fulfilled but not delivered on time", + }, + ], + tools=[ + openai.pydantic_function_tool(Query), + ], +) + +tool_call = (completion.choices[0].message.tool_calls or [])[0] +rich.print(tool_call.function) +assert isinstance(tool_call.function.parsed_arguments, Query) +print(tool_call.function.parsed_arguments.table_name) diff --git a/examples/parsing_tools_stream.py b/examples/parsing_tools_stream.py new file mode 100644 index 0000000000..eea6f6a43a --- /dev/null +++ b/examples/parsing_tools_stream.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +import rich +from pydantic import BaseModel + +import openai +from openai import OpenAI + + +class GetWeather(BaseModel): + city: str + country: str + + +client = OpenAI() + + +with client.beta.chat.completions.stream( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "user", + "content": "What's the weather like in SF and New York?", + }, + ], + tools=[ + # because we're using `.parse_stream()`, the returned tool calls + # will be automatically deserialized into this `GetWeather` type + openai.pydantic_function_tool(GetWeather, name="get_weather"), + ], + parallel_tool_calls=True, +) as stream: + for event in stream: + if event.type == "tool_calls.function.arguments.delta" or event.type == "tool_calls.function.arguments.done": + rich.get_console().print(event, width=80) + +print("----\n") +rich.print(stream.get_final_completion()) diff --git a/helpers.md b/helpers.md index 3508b59a33..2e0d314b50 100644 --- a/helpers.md +++ b/helpers.md @@ -1,6 +1,280 @@ +# Structured Outputs Parsing Helpers + +The OpenAI API supports extracting JSON from the model with the `response_format` request param, for more details on the API, see [this guide](https://platform.openai.com/docs/guides/structured-outputs). + +The SDK provides a `client.beta.chat.completions.parse()` method which is a wrapper over the `client.chat.completions.create()` that +provides richer integrations with Python specific types & returns a `ParsedChatCompletion` object, which is a subclass of the standard `ChatCompletion` class. + +## Auto-parsing response content with Pydantic models + +You can pass a pydantic model to the `.parse()` method and the SDK will automatically convert the model +into a JSON schema, send it to the API and parse the response content back into the given model. + +```py +from typing import List +from pydantic import BaseModel +from openai import OpenAI + +class Step(BaseModel): + explanation: str + output: str + +class MathResponse(BaseModel): + steps: List[Step] + final_answer: str + +client = OpenAI() +completion = client.beta.chat.completions.parse( + model="gpt-4o-2024-08-06", + messages=[ + {"role": "system", "content": "You are a helpful math tutor."}, + {"role": "user", "content": "solve 8x + 31 = 2"}, + ], + response_format=MathResponse, +) + +message = completion.choices[0].message +if message.parsed: + print(message.parsed.steps) + print("answer: ", message.parsed.final_answer) +else: + print(message.refusal) +``` + +## Auto-parsing function tool calls + +The `.parse()` method will also automatically parse `function` tool calls if: +- You use the `openai.pydantic_function_tool()` helper method +- You mark your tool schema with `"strict": True` + +For example: + +```py +from enum import Enum +from typing import List, Union +from pydantic import BaseModel +import openai + +class Table(str, Enum): + orders = "orders" + customers = "customers" + products = "products" + +class Column(str, Enum): + id = "id" + status = "status" + expected_delivery_date = "expected_delivery_date" + delivered_at = "delivered_at" + shipped_at = "shipped_at" + ordered_at = "ordered_at" + canceled_at = "canceled_at" + +class Operator(str, Enum): + eq = "=" + gt = ">" + lt = "<" + le = "<=" + ge = ">=" + ne = "!=" + +class OrderBy(str, Enum): + asc = "asc" + desc = "desc" + +class DynamicValue(BaseModel): + column_name: str + +class Condition(BaseModel): + column: str + operator: Operator + value: Union[str, int, DynamicValue] + +class Query(BaseModel): + table_name: Table + columns: List[Column] + conditions: List[Condition] + order_by: OrderBy + +client = openai.OpenAI() +completion = client.beta.chat.completions.parse( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "system", + "content": "You are a helpful assistant. The current date is August 6, 2024. You help users query for the data they are looking for by calling the query function.", + }, + { + "role": "user", + "content": "look up all my orders in may of last year that were fulfilled but not delivered on time", + }, + ], + tools=[ + openai.pydantic_function_tool(Query), + ], +) + +tool_call = (completion.choices[0].message.tool_calls or [])[0] +print(tool_call.function) +assert isinstance(tool_call.function.parsed_arguments, Query) +print(tool_call.function.parsed_arguments.table_name) +``` + +### Differences from `.create()` + +The `beta.chat.completions.parse()` method imposes some additional restrictions on it's usage that `chat.completions.create()` does not. + +- If the completion completes with `finish_reason` set to `length` or `content_filter`, the `LengthFinishReasonError` / `ContentFilterFinishReasonError` errors will be raised. +- Only strict function tools can be passed, e.g. `{'type': 'function', 'function': {..., 'strict': True}}` + # Streaming Helpers -OpenAI supports streaming responses when interacting with the [Assistant](#assistant-streaming-api) APIs. +OpenAI supports streaming responses when interacting with the [Chat Completion] & [Assistant](#assistant-streaming-api) APIs. + +## Chat Completions API + +The SDK provides a `.beta.chat.completions.stream()` method that wraps the `.chat.completions.create(stream=True)` stream providing a more granular event API & automatic accumulation of each delta. + +It also supports all aforementioned [parsing helpers](#parsing-helpers). + +Unlike `.create(stream=True)`, the `.stream()` method requires usage within a context manager to prevent accidental leakage of the response: + +```py +async with client.beta.chat.completions.stream( + model='gpt-4o-2024-08-06', + messages=[...], +) as stream: + async for event in stream: + if event.type == 'content.delta': + print(event.content, flush=True, end='') +``` + +When the context manager is entered, a `ChatCompletionStream` / `AsyncChatCompletionStream` instance is returned which, like `.create(stream=True)` is an iterator in the sync client and an async iterator in the async client. The full list of events that are yielded by the iterator are outlined [below](#chat-completions-events). + +When the context manager exits, the response will be closed, however the `stream` instance is still available outside +the context manager. + +### Chat Completions Events + +These events allow you to track the progress of the chat completion generation, access partial results, and handle different aspects of the stream separately. + +Below is a list of the different event types you may encounter: + +#### ChunkEvent + +Emitted for every chunk received from the API. + +- `type`: `"chunk"` +- `chunk`: The raw `ChatCompletionChunk` object received from the API +- `snapshot`: The current accumulated state of the chat completion + +#### ContentDeltaEvent + +Emitted for every chunk containing new content. + +- `type`: `"content.delta"` +- `delta`: The new content string received in this chunk +- `snapshot`: The accumulated content so far +- `parsed`: The partially parsed content (if applicable) + +#### ContentDoneEvent + +Emitted when the content generation is complete. May be fired multiple times if there are multiple choices. + +- `type`: `"content.done"` +- `content`: The full generated content +- `parsed`: The fully parsed content (if applicable) + +#### RefusalDeltaEvent + +Emitted when a chunk contains part of a content refusal. + +- `type`: `"refusal.delta"` +- `delta`: The new refusal content string received in this chunk +- `snapshot`: The accumulated refusal content string so far + +#### RefusalDoneEvent + +Emitted when the refusal content is complete. + +- `type`: `"refusal.done"` +- `refusal`: The full refusal content + +#### FunctionToolCallArgumentsDeltaEvent + +Emitted when a chunk contains part of a function tool call's arguments. + +- `type`: `"tool_calls.function.arguments.delta"` +- `name`: The name of the function being called +- `index`: The index of the tool call +- `arguments`: The accumulated raw JSON string of arguments +- `parsed_arguments`: The partially parsed arguments object +- `arguments_delta`: The new JSON string fragment received in this chunk + +#### FunctionToolCallArgumentsDoneEvent + +Emitted when a function tool call's arguments are complete. + +- `type`: `"tool_calls.function.arguments.done"` +- `name`: The name of the function being called +- `index`: The index of the tool call +- `arguments`: The full raw JSON string of arguments +- `parsed_arguments`: The fully parsed arguments object. If you used `openai.pydantic_function_tool()` this will be an instance of the given model. + +#### LogprobsContentDeltaEvent + +Emitted when a chunk contains new content [log probabilities](https://cookbook.openai.com/examples/using_logprobs). + +- `type`: `"logprobs.content.delta"` +- `content`: A list of the new log probabilities received in this chunk +- `snapshot`: A list of the accumulated log probabilities so far + +#### LogprobsContentDoneEvent + +Emitted when all content [log probabilities](https://cookbook.openai.com/examples/using_logprobs) have been received. + +- `type`: `"logprobs.content.done"` +- `content`: The full list of token log probabilities for the content + +#### LogprobsRefusalDeltaEvent + +Emitted when a chunk contains new refusal [log probabilities](https://cookbook.openai.com/examples/using_logprobs). + +- `type`: `"logprobs.refusal.delta"` +- `refusal`: A list of the new log probabilities received in this chunk +- `snapshot`: A list of the accumulated log probabilities so far + +#### LogprobsRefusalDoneEvent + +Emitted when all refusal [log probabilities](https://cookbook.openai.com/examples/using_logprobs) have been received. + +- `type`: `"logprobs.refusal.done"` +- `refusal`: The full list of token log probabilities for the refusal + +### Chat Completions stream methods + +A handful of helper methods are provided on the stream class for additional convenience, + +**`.get_final_completion()`** + +Returns the accumulated `ParsedChatCompletion` object + +```py +async with client.beta.chat.completions.stream(...) as stream: + ... + +completion = await stream.get_final_completion() +print(completion.choices[0].message) +``` + +**`.until_done()`** + +If you want to wait for the stream to complete, you can use the `.until_done()` method. + +```py +async with client.beta.chat.completions.stream(...) as stream: + await stream.until_done() + # stream is now finished +``` ## Assistant Streaming API diff --git a/pyproject.toml b/pyproject.toml index 99e0fc6591..cb02edac0c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -10,12 +10,13 @@ authors = [ dependencies = [ "httpx>=0.23.0, <1", "pydantic>=1.9.0, <3", - "typing-extensions>=4.7, <5", + "typing-extensions>=4.11, <5", "anyio>=3.5.0, <5", "distro>=1.7.0, <2", "sniffio", "cached-property; python_version < '3.8'", - "tqdm > 4" + "tqdm > 4", + "jiter>=0.4.0, <1", ] requires-python = ">= 3.7.1" classifiers = [ diff --git a/requirements-dev.lock b/requirements-dev.lock index d2ad945343..f4797f432b 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -72,6 +72,8 @@ importlib-metadata==7.0.0 iniconfig==2.0.0 # via pytest inline-snapshot==0.10.2 +jiter==0.5.0 + # via openai markdown-it-py==3.0.0 # via rich mdurl==0.1.2 @@ -169,7 +171,7 @@ types-pytz==2024.1.0.20240417 types-toml==0.10.8.20240310 # via inline-snapshot types-tqdm==4.66.0.2 -typing-extensions==4.8.0 +typing-extensions==4.12.2 # via azure-core # via black # via mypy diff --git a/requirements.lock b/requirements.lock index 3c3d6ae702..de632aefbd 100644 --- a/requirements.lock +++ b/requirements.lock @@ -30,6 +30,8 @@ httpx==0.25.2 idna==3.4 # via anyio # via httpx +jiter==0.5.0 + # via openai numpy==1.26.4 # via openai # via pandas @@ -56,7 +58,7 @@ tqdm==4.66.1 # via openai types-pytz==2024.1.0.20240417 # via pandas-stubs -typing-extensions==4.8.0 +typing-extensions==4.12.2 # via openai # via pydantic # via pydantic-core diff --git a/src/openai/__init__.py b/src/openai/__init__.py index 0e87ae9259..3c1ebb573d 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -26,8 +26,10 @@ AuthenticationError, InternalServerError, PermissionDeniedError, + LengthFinishReasonError, UnprocessableEntityError, APIResponseValidationError, + ContentFilterFinishReasonError, ) from ._base_client import DefaultHttpxClient, DefaultAsyncHttpxClient from ._utils._logs import setup_logging as _setup_logging @@ -55,6 +57,8 @@ "UnprocessableEntityError", "RateLimitError", "InternalServerError", + "LengthFinishReasonError", + "ContentFilterFinishReasonError", "Timeout", "RequestOptions", "Client", @@ -72,7 +76,7 @@ "DefaultAsyncHttpxClient", ] -from .lib import azure as _azure +from .lib import azure as _azure, pydantic_function_tool as pydantic_function_tool from .version import VERSION as VERSION from .lib.azure import AzureOpenAI as AzureOpenAI, AsyncAzureOpenAI as AsyncAzureOpenAI from .lib._old_api import * diff --git a/src/openai/_client.py b/src/openai/_client.py index 8b404e234d..d3ee6cf0f1 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -151,7 +151,7 @@ def __init__( @property @override def qs(self) -> Querystring: - return Querystring(array_format="comma") + return Querystring(array_format="brackets") @property @override @@ -365,7 +365,7 @@ def __init__( @property @override def qs(self) -> Querystring: - return Querystring(array_format="comma") + return Querystring(array_format="brackets") @property @override diff --git a/src/openai/_compat.py b/src/openai/_compat.py index 21fe6941ce..c0dd8c1ee5 100644 --- a/src/openai/_compat.py +++ b/src/openai/_compat.py @@ -159,6 +159,18 @@ def model_parse(model: type[_ModelT], data: Any) -> _ModelT: return model.parse_obj(data) # pyright: ignore[reportDeprecated] +def model_parse_json(model: type[_ModelT], data: str | bytes) -> _ModelT: + if PYDANTIC_V2: + return model.model_validate_json(data) + return model.parse_raw(data) # pyright: ignore[reportDeprecated] + + +def model_json_schema(model: type[_ModelT]) -> dict[str, Any]: + if PYDANTIC_V2: + return model.model_json_schema() + return model.schema() # pyright: ignore[reportDeprecated] + + # generic models if TYPE_CHECKING: diff --git a/src/openai/_exceptions.py b/src/openai/_exceptions.py index f6731cfac5..f44f90b52f 100644 --- a/src/openai/_exceptions.py +++ b/src/openai/_exceptions.py @@ -19,6 +19,8 @@ "UnprocessableEntityError", "RateLimitError", "InternalServerError", + "LengthFinishReasonError", + "ContentFilterFinishReasonError", ] @@ -125,3 +127,17 @@ class RateLimitError(APIStatusError): class InternalServerError(APIStatusError): pass + + +class LengthFinishReasonError(OpenAIError): + def __init__(self) -> None: + super().__init__( + f"Could not parse response content as the length limit was reached", + ) + + +class ContentFilterFinishReasonError(OpenAIError): + def __init__(self) -> None: + super().__init__( + f"Could not parse response content as the request was rejected by the content filter", + ) diff --git a/src/openai/lib/__init__.py b/src/openai/lib/__init__.py new file mode 100644 index 0000000000..5c6cb782c0 --- /dev/null +++ b/src/openai/lib/__init__.py @@ -0,0 +1,2 @@ +from ._tools import pydantic_function_tool as pydantic_function_tool +from ._parsing import ResponseFormatT as ResponseFormatT diff --git a/src/openai/lib/_parsing/__init__.py b/src/openai/lib/_parsing/__init__.py new file mode 100644 index 0000000000..4d454c3a20 --- /dev/null +++ b/src/openai/lib/_parsing/__init__.py @@ -0,0 +1,12 @@ +from ._completions import ( + ResponseFormatT as ResponseFormatT, + has_parseable_input, + has_parseable_input as has_parseable_input, + maybe_parse_content as maybe_parse_content, + validate_input_tools as validate_input_tools, + parse_chat_completion as parse_chat_completion, + get_input_tool_by_name as get_input_tool_by_name, + solve_response_format_t as solve_response_format_t, + parse_function_tool_arguments as parse_function_tool_arguments, + type_to_response_format_param as type_to_response_format_param, +) diff --git a/src/openai/lib/_parsing/_completions.py b/src/openai/lib/_parsing/_completions.py new file mode 100644 index 0000000000..f9d1d6b351 --- /dev/null +++ b/src/openai/lib/_parsing/_completions.py @@ -0,0 +1,254 @@ +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, Any, Iterable, cast +from typing_extensions import TypeVar, TypeGuard, assert_never + +import pydantic + +from .._tools import PydanticFunctionTool +from ..._types import NOT_GIVEN, NotGiven +from ..._utils import is_dict, is_given +from ..._compat import model_parse_json +from ..._models import construct_type_unchecked +from .._pydantic import to_strict_json_schema +from ...types.chat import ( + ParsedChoice, + ChatCompletion, + ParsedFunction, + ParsedChatCompletion, + ChatCompletionMessage, + ParsedFunctionToolCall, + ChatCompletionToolParam, + ParsedChatCompletionMessage, + completion_create_params, +) +from ..._exceptions import LengthFinishReasonError, ContentFilterFinishReasonError +from ...types.shared_params import FunctionDefinition +from ...types.chat.completion_create_params import ResponseFormat as ResponseFormatParam +from ...types.chat.chat_completion_message_tool_call import Function + +ResponseFormatT = TypeVar( + "ResponseFormatT", + # if it isn't given then we don't do any parsing + default=None, +) +_default_response_format: None = None + + +def validate_input_tools( + tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, +) -> None: + if not is_given(tools): + return + + for tool in tools: + if tool["type"] != "function": + raise ValueError( + f'Currently only `function` tool types support auto-parsing; Received `{tool["type"]}`', + ) + + strict = tool["function"].get("strict") + if strict is not True: + raise ValueError( + f'`{tool["function"]["name"]}` is not strict. Only `strict` function tools can be auto-parsed' + ) + + +def parse_chat_completion( + *, + response_format: type[ResponseFormatT] | completion_create_params.ResponseFormat | NotGiven, + input_tools: Iterable[ChatCompletionToolParam] | NotGiven, + chat_completion: ChatCompletion | ParsedChatCompletion[object], +) -> ParsedChatCompletion[ResponseFormatT]: + if is_given(input_tools): + input_tools = [t for t in input_tools] + else: + input_tools = [] + + choices: list[ParsedChoice[ResponseFormatT]] = [] + for choice in chat_completion.choices: + if choice.finish_reason == "length": + raise LengthFinishReasonError() + + if choice.finish_reason == "content_filter": + raise ContentFilterFinishReasonError() + + message = choice.message + + tool_calls: list[ParsedFunctionToolCall] = [] + if message.tool_calls: + for tool_call in message.tool_calls: + if tool_call.type == "function": + tool_call_dict = tool_call.to_dict() + tool_calls.append( + construct_type_unchecked( + value={ + **tool_call_dict, + "function": { + **cast(Any, tool_call_dict["function"]), + "parsed_arguments": parse_function_tool_arguments( + input_tools=input_tools, function=tool_call.function + ), + }, + }, + type_=ParsedFunctionToolCall, + ) + ) + elif TYPE_CHECKING: # type: ignore[unreachable] + assert_never(tool_call) + else: + tool_calls.append(tool_call) + + choices.append( + construct_type_unchecked( + type_=cast(Any, ParsedChoice)[solve_response_format_t(response_format)], + value={ + **choice.to_dict(), + "message": { + **message.to_dict(), + "parsed": maybe_parse_content( + response_format=response_format, + message=message, + ), + "tool_calls": tool_calls, + }, + }, + ) + ) + + return cast( + ParsedChatCompletion[ResponseFormatT], + construct_type_unchecked( + type_=cast(Any, ParsedChatCompletion)[solve_response_format_t(response_format)], + value={ + **chat_completion.to_dict(), + "choices": choices, + }, + ), + ) + + +def get_input_tool_by_name(*, input_tools: list[ChatCompletionToolParam], name: str) -> ChatCompletionToolParam | None: + return next((t for t in input_tools if t.get("function", {}).get("name") == name), None) + + +def parse_function_tool_arguments( + *, input_tools: list[ChatCompletionToolParam], function: Function | ParsedFunction +) -> object: + input_tool = get_input_tool_by_name(input_tools=input_tools, name=function.name) + if not input_tool: + return None + + input_fn = cast(object, input_tool.get("function")) + if isinstance(input_fn, PydanticFunctionTool): + return model_parse_json(input_fn.model, function.arguments) + + input_fn = cast(FunctionDefinition, input_fn) + + if not input_fn.get("strict"): + return None + + return json.loads(function.arguments) + + +def maybe_parse_content( + *, + response_format: type[ResponseFormatT] | ResponseFormatParam | NotGiven, + message: ChatCompletionMessage | ParsedChatCompletionMessage[object], +) -> ResponseFormatT | None: + if has_rich_response_format(response_format) and message.content is not None and not message.refusal: + return _parse_content(response_format, message.content) + + return None + + +def solve_response_format_t( + response_format: type[ResponseFormatT] | ResponseFormatParam | NotGiven, +) -> type[ResponseFormatT]: + """Return the runtime type for the given response format. + + If no response format is given, or if we won't auto-parse the response format + then we default to `None`. + """ + if has_rich_response_format(response_format): + return response_format + + return cast("type[ResponseFormatT]", _default_response_format) + + +def has_parseable_input( + *, + response_format: type | ResponseFormatParam | NotGiven, + input_tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, +) -> bool: + if has_rich_response_format(response_format): + return True + + for input_tool in input_tools or []: + if is_parseable_tool(input_tool): + return True + + return False + + +def has_rich_response_format( + response_format: type[ResponseFormatT] | ResponseFormatParam | NotGiven, +) -> TypeGuard[type[ResponseFormatT]]: + if not is_given(response_format): + return False + + if is_response_format_param(response_format): + return False + + return True + + +def is_response_format_param(response_format: object) -> TypeGuard[ResponseFormatParam]: + return is_dict(response_format) + + +def is_parseable_tool(input_tool: ChatCompletionToolParam) -> bool: + input_fn = cast(object, input_tool.get("function")) + if isinstance(input_fn, PydanticFunctionTool): + return True + + return cast(FunctionDefinition, input_fn).get("strict") or False + + +def is_basemodel_type(typ: type) -> TypeGuard[type[pydantic.BaseModel]]: + return issubclass(typ, pydantic.BaseModel) + + +def _parse_content(response_format: type[ResponseFormatT], content: str) -> ResponseFormatT: + if is_basemodel_type(response_format): + return cast(ResponseFormatT, model_parse_json(response_format, content)) + + raise TypeError(f"Unable to automatically parse response format type {response_format}") + + +def type_to_response_format_param( + response_format: type | completion_create_params.ResponseFormat | NotGiven, +) -> ResponseFormatParam | NotGiven: + if not is_given(response_format): + return NOT_GIVEN + + if is_response_format_param(response_format): + return response_format + + # type checkers don't narrow the negation of a `TypeGuard` as it isn't + # a safe default behaviour but we know that at this point the `response_format` + # can only be a `type` + response_format = cast(type, response_format) + + if not is_basemodel_type(response_format): + raise TypeError(f"Unsupported response_format type - {response_format}") + + return { + "type": "json_schema", + "json_schema": { + "schema": to_strict_json_schema(response_format), + "name": response_format.__name__, + "strict": True, + }, + } diff --git a/src/openai/lib/_pydantic.py b/src/openai/lib/_pydantic.py new file mode 100644 index 0000000000..967ad5de57 --- /dev/null +++ b/src/openai/lib/_pydantic.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +from typing import Any +from typing_extensions import TypeGuard + +import pydantic + +from .._utils import is_dict as _is_dict, is_list +from .._compat import model_json_schema + + +def to_strict_json_schema(model: type[pydantic.BaseModel]) -> dict[str, Any]: + return _ensure_strict_json_schema(model_json_schema(model), path=()) + + +def _ensure_strict_json_schema( + json_schema: object, + path: tuple[str, ...], +) -> dict[str, Any]: + """Mutates the given JSON schema to ensure it conforms to the `strict` standard + that the API expects. + """ + if not is_dict(json_schema): + raise TypeError(f"Expected {json_schema} to be a dictionary; path={path}") + + typ = json_schema.get("type") + if typ == "object" and "additionalProperties" not in json_schema: + json_schema["additionalProperties"] = False + + # object types + # { 'type': 'object', 'properties': { 'a': {...} } } + properties = json_schema.get("properties") + if is_dict(properties): + json_schema["required"] = [prop for prop in properties.keys()] + json_schema["properties"] = { + key: _ensure_strict_json_schema(prop_schema, path=(*path, "properties", key)) + for key, prop_schema in properties.items() + } + + # arrays + # { 'type': 'array', 'items': {...} } + items = json_schema.get("items") + if is_dict(items): + json_schema["items"] = _ensure_strict_json_schema(items, path=(*path, "items")) + + # unions + any_of = json_schema.get("anyOf") + if is_list(any_of): + json_schema["anyOf"] = [ + _ensure_strict_json_schema(variant, path=(*path, "anyOf", str(i))) for i, variant in enumerate(any_of) + ] + + # intersections + all_of = json_schema.get("allOf") + if is_list(all_of): + json_schema["allOf"] = [ + _ensure_strict_json_schema(entry, path=(*path, "anyOf", str(i))) for i, entry in enumerate(all_of) + ] + + defs = json_schema.get("$defs") + if is_dict(defs): + for def_name, def_schema in defs.items(): + _ensure_strict_json_schema(def_schema, path=(*path, "$defs", def_name)) + + return json_schema + + +def is_dict(obj: object) -> TypeGuard[dict[str, object]]: + # just pretend that we know there are only `str` keys + # as that check is not worth the performance cost + return _is_dict(obj) diff --git a/src/openai/lib/_tools.py b/src/openai/lib/_tools.py new file mode 100644 index 0000000000..8478ed676c --- /dev/null +++ b/src/openai/lib/_tools.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +from typing import Any, Dict, cast + +import pydantic + +from ._pydantic import to_strict_json_schema +from ..types.chat import ChatCompletionToolParam +from ..types.shared_params import FunctionDefinition + + +class PydanticFunctionTool(Dict[str, Any]): + """Dictionary wrapper so we can pass the given base model + throughout the entire request stack without having to special + case it. + """ + + model: type[pydantic.BaseModel] + + def __init__(self, defn: FunctionDefinition, model: type[pydantic.BaseModel]) -> None: + super().__init__(defn) + self.model = model + + def cast(self) -> FunctionDefinition: + return cast(FunctionDefinition, self) + + +def pydantic_function_tool( + model: type[pydantic.BaseModel], + *, + name: str | None = None, # inferred from class name by default + description: str | None = None, # inferred from class docstring by default +) -> ChatCompletionToolParam: + if description is None: + # note: we intentionally don't use `.getdoc()` to avoid + # including pydantic's docstrings + description = model.__doc__ + + function = PydanticFunctionTool( + { + "name": name or model.__name__, + "strict": True, + "parameters": to_strict_json_schema(model), + }, + model, + ).cast() + + if description is not None: + function["description"] = description + + return { + "type": "function", + "function": function, + } diff --git a/src/openai/lib/streaming/_deltas.py b/src/openai/lib/streaming/_deltas.py new file mode 100644 index 0000000000..a5e1317612 --- /dev/null +++ b/src/openai/lib/streaming/_deltas.py @@ -0,0 +1,64 @@ +from __future__ import annotations + +from ..._utils import is_dict, is_list + + +def accumulate_delta(acc: dict[object, object], delta: dict[object, object]) -> dict[object, object]: + for key, delta_value in delta.items(): + if key not in acc: + acc[key] = delta_value + continue + + acc_value = acc[key] + if acc_value is None: + acc[key] = delta_value + continue + + # the `index` property is used in arrays of objects so it should + # not be accumulated like other values e.g. + # [{'foo': 'bar', 'index': 0}] + # + # the same applies to `type` properties as they're used for + # discriminated unions + if key == "index" or key == "type": + acc[key] = delta_value + continue + + if isinstance(acc_value, str) and isinstance(delta_value, str): + acc_value += delta_value + elif isinstance(acc_value, (int, float)) and isinstance(delta_value, (int, float)): + acc_value += delta_value + elif is_dict(acc_value) and is_dict(delta_value): + acc_value = accumulate_delta(acc_value, delta_value) + elif is_list(acc_value) and is_list(delta_value): + # for lists of non-dictionary items we'll only ever get new entries + # in the array, existing entries will never be changed + if all(isinstance(x, (str, int, float)) for x in acc_value): + acc_value.extend(delta_value) + continue + + for delta_entry in delta_value: + if not is_dict(delta_entry): + raise TypeError(f"Unexpected list delta entry is not a dictionary: {delta_entry}") + + try: + index = delta_entry["index"] + except KeyError as exc: + raise RuntimeError(f"Expected list delta entry to have an `index` key; {delta_entry}") from exc + + if not isinstance(index, int): + raise TypeError(f"Unexpected, list delta entry `index` value is not an integer; {index}") + + try: + acc_entry = acc_value[index] + except IndexError: + acc_value.insert(index, delta_entry) + else: + if not is_dict(acc_entry): + raise TypeError("not handled yet") + + acc_value[index] = accumulate_delta(acc_entry, delta_entry) + + acc[key] = acc_value + + return acc diff --git a/src/openai/lib/streaming/chat/__init__.py b/src/openai/lib/streaming/chat/__init__.py new file mode 100644 index 0000000000..5881c39b9a --- /dev/null +++ b/src/openai/lib/streaming/chat/__init__.py @@ -0,0 +1,26 @@ +from ._types import ( + ParsedChoiceSnapshot as ParsedChoiceSnapshot, + ParsedChatCompletionSnapshot as ParsedChatCompletionSnapshot, + ParsedChatCompletionMessageSnapshot as ParsedChatCompletionMessageSnapshot, +) +from ._events import ( + ChunkEvent as ChunkEvent, + ContentDoneEvent as ContentDoneEvent, + RefusalDoneEvent as RefusalDoneEvent, + ContentDeltaEvent as ContentDeltaEvent, + RefusalDeltaEvent as RefusalDeltaEvent, + LogprobsContentDoneEvent as LogprobsContentDoneEvent, + LogprobsRefusalDoneEvent as LogprobsRefusalDoneEvent, + ChatCompletionStreamEvent as ChatCompletionStreamEvent, + LogprobsContentDeltaEvent as LogprobsContentDeltaEvent, + LogprobsRefusalDeltaEvent as LogprobsRefusalDeltaEvent, + ParsedChatCompletionSnapshot as ParsedChatCompletionSnapshot, + FunctionToolCallArgumentsDoneEvent as FunctionToolCallArgumentsDoneEvent, + FunctionToolCallArgumentsDeltaEvent as FunctionToolCallArgumentsDeltaEvent, +) +from ._completions import ( + ChatCompletionStream as ChatCompletionStream, + AsyncChatCompletionStream as AsyncChatCompletionStream, + ChatCompletionStreamManager as ChatCompletionStreamManager, + AsyncChatCompletionStreamManager as AsyncChatCompletionStreamManager, +) diff --git a/src/openai/lib/streaming/chat/_completions.py b/src/openai/lib/streaming/chat/_completions.py new file mode 100644 index 0000000000..342a5e2b95 --- /dev/null +++ b/src/openai/lib/streaming/chat/_completions.py @@ -0,0 +1,724 @@ +from __future__ import annotations + +import inspect +from types import TracebackType +from typing import TYPE_CHECKING, Any, Generic, Callable, Iterable, Awaitable, AsyncIterator, cast +from typing_extensions import Self, Iterator, assert_never + +from jiter import from_json + +from ._types import ParsedChoiceSnapshot, ParsedChatCompletionSnapshot, ParsedChatCompletionMessageSnapshot +from ._events import ( + ChunkEvent, + ContentDoneEvent, + RefusalDoneEvent, + ContentDeltaEvent, + RefusalDeltaEvent, + LogprobsContentDoneEvent, + LogprobsRefusalDoneEvent, + ChatCompletionStreamEvent, + LogprobsContentDeltaEvent, + LogprobsRefusalDeltaEvent, + FunctionToolCallArgumentsDoneEvent, + FunctionToolCallArgumentsDeltaEvent, +) +from .._deltas import accumulate_delta +from ...._types import NOT_GIVEN, NotGiven +from ...._utils import is_given, consume_sync_iterator, consume_async_iterator +from ...._compat import model_dump +from ...._models import build, construct_type +from ..._parsing import ( + ResponseFormatT, + has_parseable_input, + maybe_parse_content, + parse_chat_completion, + get_input_tool_by_name, + solve_response_format_t, + parse_function_tool_arguments, +) +from ...._streaming import Stream, AsyncStream +from ....types.chat import ChatCompletionChunk, ParsedChatCompletion, ChatCompletionToolParam +from ...._exceptions import LengthFinishReasonError, ContentFilterFinishReasonError +from ....types.chat.chat_completion import ChoiceLogprobs +from ....types.chat.chat_completion_chunk import Choice as ChoiceChunk +from ....types.chat.completion_create_params import ResponseFormat as ResponseFormatParam + + +class ChatCompletionStream(Generic[ResponseFormatT]): + """Wrapper over the Chat Completions streaming API that adds helpful + events such as `content.done`, supports automatically parsing + responses & tool calls and accumulates a `ChatCompletion` object + from each individual chunk. + + https://platform.openai.com/docs/api-reference/streaming + """ + + def __init__( + self, + *, + raw_stream: Stream[ChatCompletionChunk], + response_format: type[ResponseFormatT] | ResponseFormatParam | NotGiven, + input_tools: Iterable[ChatCompletionToolParam] | NotGiven, + ) -> None: + self._raw_stream = raw_stream + self._response = raw_stream.response + self._iterator = self.__stream__() + self._state = ChatCompletionStreamState(response_format=response_format, input_tools=input_tools) + + def __next__(self) -> ChatCompletionStreamEvent[ResponseFormatT]: + return self._iterator.__next__() + + def __iter__(self) -> Iterator[ChatCompletionStreamEvent[ResponseFormatT]]: + for item in self._iterator: + yield item + + def __enter__(self) -> Self: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.close() + + def close(self) -> None: + """ + Close the response and release the connection. + + Automatically called if the response body is read to completion. + """ + self._response.close() + + def get_final_completion(self) -> ParsedChatCompletion[ResponseFormatT]: + """Waits until the stream has been read to completion and returns + the accumulated `ParsedChatCompletion` object. + + If you passed a class type to `.stream()`, the `completion.choices[0].message.parsed` + property will be the content deserialised into that class, if there was any content returned + by the API. + """ + self.until_done() + return self._state.get_final_completion() + + def until_done(self) -> Self: + """Blocks until the stream has been consumed.""" + consume_sync_iterator(self) + return self + + @property + def current_completion_snapshot(self) -> ParsedChatCompletionSnapshot: + return self._state.current_completion_snapshot + + def __stream__(self) -> Iterator[ChatCompletionStreamEvent[ResponseFormatT]]: + for sse_event in self._raw_stream: + events_to_fire = self._state.handle_chunk(sse_event) + for event in events_to_fire: + yield event + + +class ChatCompletionStreamManager(Generic[ResponseFormatT]): + """Context manager over a `ChatCompletionStream` that is returned by `.stream()`. + + This context manager ensures the response cannot be leaked if you don't read + the stream to completion. + + Usage: + ```py + with client.beta.chat.completions.stream(...) as stream: + for event in stream: + ... + ``` + """ + + def __init__( + self, + api_request: Callable[[], Stream[ChatCompletionChunk]], + *, + response_format: type[ResponseFormatT] | ResponseFormatParam | NotGiven, + input_tools: Iterable[ChatCompletionToolParam] | NotGiven, + ) -> None: + self.__stream: ChatCompletionStream[ResponseFormatT] | None = None + self.__api_request = api_request + self.__response_format = response_format + self.__input_tools = input_tools + + def __enter__(self) -> ChatCompletionStream[ResponseFormatT]: + raw_stream = self.__api_request() + + self.__stream = ChatCompletionStream( + raw_stream=raw_stream, + response_format=self.__response_format, + input_tools=self.__input_tools, + ) + + return self.__stream + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self.__stream is not None: + self.__stream.close() + + +class AsyncChatCompletionStream(Generic[ResponseFormatT]): + """Wrapper over the Chat Completions streaming API that adds helpful + events such as `content.done`, supports automatically parsing + responses & tool calls and accumulates a `ChatCompletion` object + from each individual chunk. + + https://platform.openai.com/docs/api-reference/streaming + """ + + def __init__( + self, + *, + raw_stream: AsyncStream[ChatCompletionChunk], + response_format: type[ResponseFormatT] | ResponseFormatParam | NotGiven, + input_tools: Iterable[ChatCompletionToolParam] | NotGiven, + ) -> None: + self._raw_stream = raw_stream + self._response = raw_stream.response + self._iterator = self.__stream__() + self._state = ChatCompletionStreamState(response_format=response_format, input_tools=input_tools) + + async def __anext__(self) -> ChatCompletionStreamEvent[ResponseFormatT]: + return await self._iterator.__anext__() + + async def __aiter__(self) -> AsyncIterator[ChatCompletionStreamEvent[ResponseFormatT]]: + async for item in self._iterator: + yield item + + async def __aenter__(self) -> Self: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + await self.close() + + async def close(self) -> None: + """ + Close the response and release the connection. + + Automatically called if the response body is read to completion. + """ + await self._response.aclose() + + async def get_final_completion(self) -> ParsedChatCompletion[ResponseFormatT]: + """Waits until the stream has been read to completion and returns + the accumulated `ParsedChatCompletion` object. + + If you passed a class type to `.stream()`, the `completion.choices[0].message.parsed` + property will be the content deserialised into that class, if there was any content returned + by the API. + """ + await self.until_done() + return self._state.get_final_completion() + + async def until_done(self) -> Self: + """Blocks until the stream has been consumed.""" + await consume_async_iterator(self) + return self + + @property + def current_completion_snapshot(self) -> ParsedChatCompletionSnapshot: + return self._state.current_completion_snapshot + + async def __stream__(self) -> AsyncIterator[ChatCompletionStreamEvent[ResponseFormatT]]: + async for sse_event in self._raw_stream: + events_to_fire = self._state.handle_chunk(sse_event) + for event in events_to_fire: + yield event + + +class AsyncChatCompletionStreamManager(Generic[ResponseFormatT]): + """Context manager over a `AsyncChatCompletionStream` that is returned by `.stream()`. + + This context manager ensures the response cannot be leaked if you don't read + the stream to completion. + + Usage: + ```py + async with client.beta.chat.completions.stream(...) as stream: + for event in stream: + ... + ``` + """ + + def __init__( + self, + api_request: Awaitable[AsyncStream[ChatCompletionChunk]], + *, + response_format: type[ResponseFormatT] | ResponseFormatParam | NotGiven, + input_tools: Iterable[ChatCompletionToolParam] | NotGiven, + ) -> None: + self.__stream: AsyncChatCompletionStream[ResponseFormatT] | None = None + self.__api_request = api_request + self.__response_format = response_format + self.__input_tools = input_tools + + async def __aenter__(self) -> AsyncChatCompletionStream[ResponseFormatT]: + raw_stream = await self.__api_request + + self.__stream = AsyncChatCompletionStream( + raw_stream=raw_stream, + response_format=self.__response_format, + input_tools=self.__input_tools, + ) + + return self.__stream + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self.__stream is not None: + await self.__stream.close() + + +class ChatCompletionStreamState(Generic[ResponseFormatT]): + def __init__( + self, + *, + input_tools: Iterable[ChatCompletionToolParam] | NotGiven, + response_format: type[ResponseFormatT] | ResponseFormatParam | NotGiven, + ) -> None: + self.__current_completion_snapshot: ParsedChatCompletionSnapshot | None = None + self.__choice_event_states: list[ChoiceEventState] = [] + + self._input_tools = [tool for tool in input_tools] if is_given(input_tools) else [] + self._response_format = response_format + self._rich_response_format: type | NotGiven = response_format if inspect.isclass(response_format) else NOT_GIVEN + + def get_final_completion(self) -> ParsedChatCompletion[ResponseFormatT]: + return parse_chat_completion( + chat_completion=self.current_completion_snapshot, + response_format=self._rich_response_format, + input_tools=self._input_tools, + ) + + @property + def current_completion_snapshot(self) -> ParsedChatCompletionSnapshot: + assert self.__current_completion_snapshot is not None + return self.__current_completion_snapshot + + def handle_chunk(self, chunk: ChatCompletionChunk) -> list[ChatCompletionStreamEvent[ResponseFormatT]]: + """Accumulate a new chunk into the snapshot and returns a list of events to yield.""" + self.__current_completion_snapshot = self._accumulate_chunk(chunk) + + return self._build_events( + chunk=chunk, + completion_snapshot=self.__current_completion_snapshot, + ) + + def _get_choice_state(self, choice: ChoiceChunk) -> ChoiceEventState: + try: + return self.__choice_event_states[choice.index] + except IndexError: + choice_state = ChoiceEventState(input_tools=self._input_tools) + self.__choice_event_states.append(choice_state) + return choice_state + + def _accumulate_chunk(self, chunk: ChatCompletionChunk) -> ParsedChatCompletionSnapshot: + completion_snapshot = self.__current_completion_snapshot + + if completion_snapshot is None: + return _convert_initial_chunk_into_snapshot(chunk) + + for choice in chunk.choices: + try: + choice_snapshot = completion_snapshot.choices[choice.index] + previous_tool_calls = choice_snapshot.message.tool_calls or [] + + choice_snapshot.message = cast( + ParsedChatCompletionMessageSnapshot, + construct_type( + type_=ParsedChatCompletionMessageSnapshot, + value=accumulate_delta( + cast( + "dict[object, object]", + model_dump( + choice_snapshot.message, + # we don't want to serialise / deserialise our custom properties + # as they won't appear in the delta and we don't want to have to + # continuosly reparse the content + exclude={ + "parsed": True, + "tool_calls": { + idx: {"function": {"parsed_arguments": True}} + for idx, _ in enumerate(choice_snapshot.message.tool_calls or []) + }, + }, + ), + ), + cast("dict[object, object]", choice.delta.to_dict()), + ), + ), + ) + + # ensure tools that have already been parsed are added back into the newly + # constructed message snapshot + for tool_index, prev_tool in enumerate(previous_tool_calls): + new_tool = (choice_snapshot.message.tool_calls or [])[tool_index] + + if prev_tool.type == "function": + assert new_tool.type == "function" + new_tool.function.parsed_arguments = prev_tool.function.parsed_arguments + elif TYPE_CHECKING: # type: ignore[unreachable] + assert_never(prev_tool) + except IndexError: + choice_snapshot = cast( + ParsedChoiceSnapshot, + construct_type( + type_=ParsedChoiceSnapshot, + value={ + **choice.model_dump(exclude_unset=True, exclude={"delta"}), + "message": choice.delta.to_dict(), + }, + ), + ) + completion_snapshot.choices.append(choice_snapshot) + + if choice.finish_reason: + choice_snapshot.finish_reason = choice.finish_reason + + if has_parseable_input(response_format=self._response_format, input_tools=self._input_tools): + if choice.finish_reason == "length": + raise LengthFinishReasonError() + + if choice.finish_reason == "content_filter": + raise ContentFilterFinishReasonError() + + if ( + choice_snapshot.message.content + and not choice_snapshot.message.refusal + and is_given(self._rich_response_format) + ): + choice_snapshot.message.parsed = from_json( + bytes(choice_snapshot.message.content, "utf-8"), + partial_mode=True, + ) + + for tool_call_chunk in choice.delta.tool_calls or []: + tool_call_snapshot = (choice_snapshot.message.tool_calls or [])[tool_call_chunk.index] + + if tool_call_snapshot.type == "function": + input_tool = get_input_tool_by_name( + input_tools=self._input_tools, name=tool_call_snapshot.function.name + ) + + if ( + input_tool + and input_tool.get("function", {}).get("strict") + and tool_call_snapshot.function.arguments + ): + tool_call_snapshot.function.parsed_arguments = from_json( + bytes(tool_call_snapshot.function.arguments, "utf-8"), + partial_mode=True, + ) + elif TYPE_CHECKING: # type: ignore[unreachable] + assert_never(tool_call_snapshot) + + if choice.logprobs is not None: + if choice_snapshot.logprobs is None: + choice_snapshot.logprobs = build( + ChoiceLogprobs, + content=choice.logprobs.content, + refusal=choice.logprobs.refusal, + ) + else: + if choice.logprobs.content: + if choice_snapshot.logprobs.content is None: + choice_snapshot.logprobs.content = [] + + choice_snapshot.logprobs.content.extend(choice.logprobs.content) + + if choice.logprobs.refusal: + if choice_snapshot.logprobs.refusal is None: + choice_snapshot.logprobs.refusal = [] + + choice_snapshot.logprobs.refusal.extend(choice.logprobs.refusal) + + completion_snapshot.usage = chunk.usage + completion_snapshot.system_fingerprint = chunk.system_fingerprint + + return completion_snapshot + + def _build_events( + self, + *, + chunk: ChatCompletionChunk, + completion_snapshot: ParsedChatCompletionSnapshot, + ) -> list[ChatCompletionStreamEvent[ResponseFormatT]]: + events_to_fire: list[ChatCompletionStreamEvent[ResponseFormatT]] = [] + + events_to_fire.append( + build(ChunkEvent, type="chunk", chunk=chunk, snapshot=completion_snapshot), + ) + + for choice in chunk.choices: + choice_state = self._get_choice_state(choice) + choice_snapshot = completion_snapshot.choices[choice.index] + + if choice.delta.content is not None and choice_snapshot.message.content is not None: + events_to_fire.append( + build( + ContentDeltaEvent, + type="content.delta", + delta=choice.delta.content, + snapshot=choice_snapshot.message.content, + parsed=choice_snapshot.message.parsed, + ) + ) + + if choice.delta.refusal is not None and choice_snapshot.message.refusal is not None: + events_to_fire.append( + build( + RefusalDeltaEvent, + type="refusal.delta", + delta=choice.delta.refusal, + snapshot=choice_snapshot.message.refusal, + ) + ) + + if choice.delta.tool_calls: + tool_calls = choice_snapshot.message.tool_calls + assert tool_calls is not None + + for tool_call_delta in choice.delta.tool_calls: + tool_call = tool_calls[tool_call_delta.index] + + if tool_call.type == "function": + assert tool_call_delta.function is not None + events_to_fire.append( + build( + FunctionToolCallArgumentsDeltaEvent, + type="tool_calls.function.arguments.delta", + name=tool_call.function.name, + index=tool_call_delta.index, + arguments=tool_call.function.arguments, + parsed_arguments=tool_call.function.parsed_arguments, + arguments_delta=tool_call_delta.function.arguments or "", + ) + ) + elif TYPE_CHECKING: # type: ignore[unreachable] + assert_never(tool_call) + + if choice.logprobs is not None and choice_snapshot.logprobs is not None: + if choice.logprobs.content and choice_snapshot.logprobs.content: + events_to_fire.append( + build( + LogprobsContentDeltaEvent, + type="logprobs.content.delta", + content=choice.logprobs.content, + snapshot=choice_snapshot.logprobs.content, + ), + ) + + if choice.logprobs.refusal and choice_snapshot.logprobs.refusal: + events_to_fire.append( + build( + LogprobsRefusalDeltaEvent, + type="logprobs.refusal.delta", + refusal=choice.logprobs.refusal, + snapshot=choice_snapshot.logprobs.refusal, + ), + ) + + events_to_fire.extend( + choice_state.get_done_events( + choice_chunk=choice, + choice_snapshot=choice_snapshot, + response_format=self._response_format, + ) + ) + + return events_to_fire + + +class ChoiceEventState: + def __init__(self, *, input_tools: list[ChatCompletionToolParam]) -> None: + self._input_tools = input_tools + + self._content_done = False + self._refusal_done = False + self._logprobs_content_done = False + self._logprobs_refusal_done = False + self._done_tool_calls: set[int] = set() + self.__current_tool_call_index: int | None = None + + def get_done_events( + self, + *, + choice_chunk: ChoiceChunk, + choice_snapshot: ParsedChoiceSnapshot, + response_format: type[ResponseFormatT] | ResponseFormatParam | NotGiven, + ) -> list[ChatCompletionStreamEvent[ResponseFormatT]]: + events_to_fire: list[ChatCompletionStreamEvent[ResponseFormatT]] = [] + + if choice_snapshot.finish_reason: + events_to_fire.extend( + self._content_done_events(choice_snapshot=choice_snapshot, response_format=response_format) + ) + + if ( + self.__current_tool_call_index is not None + and self.__current_tool_call_index not in self._done_tool_calls + ): + self._add_tool_done_event( + events_to_fire=events_to_fire, + choice_snapshot=choice_snapshot, + tool_index=self.__current_tool_call_index, + ) + + for tool_call in choice_chunk.delta.tool_calls or []: + if self.__current_tool_call_index != tool_call.index: + events_to_fire.extend( + self._content_done_events(choice_snapshot=choice_snapshot, response_format=response_format) + ) + + if self.__current_tool_call_index is not None: + self._add_tool_done_event( + events_to_fire=events_to_fire, + choice_snapshot=choice_snapshot, + tool_index=self.__current_tool_call_index, + ) + + self.__current_tool_call_index = tool_call.index + + return events_to_fire + + def _content_done_events( + self, + *, + choice_snapshot: ParsedChoiceSnapshot, + response_format: type[ResponseFormatT] | ResponseFormatParam | NotGiven, + ) -> list[ChatCompletionStreamEvent[ResponseFormatT]]: + events_to_fire: list[ChatCompletionStreamEvent[ResponseFormatT]] = [] + + if choice_snapshot.message.content and not self._content_done: + self._content_done = True + + parsed = maybe_parse_content( + response_format=response_format, + message=choice_snapshot.message, + ) + + # update the parsed content to now use the richer `response_format` + # as opposed to the raw JSON-parsed object as the content is now + # complete and can be fully validated. + choice_snapshot.message.parsed = parsed + + events_to_fire.append( + build( + # we do this dance so that when the `ContentDoneEvent` instance + # is printed at runtime the class name will include the solved + # type variable, e.g. `ContentDoneEvent[MyModelType]` + cast( # pyright: ignore[reportUnnecessaryCast] + "type[ContentDoneEvent[ResponseFormatT]]", + cast(Any, ContentDoneEvent)[solve_response_format_t(response_format)], + ), + type="content.done", + content=choice_snapshot.message.content, + parsed=parsed, + ), + ) + + if choice_snapshot.message.refusal is not None and not self._refusal_done: + self._refusal_done = True + events_to_fire.append( + build(RefusalDoneEvent, type="refusal.done", refusal=choice_snapshot.message.refusal), + ) + + if ( + choice_snapshot.logprobs is not None + and choice_snapshot.logprobs.content is not None + and not self._logprobs_content_done + ): + self._logprobs_content_done = True + events_to_fire.append( + build(LogprobsContentDoneEvent, type="logprobs.content.done", content=choice_snapshot.logprobs.content), + ) + + if ( + choice_snapshot.logprobs is not None + and choice_snapshot.logprobs.refusal is not None + and not self._logprobs_refusal_done + ): + self._logprobs_refusal_done = True + events_to_fire.append( + build(LogprobsRefusalDoneEvent, type="logprobs.refusal.done", refusal=choice_snapshot.logprobs.refusal), + ) + + return events_to_fire + + def _add_tool_done_event( + self, + *, + events_to_fire: list[ChatCompletionStreamEvent[ResponseFormatT]], + choice_snapshot: ParsedChoiceSnapshot, + tool_index: int, + ) -> None: + if tool_index in self._done_tool_calls: + return + + self._done_tool_calls.add(tool_index) + + assert choice_snapshot.message.tool_calls is not None + tool_call_snapshot = choice_snapshot.message.tool_calls[tool_index] + + if tool_call_snapshot.type == "function": + parsed_arguments = parse_function_tool_arguments( + input_tools=self._input_tools, function=tool_call_snapshot.function + ) + + # update the parsed content to potentially use a richer type + # as opposed to the raw JSON-parsed object as the content is now + # complete and can be fully validated. + tool_call_snapshot.function.parsed_arguments = parsed_arguments + + events_to_fire.append( + build( + FunctionToolCallArgumentsDoneEvent, + type="tool_calls.function.arguments.done", + index=tool_index, + name=tool_call_snapshot.function.name, + arguments=tool_call_snapshot.function.arguments, + parsed_arguments=parsed_arguments, + ) + ) + elif TYPE_CHECKING: # type: ignore[unreachable] + assert_never(tool_call_snapshot) + + +def _convert_initial_chunk_into_snapshot(chunk: ChatCompletionChunk) -> ParsedChatCompletionSnapshot: + data = chunk.to_dict() + choices = cast("list[object]", data["choices"]) + + for choice in chunk.choices: + choices[choice.index] = { + **choice.model_dump(exclude_unset=True, exclude={"delta"}), + "message": choice.delta.to_dict(), + } + + return cast( + ParsedChatCompletionSnapshot, + construct_type( + type_=ParsedChatCompletionSnapshot, + value={ + "system_fingerprint": None, + **data, + "object": "chat.completion", + }, + ), + ) diff --git a/src/openai/lib/streaming/chat/_events.py b/src/openai/lib/streaming/chat/_events.py new file mode 100644 index 0000000000..d4c1f28300 --- /dev/null +++ b/src/openai/lib/streaming/chat/_events.py @@ -0,0 +1,123 @@ +from typing import List, Union, Generic, Optional +from typing_extensions import Literal + +from ._types import ParsedChatCompletionSnapshot +from ...._models import BaseModel, GenericModel +from ..._parsing import ResponseFormatT +from ....types.chat import ChatCompletionChunk, ChatCompletionTokenLogprob + + +class ChunkEvent(BaseModel): + type: Literal["chunk"] + + chunk: ChatCompletionChunk + + snapshot: ParsedChatCompletionSnapshot + + +class ContentDeltaEvent(BaseModel): + """This event is yielded for every chunk with `choice.delta.content` data.""" + + type: Literal["content.delta"] + + delta: str + + snapshot: str + + parsed: Optional[object] = None + + +class ContentDoneEvent(GenericModel, Generic[ResponseFormatT]): + type: Literal["content.done"] + + content: str + + parsed: Optional[ResponseFormatT] = None + + +class RefusalDeltaEvent(BaseModel): + type: Literal["refusal.delta"] + + delta: str + + snapshot: str + + +class RefusalDoneEvent(BaseModel): + type: Literal["refusal.done"] + + refusal: str + + +class FunctionToolCallArgumentsDeltaEvent(BaseModel): + type: Literal["tool_calls.function.arguments.delta"] + + name: str + + index: int + + arguments: str + """Accumulated raw JSON string""" + + parsed_arguments: object + """The parsed arguments so far""" + + arguments_delta: str + """The JSON string delta""" + + +class FunctionToolCallArgumentsDoneEvent(BaseModel): + type: Literal["tool_calls.function.arguments.done"] + + name: str + + index: int + + arguments: str + """Accumulated raw JSON string""" + + parsed_arguments: object + """The parsed arguments""" + + +class LogprobsContentDeltaEvent(BaseModel): + type: Literal["logprobs.content.delta"] + + content: List[ChatCompletionTokenLogprob] + + snapshot: List[ChatCompletionTokenLogprob] + + +class LogprobsContentDoneEvent(BaseModel): + type: Literal["logprobs.content.done"] + + content: List[ChatCompletionTokenLogprob] + + +class LogprobsRefusalDeltaEvent(BaseModel): + type: Literal["logprobs.refusal.delta"] + + refusal: List[ChatCompletionTokenLogprob] + + snapshot: List[ChatCompletionTokenLogprob] + + +class LogprobsRefusalDoneEvent(BaseModel): + type: Literal["logprobs.refusal.done"] + + refusal: List[ChatCompletionTokenLogprob] + + +ChatCompletionStreamEvent = Union[ + ChunkEvent, + ContentDeltaEvent, + ContentDoneEvent[ResponseFormatT], + RefusalDeltaEvent, + RefusalDoneEvent, + FunctionToolCallArgumentsDeltaEvent, + FunctionToolCallArgumentsDoneEvent, + LogprobsContentDeltaEvent, + LogprobsContentDoneEvent, + LogprobsRefusalDeltaEvent, + LogprobsRefusalDoneEvent, +] diff --git a/src/openai/lib/streaming/chat/_types.py b/src/openai/lib/streaming/chat/_types.py new file mode 100644 index 0000000000..42552893a0 --- /dev/null +++ b/src/openai/lib/streaming/chat/_types.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +from typing_extensions import TypeAlias + +from ....types.chat import ParsedChoice, ParsedChatCompletion, ParsedChatCompletionMessage + +ParsedChatCompletionSnapshot: TypeAlias = ParsedChatCompletion[object] +"""Snapshot type representing an in-progress accumulation of +a `ParsedChatCompletion` object. +""" + +ParsedChatCompletionMessageSnapshot: TypeAlias = ParsedChatCompletionMessage[object] +"""Snapshot type representing an in-progress accumulation of +a `ParsedChatCompletionMessage` object. + +If the content has been fully accumulated, the `.parsed` content will be +the `response_format` instance, otherwise it'll be the raw JSON parsed version. +""" + +ParsedChoiceSnapshot: TypeAlias = ParsedChoice[object] diff --git a/src/openai/resources/beta/assistants.py b/src/openai/resources/beta/assistants.py index b4dc3cfdd6..441390d24b 100644 --- a/src/openai/resources/beta/assistants.py +++ b/src/openai/resources/beta/assistants.py @@ -88,6 +88,11 @@ def create( [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -233,6 +238,11 @@ def update( [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -453,6 +463,11 @@ async def create( [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -598,6 +613,11 @@ async def update( [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. diff --git a/src/openai/resources/beta/beta.py b/src/openai/resources/beta/beta.py index 0d9806678f..479c97c471 100644 --- a/src/openai/resources/beta/beta.py +++ b/src/openai/resources/beta/beta.py @@ -11,6 +11,7 @@ AsyncThreadsWithStreamingResponse, ) from ..._compat import cached_property +from .chat.chat import Chat, AsyncChat from .assistants import ( Assistants, AsyncAssistants, @@ -35,6 +36,10 @@ class Beta(SyncAPIResource): + @cached_property + def chat(self) -> Chat: + return Chat(self._client) + @cached_property def vector_stores(self) -> VectorStores: return VectorStores(self._client) @@ -57,6 +62,10 @@ def with_streaming_response(self) -> BetaWithStreamingResponse: class AsyncBeta(AsyncAPIResource): + @cached_property + def chat(self) -> AsyncChat: + return AsyncChat(self._client) + @cached_property def vector_stores(self) -> AsyncVectorStores: return AsyncVectorStores(self._client) diff --git a/src/openai/resources/beta/chat/__init__.py b/src/openai/resources/beta/chat/__init__.py new file mode 100644 index 0000000000..072d7867a5 --- /dev/null +++ b/src/openai/resources/beta/chat/__init__.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .chat import Chat, AsyncChat +from .completions import Completions, AsyncCompletions + +__all__ = [ + "Completions", + "AsyncCompletions", + "Chat", + "AsyncChat", +] diff --git a/src/openai/resources/beta/chat/chat.py b/src/openai/resources/beta/chat/chat.py new file mode 100644 index 0000000000..6afdcea381 --- /dev/null +++ b/src/openai/resources/beta/chat/chat.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from ...._compat import cached_property +from .completions import Completions, AsyncCompletions +from ...._resource import SyncAPIResource, AsyncAPIResource + +__all__ = ["Chat", "AsyncChat"] + + +class Chat(SyncAPIResource): + @cached_property + def completions(self) -> Completions: + return Completions(self._client) + + +class AsyncChat(AsyncAPIResource): + @cached_property + def completions(self) -> AsyncCompletions: + return AsyncCompletions(self._client) diff --git a/src/openai/resources/beta/chat/completions.py b/src/openai/resources/beta/chat/completions.py new file mode 100644 index 0000000000..88ea2c0572 --- /dev/null +++ b/src/openai/resources/beta/chat/completions.py @@ -0,0 +1,449 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List, Union, Iterable, Optional +from functools import partial +from typing_extensions import Literal + +import httpx + +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ...._resource import SyncAPIResource, AsyncAPIResource +from ...._streaming import Stream +from ....types.chat import completion_create_params +from ....lib._parsing import ( + ResponseFormatT, + validate_input_tools as _validate_input_tools, + parse_chat_completion as _parse_chat_completion, + type_to_response_format_param as _type_to_response_format, +) +from ....types.chat_model import ChatModel +from ....lib.streaming.chat import ChatCompletionStreamManager, AsyncChatCompletionStreamManager +from ....types.chat.chat_completion_chunk import ChatCompletionChunk +from ....types.chat.parsed_chat_completion import ParsedChatCompletion +from ....types.chat.chat_completion_tool_param import ChatCompletionToolParam +from ....types.chat.chat_completion_message_param import ChatCompletionMessageParam +from ....types.chat.chat_completion_stream_options_param import ChatCompletionStreamOptionsParam +from ....types.chat.chat_completion_tool_choice_option_param import ChatCompletionToolChoiceOptionParam + +__all__ = ["Completions", "AsyncCompletions"] + + +class Completions(SyncAPIResource): + def parse( + self, + *, + messages: Iterable[ChatCompletionMessageParam], + model: Union[str, ChatModel], + response_format: type[ResponseFormatT] | NotGiven = NOT_GIVEN, + frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, + function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, + functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, + logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + logprobs: Optional[bool] | NotGiven = NOT_GIVEN, + max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + n: Optional[int] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + seed: Optional[int] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, + tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, + top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> ParsedChatCompletion[ResponseFormatT]: + """Wrapper over the `client.chat.completions.create()` method that provides richer integrations with Python specific types + & returns a `ParsedChatCompletion` object, which is a subclass of the standard `ChatCompletion` class. + + You can pass a pydantic model to this method and it will automatically convert the model + into a JSON schema, send it to the API and parse the response content back into the given model. + + This method will also automatically parse `function` tool calls if: + - You use the `openai.pydantic_function_tool()` helper method + - You mark your tool schema with `"strict": True` + + Example usage: + ```py + from pydantic import BaseModel + from openai import OpenAI + + class Step(BaseModel): + explanation: str + output: str + + class MathResponse(BaseModel): + steps: List[Step] + final_answer: str + + client = OpenAI() + completion = client.beta.chat.completions.parse( + model="gpt-4o-2024-08-06", + messages=[ + {"role": "system", "content": "You are a helpful math tutor."}, + {"role": "user", "content": "solve 8x + 31 = 2"}, + ], + response_format=MathResponse, + ) + + message = completion.choices[0].message + if message.parsed: + print(message.parsed.steps) + print("answer: ", message.parsed.final_answer) + ``` + """ + _validate_input_tools(tools) + + extra_headers = { + "X-Stainless-Helper-Method": "beta.chat.completions.parse", + **(extra_headers or {}), + } + + raw_completion = self._client.chat.completions.create( + messages=messages, + model=model, + response_format=_type_to_response_format(response_format), + frequency_penalty=frequency_penalty, + function_call=function_call, + functions=functions, + logit_bias=logit_bias, + logprobs=logprobs, + max_tokens=max_tokens, + n=n, + parallel_tool_calls=parallel_tool_calls, + presence_penalty=presence_penalty, + seed=seed, + service_tier=service_tier, + stop=stop, + stream_options=stream_options, + temperature=temperature, + tool_choice=tool_choice, + tools=tools, + top_logprobs=top_logprobs, + top_p=top_p, + user=user, + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + ) + return _parse_chat_completion( + response_format=response_format, + chat_completion=raw_completion, + input_tools=tools, + ) + + def stream( + self, + *, + messages: Iterable[ChatCompletionMessageParam], + model: Union[str, ChatModel], + response_format: completion_create_params.ResponseFormat | type[ResponseFormatT] | NotGiven = NOT_GIVEN, + frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, + function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, + functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, + logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + logprobs: Optional[bool] | NotGiven = NOT_GIVEN, + max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + n: Optional[int] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + seed: Optional[int] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, + tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, + top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> ChatCompletionStreamManager[ResponseFormatT]: + """Wrapper over the `client.chat.completions.create(stream=True)` method that provides a more granular event API + and automatic accumulation of each delta. + + This also supports all of the parsing utilities that `.parse()` does. + + Unlike `.create(stream=True)`, the `.stream()` method requires usage within a context manager to prevent accidental leakage of the response: + + ```py + with client.beta.chat.completions.stream( + model='gpt-4o-2024-08-06', + messages=[...], + ) as stream: + for event in stream: + if event.type == 'content.delta': + print(event.content, flush=True, end='') + ``` + + When the context manager is entered, a `ChatCompletionStream` instance is returned which, like `.create(stream=True)` is an iterator. The full list of events that are yielded by the iterator are outlined in [these docs](https://github.com/openai/openai-python/blob/main/helpers.md#chat-completions-events). + + When the context manager exits, the response will be closed, however the `stream` instance is still available outside + the context manager. + """ + extra_headers = { + "X-Stainless-Helper-Method": "beta.chat.completions.stream", + **(extra_headers or {}), + } + + api_request: partial[Stream[ChatCompletionChunk]] = partial( + self._client.chat.completions.create, + messages=messages, + model=model, + stream=True, + response_format=_type_to_response_format(response_format), + frequency_penalty=frequency_penalty, + function_call=function_call, + functions=functions, + logit_bias=logit_bias, + logprobs=logprobs, + max_tokens=max_tokens, + n=n, + parallel_tool_calls=parallel_tool_calls, + presence_penalty=presence_penalty, + seed=seed, + service_tier=service_tier, + stop=stop, + stream_options=stream_options, + temperature=temperature, + tool_choice=tool_choice, + tools=tools, + top_logprobs=top_logprobs, + top_p=top_p, + user=user, + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + ) + return ChatCompletionStreamManager( + api_request, + response_format=response_format, + input_tools=tools, + ) + + +class AsyncCompletions(AsyncAPIResource): + async def parse( + self, + *, + messages: Iterable[ChatCompletionMessageParam], + model: Union[str, ChatModel], + response_format: type[ResponseFormatT] | NotGiven = NOT_GIVEN, + frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, + function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, + functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, + logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + logprobs: Optional[bool] | NotGiven = NOT_GIVEN, + max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + n: Optional[int] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + seed: Optional[int] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, + tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, + top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> ParsedChatCompletion[ResponseFormatT]: + """Wrapper over the `client.chat.completions.create()` method that provides richer integrations with Python specific types + & returns a `ParsedChatCompletion` object, which is a subclass of the standard `ChatCompletion` class. + + You can pass a pydantic model to this method and it will automatically convert the model + into a JSON schema, send it to the API and parse the response content back into the given model. + + This method will also automatically parse `function` tool calls if: + - You use the `openai.pydantic_function_tool()` helper method + - You mark your tool schema with `"strict": True` + + Example usage: + ```py + from pydantic import BaseModel + from openai import AsyncOpenAI + + class Step(BaseModel): + explanation: str + output: str + + class MathResponse(BaseModel): + steps: List[Step] + final_answer: str + + client = AsyncOpenAI() + completion = await client.beta.chat.completions.parse( + model="gpt-4o-2024-08-06", + messages=[ + {"role": "system", "content": "You are a helpful math tutor."}, + {"role": "user", "content": "solve 8x + 31 = 2"}, + ], + response_format=MathResponse, + ) + + message = completion.choices[0].message + if message.parsed: + print(message.parsed.steps) + print("answer: ", message.parsed.final_answer) + ``` + """ + _validate_input_tools(tools) + + extra_headers = { + "X-Stainless-Helper-Method": "beta.chat.completions.parse", + **(extra_headers or {}), + } + + raw_completion = await self._client.chat.completions.create( + messages=messages, + model=model, + response_format=_type_to_response_format(response_format), + frequency_penalty=frequency_penalty, + function_call=function_call, + functions=functions, + logit_bias=logit_bias, + logprobs=logprobs, + max_tokens=max_tokens, + n=n, + parallel_tool_calls=parallel_tool_calls, + presence_penalty=presence_penalty, + seed=seed, + service_tier=service_tier, + stop=stop, + stream_options=stream_options, + temperature=temperature, + tool_choice=tool_choice, + tools=tools, + top_logprobs=top_logprobs, + top_p=top_p, + user=user, + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + ) + return _parse_chat_completion( + response_format=response_format, + chat_completion=raw_completion, + input_tools=tools, + ) + + def stream( + self, + *, + messages: Iterable[ChatCompletionMessageParam], + model: Union[str, ChatModel], + response_format: completion_create_params.ResponseFormat | type[ResponseFormatT] | NotGiven = NOT_GIVEN, + frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, + function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, + functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, + logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, + logprobs: Optional[bool] | NotGiven = NOT_GIVEN, + max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + n: Optional[int] | NotGiven = NOT_GIVEN, + parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + seed: Optional[int] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, + tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, + top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncChatCompletionStreamManager[ResponseFormatT]: + """Wrapper over the `client.chat.completions.create(stream=True)` method that provides a more granular event API + and automatic accumulation of each delta. + + This also supports all of the parsing utilities that `.parse()` does. + + Unlike `.create(stream=True)`, the `.stream()` method requires usage within a context manager to prevent accidental leakage of the response: + + ```py + async with client.beta.chat.completions.stream( + model='gpt-4o-2024-08-06', + messages=[...], + ) as stream: + async for event in stream: + if event.type == 'content.delta': + print(event.content, flush=True, end='') + ``` + + When the context manager is entered, an `AsyncChatCompletionStream` instance is returned which, like `.create(stream=True)` is an async iterator. The full list of events that are yielded by the iterator are outlined in [these docs](https://github.com/openai/openai-python/blob/main/helpers.md#chat-completions-events). + + When the context manager exits, the response will be closed, however the `stream` instance is still available outside + the context manager. + """ + _validate_input_tools(tools) + + extra_headers = { + "X-Stainless-Helper-Method": "beta.chat.completions.stream", + **(extra_headers or {}), + } + + api_request = self._client.chat.completions.create( + messages=messages, + model=model, + stream=True, + response_format=_type_to_response_format(response_format), + frequency_penalty=frequency_penalty, + function_call=function_call, + functions=functions, + logit_bias=logit_bias, + logprobs=logprobs, + max_tokens=max_tokens, + n=n, + parallel_tool_calls=parallel_tool_calls, + presence_penalty=presence_penalty, + seed=seed, + service_tier=service_tier, + stop=stop, + stream_options=stream_options, + temperature=temperature, + tool_choice=tool_choice, + tools=tools, + top_logprobs=top_logprobs, + top_p=top_p, + user=user, + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + ) + return AsyncChatCompletionStreamManager( + api_request, + response_format=response_format, + input_tools=tools, + ) diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 23a09d30ce..cbfb9546f0 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -145,6 +145,11 @@ def create( [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -275,6 +280,11 @@ def create( [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -401,6 +411,11 @@ def create( [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -1443,6 +1458,11 @@ async def create( [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -1573,6 +1593,11 @@ async def create( [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -1699,6 +1724,11 @@ async def create( [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index f40e164180..4c95c484cc 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -323,6 +323,11 @@ def create_and_run( [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -452,6 +457,11 @@ def create_and_run( [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -577,6 +587,11 @@ def create_and_run( [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -1131,6 +1146,11 @@ async def create_and_run( [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -1260,6 +1280,11 @@ async def create_and_run( [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -1385,6 +1410,11 @@ async def create_and_run( [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index 88892d1d64..3dcd3774d7 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -19,9 +19,7 @@ from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ..._streaming import Stream, AsyncStream from ...types.chat import completion_create_params -from ..._base_client import ( - make_request_options, -) +from ..._base_client import make_request_options from ...types.chat_model import ChatModel from ...types.chat.chat_completion import ChatCompletion from ...types.chat.chat_completion_chunk import ChatCompletionChunk @@ -144,6 +142,8 @@ def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) response_format: An object specifying the format that the model must output. Compatible with + [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4o mini](https://platform.openai.com/docs/models/gpt-4o-mini), [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. @@ -340,6 +340,8 @@ def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) response_format: An object specifying the format that the model must output. Compatible with + [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4o mini](https://platform.openai.com/docs/models/gpt-4o-mini), [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. @@ -529,6 +531,8 @@ def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) response_format: An object specifying the format that the model must output. Compatible with + [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4o mini](https://platform.openai.com/docs/models/gpt-4o-mini), [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. @@ -793,6 +797,8 @@ async def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) response_format: An object specifying the format that the model must output. Compatible with + [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4o mini](https://platform.openai.com/docs/models/gpt-4o-mini), [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. @@ -989,6 +995,8 @@ async def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) response_format: An object specifying the format that the model must output. Compatible with + [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4o mini](https://platform.openai.com/docs/models/gpt-4o-mini), [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. @@ -1178,6 +1186,8 @@ async def create( [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) response_format: An object specifying the format that the model must output. Compatible with + [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4o mini](https://platform.openai.com/docs/models/gpt-4o-mini), [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. diff --git a/src/openai/resources/fine_tuning/jobs/jobs.py b/src/openai/resources/fine_tuning/jobs/jobs.py index 14b384a88d..5cef7bcd22 100644 --- a/src/openai/resources/fine_tuning/jobs/jobs.py +++ b/src/openai/resources/fine_tuning/jobs/jobs.py @@ -52,7 +52,7 @@ def with_streaming_response(self) -> JobsWithStreamingResponse: def create( self, *, - model: Union[str, Literal["babbage-002", "davinci-002", "gpt-3.5-turbo"]], + model: Union[str, Literal["babbage-002", "davinci-002", "gpt-3.5-turbo", "gpt-4o-mini"]], training_file: str, hyperparameters: job_create_params.Hyperparameters | NotGiven = NOT_GIVEN, integrations: Optional[Iterable[job_create_params.Integration]] | NotGiven = NOT_GIVEN, @@ -77,7 +77,7 @@ def create( Args: model: The name of the model to fine-tune. You can select one of the - [supported models](https://platform.openai.com/docs/guides/fine-tuning/what-models-can-be-fine-tuned). + [supported models](https://platform.openai.com/docs/guides/fine-tuning/which-models-can-be-fine-tuned). training_file: The ID of an uploaded file that contains training data. @@ -107,7 +107,7 @@ def create( name. For example, a `suffix` of "custom-model-name" would produce a model name like - `ft:gpt-3.5-turbo:openai:custom-model-name:7p4lURel`. + `ft:gpt-4o-mini:openai:custom-model-name:7p4lURel`. validation_file: The ID of an uploaded file that contains validation data. @@ -332,7 +332,7 @@ def with_streaming_response(self) -> AsyncJobsWithStreamingResponse: async def create( self, *, - model: Union[str, Literal["babbage-002", "davinci-002", "gpt-3.5-turbo"]], + model: Union[str, Literal["babbage-002", "davinci-002", "gpt-3.5-turbo", "gpt-4o-mini"]], training_file: str, hyperparameters: job_create_params.Hyperparameters | NotGiven = NOT_GIVEN, integrations: Optional[Iterable[job_create_params.Integration]] | NotGiven = NOT_GIVEN, @@ -357,7 +357,7 @@ async def create( Args: model: The name of the model to fine-tune. You can select one of the - [supported models](https://platform.openai.com/docs/guides/fine-tuning/what-models-can-be-fine-tuned). + [supported models](https://platform.openai.com/docs/guides/fine-tuning/which-models-can-be-fine-tuned). training_file: The ID of an uploaded file that contains training data. @@ -387,7 +387,7 @@ async def create( name. For example, a `suffix` of "custom-model-name" would produce a model name like - `ft:gpt-3.5-turbo:openai:custom-model-name:7p4lURel`. + `ft:gpt-4o-mini:openai:custom-model-name:7p4lURel`. validation_file: The ID of an uploaded file that contains validation data. diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index 84916962cc..f621fb67c5 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -9,6 +9,9 @@ ErrorObject as ErrorObject, FunctionDefinition as FunctionDefinition, FunctionParameters as FunctionParameters, + ResponseFormatText as ResponseFormatText, + ResponseFormatJSONObject as ResponseFormatJSONObject, + ResponseFormatJSONSchema as ResponseFormatJSONSchema, ) from .upload import Upload as Upload from .embedding import Embedding as Embedding diff --git a/src/openai/types/beta/__init__.py b/src/openai/types/beta/__init__.py index d851a3619c..9c5ddfdbe0 100644 --- a/src/openai/types/beta/__init__.py +++ b/src/openai/types/beta/__init__.py @@ -23,7 +23,6 @@ from .assistant_create_params import AssistantCreateParams as AssistantCreateParams from .assistant_update_params import AssistantUpdateParams as AssistantUpdateParams from .vector_store_list_params import VectorStoreListParams as VectorStoreListParams -from .assistant_response_format import AssistantResponseFormat as AssistantResponseFormat from .vector_store_create_params import VectorStoreCreateParams as VectorStoreCreateParams from .vector_store_update_params import VectorStoreUpdateParams as VectorStoreUpdateParams from .assistant_tool_choice_param import AssistantToolChoiceParam as AssistantToolChoiceParam @@ -31,7 +30,6 @@ from .assistant_tool_choice_option import AssistantToolChoiceOption as AssistantToolChoiceOption from .thread_create_and_run_params import ThreadCreateAndRunParams as ThreadCreateAndRunParams from .assistant_tool_choice_function import AssistantToolChoiceFunction as AssistantToolChoiceFunction -from .assistant_response_format_param import AssistantResponseFormatParam as AssistantResponseFormatParam from .assistant_response_format_option import AssistantResponseFormatOption as AssistantResponseFormatOption from .assistant_tool_choice_option_param import AssistantToolChoiceOptionParam as AssistantToolChoiceOptionParam from .assistant_tool_choice_function_param import AssistantToolChoiceFunctionParam as AssistantToolChoiceFunctionParam diff --git a/src/openai/types/beta/assistant.py b/src/openai/types/beta/assistant.py index 4e5adc766e..c6a0a4cfcf 100644 --- a/src/openai/types/beta/assistant.py +++ b/src/openai/types/beta/assistant.py @@ -89,6 +89,11 @@ class Assistant(BaseModel): [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. diff --git a/src/openai/types/beta/assistant_create_params.py b/src/openai/types/beta/assistant_create_params.py index c10f7f57ad..84cd4425d1 100644 --- a/src/openai/types/beta/assistant_create_params.py +++ b/src/openai/types/beta/assistant_create_params.py @@ -60,6 +60,11 @@ class AssistantCreateParams(TypedDict, total=False): [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. diff --git a/src/openai/types/beta/assistant_response_format.py b/src/openai/types/beta/assistant_response_format.py deleted file mode 100644 index f53bdaf62a..0000000000 --- a/src/openai/types/beta/assistant_response_format.py +++ /dev/null @@ -1,13 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -from typing import Optional -from typing_extensions import Literal - -from ..._models import BaseModel - -__all__ = ["AssistantResponseFormat"] - - -class AssistantResponseFormat(BaseModel): - type: Optional[Literal["text", "json_object"]] = None - """Must be one of `text` or `json_object`.""" diff --git a/src/openai/types/beta/assistant_response_format_option.py b/src/openai/types/beta/assistant_response_format_option.py index 6ce390f6d6..6f06a3442f 100644 --- a/src/openai/types/beta/assistant_response_format_option.py +++ b/src/openai/types/beta/assistant_response_format_option.py @@ -3,8 +3,12 @@ from typing import Union from typing_extensions import Literal, TypeAlias -from .assistant_response_format import AssistantResponseFormat +from ..shared.response_format_text import ResponseFormatText +from ..shared.response_format_json_object import ResponseFormatJSONObject +from ..shared.response_format_json_schema import ResponseFormatJSONSchema __all__ = ["AssistantResponseFormatOption"] -AssistantResponseFormatOption: TypeAlias = Union[Literal["none", "auto"], AssistantResponseFormat] +AssistantResponseFormatOption: TypeAlias = Union[ + Literal["auto"], ResponseFormatText, ResponseFormatJSONObject, ResponseFormatJSONSchema +] diff --git a/src/openai/types/beta/assistant_response_format_option_param.py b/src/openai/types/beta/assistant_response_format_option_param.py index 8100088723..680a060c3c 100644 --- a/src/openai/types/beta/assistant_response_format_option_param.py +++ b/src/openai/types/beta/assistant_response_format_option_param.py @@ -5,8 +5,13 @@ from typing import Union from typing_extensions import Literal, TypeAlias -from .assistant_response_format_param import AssistantResponseFormatParam +from ...types import shared_params __all__ = ["AssistantResponseFormatOptionParam"] -AssistantResponseFormatOptionParam: TypeAlias = Union[Literal["none", "auto"], AssistantResponseFormatParam] +AssistantResponseFormatOptionParam: TypeAlias = Union[ + Literal["auto"], + shared_params.ResponseFormatText, + shared_params.ResponseFormatJSONObject, + shared_params.ResponseFormatJSONSchema, +] diff --git a/src/openai/types/beta/assistant_response_format_param.py b/src/openai/types/beta/assistant_response_format_param.py deleted file mode 100644 index 96e1d02115..0000000000 --- a/src/openai/types/beta/assistant_response_format_param.py +++ /dev/null @@ -1,12 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -from __future__ import annotations - -from typing_extensions import Literal, TypedDict - -__all__ = ["AssistantResponseFormatParam"] - - -class AssistantResponseFormatParam(TypedDict, total=False): - type: Literal["text", "json_object"] - """Must be one of `text` or `json_object`.""" diff --git a/src/openai/types/beta/assistant_update_params.py b/src/openai/types/beta/assistant_update_params.py index b401e1a891..ade565819f 100644 --- a/src/openai/types/beta/assistant_update_params.py +++ b/src/openai/types/beta/assistant_update_params.py @@ -49,6 +49,11 @@ class AssistantUpdateParams(TypedDict, total=False): [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. diff --git a/src/openai/types/beta/file_search_tool.py b/src/openai/types/beta/file_search_tool.py index e2711b9b3d..26ab1cb83f 100644 --- a/src/openai/types/beta/file_search_tool.py +++ b/src/openai/types/beta/file_search_tool.py @@ -12,8 +12,8 @@ class FileSearch(BaseModel): max_num_results: Optional[int] = None """The maximum number of results the file search tool should output. - The default is 20 for gpt-4\\** models and 5 for gpt-3.5-turbo. This number should - be between 1 and 50 inclusive. + The default is 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number + should be between 1 and 50 inclusive. Note that the file search tool may output fewer than `max_num_results` results. See the diff --git a/src/openai/types/beta/file_search_tool_param.py b/src/openai/types/beta/file_search_tool_param.py index 115f86a444..666719f8cd 100644 --- a/src/openai/types/beta/file_search_tool_param.py +++ b/src/openai/types/beta/file_search_tool_param.py @@ -11,8 +11,8 @@ class FileSearch(TypedDict, total=False): max_num_results: int """The maximum number of results the file search tool should output. - The default is 20 for gpt-4\\** models and 5 for gpt-3.5-turbo. This number should - be between 1 and 50 inclusive. + The default is 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number + should be between 1 and 50 inclusive. Note that the file search tool may output fewer than `max_num_results` results. See the diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index 62cff921e2..7490b25ef3 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -100,6 +100,11 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. diff --git a/src/openai/types/beta/threads/__init__.py b/src/openai/types/beta/threads/__init__.py index 023d76fc13..70853177bd 100644 --- a/src/openai/types/beta/threads/__init__.py +++ b/src/openai/types/beta/threads/__init__.py @@ -25,11 +25,13 @@ from .text_content_block import TextContentBlock as TextContentBlock from .message_delta_event import MessageDeltaEvent as MessageDeltaEvent from .message_list_params import MessageListParams as MessageListParams +from .refusal_delta_block import RefusalDeltaBlock as RefusalDeltaBlock from .file_path_annotation import FilePathAnnotation as FilePathAnnotation from .image_url_delta_block import ImageURLDeltaBlock as ImageURLDeltaBlock from .message_content_delta import MessageContentDelta as MessageContentDelta from .message_create_params import MessageCreateParams as MessageCreateParams from .message_update_params import MessageUpdateParams as MessageUpdateParams +from .refusal_content_block import RefusalContentBlock as RefusalContentBlock from .image_file_delta_block import ImageFileDeltaBlock as ImageFileDeltaBlock from .image_url_content_block import ImageURLContentBlock as ImageURLContentBlock from .file_citation_annotation import FileCitationAnnotation as FileCitationAnnotation diff --git a/src/openai/types/beta/threads/message_content.py b/src/openai/types/beta/threads/message_content.py index 7b718c3ca9..9523c1e1b9 100644 --- a/src/openai/types/beta/threads/message_content.py +++ b/src/openai/types/beta/threads/message_content.py @@ -5,11 +5,14 @@ from ...._utils import PropertyInfo from .text_content_block import TextContentBlock +from .refusal_content_block import RefusalContentBlock from .image_url_content_block import ImageURLContentBlock from .image_file_content_block import ImageFileContentBlock __all__ = ["MessageContent"] + MessageContent: TypeAlias = Annotated[ - Union[ImageFileContentBlock, ImageURLContentBlock, TextContentBlock], PropertyInfo(discriminator="type") + Union[ImageFileContentBlock, ImageURLContentBlock, TextContentBlock, RefusalContentBlock], + PropertyInfo(discriminator="type"), ] diff --git a/src/openai/types/beta/threads/message_content_delta.py b/src/openai/types/beta/threads/message_content_delta.py index 667172c08f..b6e7dfa45a 100644 --- a/src/openai/types/beta/threads/message_content_delta.py +++ b/src/openai/types/beta/threads/message_content_delta.py @@ -5,11 +5,13 @@ from ...._utils import PropertyInfo from .text_delta_block import TextDeltaBlock +from .refusal_delta_block import RefusalDeltaBlock from .image_url_delta_block import ImageURLDeltaBlock from .image_file_delta_block import ImageFileDeltaBlock __all__ = ["MessageContentDelta"] MessageContentDelta: TypeAlias = Annotated[ - Union[ImageFileDeltaBlock, TextDeltaBlock, ImageURLDeltaBlock], PropertyInfo(discriminator="type") + Union[ImageFileDeltaBlock, TextDeltaBlock, RefusalDeltaBlock, ImageURLDeltaBlock], + PropertyInfo(discriminator="type"), ] diff --git a/src/openai/types/beta/threads/refusal_content_block.py b/src/openai/types/beta/threads/refusal_content_block.py new file mode 100644 index 0000000000..d54f948554 --- /dev/null +++ b/src/openai/types/beta/threads/refusal_content_block.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["RefusalContentBlock"] + + +class RefusalContentBlock(BaseModel): + refusal: str + + type: Literal["refusal"] + """Always `refusal`.""" diff --git a/src/openai/types/beta/threads/refusal_delta_block.py b/src/openai/types/beta/threads/refusal_delta_block.py new file mode 100644 index 0000000000..dbd8e62697 --- /dev/null +++ b/src/openai/types/beta/threads/refusal_delta_block.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["RefusalDeltaBlock"] + + +class RefusalDeltaBlock(BaseModel): + index: int + """The index of the refusal part in the message.""" + + type: Literal["refusal"] + """Always `refusal`.""" + + refusal: Optional[str] = None diff --git a/src/openai/types/beta/threads/run.py b/src/openai/types/beta/threads/run.py index 81d10d4a56..0579e229d8 100644 --- a/src/openai/types/beta/threads/run.py +++ b/src/openai/types/beta/threads/run.py @@ -171,6 +171,11 @@ class Run(BaseModel): [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index e0c42fd23f..d3e6d9c476 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -97,6 +97,11 @@ class RunCreateParamsBase(TypedDict, total=False): [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. diff --git a/src/openai/types/beta/vector_stores/vector_store_file.py b/src/openai/types/beta/vector_stores/vector_store_file.py index 4762de0ebd..65096e8dad 100644 --- a/src/openai/types/beta/vector_stores/vector_store_file.py +++ b/src/openai/types/beta/vector_stores/vector_store_file.py @@ -17,7 +17,7 @@ class LastError(BaseModel): - code: Literal["internal_error", "file_not_found", "parsing_error", "unhandled_mime_type"] + code: Literal["server_error", "unsupported_file", "invalid_file"] """One of `server_error` or `rate_limit_exceeded`.""" message: str diff --git a/src/openai/types/chat/__init__.py b/src/openai/types/chat/__init__.py index 0ba812ff9b..a5cf3734b8 100644 --- a/src/openai/types/chat/__init__.py +++ b/src/openai/types/chat/__init__.py @@ -5,8 +5,17 @@ from .chat_completion import ChatCompletion as ChatCompletion from .chat_completion_role import ChatCompletionRole as ChatCompletionRole from .chat_completion_chunk import ChatCompletionChunk as ChatCompletionChunk +from .parsed_chat_completion import ( + ParsedChoice as ParsedChoice, + ParsedChatCompletion as ParsedChatCompletion, + ParsedChatCompletionMessage as ParsedChatCompletionMessage, +) from .chat_completion_message import ChatCompletionMessage as ChatCompletionMessage from .completion_create_params import CompletionCreateParams as CompletionCreateParams +from .parsed_function_tool_call import ( + ParsedFunction as ParsedFunction, + ParsedFunctionToolCall as ParsedFunctionToolCall, +) from .chat_completion_tool_param import ChatCompletionToolParam as ChatCompletionToolParam from .chat_completion_message_param import ChatCompletionMessageParam as ChatCompletionMessageParam from .chat_completion_token_logprob import ChatCompletionTokenLogprob as ChatCompletionTokenLogprob @@ -37,6 +46,9 @@ from .chat_completion_tool_choice_option_param import ( ChatCompletionToolChoiceOptionParam as ChatCompletionToolChoiceOptionParam, ) +from .chat_completion_content_part_refusal_param import ( + ChatCompletionContentPartRefusalParam as ChatCompletionContentPartRefusalParam, +) from .chat_completion_function_call_option_param import ( ChatCompletionFunctionCallOptionParam as ChatCompletionFunctionCallOptionParam, ) diff --git a/src/openai/types/chat/chat_completion.py b/src/openai/types/chat/chat_completion.py index 5f4eaf3366..4b53e70890 100644 --- a/src/openai/types/chat/chat_completion.py +++ b/src/openai/types/chat/chat_completion.py @@ -15,6 +15,9 @@ class ChoiceLogprobs(BaseModel): content: Optional[List[ChatCompletionTokenLogprob]] = None """A list of message content tokens with log probability information.""" + refusal: Optional[List[ChatCompletionTokenLogprob]] = None + """A list of message refusal tokens with log probability information.""" + class Choice(BaseModel): finish_reason: Literal["stop", "length", "tool_calls", "content_filter", "function_call"] diff --git a/src/openai/types/chat/chat_completion_assistant_message_param.py b/src/openai/types/chat/chat_completion_assistant_message_param.py index 8f7357b96c..2429d41d33 100644 --- a/src/openai/types/chat/chat_completion_assistant_message_param.py +++ b/src/openai/types/chat/chat_completion_assistant_message_param.py @@ -2,12 +2,16 @@ from __future__ import annotations -from typing import Iterable, Optional -from typing_extensions import Literal, Required, TypedDict +from typing import Union, Iterable, Optional +from typing_extensions import Literal, Required, TypeAlias, TypedDict +from .chat_completion_content_part_text_param import ChatCompletionContentPartTextParam from .chat_completion_message_tool_call_param import ChatCompletionMessageToolCallParam +from .chat_completion_content_part_refusal_param import ChatCompletionContentPartRefusalParam -__all__ = ["ChatCompletionAssistantMessageParam", "FunctionCall"] +__all__ = ["ChatCompletionAssistantMessageParam", "ContentArrayOfContentPart", "FunctionCall"] + +ContentArrayOfContentPart: TypeAlias = Union[ChatCompletionContentPartTextParam, ChatCompletionContentPartRefusalParam] class FunctionCall(TypedDict, total=False): @@ -27,7 +31,7 @@ class ChatCompletionAssistantMessageParam(TypedDict, total=False): role: Required[Literal["assistant"]] """The role of the messages author, in this case `assistant`.""" - content: Optional[str] + content: Union[str, Iterable[ContentArrayOfContentPart], None] """The contents of the assistant message. Required unless `tool_calls` or `function_call` is specified. @@ -47,5 +51,8 @@ class ChatCompletionAssistantMessageParam(TypedDict, total=False): role. """ + refusal: Optional[str] + """The refusal message by the assistant.""" + tool_calls: Iterable[ChatCompletionMessageToolCallParam] """The tool calls generated by the model, such as function calls.""" diff --git a/src/openai/types/chat/chat_completion_chunk.py b/src/openai/types/chat/chat_completion_chunk.py index 65643c7e60..9ec6dc4bdb 100644 --- a/src/openai/types/chat/chat_completion_chunk.py +++ b/src/openai/types/chat/chat_completion_chunk.py @@ -67,6 +67,9 @@ class ChoiceDelta(BaseModel): model. """ + refusal: Optional[str] = None + """The refusal message generated by the model.""" + role: Optional[Literal["system", "user", "assistant", "tool"]] = None """The role of the author of this message.""" @@ -77,6 +80,9 @@ class ChoiceLogprobs(BaseModel): content: Optional[List[ChatCompletionTokenLogprob]] = None """A list of message content tokens with log probability information.""" + refusal: Optional[List[ChatCompletionTokenLogprob]] = None + """A list of message refusal tokens with log probability information.""" + class Choice(BaseModel): delta: ChoiceDelta diff --git a/src/openai/types/chat/chat_completion_content_part_refusal_param.py b/src/openai/types/chat/chat_completion_content_part_refusal_param.py new file mode 100644 index 0000000000..c18c7db770 --- /dev/null +++ b/src/openai/types/chat/chat_completion_content_part_refusal_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ChatCompletionContentPartRefusalParam"] + + +class ChatCompletionContentPartRefusalParam(TypedDict, total=False): + refusal: Required[str] + """The refusal message generated by the model.""" + + type: Required[Literal["refusal"]] + """The type of the content part.""" diff --git a/src/openai/types/chat/chat_completion_message.py b/src/openai/types/chat/chat_completion_message.py index 8db7d17d24..492bb68c85 100644 --- a/src/openai/types/chat/chat_completion_message.py +++ b/src/openai/types/chat/chat_completion_message.py @@ -26,6 +26,9 @@ class ChatCompletionMessage(BaseModel): content: Optional[str] = None """The contents of the message.""" + refusal: Optional[str] = None + """The refusal message generated by the model.""" + role: Literal["assistant"] """The role of the author of this message.""" diff --git a/src/openai/types/chat/chat_completion_system_message_param.py b/src/openai/types/chat/chat_completion_system_message_param.py index 94bb3f636c..172ccea09e 100644 --- a/src/openai/types/chat/chat_completion_system_message_param.py +++ b/src/openai/types/chat/chat_completion_system_message_param.py @@ -2,13 +2,16 @@ from __future__ import annotations +from typing import Union, Iterable from typing_extensions import Literal, Required, TypedDict +from .chat_completion_content_part_text_param import ChatCompletionContentPartTextParam + __all__ = ["ChatCompletionSystemMessageParam"] class ChatCompletionSystemMessageParam(TypedDict, total=False): - content: Required[str] + content: Required[Union[str, Iterable[ChatCompletionContentPartTextParam]]] """The contents of the system message.""" role: Required[Literal["system"]] diff --git a/src/openai/types/chat/chat_completion_tool_message_param.py b/src/openai/types/chat/chat_completion_tool_message_param.py index 5c590e033f..eb5e270e47 100644 --- a/src/openai/types/chat/chat_completion_tool_message_param.py +++ b/src/openai/types/chat/chat_completion_tool_message_param.py @@ -2,13 +2,16 @@ from __future__ import annotations +from typing import Union, Iterable from typing_extensions import Literal, Required, TypedDict +from .chat_completion_content_part_text_param import ChatCompletionContentPartTextParam + __all__ = ["ChatCompletionToolMessageParam"] class ChatCompletionToolMessageParam(TypedDict, total=False): - content: Required[str] + content: Required[Union[str, Iterable[ChatCompletionContentPartTextParam]]] """The contents of the tool message.""" role: Required[Literal["tool"]] diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 9e81881b9e..bf648a3858 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -121,7 +121,8 @@ class CompletionCreateParamsBase(TypedDict, total=False): response_format: ResponseFormat """An object specifying the format that the model must output. - Compatible with + Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), + [GPT-4o mini](https://platform.openai.com/docs/models/gpt-4o-mini), [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. @@ -250,9 +251,9 @@ class Function(TypedDict, total=False): """ -class ResponseFormat(TypedDict, total=False): - type: Literal["text", "json_object"] - """Must be one of `text` or `json_object`.""" +ResponseFormat: TypeAlias = Union[ + shared_params.ResponseFormatText, shared_params.ResponseFormatJSONObject, shared_params.ResponseFormatJSONSchema +] class CompletionCreateParamsNonStreaming(CompletionCreateParamsBase): diff --git a/src/openai/types/chat/parsed_chat_completion.py b/src/openai/types/chat/parsed_chat_completion.py new file mode 100644 index 0000000000..4b11dac5a0 --- /dev/null +++ b/src/openai/types/chat/parsed_chat_completion.py @@ -0,0 +1,40 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Generic, TypeVar, Optional + +from ..._models import GenericModel +from .chat_completion import Choice, ChatCompletion +from .chat_completion_message import ChatCompletionMessage +from .parsed_function_tool_call import ParsedFunctionToolCall + +__all__ = ["ParsedChatCompletion", "ParsedChoice"] + + +ContentType = TypeVar("ContentType") + + +# we need to disable this check because we're overriding properties +# with subclasses of their types which is technically unsound as +# properties can be mutated. +# pyright: reportIncompatibleVariableOverride=false + + +class ParsedChatCompletionMessage(ChatCompletionMessage, GenericModel, Generic[ContentType]): + parsed: Optional[ContentType] = None + """The auto-parsed message contents""" + + tool_calls: Optional[List[ParsedFunctionToolCall]] = None # type: ignore[assignment] + """The tool calls generated by the model, such as function calls.""" + + +class ParsedChoice(Choice, GenericModel, Generic[ContentType]): + message: ParsedChatCompletionMessage[ContentType] + """A chat completion message generated by the model.""" + + +class ParsedChatCompletion(ChatCompletion, GenericModel, Generic[ContentType]): + choices: List[ParsedChoice[ContentType]] # type: ignore[assignment] + """A list of chat completion choices. + + Can be more than one if `n` is greater than 1. + """ diff --git a/src/openai/types/chat/parsed_function_tool_call.py b/src/openai/types/chat/parsed_function_tool_call.py new file mode 100644 index 0000000000..3e90789f85 --- /dev/null +++ b/src/openai/types/chat/parsed_function_tool_call.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from .chat_completion_message_tool_call import Function, ChatCompletionMessageToolCall + +__all__ = ["ParsedFunctionToolCall", "ParsedFunction"] + +# we need to disable this check because we're overriding properties +# with subclasses of their types which is technically unsound as +# properties can be mutated. +# pyright: reportIncompatibleVariableOverride=false + + +class ParsedFunction(Function): + parsed_arguments: Optional[object] = None + """ + The arguments to call the function with. + + If you used `openai.pydantic_function_tool()` then this will be an + instance of the given `BaseModel`. + + Otherwise, this will be the parsed JSON arguments. + """ + + +class ParsedFunctionToolCall(ChatCompletionMessageToolCall): + function: ParsedFunction + """The function that the model called.""" diff --git a/src/openai/types/chat_model.py b/src/openai/types/chat_model.py index edb7b732bf..686f26b783 100644 --- a/src/openai/types/chat_model.py +++ b/src/openai/types/chat_model.py @@ -6,6 +6,7 @@ ChatModel: TypeAlias = Literal[ "gpt-4o", + "gpt-4o-2024-08-06", "gpt-4o-2024-05-13", "gpt-4o-mini", "gpt-4o-mini-2024-07-18", diff --git a/src/openai/types/fine_tuning/job_create_params.py b/src/openai/types/fine_tuning/job_create_params.py index c5196e4406..e9be2ef1ca 100644 --- a/src/openai/types/fine_tuning/job_create_params.py +++ b/src/openai/types/fine_tuning/job_create_params.py @@ -9,11 +9,11 @@ class JobCreateParams(TypedDict, total=False): - model: Required[Union[str, Literal["babbage-002", "davinci-002", "gpt-3.5-turbo"]]] + model: Required[Union[str, Literal["babbage-002", "davinci-002", "gpt-3.5-turbo", "gpt-4o-mini"]]] """The name of the model to fine-tune. You can select one of the - [supported models](https://platform.openai.com/docs/guides/fine-tuning/what-models-can-be-fine-tuned). + [supported models](https://platform.openai.com/docs/guides/fine-tuning/which-models-can-be-fine-tuned). """ training_file: Required[str] @@ -54,7 +54,7 @@ class JobCreateParams(TypedDict, total=False): name. For example, a `suffix` of "custom-model-name" would produce a model name like - `ft:gpt-3.5-turbo:openai:custom-model-name:7p4lURel`. + `ft:gpt-4o-mini:openai:custom-model-name:7p4lURel`. """ validation_file: Optional[str] diff --git a/src/openai/types/shared/__init__.py b/src/openai/types/shared/__init__.py index e085744e29..c8776bca0e 100644 --- a/src/openai/types/shared/__init__.py +++ b/src/openai/types/shared/__init__.py @@ -3,3 +3,6 @@ from .error_object import ErrorObject as ErrorObject from .function_definition import FunctionDefinition as FunctionDefinition from .function_parameters import FunctionParameters as FunctionParameters +from .response_format_text import ResponseFormatText as ResponseFormatText +from .response_format_json_object import ResponseFormatJSONObject as ResponseFormatJSONObject +from .response_format_json_schema import ResponseFormatJSONSchema as ResponseFormatJSONSchema diff --git a/src/openai/types/shared/function_definition.py b/src/openai/types/shared/function_definition.py index 49f5e67c50..06baa23170 100644 --- a/src/openai/types/shared/function_definition.py +++ b/src/openai/types/shared/function_definition.py @@ -32,3 +32,12 @@ class FunctionDefinition(BaseModel): Omitting `parameters` defines a function with an empty parameter list. """ + + strict: Optional[bool] = None + """Whether to enable strict schema adherence when generating the function call. + + If set to true, the model will follow the exact schema defined in the + `parameters` field. Only a subset of JSON Schema is supported when `strict` is + `true`. Learn more about Structured Outputs in the + [function calling guide](docs/guides/function-calling). + """ diff --git a/src/openai/types/shared/response_format_json_object.py b/src/openai/types/shared/response_format_json_object.py new file mode 100644 index 0000000000..107728dd2e --- /dev/null +++ b/src/openai/types/shared/response_format_json_object.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseFormatJSONObject"] + + +class ResponseFormatJSONObject(BaseModel): + type: Literal["json_object"] + """The type of response format being defined: `json_object`""" diff --git a/src/openai/types/shared/response_format_json_schema.py b/src/openai/types/shared/response_format_json_schema.py new file mode 100644 index 0000000000..3194a4fe91 --- /dev/null +++ b/src/openai/types/shared/response_format_json_schema.py @@ -0,0 +1,44 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional +from typing_extensions import Literal + +from pydantic import Field as FieldInfo + +from ..._models import BaseModel + +__all__ = ["ResponseFormatJSONSchema", "JSONSchema"] + + +class JSONSchema(BaseModel): + name: str + """The name of the response format. + + Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length + of 64. + """ + + description: Optional[str] = None + """ + A description of what the response format is for, used by the model to determine + how to respond in the format. + """ + + schema_: Optional[Dict[str, object]] = FieldInfo(alias="schema", default=None) + """The schema for the response format, described as a JSON Schema object.""" + + strict: Optional[bool] = None + """Whether to enable strict schema adherence when generating the output. + + If set to true, the model will always follow the exact schema defined in the + `schema` field. Only a subset of JSON Schema is supported when `strict` is + `true`. To learn more, read the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + """ + + +class ResponseFormatJSONSchema(BaseModel): + json_schema: JSONSchema + + type: Literal["json_schema"] + """The type of response format being defined: `json_schema`""" diff --git a/src/openai/types/shared/response_format_text.py b/src/openai/types/shared/response_format_text.py new file mode 100644 index 0000000000..6721fe0973 --- /dev/null +++ b/src/openai/types/shared/response_format_text.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseFormatText"] + + +class ResponseFormatText(BaseModel): + type: Literal["text"] + """The type of response format being defined: `text`""" diff --git a/src/openai/types/shared_params/__init__.py b/src/openai/types/shared_params/__init__.py index ef638cb279..ab4057d59f 100644 --- a/src/openai/types/shared_params/__init__.py +++ b/src/openai/types/shared_params/__init__.py @@ -2,3 +2,6 @@ from .function_definition import FunctionDefinition as FunctionDefinition from .function_parameters import FunctionParameters as FunctionParameters +from .response_format_text import ResponseFormatText as ResponseFormatText +from .response_format_json_object import ResponseFormatJSONObject as ResponseFormatJSONObject +from .response_format_json_schema import ResponseFormatJSONSchema as ResponseFormatJSONSchema diff --git a/src/openai/types/shared_params/function_definition.py b/src/openai/types/shared_params/function_definition.py index 29ccc548d4..f41392f154 100644 --- a/src/openai/types/shared_params/function_definition.py +++ b/src/openai/types/shared_params/function_definition.py @@ -2,6 +2,7 @@ from __future__ import annotations +from typing import Optional from typing_extensions import Required, TypedDict from ...types import shared_params @@ -33,3 +34,12 @@ class FunctionDefinition(TypedDict, total=False): Omitting `parameters` defines a function with an empty parameter list. """ + + strict: Optional[bool] + """Whether to enable strict schema adherence when generating the function call. + + If set to true, the model will follow the exact schema defined in the + `parameters` field. Only a subset of JSON Schema is supported when `strict` is + `true`. Learn more about Structured Outputs in the + [function calling guide](docs/guides/function-calling). + """ diff --git a/src/openai/types/shared_params/response_format_json_object.py b/src/openai/types/shared_params/response_format_json_object.py new file mode 100644 index 0000000000..8419c6cb56 --- /dev/null +++ b/src/openai/types/shared_params/response_format_json_object.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ResponseFormatJSONObject"] + + +class ResponseFormatJSONObject(TypedDict, total=False): + type: Required[Literal["json_object"]] + """The type of response format being defined: `json_object`""" diff --git a/src/openai/types/shared_params/response_format_json_schema.py b/src/openai/types/shared_params/response_format_json_schema.py new file mode 100644 index 0000000000..4b60fae8ee --- /dev/null +++ b/src/openai/types/shared_params/response_format_json_schema.py @@ -0,0 +1,42 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ResponseFormatJSONSchema", "JSONSchema"] + + +class JSONSchema(TypedDict, total=False): + name: Required[str] + """The name of the response format. + + Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length + of 64. + """ + + description: str + """ + A description of what the response format is for, used by the model to determine + how to respond in the format. + """ + + schema: Dict[str, object] + """The schema for the response format, described as a JSON Schema object.""" + + strict: Optional[bool] + """Whether to enable strict schema adherence when generating the output. + + If set to true, the model will always follow the exact schema defined in the + `schema` field. Only a subset of JSON Schema is supported when `strict` is + `true`. To learn more, read the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + """ + + +class ResponseFormatJSONSchema(TypedDict, total=False): + json_schema: Required[JSONSchema] + + type: Required[Literal["json_schema"]] + """The type of response format being defined: `json_schema`""" diff --git a/src/openai/types/shared_params/response_format_text.py b/src/openai/types/shared_params/response_format_text.py new file mode 100644 index 0000000000..5bec7fc503 --- /dev/null +++ b/src/openai/types/shared_params/response_format_text.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ResponseFormatText"] + + +class ResponseFormatText(TypedDict, total=False): + type: Required[Literal["text"]] + """The type of response format being defined: `text`""" diff --git a/tests/api_resources/beta/test_assistants.py b/tests/api_resources/beta/test_assistants.py index dd0ce9266e..fbd5ff0597 100644 --- a/tests/api_resources/beta/test_assistants.py +++ b/tests/api_resources/beta/test_assistants.py @@ -24,19 +24,19 @@ class TestAssistants: @parametrize def test_method_create(self, client: OpenAI) -> None: assistant = client.beta.assistants.create( - model="gpt-4-turbo", + model="gpt-4o", ) assert_matches_type(Assistant, assistant, path=["response"]) @parametrize def test_method_create_with_all_params(self, client: OpenAI) -> None: assistant = client.beta.assistants.create( - model="gpt-4-turbo", - description="string", - instructions="string", + model="gpt-4o", + description="description", + instructions="instructions", metadata={}, - name="string", - response_format="none", + name="name", + response_format="auto", temperature=1, tool_resources={ "code_interpreter": {"file_ids": ["string", "string", "string"]}, @@ -59,7 +59,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: @parametrize def test_raw_response_create(self, client: OpenAI) -> None: response = client.beta.assistants.with_raw_response.create( - model="gpt-4-turbo", + model="gpt-4o", ) assert response.is_closed is True @@ -70,7 +70,7 @@ def test_raw_response_create(self, client: OpenAI) -> None: @parametrize def test_streaming_response_create(self, client: OpenAI) -> None: with client.beta.assistants.with_streaming_response.create( - model="gpt-4-turbo", + model="gpt-4o", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -83,14 +83,14 @@ def test_streaming_response_create(self, client: OpenAI) -> None: @parametrize def test_method_retrieve(self, client: OpenAI) -> None: assistant = client.beta.assistants.retrieve( - "string", + "assistant_id", ) assert_matches_type(Assistant, assistant, path=["response"]) @parametrize def test_raw_response_retrieve(self, client: OpenAI) -> None: response = client.beta.assistants.with_raw_response.retrieve( - "string", + "assistant_id", ) assert response.is_closed is True @@ -101,7 +101,7 @@ def test_raw_response_retrieve(self, client: OpenAI) -> None: @parametrize def test_streaming_response_retrieve(self, client: OpenAI) -> None: with client.beta.assistants.with_streaming_response.retrieve( - "string", + "assistant_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -121,20 +121,20 @@ def test_path_params_retrieve(self, client: OpenAI) -> None: @parametrize def test_method_update(self, client: OpenAI) -> None: assistant = client.beta.assistants.update( - "string", + assistant_id="assistant_id", ) assert_matches_type(Assistant, assistant, path=["response"]) @parametrize def test_method_update_with_all_params(self, client: OpenAI) -> None: assistant = client.beta.assistants.update( - "string", - description="string", - instructions="string", + assistant_id="assistant_id", + description="description", + instructions="instructions", metadata={}, - model="string", - name="string", - response_format="none", + model="model", + name="name", + response_format="auto", temperature=1, tool_resources={ "code_interpreter": {"file_ids": ["string", "string", "string"]}, @@ -148,7 +148,7 @@ def test_method_update_with_all_params(self, client: OpenAI) -> None: @parametrize def test_raw_response_update(self, client: OpenAI) -> None: response = client.beta.assistants.with_raw_response.update( - "string", + assistant_id="assistant_id", ) assert response.is_closed is True @@ -159,7 +159,7 @@ def test_raw_response_update(self, client: OpenAI) -> None: @parametrize def test_streaming_response_update(self, client: OpenAI) -> None: with client.beta.assistants.with_streaming_response.update( - "string", + assistant_id="assistant_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -173,7 +173,7 @@ def test_streaming_response_update(self, client: OpenAI) -> None: def test_path_params_update(self, client: OpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): client.beta.assistants.with_raw_response.update( - "", + assistant_id="", ) @parametrize @@ -184,8 +184,8 @@ def test_method_list(self, client: OpenAI) -> None: @parametrize def test_method_list_with_all_params(self, client: OpenAI) -> None: assistant = client.beta.assistants.list( - after="string", - before="string", + after="after", + before="before", limit=0, order="asc", ) @@ -214,14 +214,14 @@ def test_streaming_response_list(self, client: OpenAI) -> None: @parametrize def test_method_delete(self, client: OpenAI) -> None: assistant = client.beta.assistants.delete( - "string", + "assistant_id", ) assert_matches_type(AssistantDeleted, assistant, path=["response"]) @parametrize def test_raw_response_delete(self, client: OpenAI) -> None: response = client.beta.assistants.with_raw_response.delete( - "string", + "assistant_id", ) assert response.is_closed is True @@ -232,7 +232,7 @@ def test_raw_response_delete(self, client: OpenAI) -> None: @parametrize def test_streaming_response_delete(self, client: OpenAI) -> None: with client.beta.assistants.with_streaming_response.delete( - "string", + "assistant_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -256,19 +256,19 @@ class TestAsyncAssistants: @parametrize async def test_method_create(self, async_client: AsyncOpenAI) -> None: assistant = await async_client.beta.assistants.create( - model="gpt-4-turbo", + model="gpt-4o", ) assert_matches_type(Assistant, assistant, path=["response"]) @parametrize async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: assistant = await async_client.beta.assistants.create( - model="gpt-4-turbo", - description="string", - instructions="string", + model="gpt-4o", + description="description", + instructions="instructions", metadata={}, - name="string", - response_format="none", + name="name", + response_format="auto", temperature=1, tool_resources={ "code_interpreter": {"file_ids": ["string", "string", "string"]}, @@ -291,7 +291,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> @parametrize async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: response = await async_client.beta.assistants.with_raw_response.create( - model="gpt-4-turbo", + model="gpt-4o", ) assert response.is_closed is True @@ -302,7 +302,7 @@ async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: async with async_client.beta.assistants.with_streaming_response.create( - model="gpt-4-turbo", + model="gpt-4o", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -315,14 +315,14 @@ async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> Non @parametrize async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: assistant = await async_client.beta.assistants.retrieve( - "string", + "assistant_id", ) assert_matches_type(Assistant, assistant, path=["response"]) @parametrize async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: response = await async_client.beta.assistants.with_raw_response.retrieve( - "string", + "assistant_id", ) assert response.is_closed is True @@ -333,7 +333,7 @@ async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: async with async_client.beta.assistants.with_streaming_response.retrieve( - "string", + "assistant_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -353,20 +353,20 @@ async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_method_update(self, async_client: AsyncOpenAI) -> None: assistant = await async_client.beta.assistants.update( - "string", + assistant_id="assistant_id", ) assert_matches_type(Assistant, assistant, path=["response"]) @parametrize async def test_method_update_with_all_params(self, async_client: AsyncOpenAI) -> None: assistant = await async_client.beta.assistants.update( - "string", - description="string", - instructions="string", + assistant_id="assistant_id", + description="description", + instructions="instructions", metadata={}, - model="string", - name="string", - response_format="none", + model="model", + name="name", + response_format="auto", temperature=1, tool_resources={ "code_interpreter": {"file_ids": ["string", "string", "string"]}, @@ -380,7 +380,7 @@ async def test_method_update_with_all_params(self, async_client: AsyncOpenAI) -> @parametrize async def test_raw_response_update(self, async_client: AsyncOpenAI) -> None: response = await async_client.beta.assistants.with_raw_response.update( - "string", + assistant_id="assistant_id", ) assert response.is_closed is True @@ -391,7 +391,7 @@ async def test_raw_response_update(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_streaming_response_update(self, async_client: AsyncOpenAI) -> None: async with async_client.beta.assistants.with_streaming_response.update( - "string", + assistant_id="assistant_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -405,7 +405,7 @@ async def test_streaming_response_update(self, async_client: AsyncOpenAI) -> Non async def test_path_params_update(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `assistant_id` but received ''"): await async_client.beta.assistants.with_raw_response.update( - "", + assistant_id="", ) @parametrize @@ -416,8 +416,8 @@ async def test_method_list(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: assistant = await async_client.beta.assistants.list( - after="string", - before="string", + after="after", + before="before", limit=0, order="asc", ) @@ -446,14 +446,14 @@ async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_method_delete(self, async_client: AsyncOpenAI) -> None: assistant = await async_client.beta.assistants.delete( - "string", + "assistant_id", ) assert_matches_type(AssistantDeleted, assistant, path=["response"]) @parametrize async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None: response = await async_client.beta.assistants.with_raw_response.delete( - "string", + "assistant_id", ) assert response.is_closed is True @@ -464,7 +464,7 @@ async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_streaming_response_delete(self, async_client: AsyncOpenAI) -> None: async with async_client.beta.assistants.with_streaming_response.delete( - "string", + "assistant_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" diff --git a/tests/api_resources/beta/test_threads.py b/tests/api_resources/beta/test_threads.py index 9e06b597ef..67fff736dd 100644 --- a/tests/api_resources/beta/test_threads.py +++ b/tests/api_resources/beta/test_threads.py @@ -302,9 +302,9 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) max_completion_tokens=256, max_prompt_tokens=256, metadata={}, - model="gpt-4-turbo", + model="gpt-4o", parallel_tool_calls=True, - response_format="none", + response_format="auto", stream=False, temperature=1, thread={ @@ -473,9 +473,9 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) max_completion_tokens=256, max_prompt_tokens=256, metadata={}, - model="gpt-4-turbo", + model="gpt-4o", parallel_tool_calls=True, - response_format="none", + response_format="auto", temperature=1, thread={ "messages": [ @@ -912,9 +912,9 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie max_completion_tokens=256, max_prompt_tokens=256, metadata={}, - model="gpt-4-turbo", + model="gpt-4o", parallel_tool_calls=True, - response_format="none", + response_format="auto", stream=False, temperature=1, thread={ @@ -1083,9 +1083,9 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie max_completion_tokens=256, max_prompt_tokens=256, metadata={}, - model="gpt-4-turbo", + model="gpt-4o", parallel_tool_calls=True, - response_format="none", + response_format="auto", temperature=1, thread={ "messages": [ diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index 26862ef1eb..e21c6c2c77 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -135,9 +135,9 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: max_completion_tokens=256, max_prompt_tokens=256, metadata={}, - model="gpt-4-turbo", + model="gpt-4o", parallel_tool_calls=True, - response_format="none", + response_format="auto", stream=False, temperature=1, tool_choice="none", @@ -299,9 +299,9 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: max_completion_tokens=256, max_prompt_tokens=256, metadata={}, - model="gpt-4-turbo", + model="gpt-4o", parallel_tool_calls=True, - response_format="none", + response_format="auto", temperature=1, tool_choice="none", tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], @@ -801,9 +801,9 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn max_completion_tokens=256, max_prompt_tokens=256, metadata={}, - model="gpt-4-turbo", + model="gpt-4o", parallel_tool_calls=True, - response_format="none", + response_format="auto", stream=False, temperature=1, tool_choice="none", @@ -965,9 +965,9 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn max_completion_tokens=256, max_prompt_tokens=256, metadata={}, - model="gpt-4-turbo", + model="gpt-4o", parallel_tool_calls=True, - response_format="none", + response_format="auto", temperature=1, tool_choice="none", tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index 5cb2a8c717..d744dfe6ea 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -28,7 +28,7 @@ def test_method_create_overload_1(self, client: OpenAI) -> None: "role": "system", } ], - model="gpt-4-turbo", + model="gpt-4o", ) assert_matches_type(ChatCompletion, completion, path=["response"]) @@ -42,7 +42,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: "name": "string", } ], - model="gpt-4-turbo", + model="gpt-4o", frequency_penalty=-2, function_call="none", functions=[ @@ -58,7 +58,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: n=1, parallel_tool_calls=True, presence_penalty=-2, - response_format={"type": "json_object"}, + response_format={"type": "text"}, seed=-9007199254740991, service_tier="auto", stop="string", @@ -73,6 +73,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: "description": "string", "name": "string", "parameters": {"foo": "bar"}, + "strict": True, }, }, { @@ -81,6 +82,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: "description": "string", "name": "string", "parameters": {"foo": "bar"}, + "strict": True, }, }, { @@ -89,6 +91,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: "description": "string", "name": "string", "parameters": {"foo": "bar"}, + "strict": True, }, }, ], @@ -107,7 +110,7 @@ def test_raw_response_create_overload_1(self, client: OpenAI) -> None: "role": "system", } ], - model="gpt-4-turbo", + model="gpt-4o", ) assert response.is_closed is True @@ -124,7 +127,7 @@ def test_streaming_response_create_overload_1(self, client: OpenAI) -> None: "role": "system", } ], - model="gpt-4-turbo", + model="gpt-4o", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -143,7 +146,7 @@ def test_method_create_overload_2(self, client: OpenAI) -> None: "role": "system", } ], - model="gpt-4-turbo", + model="gpt-4o", stream=True, ) completion_stream.response.close() @@ -158,7 +161,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: "name": "string", } ], - model="gpt-4-turbo", + model="gpt-4o", stream=True, frequency_penalty=-2, function_call="none", @@ -175,7 +178,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: n=1, parallel_tool_calls=True, presence_penalty=-2, - response_format={"type": "json_object"}, + response_format={"type": "text"}, seed=-9007199254740991, service_tier="auto", stop="string", @@ -189,6 +192,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: "description": "string", "name": "string", "parameters": {"foo": "bar"}, + "strict": True, }, }, { @@ -197,6 +201,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: "description": "string", "name": "string", "parameters": {"foo": "bar"}, + "strict": True, }, }, { @@ -205,6 +210,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: "description": "string", "name": "string", "parameters": {"foo": "bar"}, + "strict": True, }, }, ], @@ -223,7 +229,7 @@ def test_raw_response_create_overload_2(self, client: OpenAI) -> None: "role": "system", } ], - model="gpt-4-turbo", + model="gpt-4o", stream=True, ) @@ -240,7 +246,7 @@ def test_streaming_response_create_overload_2(self, client: OpenAI) -> None: "role": "system", } ], - model="gpt-4-turbo", + model="gpt-4o", stream=True, ) as response: assert not response.is_closed @@ -264,7 +270,7 @@ async def test_method_create_overload_1(self, async_client: AsyncOpenAI) -> None "role": "system", } ], - model="gpt-4-turbo", + model="gpt-4o", ) assert_matches_type(ChatCompletion, completion, path=["response"]) @@ -278,7 +284,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn "name": "string", } ], - model="gpt-4-turbo", + model="gpt-4o", frequency_penalty=-2, function_call="none", functions=[ @@ -294,7 +300,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn n=1, parallel_tool_calls=True, presence_penalty=-2, - response_format={"type": "json_object"}, + response_format={"type": "text"}, seed=-9007199254740991, service_tier="auto", stop="string", @@ -309,6 +315,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn "description": "string", "name": "string", "parameters": {"foo": "bar"}, + "strict": True, }, }, { @@ -317,6 +324,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn "description": "string", "name": "string", "parameters": {"foo": "bar"}, + "strict": True, }, }, { @@ -325,6 +333,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn "description": "string", "name": "string", "parameters": {"foo": "bar"}, + "strict": True, }, }, ], @@ -343,7 +352,7 @@ async def test_raw_response_create_overload_1(self, async_client: AsyncOpenAI) - "role": "system", } ], - model="gpt-4-turbo", + model="gpt-4o", ) assert response.is_closed is True @@ -360,7 +369,7 @@ async def test_streaming_response_create_overload_1(self, async_client: AsyncOpe "role": "system", } ], - model="gpt-4-turbo", + model="gpt-4o", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -379,7 +388,7 @@ async def test_method_create_overload_2(self, async_client: AsyncOpenAI) -> None "role": "system", } ], - model="gpt-4-turbo", + model="gpt-4o", stream=True, ) await completion_stream.response.aclose() @@ -394,7 +403,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn "name": "string", } ], - model="gpt-4-turbo", + model="gpt-4o", stream=True, frequency_penalty=-2, function_call="none", @@ -411,7 +420,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn n=1, parallel_tool_calls=True, presence_penalty=-2, - response_format={"type": "json_object"}, + response_format={"type": "text"}, seed=-9007199254740991, service_tier="auto", stop="string", @@ -425,6 +434,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn "description": "string", "name": "string", "parameters": {"foo": "bar"}, + "strict": True, }, }, { @@ -433,6 +443,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn "description": "string", "name": "string", "parameters": {"foo": "bar"}, + "strict": True, }, }, { @@ -441,6 +452,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn "description": "string", "name": "string", "parameters": {"foo": "bar"}, + "strict": True, }, }, ], @@ -459,7 +471,7 @@ async def test_raw_response_create_overload_2(self, async_client: AsyncOpenAI) - "role": "system", } ], - model="gpt-4-turbo", + model="gpt-4o", stream=True, ) @@ -476,7 +488,7 @@ async def test_streaming_response_create_overload_2(self, async_client: AsyncOpe "role": "system", } ], - model="gpt-4-turbo", + model="gpt-4o", stream=True, ) as response: assert not response.is_closed diff --git a/tests/api_resources/fine_tuning/test_jobs.py b/tests/api_resources/fine_tuning/test_jobs.py index 1ff6d63b31..68b3d73ac5 100644 --- a/tests/api_resources/fine_tuning/test_jobs.py +++ b/tests/api_resources/fine_tuning/test_jobs.py @@ -24,7 +24,7 @@ class TestJobs: @parametrize def test_method_create(self, client: OpenAI) -> None: job = client.fine_tuning.jobs.create( - model="gpt-3.5-turbo", + model="gpt-4o-mini", training_file="file-abc123", ) assert_matches_type(FineTuningJob, job, path=["response"]) @@ -32,7 +32,7 @@ def test_method_create(self, client: OpenAI) -> None: @parametrize def test_method_create_with_all_params(self, client: OpenAI) -> None: job = client.fine_tuning.jobs.create( - model="gpt-3.5-turbo", + model="gpt-4o-mini", training_file="file-abc123", hyperparameters={ "batch_size": "auto", @@ -77,7 +77,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: @parametrize def test_raw_response_create(self, client: OpenAI) -> None: response = client.fine_tuning.jobs.with_raw_response.create( - model="gpt-3.5-turbo", + model="gpt-4o-mini", training_file="file-abc123", ) @@ -89,7 +89,7 @@ def test_raw_response_create(self, client: OpenAI) -> None: @parametrize def test_streaming_response_create(self, client: OpenAI) -> None: with client.fine_tuning.jobs.with_streaming_response.create( - model="gpt-3.5-turbo", + model="gpt-4o-mini", training_file="file-abc123", ) as response: assert not response.is_closed @@ -263,7 +263,7 @@ class TestAsyncJobs: @parametrize async def test_method_create(self, async_client: AsyncOpenAI) -> None: job = await async_client.fine_tuning.jobs.create( - model="gpt-3.5-turbo", + model="gpt-4o-mini", training_file="file-abc123", ) assert_matches_type(FineTuningJob, job, path=["response"]) @@ -271,7 +271,7 @@ async def test_method_create(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: job = await async_client.fine_tuning.jobs.create( - model="gpt-3.5-turbo", + model="gpt-4o-mini", training_file="file-abc123", hyperparameters={ "batch_size": "auto", @@ -316,7 +316,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> @parametrize async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: response = await async_client.fine_tuning.jobs.with_raw_response.create( - model="gpt-3.5-turbo", + model="gpt-4o-mini", training_file="file-abc123", ) @@ -328,7 +328,7 @@ async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: async with async_client.fine_tuning.jobs.with_streaming_response.create( - model="gpt-3.5-turbo", + model="gpt-4o-mini", training_file="file-abc123", ) as response: assert not response.is_closed diff --git a/tests/api_resources/test_models.py b/tests/api_resources/test_models.py index 71f8e5834b..8791507c3e 100644 --- a/tests/api_resources/test_models.py +++ b/tests/api_resources/test_models.py @@ -21,14 +21,14 @@ class TestModels: @parametrize def test_method_retrieve(self, client: OpenAI) -> None: model = client.models.retrieve( - "gpt-3.5-turbo", + "gpt-4o-mini", ) assert_matches_type(Model, model, path=["response"]) @parametrize def test_raw_response_retrieve(self, client: OpenAI) -> None: response = client.models.with_raw_response.retrieve( - "gpt-3.5-turbo", + "gpt-4o-mini", ) assert response.is_closed is True @@ -39,7 +39,7 @@ def test_raw_response_retrieve(self, client: OpenAI) -> None: @parametrize def test_streaming_response_retrieve(self, client: OpenAI) -> None: with client.models.with_streaming_response.retrieve( - "gpt-3.5-turbo", + "gpt-4o-mini", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -84,14 +84,14 @@ def test_streaming_response_list(self, client: OpenAI) -> None: @parametrize def test_method_delete(self, client: OpenAI) -> None: model = client.models.delete( - "ft:gpt-3.5-turbo:acemeco:suffix:abc123", + "ft:gpt-4o-mini:acemeco:suffix:abc123", ) assert_matches_type(ModelDeleted, model, path=["response"]) @parametrize def test_raw_response_delete(self, client: OpenAI) -> None: response = client.models.with_raw_response.delete( - "ft:gpt-3.5-turbo:acemeco:suffix:abc123", + "ft:gpt-4o-mini:acemeco:suffix:abc123", ) assert response.is_closed is True @@ -102,7 +102,7 @@ def test_raw_response_delete(self, client: OpenAI) -> None: @parametrize def test_streaming_response_delete(self, client: OpenAI) -> None: with client.models.with_streaming_response.delete( - "ft:gpt-3.5-turbo:acemeco:suffix:abc123", + "ft:gpt-4o-mini:acemeco:suffix:abc123", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -126,14 +126,14 @@ class TestAsyncModels: @parametrize async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: model = await async_client.models.retrieve( - "gpt-3.5-turbo", + "gpt-4o-mini", ) assert_matches_type(Model, model, path=["response"]) @parametrize async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: response = await async_client.models.with_raw_response.retrieve( - "gpt-3.5-turbo", + "gpt-4o-mini", ) assert response.is_closed is True @@ -144,7 +144,7 @@ async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: async with async_client.models.with_streaming_response.retrieve( - "gpt-3.5-turbo", + "gpt-4o-mini", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -189,14 +189,14 @@ async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_method_delete(self, async_client: AsyncOpenAI) -> None: model = await async_client.models.delete( - "ft:gpt-3.5-turbo:acemeco:suffix:abc123", + "ft:gpt-4o-mini:acemeco:suffix:abc123", ) assert_matches_type(ModelDeleted, model, path=["response"]) @parametrize async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None: response = await async_client.models.with_raw_response.delete( - "ft:gpt-3.5-turbo:acemeco:suffix:abc123", + "ft:gpt-4o-mini:acemeco:suffix:abc123", ) assert response.is_closed is True @@ -207,7 +207,7 @@ async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_streaming_response_delete(self, async_client: AsyncOpenAI) -> None: async with async_client.models.with_streaming_response.delete( - "ft:gpt-3.5-turbo:acemeco:suffix:abc123", + "ft:gpt-4o-mini:acemeco:suffix:abc123", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" diff --git a/tests/lib/__init__.py b/tests/lib/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/lib/chat/__init__.py b/tests/lib/chat/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/lib/chat/_utils.py b/tests/lib/chat/_utils.py new file mode 100644 index 0000000000..dcc32b17fd --- /dev/null +++ b/tests/lib/chat/_utils.py @@ -0,0 +1,59 @@ +from __future__ import annotations + +import io +import inspect +from typing import Any, Iterable +from typing_extensions import TypeAlias + +import rich +import pytest +import pydantic + +ReprArgs: TypeAlias = "Iterable[tuple[str | None, Any]]" + + +def print_obj(obj: object, monkeypatch: pytest.MonkeyPatch) -> str: + """Pretty print an object to a string""" + + # monkeypatch pydantic model printing so that model fields + # are always printed in the same order so we can reliably + # use this for snapshot tests + original_repr = pydantic.BaseModel.__repr_args__ + + def __repr_args__(self: pydantic.BaseModel) -> ReprArgs: + return sorted(original_repr(self), key=lambda arg: arg[0] or arg) + + with monkeypatch.context() as m: + m.setattr(pydantic.BaseModel, "__repr_args__", __repr_args__) + + buf = io.StringIO() + + console = rich.console.Console(file=buf, width=120) + console.print(obj) + + string = buf.getvalue() + + # we remove all `fn_name..` occurences + # so that we can share the same snapshots between + # pydantic v1 and pydantic v2 as their output for + # generic models differs, e.g. + # + # v2: `ParsedChatCompletion[test_parse_pydantic_model..Location]` + # v1: `ParsedChatCompletion[Location]` + return clear_locals(string, stacklevel=2) + + +def get_caller_name(*, stacklevel: int = 1) -> str: + frame = inspect.currentframe() + assert frame is not None + + for i in range(stacklevel): + frame = frame.f_back + assert frame is not None, f"no {i}th frame" + + return frame.f_code.co_name + + +def clear_locals(string: str, *, stacklevel: int) -> str: + caller = get_caller_name(stacklevel=stacklevel + 1) + return string.replace(f"{caller}..", "") diff --git a/tests/lib/chat/test_completions.py b/tests/lib/chat/test_completions.py new file mode 100644 index 0000000000..db370e4332 --- /dev/null +++ b/tests/lib/chat/test_completions.py @@ -0,0 +1,633 @@ +from __future__ import annotations + +import os +import json +from typing import Any, Callable +from typing_extensions import Literal, TypeVar + +import httpx +import pytest +from respx import MockRouter +from pydantic import BaseModel +from inline_snapshot import snapshot + +import openai +from openai import OpenAI, AsyncOpenAI +from openai._utils import assert_signatures_in_sync + +from ._utils import print_obj +from ...conftest import base_url +from ..schema_types.query import Query + +_T = TypeVar("_T") + +# all the snapshots in this file are auto-generated from the live API +# +# you can update them with +# +# `OPENAI_LIVE=1 pytest --inline-snapshot=fix` + + +@pytest.mark.respx(base_url=base_url) +def test_parse_nothing(client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: + completion = _make_snapshot_request( + lambda c: c.beta.chat.completions.parse( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "user", + "content": "What's the weather like in SF?", + }, + ], + ), + content_snapshot=snapshot( + '{"id": "chatcmpl-9tABLlmqdEOYnmmWATUI3dNKlfXa3", "object": "chat.completion", "created": 1722934207, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "I\'m unable to provide real-time weather updates. For the current weather in San Francisco, I recommend checking a reliable weather website or app.", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 14, "completion_tokens": 27, "total_tokens": 41}, "system_fingerprint": "fp_e1a05a1dce"}' + ), + mock_client=client, + respx_mock=respx_mock, + ) + + assert print_obj(completion, monkeypatch) == snapshot( + """\ +ParsedChatCompletion[NoneType]( + choices=[ + ParsedChoice[NoneType]( + finish_reason='stop', + index=0, + logprobs=None, + message=ParsedChatCompletionMessage[NoneType]( + content="I'm unable to provide real-time weather updates. For the current weather in San Francisco, I +recommend checking a reliable weather website or app.", + function_call=None, + parsed=None, + refusal=None, + role='assistant', + tool_calls=[] + ) + ) + ], + created=1722934207, + id='chatcmpl-9tABLlmqdEOYnmmWATUI3dNKlfXa3', + model='gpt-4o-2024-08-06', + object='chat.completion', + service_tier=None, + system_fingerprint='fp_e1a05a1dce', + usage=CompletionUsage(completion_tokens=27, prompt_tokens=14, total_tokens=41) +) +""" + ) + + +@pytest.mark.respx(base_url=base_url) +def test_parse_pydantic_model(client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: + class Location(BaseModel): + city: str + temperature: float + units: Literal["c", "f"] + + completion = _make_snapshot_request( + lambda c: c.beta.chat.completions.parse( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "user", + "content": "What's the weather like in SF?", + }, + ], + response_format=Location, + ), + content_snapshot=snapshot( + '{"id": "chatcmpl-9tABUwdw3Kbe3VPRnMofh9lJkFkLV", "object": "chat.completion", "created": 1722934216, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"city\\":\\"San Francisco\\",\\"temperature\\":65,\\"units\\":\\"f\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 17, "completion_tokens": 14, "total_tokens": 31}, "system_fingerprint": "fp_e1a05a1dce"}' + ), + mock_client=client, + respx_mock=respx_mock, + ) + + assert print_obj(completion, monkeypatch) == snapshot( + """\ +ParsedChatCompletion[Location]( + choices=[ + ParsedChoice[Location]( + finish_reason='stop', + index=0, + logprobs=None, + message=ParsedChatCompletionMessage[Location]( + content='{"city":"San Francisco","temperature":65,"units":"f"}', + function_call=None, + parsed=Location(city='San Francisco', temperature=65.0, units='f'), + refusal=None, + role='assistant', + tool_calls=[] + ) + ) + ], + created=1722934216, + id='chatcmpl-9tABUwdw3Kbe3VPRnMofh9lJkFkLV', + model='gpt-4o-2024-08-06', + object='chat.completion', + service_tier=None, + system_fingerprint='fp_e1a05a1dce', + usage=CompletionUsage(completion_tokens=14, prompt_tokens=17, total_tokens=31) +) +""" + ) + + +@pytest.mark.respx(base_url=base_url) +def test_parse_pydantic_model_multiple_choices( + client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch +) -> None: + class Location(BaseModel): + city: str + temperature: float + units: Literal["c", "f"] + + completion = _make_snapshot_request( + lambda c: c.beta.chat.completions.parse( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "user", + "content": "What's the weather like in SF?", + }, + ], + n=3, + response_format=Location, + ), + content_snapshot=snapshot( + '{"id": "chatcmpl-9tABVfBu4ZdyQFKe8RgsWsyL7UoIj", "object": "chat.completion", "created": 1722934217, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"city\\":\\"San Francisco\\",\\"temperature\\":58.0,\\"units\\":\\"f\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}, {"index": 1, "message": {"role": "assistant", "content": "{\\"city\\":\\"San Francisco\\",\\"temperature\\":61,\\"units\\":\\"f\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}, {"index": 2, "message": {"role": "assistant", "content": "{\\"city\\":\\"San Francisco\\",\\"temperature\\":65,\\"units\\":\\"f\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 17, "completion_tokens": 44, "total_tokens": 61}, "system_fingerprint": "fp_e1a05a1dce"}' + ), + mock_client=client, + respx_mock=respx_mock, + ) + + assert print_obj(completion.choices, monkeypatch) == snapshot( + """\ +[ + ParsedChoice[Location]( + finish_reason='stop', + index=0, + logprobs=None, + message=ParsedChatCompletionMessage[Location]( + content='{"city":"San Francisco","temperature":58.0,"units":"f"}', + function_call=None, + parsed=Location(city='San Francisco', temperature=58.0, units='f'), + refusal=None, + role='assistant', + tool_calls=[] + ) + ), + ParsedChoice[Location]( + finish_reason='stop', + index=1, + logprobs=None, + message=ParsedChatCompletionMessage[Location]( + content='{"city":"San Francisco","temperature":61,"units":"f"}', + function_call=None, + parsed=Location(city='San Francisco', temperature=61.0, units='f'), + refusal=None, + role='assistant', + tool_calls=[] + ) + ), + ParsedChoice[Location]( + finish_reason='stop', + index=2, + logprobs=None, + message=ParsedChatCompletionMessage[Location]( + content='{"city":"San Francisco","temperature":65,"units":"f"}', + function_call=None, + parsed=Location(city='San Francisco', temperature=65.0, units='f'), + refusal=None, + role='assistant', + tool_calls=[] + ) + ) +] +""" + ) + + +@pytest.mark.respx(base_url=base_url) +def test_pydantic_tool_model_all_types(client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: + completion = _make_snapshot_request( + lambda c: c.beta.chat.completions.parse( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "user", + "content": "look up all my orders in may of last year that were fulfilled but not delivered on time", + }, + ], + tools=[openai.pydantic_function_tool(Query)], + response_format=Query, + ), + content_snapshot=snapshot( + '{"id": "chatcmpl-9tABVRLORZbby5zZjZhyrUdDU1XhB", "object": "chat.completion", "created": 1722934217, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "tool_calls": [{"id": "call_VcgQcA1C047fQnXDG0PQXG7O", "type": "function", "function": {"name": "Query", "arguments": "{\\"table_name\\":\\"orders\\",\\"columns\\":[\\"id\\",\\"status\\",\\"expected_delivery_date\\",\\"delivered_at\\"],\\"conditions\\":[{\\"column\\":\\"ordered_at\\",\\"operator\\":\\"=\\",\\"value\\":\\"2022-05\\"},{\\"column\\":\\"status\\",\\"operator\\":\\"=\\",\\"value\\":\\"fulfilled\\"},{\\"column\\":\\"delivered_at\\",\\"operator\\":\\">\\",\\"value\\":{\\"column_name\\":\\"expected_delivery_date\\"}}],\\"order_by\\":\\"asc\\"}"}}], "refusal": null}, "logprobs": null, "finish_reason": "tool_calls"}], "usage": {"prompt_tokens": 195, "completion_tokens": 85, "total_tokens": 280}, "system_fingerprint": "fp_e1a05a1dce"}' + ), + mock_client=client, + respx_mock=respx_mock, + ) + + assert print_obj(completion.choices[0], monkeypatch) == snapshot( + """\ +ParsedChoice[Query]( + finish_reason='tool_calls', + index=0, + logprobs=None, + message=ParsedChatCompletionMessage[Query]( + content=None, + function_call=None, + parsed=None, + refusal=None, + role='assistant', + tool_calls=[ + ParsedFunctionToolCall( + function=ParsedFunction( + arguments='{"table_name":"orders","columns":["id","status","expected_delivery_date","delivered_at"], +"conditions":[{"column":"ordered_at","operator":"=","value":"2022-05"},{"column":"status","operator":"=","value":"fulfil +led"},{"column":"delivered_at","operator":">","value":{"column_name":"expected_delivery_date"}}],"order_by":"asc"}', + name='Query', + parsed_arguments=Query( + columns=[ + , + , + , + + ], + conditions=[ + Condition(column='ordered_at', operator='>, + value=DynamicValue(column_name='expected_delivery_date') + ) + ], + order_by=, + table_name= + ) + ), + id='call_VcgQcA1C047fQnXDG0PQXG7O', + type='function' + ) + ] + ) +) +""" + ) + + +@pytest.mark.respx(base_url=base_url) +def test_parse_max_tokens_reached(client: OpenAI, respx_mock: MockRouter) -> None: + class Location(BaseModel): + city: str + temperature: float + units: Literal["c", "f"] + + with pytest.raises(openai.LengthFinishReasonError): + _make_snapshot_request( + lambda c: c.beta.chat.completions.parse( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "user", + "content": "What's the weather like in SF?", + }, + ], + max_tokens=1, + response_format=Location, + ), + content_snapshot=snapshot( + '{"id": "chatcmpl-9tABXbi3qast6oJvdaqQcK9C7k9fn", "object": "chat.completion", "created": 1722934219, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"", "refusal": null}, "logprobs": null, "finish_reason": "length"}], "usage": {"prompt_tokens": 17, "completion_tokens": 1, "total_tokens": 18}, "system_fingerprint": "fp_e1a05a1dce"}' + ), + mock_client=client, + respx_mock=respx_mock, + ) + + +@pytest.mark.respx(base_url=base_url) +def test_parse_pydantic_model_refusal(client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: + class Location(BaseModel): + city: str + temperature: float + units: Literal["c", "f"] + + completion = _make_snapshot_request( + lambda c: c.beta.chat.completions.parse( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "user", + "content": "How do I make anthrax?", + }, + ], + response_format=Location, + ), + content_snapshot=snapshot( + '{"id": "chatcmpl-9tABXJEffhEWxp24MeLxkDJCMtWmx", "object": "chat.completion", "created": 1722934219, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "refusal": "I\'m very sorry, but I can\'t assist with that."}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 17, "completion_tokens": 12, "total_tokens": 29}, "system_fingerprint": "fp_e1a05a1dce"}' + ), + mock_client=client, + respx_mock=respx_mock, + ) + + assert print_obj(completion.choices, monkeypatch) == snapshot( + """\ +[ + ParsedChoice[Location]( + finish_reason='stop', + index=0, + logprobs=None, + message=ParsedChatCompletionMessage[Location]( + content=None, + function_call=None, + parsed=None, + refusal="I'm very sorry, but I can't assist with that.", + role='assistant', + tool_calls=[] + ) + ) +] +""" + ) + + +@pytest.mark.respx(base_url=base_url) +def test_parse_pydantic_tool(client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: + class GetWeatherArgs(BaseModel): + city: str + country: str + units: Literal["c", "f"] = "c" + + completion = _make_snapshot_request( + lambda c: c.beta.chat.completions.parse( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "user", + "content": "What's the weather like in Edinburgh?", + }, + ], + tools=[ + openai.pydantic_function_tool(GetWeatherArgs), + ], + ), + content_snapshot=snapshot( + '{"id": "chatcmpl-9tABgtKnF7Gbri4CmpOocmhg0UgBF", "object": "chat.completion", "created": 1722934228, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "tool_calls": [{"id": "call_9rqjEc1DQRADTYGVV45LbZwL", "type": "function", "function": {"name": "GetWeatherArgs", "arguments": "{\\"city\\":\\"Edinburgh\\",\\"country\\":\\"UK\\",\\"units\\":\\"c\\"}"}}], "refusal": null}, "logprobs": null, "finish_reason": "tool_calls"}], "usage": {"prompt_tokens": 76, "completion_tokens": 24, "total_tokens": 100}, "system_fingerprint": "fp_e1a05a1dce"}' + ), + mock_client=client, + respx_mock=respx_mock, + ) + + assert print_obj(completion.choices, monkeypatch) == snapshot( + """\ +[ + ParsedChoice[NoneType]( + finish_reason='tool_calls', + index=0, + logprobs=None, + message=ParsedChatCompletionMessage[NoneType]( + content=None, + function_call=None, + parsed=None, + refusal=None, + role='assistant', + tool_calls=[ + ParsedFunctionToolCall( + function=ParsedFunction( + arguments='{"city":"Edinburgh","country":"UK","units":"c"}', + name='GetWeatherArgs', + parsed_arguments=GetWeatherArgs(city='Edinburgh', country='UK', units='c') + ), + id='call_9rqjEc1DQRADTYGVV45LbZwL', + type='function' + ) + ] + ) + ) +] +""" + ) + + +@pytest.mark.respx(base_url=base_url) +def test_parse_multiple_pydantic_tools(client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: + class GetWeatherArgs(BaseModel): + """Get the temperature for the given country/city combo""" + + city: str + country: str + units: Literal["c", "f"] = "c" + + class GetStockPrice(BaseModel): + ticker: str + exchange: str + + completion = _make_snapshot_request( + lambda c: c.beta.chat.completions.parse( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "user", + "content": "What's the weather like in Edinburgh?", + }, + { + "role": "user", + "content": "What's the price of AAPL?", + }, + ], + tools=[ + openai.pydantic_function_tool(GetWeatherArgs), + openai.pydantic_function_tool( + GetStockPrice, name="get_stock_price", description="Fetch the latest price for a given ticker" + ), + ], + ), + content_snapshot=snapshot( + '{"id": "chatcmpl-9tABqDpvDTi0Cg8PHtKdNSFoh4UJv", "object": "chat.completion", "created": 1722934238, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "tool_calls": [{"id": "call_Yeg67XmQbMcohm3NGj0g12ty", "type": "function", "function": {"name": "GetWeatherArgs", "arguments": "{\\"city\\": \\"Edinburgh\\", \\"country\\": \\"GB\\", \\"units\\": \\"c\\"}"}}, {"id": "call_OGg3UZC2ksjAg7yrLXy8t1MO", "type": "function", "function": {"name": "get_stock_price", "arguments": "{\\"ticker\\": \\"AAPL\\", \\"exchange\\": \\"NASDAQ\\"}"}}], "refusal": null}, "logprobs": null, "finish_reason": "tool_calls"}], "usage": {"prompt_tokens": 149, "completion_tokens": 60, "total_tokens": 209}, "system_fingerprint": "fp_e1a05a1dce"}' + ), + mock_client=client, + respx_mock=respx_mock, + ) + + assert print_obj(completion.choices, monkeypatch) == snapshot( + """\ +[ + ParsedChoice[NoneType]( + finish_reason='tool_calls', + index=0, + logprobs=None, + message=ParsedChatCompletionMessage[NoneType]( + content=None, + function_call=None, + parsed=None, + refusal=None, + role='assistant', + tool_calls=[ + ParsedFunctionToolCall( + function=ParsedFunction( + arguments='{"city": "Edinburgh", "country": "GB", "units": "c"}', + name='GetWeatherArgs', + parsed_arguments=GetWeatherArgs(city='Edinburgh', country='GB', units='c') + ), + id='call_Yeg67XmQbMcohm3NGj0g12ty', + type='function' + ), + ParsedFunctionToolCall( + function=ParsedFunction( + arguments='{"ticker": "AAPL", "exchange": "NASDAQ"}', + name='get_stock_price', + parsed_arguments=GetStockPrice(exchange='NASDAQ', ticker='AAPL') + ), + id='call_OGg3UZC2ksjAg7yrLXy8t1MO', + type='function' + ) + ] + ) + ) +] +""" + ) + + +@pytest.mark.respx(base_url=base_url) +def test_parse_strict_tools(client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: + completion = _make_snapshot_request( + lambda c: c.beta.chat.completions.parse( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "user", + "content": "What's the weather like in SF?", + }, + ], + tools=[ + { + "type": "function", + "function": { + "name": "get_weather", + "parameters": { + "type": "object", + "properties": { + "city": {"type": "string"}, + "state": {"type": "string"}, + }, + "required": [ + "city", + "state", + ], + "additionalProperties": False, + }, + "strict": True, + }, + } + ], + ), + content_snapshot=snapshot( + '{"id": "chatcmpl-9tAC0vDx3MfupXmsduSZavLVaLcrA", "object": "chat.completion", "created": 1722934248, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "tool_calls": [{"id": "call_iNznvWR4R81mizFFHjgh7o4i", "type": "function", "function": {"name": "get_weather", "arguments": "{\\"city\\":\\"San Francisco\\",\\"state\\":\\"CA\\"}"}}], "refusal": null}, "logprobs": null, "finish_reason": "tool_calls"}], "usage": {"prompt_tokens": 48, "completion_tokens": 19, "total_tokens": 67}, "system_fingerprint": "fp_e1a05a1dce"}' + ), + mock_client=client, + respx_mock=respx_mock, + ) + + assert print_obj(completion.choices, monkeypatch) == snapshot( + """\ +[ + ParsedChoice[NoneType]( + finish_reason='tool_calls', + index=0, + logprobs=None, + message=ParsedChatCompletionMessage[NoneType]( + content=None, + function_call=None, + parsed=None, + refusal=None, + role='assistant', + tool_calls=[ + ParsedFunctionToolCall( + function=ParsedFunction( + arguments='{"city":"San Francisco","state":"CA"}', + name='get_weather', + parsed_arguments={'city': 'San Francisco', 'state': 'CA'} + ), + id='call_iNznvWR4R81mizFFHjgh7o4i', + type='function' + ) + ] + ) + ) +] +""" + ) + + +def test_parse_non_strict_tools(client: OpenAI) -> None: + with pytest.raises( + ValueError, match="`get_weather` is not strict. Only `strict` function tools can be auto-parsed" + ): + client.beta.chat.completions.parse( + model="gpt-4o-2024-08-06", + messages=[], + tools=[ + { + "type": "function", + "function": { + "name": "get_weather", + "parameters": {}, + }, + } + ], + ) + + +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +def test_parse_method_in_sync(sync: bool, client: OpenAI, async_client: AsyncOpenAI) -> None: + checking_client: OpenAI | AsyncOpenAI = client if sync else async_client + + assert_signatures_in_sync( + checking_client.chat.completions.create, + checking_client.beta.chat.completions.parse, + exclude_params={"response_format", "stream"}, + ) + + +def _make_snapshot_request( + func: Callable[[OpenAI], _T], + *, + content_snapshot: Any, + respx_mock: MockRouter, + mock_client: OpenAI, +) -> _T: + live = os.environ.get("OPENAI_LIVE") == "1" + if live: + + def _on_response(response: httpx.Response) -> None: + # update the content snapshot + assert json.dumps(json.loads(response.read())) == content_snapshot + + respx_mock.stop() + + client = OpenAI( + http_client=httpx.Client( + event_hooks={ + "response": [_on_response], + } + ) + ) + else: + respx_mock.post("/chat/completions").mock( + return_value=httpx.Response( + 200, + content=content_snapshot._old_value, + headers={"content-type": "application/json"}, + ) + ) + + client = mock_client + + result = func(client) + + if live: + client.close() + + return result diff --git a/tests/lib/chat/test_completions_streaming.py b/tests/lib/chat/test_completions_streaming.py new file mode 100644 index 0000000000..3aaa9a0f38 --- /dev/null +++ b/tests/lib/chat/test_completions_streaming.py @@ -0,0 +1,1047 @@ +from __future__ import annotations + +import os +from typing import Any, Generic, Callable, Iterator, cast, overload +from typing_extensions import Literal, TypeVar + +import rich +import httpx +import pytest +from respx import MockRouter +from pydantic import BaseModel +from inline_snapshot import external, snapshot, outsource + +import openai +from openai import OpenAI, AsyncOpenAI +from openai._utils import assert_signatures_in_sync +from openai._compat import model_copy +from openai.lib.streaming.chat import ( + ContentDoneEvent, + ChatCompletionStream, + ChatCompletionStreamEvent, + ChatCompletionStreamManager, + ParsedChatCompletionSnapshot, +) +from openai.lib._parsing._completions import ResponseFormatT + +from ._utils import print_obj +from ...conftest import base_url + +_T = TypeVar("_T") + +# all the snapshots in this file are auto-generated from the live API +# +# you can update them with +# +# `OPENAI_LIVE=1 pytest --inline-snapshot=fix` + + +@pytest.mark.respx(base_url=base_url) +def test_parse_nothing(client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: + listener = _make_stream_snapshot_request( + lambda c: c.beta.chat.completions.stream( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "user", + "content": "What's the weather like in SF?", + }, + ], + ), + content_snapshot=snapshot(external("b9d6bee9f9b8*.bin")), + mock_client=client, + respx_mock=respx_mock, + ) + + assert print_obj(listener.stream.get_final_completion().choices, monkeypatch) == snapshot( + """\ +[ + ParsedChoice[NoneType]( + finish_reason='stop', + index=0, + logprobs=None, + message=ParsedChatCompletionMessage[NoneType]( + content="I'm unable to provide real-time weather updates. To get the latest weather information for San +Francisco, I recommend checking a reliable weather website or using a weather app.", + function_call=None, + parsed=None, + refusal=None, + role='assistant', + tool_calls=[] + ) + ) +] +""" + ) + assert print_obj(listener.get_event_by_type("content.done"), monkeypatch) == snapshot( + """\ +ContentDoneEvent[NoneType]( + content="I'm unable to provide real-time weather updates. To get the latest weather information for San Francisco, I +recommend checking a reliable weather website or using a weather app.", + parsed=None, + type='content.done' +) +""" + ) + + +@pytest.mark.respx(base_url=base_url) +def test_parse_pydantic_model(client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: + class Location(BaseModel): + city: str + temperature: float + units: Literal["c", "f"] + + done_snapshots: list[ParsedChatCompletionSnapshot] = [] + + def on_event(stream: ChatCompletionStream[Location], event: ChatCompletionStreamEvent[Location]) -> None: + if event.type == "content.done": + done_snapshots.append(model_copy(stream.current_completion_snapshot, deep=True)) + + listener = _make_stream_snapshot_request( + lambda c: c.beta.chat.completions.stream( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "user", + "content": "What's the weather like in SF?", + }, + ], + response_format=Location, + ), + content_snapshot=snapshot(external("ea9a417d533b*.bin")), + mock_client=client, + respx_mock=respx_mock, + on_event=on_event, + ) + + assert len(done_snapshots) == 1 + assert isinstance(done_snapshots[0].choices[0].message.parsed, Location) + + for event in reversed(listener.events): + if event.type == "content.delta": + data = cast(Any, event.parsed) + assert isinstance(data["city"], str), data + assert isinstance(data["temperature"], (int, float)), data + assert isinstance(data["units"], str), data + break + else: + rich.print(listener.events) + raise AssertionError("Did not find a `content.delta` event") + + assert print_obj(listener.stream.get_final_completion(), monkeypatch) == snapshot( + """\ +ParsedChatCompletion[Location]( + choices=[ + ParsedChoice[Location]( + finish_reason='stop', + index=0, + logprobs=None, + message=ParsedChatCompletionMessage[Location]( + content='{"city":"San Francisco","temperature":63,"units":"f"}', + function_call=None, + parsed=Location(city='San Francisco', temperature=63.0, units='f'), + refusal=None, + role='assistant', + tool_calls=[] + ) + ) + ], + created=1722934250, + id='chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv', + model='gpt-4o-so', + object='chat.completion', + service_tier=None, + system_fingerprint='fp_e1a05a1dce', + usage=CompletionUsage(completion_tokens=14, prompt_tokens=17, total_tokens=31) +) +""" + ) + assert print_obj(listener.get_event_by_type("content.done"), monkeypatch) == snapshot( + """\ +ContentDoneEvent[Location]( + content='{"city":"San Francisco","temperature":63,"units":"f"}', + parsed=Location(city='San Francisco', temperature=63.0, units='f'), + type='content.done' +) +""" + ) + + +@pytest.mark.respx(base_url=base_url) +def test_parse_pydantic_model_multiple_choices( + client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch +) -> None: + class Location(BaseModel): + city: str + temperature: float + units: Literal["c", "f"] + + listener = _make_stream_snapshot_request( + lambda c: c.beta.chat.completions.stream( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "user", + "content": "What's the weather like in SF?", + }, + ], + n=3, + response_format=Location, + ), + content_snapshot=snapshot(external("1437bd06a9d5*.bin")), + mock_client=client, + respx_mock=respx_mock, + ) + + assert [e.type for e in listener.events] == snapshot( + [ + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.delta", + "chunk", + "content.done", + "chunk", + "content.done", + "chunk", + "content.done", + "chunk", + ] + ) + assert print_obj(listener.stream.get_final_completion().choices, monkeypatch) == snapshot( + """\ +[ + ParsedChoice[Location]( + finish_reason='stop', + index=0, + logprobs=None, + message=ParsedChatCompletionMessage[Location]( + content='{"city":"San Francisco","temperature":64,"units":"f"}', + function_call=None, + parsed=Location(city='San Francisco', temperature=64.0, units='f'), + refusal=None, + role='assistant', + tool_calls=[] + ) + ), + ParsedChoice[Location]( + finish_reason='stop', + index=1, + logprobs=None, + message=ParsedChatCompletionMessage[Location]( + content='{"city":"San Francisco","temperature":68,"units":"f"}', + function_call=None, + parsed=Location(city='San Francisco', temperature=68.0, units='f'), + refusal=None, + role='assistant', + tool_calls=[] + ) + ), + ParsedChoice[Location]( + finish_reason='stop', + index=2, + logprobs=None, + message=ParsedChatCompletionMessage[Location]( + content='{"city":"San Francisco","temperature":64,"units":"f"}', + function_call=None, + parsed=Location(city='San Francisco', temperature=64.0, units='f'), + refusal=None, + role='assistant', + tool_calls=[] + ) + ) +] +""" + ) + + +@pytest.mark.respx(base_url=base_url) +def test_parse_max_tokens_reached(client: OpenAI, respx_mock: MockRouter) -> None: + class Location(BaseModel): + city: str + temperature: float + units: Literal["c", "f"] + + with pytest.raises(openai.LengthFinishReasonError): + _make_stream_snapshot_request( + lambda c: c.beta.chat.completions.stream( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "user", + "content": "What's the weather like in SF?", + }, + ], + max_tokens=1, + response_format=Location, + ), + content_snapshot=snapshot(external("7ae6c1a2631b*.bin")), + mock_client=client, + respx_mock=respx_mock, + ) + + +@pytest.mark.respx(base_url=base_url) +def test_parse_pydantic_model_refusal(client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: + class Location(BaseModel): + city: str + temperature: float + units: Literal["c", "f"] + + listener = _make_stream_snapshot_request( + lambda c: c.beta.chat.completions.stream( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "user", + "content": "How do I make anthrax?", + }, + ], + response_format=Location, + ), + content_snapshot=snapshot(external("d79326933c15*.bin")), + mock_client=client, + respx_mock=respx_mock, + ) + + assert print_obj(listener.get_event_by_type("refusal.done"), monkeypatch) == snapshot("""\ +RefusalDoneEvent(refusal="I'm very sorry, but I can't assist with that request.", type='refusal.done') +""") + + assert print_obj(listener.stream.get_final_completion().choices, monkeypatch) == snapshot( + """\ +[ + ParsedChoice[Location]( + finish_reason='stop', + index=0, + logprobs=None, + message=ParsedChatCompletionMessage[Location]( + content=None, + function_call=None, + parsed=None, + refusal="I'm very sorry, but I can't assist with that request.", + role='assistant', + tool_calls=[] + ) + ) +] +""" + ) + + +@pytest.mark.respx(base_url=base_url) +def test_content_logprobs_events(client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: + listener = _make_stream_snapshot_request( + lambda c: c.beta.chat.completions.stream( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "user", + "content": "Say foo", + }, + ], + logprobs=True, + ), + content_snapshot=snapshot(external("70c7df71ce72*.bin")), + mock_client=client, + respx_mock=respx_mock, + ) + + assert print_obj([e for e in listener.events if e.type.startswith("logprobs")], monkeypatch) == snapshot("""\ +[ + LogprobsContentDeltaEvent( + content=[ChatCompletionTokenLogprob(bytes=[70, 111, 111], logprob=-0.006764991, token='Foo', top_logprobs=[])], + snapshot=[ + ChatCompletionTokenLogprob(bytes=[70, 111, 111], logprob=-0.006764991, token='Foo', top_logprobs=[]) + ], + type='logprobs.content.delta' + ), + LogprobsContentDeltaEvent( + content=[ChatCompletionTokenLogprob(bytes=[33], logprob=-0.31380808, token='!', top_logprobs=[])], + snapshot=[ + ChatCompletionTokenLogprob(bytes=[70, 111, 111], logprob=-0.006764991, token='Foo', top_logprobs=[]), + ChatCompletionTokenLogprob(bytes=[33], logprob=-0.31380808, token='!', top_logprobs=[]) + ], + type='logprobs.content.delta' + ), + LogprobsContentDoneEvent( + content=[ + ChatCompletionTokenLogprob(bytes=[70, 111, 111], logprob=-0.006764991, token='Foo', top_logprobs=[]), + ChatCompletionTokenLogprob(bytes=[33], logprob=-0.31380808, token='!', top_logprobs=[]) + ], + type='logprobs.content.done' + ) +] +""") + + assert print_obj(listener.stream.get_final_completion().choices, monkeypatch) == snapshot("""\ +[ + ParsedChoice[NoneType]( + finish_reason='stop', + index=0, + logprobs=ChoiceLogprobs( + content=[ + ChatCompletionTokenLogprob(bytes=[70, 111, 111], logprob=-0.006764991, token='Foo', top_logprobs=[]), + ChatCompletionTokenLogprob(bytes=[33], logprob=-0.31380808, token='!', top_logprobs=[]) + ], + refusal=None + ), + message=ParsedChatCompletionMessage[NoneType]( + content='Foo!', + function_call=None, + parsed=None, + refusal=None, + role='assistant', + tool_calls=[] + ) + ) +] +""") + + +@pytest.mark.respx(base_url=base_url) +def test_refusal_logprobs_events(client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: + class Location(BaseModel): + city: str + temperature: float + units: Literal["c", "f"] + + listener = _make_stream_snapshot_request( + lambda c: c.beta.chat.completions.stream( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "user", + "content": "How do I make anthrax?", + }, + ], + logprobs=True, + response_format=Location, + ), + content_snapshot=snapshot(external("cb77dc69b6c8*.bin")), + mock_client=client, + respx_mock=respx_mock, + ) + + assert print_obj([e.type for e in listener.events if e.type.startswith("logprobs")], monkeypatch) == snapshot("""\ +[ + 'logprobs.refusal.delta', + 'logprobs.refusal.delta', + 'logprobs.refusal.delta', + 'logprobs.refusal.delta', + 'logprobs.refusal.delta', + 'logprobs.refusal.delta', + 'logprobs.refusal.delta', + 'logprobs.refusal.delta', + 'logprobs.refusal.delta', + 'logprobs.refusal.delta', + 'logprobs.refusal.delta', + 'logprobs.refusal.done' +] +""") + + assert print_obj(listener.stream.get_final_completion().choices, monkeypatch) == snapshot("""\ +[ + ParsedChoice[Location]( + finish_reason='stop', + index=0, + logprobs=ChoiceLogprobs( + content=None, + refusal=[ + ChatCompletionTokenLogprob(bytes=[73, 39, 109], logprob=-0.0010472201, token="I'm", top_logprobs=[]), + ChatCompletionTokenLogprob( + bytes=[32, 118, 101, 114, 121], + logprob=-0.7292482, + token=' very', + top_logprobs=[] + ), + ChatCompletionTokenLogprob( + bytes=[32, 115, 111, 114, 114, 121], + logprob=-5.080963e-06, + token=' sorry', + top_logprobs=[] + ), + ChatCompletionTokenLogprob(bytes=[44], logprob=-4.048445e-05, token=',', top_logprobs=[]), + ChatCompletionTokenLogprob( + bytes=[32, 98, 117, 116], + logprob=-0.038046427, + token=' but', + top_logprobs=[] + ), + ChatCompletionTokenLogprob(bytes=[32, 73], logprob=-0.0019351852, token=' I', top_logprobs=[]), + ChatCompletionTokenLogprob( + bytes=[32, 99, 97, 110, 39, 116], + logprob=-0.008995773, + token=" can't", + top_logprobs=[] + ), + ChatCompletionTokenLogprob( + bytes=[32, 97, 115, 115, 105, 115, 116], + logprob=-0.0033510819, + token=' assist', + top_logprobs=[] + ), + ChatCompletionTokenLogprob( + bytes=[32, 119, 105, 116, 104], + logprob=-0.0036033941, + token=' with', + top_logprobs=[] + ), + ChatCompletionTokenLogprob( + bytes=[32, 116, 104, 97, 116], + logprob=-0.0015974608, + token=' that', + top_logprobs=[] + ), + ChatCompletionTokenLogprob(bytes=[46], logprob=-0.6339823, token='.', top_logprobs=[]) + ] + ), + message=ParsedChatCompletionMessage[Location]( + content=None, + function_call=None, + parsed=None, + refusal="I'm very sorry, but I can't assist with that.", + role='assistant', + tool_calls=[] + ) + ) +] +""") + + +@pytest.mark.respx(base_url=base_url) +def test_parse_pydantic_tool(client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: + class GetWeatherArgs(BaseModel): + city: str + country: str + units: Literal["c", "f"] = "c" + + listener = _make_stream_snapshot_request( + lambda c: c.beta.chat.completions.stream( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "user", + "content": "What's the weather like in Edinburgh?", + }, + ], + tools=[ + openai.pydantic_function_tool(GetWeatherArgs), + ], + ), + content_snapshot=snapshot(external("ae070a447e1d*.bin")), + mock_client=client, + respx_mock=respx_mock, + ) + + assert print_obj(listener.stream.current_completion_snapshot.choices, monkeypatch) == snapshot( + """\ +[ + ParsedChoice[object]( + finish_reason='tool_calls', + index=0, + logprobs=None, + message=ParsedChatCompletionMessage[object]( + content=None, + function_call=None, + parsed=None, + refusal=None, + role='assistant', + tool_calls=[ + ParsedFunctionToolCall( + function=ParsedFunction( + arguments='{"city":"Edinburgh","country":"UK","units":"c"}', + name='GetWeatherArgs', + parsed_arguments=GetWeatherArgs(city='Edinburgh', country='UK', units='c') + ), + id='call_Vz6ZXciy6Y0PYfT4d9W7fYB4', + index=0, + type='function' + ) + ] + ) + ) +] +""" + ) + + assert print_obj(listener.stream.get_final_completion().choices, monkeypatch) == snapshot( + """\ +[ + ParsedChoice[NoneType]( + finish_reason='tool_calls', + index=0, + logprobs=None, + message=ParsedChatCompletionMessage[NoneType]( + content=None, + function_call=None, + parsed=None, + refusal=None, + role='assistant', + tool_calls=[ + ParsedFunctionToolCall( + function=ParsedFunction( + arguments='{"city":"Edinburgh","country":"UK","units":"c"}', + name='GetWeatherArgs', + parsed_arguments=GetWeatherArgs(city='Edinburgh', country='UK', units='c') + ), + id='call_Vz6ZXciy6Y0PYfT4d9W7fYB4', + index=0, + type='function' + ) + ] + ) + ) +] +""" + ) + + +@pytest.mark.respx(base_url=base_url) +def test_parse_multiple_pydantic_tools(client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: + class GetWeatherArgs(BaseModel): + """Get the temperature for the given country/city combo""" + + city: str + country: str + units: Literal["c", "f"] = "c" + + class GetStockPrice(BaseModel): + ticker: str + exchange: str + + listener = _make_stream_snapshot_request( + lambda c: c.beta.chat.completions.stream( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "user", + "content": "What's the weather like in Edinburgh?", + }, + { + "role": "user", + "content": "What's the price of AAPL?", + }, + ], + tools=[ + openai.pydantic_function_tool(GetWeatherArgs), + openai.pydantic_function_tool( + GetStockPrice, name="get_stock_price", description="Fetch the latest price for a given ticker" + ), + ], + ), + content_snapshot=snapshot(external("a346213bec7a*.bin")), + mock_client=client, + respx_mock=respx_mock, + ) + + assert print_obj(listener.stream.current_completion_snapshot.choices, monkeypatch) == snapshot( + """\ +[ + ParsedChoice[object]( + finish_reason='tool_calls', + index=0, + logprobs=None, + message=ParsedChatCompletionMessage[object]( + content=None, + function_call=None, + parsed=None, + refusal=None, + role='assistant', + tool_calls=[ + ParsedFunctionToolCall( + function=ParsedFunction( + arguments='{"city": "Edinburgh", "country": "UK", "units": "c"}', + name='GetWeatherArgs', + parsed_arguments=GetWeatherArgs(city='Edinburgh', country='UK', units='c') + ), + id='call_g4Q1vRbE0CaHGOs5if8mHsBq', + index=0, + type='function' + ), + ParsedFunctionToolCall( + function=ParsedFunction( + arguments='{"ticker": "AAPL", "exchange": "NASDAQ"}', + name='get_stock_price', + parsed_arguments=GetStockPrice(exchange='NASDAQ', ticker='AAPL') + ), + id='call_gWj3HQxZEHnFvyJLEHIiJKBV', + index=1, + type='function' + ) + ] + ) + ) +] +""" + ) + completion = listener.stream.get_final_completion() + assert print_obj(completion.choices[0].message.tool_calls, monkeypatch) == snapshot( + """\ +[ + ParsedFunctionToolCall( + function=ParsedFunction( + arguments='{"city": "Edinburgh", "country": "UK", "units": "c"}', + name='GetWeatherArgs', + parsed_arguments=GetWeatherArgs(city='Edinburgh', country='UK', units='c') + ), + id='call_g4Q1vRbE0CaHGOs5if8mHsBq', + index=0, + type='function' + ), + ParsedFunctionToolCall( + function=ParsedFunction( + arguments='{"ticker": "AAPL", "exchange": "NASDAQ"}', + name='get_stock_price', + parsed_arguments=GetStockPrice(exchange='NASDAQ', ticker='AAPL') + ), + id='call_gWj3HQxZEHnFvyJLEHIiJKBV', + index=1, + type='function' + ) +] +""" + ) + + +@pytest.mark.respx(base_url=base_url) +def test_parse_strict_tools(client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: + listener = _make_stream_snapshot_request( + lambda c: c.beta.chat.completions.stream( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "user", + "content": "What's the weather like in SF?", + }, + ], + tools=[ + { + "type": "function", + "function": { + "name": "get_weather", + "parameters": { + "type": "object", + "properties": { + "city": {"type": "string"}, + "state": {"type": "string"}, + }, + "required": [ + "city", + "state", + ], + "additionalProperties": False, + }, + "strict": True, + }, + } + ], + ), + content_snapshot=snapshot(external("a7097cae6a1f*.bin")), + mock_client=client, + respx_mock=respx_mock, + ) + + assert print_obj(listener.stream.current_completion_snapshot.choices, monkeypatch) == snapshot( + """\ +[ + ParsedChoice[object]( + finish_reason='tool_calls', + index=0, + logprobs=None, + message=ParsedChatCompletionMessage[object]( + content=None, + function_call=None, + parsed=None, + refusal=None, + role='assistant', + tool_calls=[ + ParsedFunctionToolCall( + function=ParsedFunction( + arguments='{"city":"San Francisco","state":"CA"}', + name='get_weather', + parsed_arguments={'city': 'San Francisco', 'state': 'CA'} + ), + id='call_rQe3kzGnTr2epjx8HREg3F2a', + index=0, + type='function' + ) + ] + ) + ) +] +""" + ) + + +@pytest.mark.respx(base_url=base_url) +def test_non_pydantic_response_format(client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: + listener = _make_stream_snapshot_request( + lambda c: c.beta.chat.completions.stream( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "user", + "content": "What's the weather like in SF? Give me any JSON back", + }, + ], + response_format={"type": "json_object"}, + ), + content_snapshot=snapshot(external("3e0df46f250d*.bin")), + mock_client=client, + respx_mock=respx_mock, + ) + + assert print_obj(listener.stream.get_final_completion().choices, monkeypatch) == snapshot( + """\ +[ + ParsedChoice[NoneType]( + finish_reason='stop', + index=0, + logprobs=None, + message=ParsedChatCompletionMessage[NoneType]( + content='{\\n "location": "San Francisco, CA",\\n "temperature": "N/A",\\n "conditions": "N/A",\\n +"humidity": "N/A",\\n "wind_speed": "N/A",\\n "timestamp": "N/A",\\n "note": "Real-time weather data is not available. +Please check a reliable weather service for the most up-to-date information on San Francisco\\'s weather conditions."}', + function_call=None, + parsed=None, + refusal=None, + role='assistant', + tool_calls=[] + ) + ) +] +""" + ) + + +@pytest.mark.respx(base_url=base_url) +def test_allows_non_strict_tools_but_no_parsing( + client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch +) -> None: + listener = _make_stream_snapshot_request( + lambda c: c.beta.chat.completions.stream( + model="gpt-4o-2024-08-06", + messages=[{"role": "user", "content": "what's the weather in NYC?"}], + tools=[ + { + "type": "function", + "function": { + "name": "get_weather", + "parameters": {"type": "object", "properties": {"city": {"type": "string"}}}, + }, + } + ], + ), + content_snapshot=snapshot(external("fb75060ede89*.bin")), + mock_client=client, + respx_mock=respx_mock, + ) + + assert print_obj(listener.get_event_by_type("tool_calls.function.arguments.done"), monkeypatch) == snapshot("""\ +FunctionToolCallArgumentsDoneEvent( + arguments='{"city":"New York City"}', + index=0, + name='get_weather', + parsed_arguments=None, + type='tool_calls.function.arguments.done' +) +""") + + assert print_obj(listener.stream.get_final_completion().choices, monkeypatch) == snapshot( + """\ +[ + ParsedChoice[NoneType]( + finish_reason='stop', + index=0, + logprobs=None, + message=ParsedChatCompletionMessage[NoneType]( + content=None, + function_call=None, + parsed=None, + refusal=None, + role='assistant', + tool_calls=[ + ParsedFunctionToolCall( + function=ParsedFunction( + arguments='{"city":"New York City"}', + name='get_weather', + parsed_arguments=None + ), + id='call_9rqjEc1DQRADTYGVV45LbZwL', + index=0, + type='function' + ) + ] + ) + ) +] +""" + ) + + +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +def test_stream_method_in_sync(sync: bool, client: OpenAI, async_client: AsyncOpenAI) -> None: + checking_client: OpenAI | AsyncOpenAI = client if sync else async_client + + assert_signatures_in_sync( + checking_client.chat.completions.create, + checking_client.beta.chat.completions.stream, + exclude_params={"response_format", "stream"}, + ) + + +class StreamListener(Generic[ResponseFormatT]): + def __init__(self, stream: ChatCompletionStream[ResponseFormatT]) -> None: + self.stream = stream + self.events: list[ChatCompletionStreamEvent[ResponseFormatT]] = [] + + def __iter__(self) -> Iterator[ChatCompletionStreamEvent[ResponseFormatT]]: + for event in self.stream: + self.events.append(event) + yield event + + @overload + def get_event_by_type(self, event_type: Literal["content.done"]) -> ContentDoneEvent[ResponseFormatT] | None: ... + + @overload + def get_event_by_type(self, event_type: str) -> ChatCompletionStreamEvent[ResponseFormatT] | None: ... + + def get_event_by_type(self, event_type: str) -> ChatCompletionStreamEvent[ResponseFormatT] | None: + return next((e for e in self.events if e.type == event_type), None) + + +def _make_stream_snapshot_request( + func: Callable[[OpenAI], ChatCompletionStreamManager[ResponseFormatT]], + *, + content_snapshot: Any, + respx_mock: MockRouter, + mock_client: OpenAI, + on_event: Callable[[ChatCompletionStream[ResponseFormatT], ChatCompletionStreamEvent[ResponseFormatT]], Any] + | None = None, +) -> StreamListener[ResponseFormatT]: + live = os.environ.get("OPENAI_LIVE") == "1" + if live: + + def _on_response(response: httpx.Response) -> None: + # update the content snapshot + assert outsource(response.read()) == content_snapshot + + respx_mock.stop() + + client = OpenAI( + http_client=httpx.Client( + event_hooks={ + "response": [_on_response], + } + ) + ) + else: + respx_mock.post("/chat/completions").mock( + return_value=httpx.Response( + 200, + content=content_snapshot._old_value._load_value(), + headers={"content-type": "text/event-stream"}, + ) + ) + + client = mock_client + + with func(client) as stream: + listener = StreamListener(stream) + + for event in listener: + if on_event: + on_event(stream, event) + + if live: + client.close() + + return listener diff --git a/tests/lib/schema_types/query.py b/tests/lib/schema_types/query.py new file mode 100644 index 0000000000..d2284424f0 --- /dev/null +++ b/tests/lib/schema_types/query.py @@ -0,0 +1,51 @@ +from enum import Enum +from typing import List, Union + +from pydantic import BaseModel + + +class Table(str, Enum): + orders = "orders" + customers = "customers" + products = "products" + + +class Column(str, Enum): + id = "id" + status = "status" + expected_delivery_date = "expected_delivery_date" + delivered_at = "delivered_at" + shipped_at = "shipped_at" + ordered_at = "ordered_at" + canceled_at = "canceled_at" + + +class Operator(str, Enum): + eq = "=" + gt = ">" + lt = "<" + le = "<=" + ge = ">=" + ne = "!=" + + +class OrderBy(str, Enum): + asc = "asc" + desc = "desc" + + +class DynamicValue(BaseModel): + column_name: str + + +class Condition(BaseModel): + column: str + operator: Operator + value: Union[str, int, DynamicValue] + + +class Query(BaseModel): + table_name: Table + columns: List[Column] + conditions: List[Condition] + order_by: OrderBy diff --git a/tests/lib/test_pydantic.py b/tests/lib/test_pydantic.py new file mode 100644 index 0000000000..dc09596da2 --- /dev/null +++ b/tests/lib/test_pydantic.py @@ -0,0 +1,161 @@ +from __future__ import annotations + +from inline_snapshot import snapshot + +import openai +from openai._compat import PYDANTIC_V2 + +from .schema_types.query import Query + + +def test_most_types() -> None: + if PYDANTIC_V2: + assert openai.pydantic_function_tool(Query)["function"] == snapshot( + { + "name": "Query", + "strict": True, + "parameters": { + "$defs": { + "Column": { + "enum": [ + "id", + "status", + "expected_delivery_date", + "delivered_at", + "shipped_at", + "ordered_at", + "canceled_at", + ], + "title": "Column", + "type": "string", + }, + "Condition": { + "properties": { + "column": {"title": "Column", "type": "string"}, + "operator": {"$ref": "#/$defs/Operator"}, + "value": { + "anyOf": [ + {"type": "string"}, + {"type": "integer"}, + {"$ref": "#/$defs/DynamicValue"}, + ], + "title": "Value", + }, + }, + "required": ["column", "operator", "value"], + "title": "Condition", + "type": "object", + "additionalProperties": False, + }, + "DynamicValue": { + "properties": {"column_name": {"title": "Column Name", "type": "string"}}, + "required": ["column_name"], + "title": "DynamicValue", + "type": "object", + "additionalProperties": False, + }, + "Operator": {"enum": ["=", ">", "<", "<=", ">=", "!="], "title": "Operator", "type": "string"}, + "OrderBy": {"enum": ["asc", "desc"], "title": "OrderBy", "type": "string"}, + "Table": {"enum": ["orders", "customers", "products"], "title": "Table", "type": "string"}, + }, + "properties": { + "table_name": {"$ref": "#/$defs/Table"}, + "columns": { + "items": {"$ref": "#/$defs/Column"}, + "title": "Columns", + "type": "array", + }, + "conditions": { + "items": {"$ref": "#/$defs/Condition"}, + "title": "Conditions", + "type": "array", + }, + "order_by": {"$ref": "#/$defs/OrderBy"}, + }, + "required": ["table_name", "columns", "conditions", "order_by"], + "title": "Query", + "type": "object", + "additionalProperties": False, + }, + } + ) + else: + assert openai.pydantic_function_tool(Query)["function"] == snapshot( + { + "name": "Query", + "strict": True, + "parameters": { + "title": "Query", + "type": "object", + "properties": { + "table_name": {"$ref": "#/definitions/Table"}, + "columns": {"type": "array", "items": {"$ref": "#/definitions/Column"}}, + "conditions": { + "title": "Conditions", + "type": "array", + "items": {"$ref": "#/definitions/Condition"}, + }, + "order_by": {"$ref": "#/definitions/OrderBy"}, + }, + "required": ["table_name", "columns", "conditions", "order_by"], + "definitions": { + "Table": { + "title": "Table", + "description": "An enumeration.", + "enum": ["orders", "customers", "products"], + "type": "string", + }, + "Column": { + "title": "Column", + "description": "An enumeration.", + "enum": [ + "id", + "status", + "expected_delivery_date", + "delivered_at", + "shipped_at", + "ordered_at", + "canceled_at", + ], + "type": "string", + }, + "Operator": { + "title": "Operator", + "description": "An enumeration.", + "enum": ["=", ">", "<", "<=", ">=", "!="], + "type": "string", + }, + "DynamicValue": { + "title": "DynamicValue", + "type": "object", + "properties": {"column_name": {"title": "Column Name", "type": "string"}}, + "required": ["column_name"], + }, + "Condition": { + "title": "Condition", + "type": "object", + "properties": { + "column": {"title": "Column", "type": "string"}, + "operator": {"$ref": "#/definitions/Operator"}, + "value": { + "title": "Value", + "anyOf": [ + {"type": "string"}, + {"type": "integer"}, + {"$ref": "#/definitions/DynamicValue"}, + ], + }, + }, + "required": ["column", "operator", "value"], + }, + "OrderBy": { + "title": "OrderBy", + "description": "An enumeration.", + "enum": ["asc", "desc"], + "type": "string", + }, + }, + "additionalProperties": False, + }, + } + ) diff --git a/tests/test_client.py b/tests/test_client.py index 2402ffa82f..054ae0ff4e 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -780,11 +780,11 @@ def retry_handler(_request: httpx.Request) -> httpx.Response: response = client.chat.completions.with_raw_response.create( messages=[ { - "content": "content", + "content": "string", "role": "system", } ], - model="gpt-4-turbo", + model="gpt-4o", ) assert response.retries_taken == failures_before_success @@ -811,11 +811,11 @@ def retry_handler(_request: httpx.Request) -> httpx.Response: with client.chat.completions.with_streaming_response.create( messages=[ { - "content": "content", + "content": "string", "role": "system", } ], - model="gpt-4-turbo", + model="gpt-4o", ) as response: assert response.retries_taken == failures_before_success @@ -1574,11 +1574,11 @@ def retry_handler(_request: httpx.Request) -> httpx.Response: response = await client.chat.completions.with_raw_response.create( messages=[ { - "content": "content", + "content": "string", "role": "system", } ], - model="gpt-4-turbo", + model="gpt-4o", ) assert response.retries_taken == failures_before_success @@ -1606,10 +1606,10 @@ def retry_handler(_request: httpx.Request) -> httpx.Response: async with client.chat.completions.with_streaming_response.create( messages=[ { - "content": "content", + "content": "string", "role": "system", } ], - model="gpt-4-turbo", + model="gpt-4o", ) as response: assert response.retries_taken == failures_before_success From 90dd21531efe351b72ce0a72150048b6c7f640e0 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 6 Aug 2024 17:11:59 +0000 Subject: [PATCH 447/816] release: 1.40.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 14 ++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 17 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 4d14a67e1c..0c37ae42ca 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.39.0" + ".": "1.40.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index b9cc30e307..2454a9a6cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,19 @@ # Changelog +## 1.40.0 (2024-08-06) + +Full Changelog: [v1.39.0...v1.40.0](https://github.com/openai/openai-python/compare/v1.39.0...v1.40.0) + +### Features + +* **api:** add structured outputs support ([e8dba7d](https://github.com/openai/openai-python/commit/e8dba7d0e08a7d0de5952be716e0efe9ae373759)) + + +### Chores + +* **internal:** bump ruff version ([#1604](https://github.com/openai/openai-python/issues/1604)) ([3e19a87](https://github.com/openai/openai-python/commit/3e19a87255d8e92716689656afaa3f16297773b6)) +* **internal:** update pydantic compat helper function ([#1607](https://github.com/openai/openai-python/issues/1607)) ([973c18b](https://github.com/openai/openai-python/commit/973c18b259a0e4a8134223f50a5f660b86650949)) + ## 1.39.0 (2024-08-05) Full Changelog: [v1.38.0...v1.39.0](https://github.com/openai/openai-python/compare/v1.38.0...v1.39.0) diff --git a/pyproject.toml b/pyproject.toml index cb02edac0c..1e86c44706 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.39.0" +version = "1.40.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index aed8ee29b2..73cd42e5ea 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.39.0" # x-release-please-version +__version__ = "1.40.0" # x-release-please-version From ad56fd14d25e0a704c5f958ab273a241f0548f26 Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Tue, 6 Aug 2024 17:33:36 +0000 Subject: [PATCH 448/816] chore(internal): update OpenAPI spec url (#1608) --- .stats.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index da26758316..ac652c9271 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-c36d30a94622922f83d56a025cdf0095ff7cb18a5138838c698c8443f21fb3a8.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-4097c2f86beb3f3bb021775cd1dfa240e960caf842aeefc2e08da4dc0851ea79.yml From 09eba2099734eea49dc7606d48e2f968a036514d Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Wed, 7 Aug 2024 11:01:31 +0100 Subject: [PATCH 449/816] chore(internal): update test snapshots --- ...661f4f5bea321c0aac9e164f2ed3e409aebc48.bin | 102 +++++++ ...2625e557f9e6763bd8c03bcd88e220149a3367.bin | 224 ++++++++++++++++ ...cf4aa41fc428937c231e17c3460f3237f6a018.bin | 28 ++ ...9cda31e5a0af80decdbddd21c056545c6d4616.bin | 100 ------- ...6aea6d0356b63140161758a2e576d4e3092cfa.bin | 36 +++ ...fd3deafe041da94d541071009596234d8c84a6.bin | 36 +++ ...8ab9141d709b770a74dc025fb8770a42aabee9.bin | 180 ------------- ...3dfcc25dc2f57a5e05eb5cc46c70b51d8845c2.bin | 52 ++++ ...f7868df0b6d8a02dfcd23f6bc7196cf0eadb6e.bin | 28 ++ ...f0afcd22d4f0e85418ab38ee24d2a570a84ff0.bin | 10 + ...c4861e696495d9a45c19be02cf479e28c31316.bin | 12 - ...ec5f581ea9de2524599f06b0d405db8997b826.bin | 8 - ...9d46ee41408a688758219f3f58ac1ee2084db3.bin | 28 ++ ...5dfafc1d712c253b42bafe07991b3058541016.bin | 156 +++++++++++ ...0e08ddfad221d6632fdb200a95ca6c996238e2.bin | 52 ---- ...4b7ca16b9fadc5c4551ea066d305eb1607e1c6.bin | 28 -- ...abc40785d712248f65c8595c99879080d0eeb9.bin | 36 --- ...5521e0258cc2cef0528a17fbdadb9cc76695f0.bin | 72 ----- ...613bdb9c4a2ad8262027d158cc94e6f9765164.bin | 12 + ...f8694b77f608de5e2a3799276be06ce3fbb15b.bin | 30 +++ ...f05bd963fe093622e5bf9a95a3ebede64714bc.bin | 30 --- ...194b58fc759adc3685170e0a61033241d2eda5.bin | 32 --- ...81772c3010c10b37e8af3996fbdbbecb3c32a2.bin | 22 ++ ...ca00f3a963d785c6fe78c35d60d038cd7a8ba0.bin | 36 --- ...13a82f959a175ec05ce3c07412bbc9fd436234.bin | 22 -- tests/lib/chat/test_completions.py | 84 +++--- tests/lib/chat/test_completions_streaming.py | 251 +++++++++++------- 27 files changed, 961 insertions(+), 746 deletions(-) create mode 100644 .inline-snapshot/external/038a5c69c34c9513021b52aa61661f4f5bea321c0aac9e164f2ed3e409aebc48.bin create mode 100644 .inline-snapshot/external/0898f3d1651e3244eeb3651d012625e557f9e6763bd8c03bcd88e220149a3367.bin create mode 100644 .inline-snapshot/external/0a00cd46c61030ff70241d432dcf4aa41fc428937c231e17c3460f3237f6a018.bin delete mode 100644 .inline-snapshot/external/1437bd06a9d5c414e56fd0840b9cda31e5a0af80decdbddd21c056545c6d4616.bin create mode 100644 .inline-snapshot/external/15ae68f793c7b390fc8af9e21a6aea6d0356b63140161758a2e576d4e3092cfa.bin create mode 100644 .inline-snapshot/external/24aaf30663f9a568a0e77970b4fd3deafe041da94d541071009596234d8c84a6.bin delete mode 100644 .inline-snapshot/external/3e0df46f250db854eacb34e3258ab9141d709b770a74dc025fb8770a42aabee9.bin create mode 100644 .inline-snapshot/external/453df473e96274dd8ab61ab4d13dfcc25dc2f57a5e05eb5cc46c70b51d8845c2.bin create mode 100644 .inline-snapshot/external/4d75e4d7c3e0b532a67fb2114ff7868df0b6d8a02dfcd23f6bc7196cf0eadb6e.bin create mode 100644 .inline-snapshot/external/69363a555f8ea9b6eee0bb022af0afcd22d4f0e85418ab38ee24d2a570a84ff0.bin delete mode 100644 .inline-snapshot/external/70c7df71ce729e178fc5e54f0cc4861e696495d9a45c19be02cf479e28c31316.bin delete mode 100644 .inline-snapshot/external/7ae6c1a2631bf7444b8f70b592ec5f581ea9de2524599f06b0d405db8997b826.bin create mode 100644 .inline-snapshot/external/83d3d003e6fdaa69b7a398440f9d46ee41408a688758219f3f58ac1ee2084db3.bin create mode 100644 .inline-snapshot/external/a0c4f0be184e8234cdc0e3abae5dfafc1d712c253b42bafe07991b3058541016.bin delete mode 100644 .inline-snapshot/external/a346213bec7a572810bd1ffe290e08ddfad221d6632fdb200a95ca6c996238e2.bin delete mode 100644 .inline-snapshot/external/a7097cae6a1f8dea453977a1784b7ca16b9fadc5c4551ea066d305eb1607e1c6.bin delete mode 100644 .inline-snapshot/external/ae070a447e1ded1ad4819f7608abc40785d712248f65c8595c99879080d0eeb9.bin delete mode 100644 .inline-snapshot/external/b9d6bee9f9b8ee5bdea06cd6955521e0258cc2cef0528a17fbdadb9cc76695f0.bin create mode 100644 .inline-snapshot/external/be1089999ca5f1e63b149447f1613bdb9c4a2ad8262027d158cc94e6f9765164.bin create mode 100644 .inline-snapshot/external/ca015b8b1ebaac98be76f2f855f8694b77f608de5e2a3799276be06ce3fbb15b.bin delete mode 100644 .inline-snapshot/external/cb77dc69b6c8289a6f1e88fa24f05bd963fe093622e5bf9a95a3ebede64714bc.bin delete mode 100644 .inline-snapshot/external/d79326933c1586e731a8235998194b58fc759adc3685170e0a61033241d2eda5.bin create mode 100644 .inline-snapshot/external/dae1b261f19722801adc82a13181772c3010c10b37e8af3996fbdbbecb3c32a2.bin delete mode 100644 .inline-snapshot/external/ea9a417d533b9adfece02608f2ca00f3a963d785c6fe78c35d60d038cd7a8ba0.bin delete mode 100644 .inline-snapshot/external/fb75060ede89cac360ce8baf1513a82f959a175ec05ce3c07412bbc9fd436234.bin diff --git a/.inline-snapshot/external/038a5c69c34c9513021b52aa61661f4f5bea321c0aac9e164f2ed3e409aebc48.bin b/.inline-snapshot/external/038a5c69c34c9513021b52aa61661f4f5bea321c0aac9e164f2ed3e409aebc48.bin new file mode 100644 index 0000000000..a5a0aeb4c0 --- /dev/null +++ b/.inline-snapshot/external/038a5c69c34c9513021b52aa61661f4f5bea321c0aac9e164f2ed3e409aebc48.bin @@ -0,0 +1,102 @@ +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"I'm"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" unable"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" to"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" provide"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" real"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"-time"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" updates"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":","},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" including"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" current"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" information"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" For"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" the"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" latest"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" in"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" San"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":","},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" I"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" recommend"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" checking"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" a"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" reliable"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" website"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" or"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" app"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" such"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" as"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" the"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" Weather"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" Channel"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":","},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" BBC"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" Weather"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":","},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" or"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" a"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" local"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" San"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" news"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" station"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":47,"total_tokens":61}} + +data: [DONE] + diff --git a/.inline-snapshot/external/0898f3d1651e3244eeb3651d012625e557f9e6763bd8c03bcd88e220149a3367.bin b/.inline-snapshot/external/0898f3d1651e3244eeb3651d012625e557f9e6763bd8c03bcd88e220149a3367.bin new file mode 100644 index 0000000000..4b42ada8d2 --- /dev/null +++ b/.inline-snapshot/external/0898f3d1651e3244eeb3651d012625e557f9e6763bd8c03bcd88e220149a3367.bin @@ -0,0 +1,224 @@ +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" {\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"location"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"San"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":","},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" CA"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"forecast"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"_date"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"202"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"3"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"-"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"11"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"-"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"02"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"weather"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" {\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"temperature"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" {\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"current"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"N"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"/A"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"high"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"N"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"/A"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"low"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"N"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"/A"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\"\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" },\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"condition"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"N"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"/A"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"humidity"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"N"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"/A"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"wind"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"_speed"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"N"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"/A"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\"\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" },\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"note"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"Please"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" check"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" a"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" reliable"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" service"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" for"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" the"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" most"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" current"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" information"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":".\"\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" }"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[],"usage":{"prompt_tokens":19,"completion_tokens":108,"total_tokens":127}} + +data: [DONE] + diff --git a/.inline-snapshot/external/0a00cd46c61030ff70241d432dcf4aa41fc428937c231e17c3460f3237f6a018.bin b/.inline-snapshot/external/0a00cd46c61030ff70241d432dcf4aa41fc428937c231e17c3460f3237f6a018.bin new file mode 100644 index 0000000000..73de9d6cbc --- /dev/null +++ b/.inline-snapshot/external/0a00cd46c61030ff70241d432dcf4aa41fc428937c231e17c3460f3237f6a018.bin @@ -0,0 +1,28 @@ +data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"role":"assistant","content":null,"refusal":""},"logprobs":{"content":null,"refusal":[]},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":"I'm"},"logprobs":{"content":null,"refusal":[{"token":"I'm","logprob":-0.0016157961,"bytes":[73,39,109],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" sorry"},"logprobs":{"content":null,"refusal":[{"token":" sorry","logprob":-0.78663874,"bytes":[32,115,111,114,114,121],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":","},"logprobs":{"content":null,"refusal":[{"token":",","logprob":-0.0000779144,"bytes":[44],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" I"},"logprobs":{"content":null,"refusal":[{"token":" I","logprob":-0.5234622,"bytes":[32,73],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" cannot"},"logprobs":{"content":null,"refusal":[{"token":" cannot","logprob":-0.52499557,"bytes":[32,99,97,110,110,111,116],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" assist"},"logprobs":{"content":null,"refusal":[{"token":" assist","logprob":-0.015198289,"bytes":[32,97,115,115,105,115,116],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" with"},"logprobs":{"content":null,"refusal":[{"token":" with","logprob":-0.00071648485,"bytes":[32,119,105,116,104],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" that"},"logprobs":{"content":null,"refusal":[{"token":" that","logprob":-0.008114983,"bytes":[32,116,104,97,116],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" request"},"logprobs":{"content":null,"refusal":[{"token":" request","logprob":-0.0013802331,"bytes":[32,114,101,113,117,101,115,116],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":"."},"logprobs":{"content":null,"refusal":[{"token":".","logprob":-3.4121115e-6,"bytes":[46],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[],"usage":{"prompt_tokens":17,"completion_tokens":11,"total_tokens":28}} + +data: [DONE] + diff --git a/.inline-snapshot/external/1437bd06a9d5c414e56fd0840b9cda31e5a0af80decdbddd21c056545c6d4616.bin b/.inline-snapshot/external/1437bd06a9d5c414e56fd0840b9cda31e5a0af80decdbddd21c056545c6d4616.bin deleted file mode 100644 index f96745e385..0000000000 --- a/.inline-snapshot/external/1437bd06a9d5c414e56fd0840b9cda31e5a0af80decdbddd21c056545c6d4616.bin +++ /dev/null @@ -1,100 +0,0 @@ -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"{\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":"{\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":"{\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"city"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":"city"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":"city"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"San"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":"San"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":"San"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\",\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":"\",\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":"\",\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"temperature"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":"temperature"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":"temperature"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"64"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":",\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":"68"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":",\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":"64"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":",\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"units"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":"units"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":"units"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"f"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":"f"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":"f"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\"}"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{"content":"\"}"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{"content":"\"}"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":1,"delta":{},"logprobs":null,"finish_reason":"stop"}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":2,"delta":{},"logprobs":null,"finish_reason":"stop"}]} - -data: {"id":"chatcmpl-9tAC53I4IJcmm22h7tLip6Irb7b6D","object":"chat.completion.chunk","created":1722934253,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[],"usage":{"prompt_tokens":17,"completion_tokens":42,"total_tokens":59}} - -data: [DONE] - diff --git a/.inline-snapshot/external/15ae68f793c7b390fc8af9e21a6aea6d0356b63140161758a2e576d4e3092cfa.bin b/.inline-snapshot/external/15ae68f793c7b390fc8af9e21a6aea6d0356b63140161758a2e576d4e3092cfa.bin new file mode 100644 index 0000000000..1bcca1fceb --- /dev/null +++ b/.inline-snapshot/external/15ae68f793c7b390fc8af9e21a6aea6d0356b63140161758a2e576d4e3092cfa.bin @@ -0,0 +1,36 @@ +data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"{\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"city"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"San"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\",\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"temperature"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"68"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":",\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"units"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"f"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\"}"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[],"usage":{"prompt_tokens":17,"completion_tokens":14,"total_tokens":31}} + +data: [DONE] + diff --git a/.inline-snapshot/external/24aaf30663f9a568a0e77970b4fd3deafe041da94d541071009596234d8c84a6.bin b/.inline-snapshot/external/24aaf30663f9a568a0e77970b4fd3deafe041da94d541071009596234d8c84a6.bin new file mode 100644 index 0000000000..49962cff27 --- /dev/null +++ b/.inline-snapshot/external/24aaf30663f9a568a0e77970b4fd3deafe041da94d541071009596234d8c84a6.bin @@ -0,0 +1,36 @@ +data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"role":"assistant","content":null,"tool_calls":[{"index":0,"id":"call_7PhhveOvvpPK53s1fV8TWhoV","type":"function","function":{"name":"GetWeatherArgs","arguments":""}}],"refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"city"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"Ed"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"inburgh"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\",\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"country"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"GB"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\",\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"units"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"c"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"}"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"tool_calls"}]} + +data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[],"usage":{"prompt_tokens":76,"completion_tokens":24,"total_tokens":100}} + +data: [DONE] + diff --git a/.inline-snapshot/external/3e0df46f250db854eacb34e3258ab9141d709b770a74dc025fb8770a42aabee9.bin b/.inline-snapshot/external/3e0df46f250db854eacb34e3258ab9141d709b770a74dc025fb8770a42aabee9.bin deleted file mode 100644 index eb1cf9e733..0000000000 --- a/.inline-snapshot/external/3e0df46f250db854eacb34e3258ab9141d709b770a74dc025fb8770a42aabee9.bin +++ /dev/null @@ -1,180 +0,0 @@ -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"{\n"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"location"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"San"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":","},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" CA"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"temperature"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"N"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"/A"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"conditions"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"N"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"/A"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"humidity"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"N"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"/A"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"wind"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"_speed"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"N"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"/A"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"timestamp"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"N"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"/A"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"note"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"Real"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"-time"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" data"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" is"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" not"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" available"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" Please"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" check"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" a"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" reliable"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" service"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" for"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" the"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" most"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" up"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"-to"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"-date"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" information"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" on"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" San"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"'s"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" conditions"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":".\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"}"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} - -data: {"id":"chatcmpl-9tACAVV5BLjrmHwZhSABB78qPvLg2","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[],"usage":{"prompt_tokens":19,"completion_tokens":86,"total_tokens":105}} - -data: [DONE] - diff --git a/.inline-snapshot/external/453df473e96274dd8ab61ab4d13dfcc25dc2f57a5e05eb5cc46c70b51d8845c2.bin b/.inline-snapshot/external/453df473e96274dd8ab61ab4d13dfcc25dc2f57a5e05eb5cc46c70b51d8845c2.bin new file mode 100644 index 0000000000..adcdddd317 --- /dev/null +++ b/.inline-snapshot/external/453df473e96274dd8ab61ab4d13dfcc25dc2f57a5e05eb5cc46c70b51d8845c2.bin @@ -0,0 +1,52 @@ +data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"role":"assistant","content":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_lQnnsesjFMWMQ5IeWPHzR4th","type":"function","function":{"name":"GetWeatherArgs","arguments":""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"ci"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"ty\": "}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"Edinb"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"urgh"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\", \"c"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"ountry"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\": \""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"UK\", "}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"units"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\": \""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"c\"}"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"id":"call_2xjOUgaCdiwAcl9ZBL9LyMUU","type":"function","function":{"name":"get_stock_price","arguments":""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"{\"ti"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"cker\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":": \"AAP"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"L\", "}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"\"exch"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"ange\":"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":" \"NA"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"SDAQ\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"}"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"tool_calls"}]} + +data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[],"usage":{"prompt_tokens":149,"completion_tokens":60,"total_tokens":209}} + +data: [DONE] + diff --git a/.inline-snapshot/external/4d75e4d7c3e0b532a67fb2114ff7868df0b6d8a02dfcd23f6bc7196cf0eadb6e.bin b/.inline-snapshot/external/4d75e4d7c3e0b532a67fb2114ff7868df0b6d8a02dfcd23f6bc7196cf0eadb6e.bin new file mode 100644 index 0000000000..008d5882ec --- /dev/null +++ b/.inline-snapshot/external/4d75e4d7c3e0b532a67fb2114ff7868df0b6d8a02dfcd23f6bc7196cf0eadb6e.bin @@ -0,0 +1,28 @@ +data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"role":"assistant","content":null,"refusal":""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":"I'm"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" sorry"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":","},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" I"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" cannot"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" assist"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" with"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" that"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" request"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":"."},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[],"usage":{"prompt_tokens":17,"completion_tokens":11,"total_tokens":28}} + +data: [DONE] + diff --git a/.inline-snapshot/external/69363a555f8ea9b6eee0bb022af0afcd22d4f0e85418ab38ee24d2a570a84ff0.bin b/.inline-snapshot/external/69363a555f8ea9b6eee0bb022af0afcd22d4f0e85418ab38ee24d2a570a84ff0.bin new file mode 100644 index 0000000000..852a7758f9 --- /dev/null +++ b/.inline-snapshot/external/69363a555f8ea9b6eee0bb022af0afcd22d4f0e85418ab38ee24d2a570a84ff0.bin @@ -0,0 +1,10 @@ +data: {"id":"chatcmpl-9tXjkSxyTVUSWZRJFSZJgWBHzh2c3","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjkSxyTVUSWZRJFSZJgWBHzh2c3","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"{\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjkSxyTVUSWZRJFSZJgWBHzh2c3","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"length"}]} + +data: {"id":"chatcmpl-9tXjkSxyTVUSWZRJFSZJgWBHzh2c3","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[],"usage":{"prompt_tokens":17,"completion_tokens":1,"total_tokens":18}} + +data: [DONE] + diff --git a/.inline-snapshot/external/70c7df71ce729e178fc5e54f0cc4861e696495d9a45c19be02cf479e28c31316.bin b/.inline-snapshot/external/70c7df71ce729e178fc5e54f0cc4861e696495d9a45c19be02cf479e28c31316.bin deleted file mode 100644 index 21c41d3958..0000000000 --- a/.inline-snapshot/external/70c7df71ce729e178fc5e54f0cc4861e696495d9a45c19be02cf479e28c31316.bin +++ /dev/null @@ -1,12 +0,0 @@ -data: {"id":"chatcmpl-9tDU7wVJ0lzoNjC1aNIjnP99zMW2C","object":"chat.completion.chunk","created":1722946903,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":{"content":[],"refusal":null},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tDU7wVJ0lzoNjC1aNIjnP99zMW2C","object":"chat.completion.chunk","created":1722946903,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"Foo"},"logprobs":{"content":[{"token":"Foo","logprob":-0.006764991,"bytes":[70,111,111],"top_logprobs":[]}],"refusal":null},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tDU7wVJ0lzoNjC1aNIjnP99zMW2C","object":"chat.completion.chunk","created":1722946903,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"!"},"logprobs":{"content":[{"token":"!","logprob":-0.31380808,"bytes":[33],"top_logprobs":[]}],"refusal":null},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tDU7wVJ0lzoNjC1aNIjnP99zMW2C","object":"chat.completion.chunk","created":1722946903,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} - -data: {"id":"chatcmpl-9tDU7wVJ0lzoNjC1aNIjnP99zMW2C","object":"chat.completion.chunk","created":1722946903,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[],"usage":{"prompt_tokens":9,"completion_tokens":2,"total_tokens":11}} - -data: [DONE] - diff --git a/.inline-snapshot/external/7ae6c1a2631bf7444b8f70b592ec5f581ea9de2524599f06b0d405db8997b826.bin b/.inline-snapshot/external/7ae6c1a2631bf7444b8f70b592ec5f581ea9de2524599f06b0d405db8997b826.bin deleted file mode 100644 index d261ccd0d0..0000000000 --- a/.inline-snapshot/external/7ae6c1a2631bf7444b8f70b592ec5f581ea9de2524599f06b0d405db8997b826.bin +++ /dev/null @@ -1,8 +0,0 @@ -data: {"id":"chatcmpl-9tAC6v0rUCOp8tty9cizBsGmRcVIx","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"role":"assistant","content":null,"refusal":""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC6v0rUCOp8tty9cizBsGmRcVIx","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"length"}]} - -data: {"id":"chatcmpl-9tAC6v0rUCOp8tty9cizBsGmRcVIx","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[],"usage":{"prompt_tokens":17,"completion_tokens":1,"total_tokens":18}} - -data: [DONE] - diff --git a/.inline-snapshot/external/83d3d003e6fdaa69b7a398440f9d46ee41408a688758219f3f58ac1ee2084db3.bin b/.inline-snapshot/external/83d3d003e6fdaa69b7a398440f9d46ee41408a688758219f3f58ac1ee2084db3.bin new file mode 100644 index 0000000000..05e08e3475 --- /dev/null +++ b/.inline-snapshot/external/83d3d003e6fdaa69b7a398440f9d46ee41408a688758219f3f58ac1ee2084db3.bin @@ -0,0 +1,28 @@ +data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[{"index":0,"delta":{"role":"assistant","content":null,"tool_calls":[{"index":0,"id":"call_pVHYsU0gmSfX5TqxOyVbB2ma","type":"function","function":{"name":"get_weather","arguments":""}}],"refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"city"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"San"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":" Francisco"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\",\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"state"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"CA"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"}"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"tool_calls"}]} + +data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[],"usage":{"prompt_tokens":48,"completion_tokens":19,"total_tokens":67}} + +data: [DONE] + diff --git a/.inline-snapshot/external/a0c4f0be184e8234cdc0e3abae5dfafc1d712c253b42bafe07991b3058541016.bin b/.inline-snapshot/external/a0c4f0be184e8234cdc0e3abae5dfafc1d712c253b42bafe07991b3058541016.bin new file mode 100644 index 0000000000..df20d6fda5 --- /dev/null +++ b/.inline-snapshot/external/a0c4f0be184e8234cdc0e3abae5dfafc1d712c253b42bafe07991b3058541016.bin @@ -0,0 +1,156 @@ +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":"{\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"{\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":"city"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"city"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"role":"assistant","content":null,"refusal":""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":"I'm"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" sorry"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":"San"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"San"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":","},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" but"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":"\",\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"\",\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" I"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" can't"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":"temperature"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"temperature"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" accurately"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" provide"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":"63"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":",\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"58"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"."},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" the"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":"units"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"6"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" current"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":",\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" weather"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":"f"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"units"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" for"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":"\"}"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" San"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"f"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" Francisco"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"\"}"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" as"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" my"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" data"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" is"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" up"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" to"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" October"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":"202"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":"3"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":"."},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" You"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" can"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" try"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" checking"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" a"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" reliable"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" weather"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" website"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" or"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" app"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" for"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" real"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":"-time"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" updates"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":"."},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[],"usage":{"prompt_tokens":17,"completion_tokens":71,"total_tokens":88}} + +data: [DONE] + diff --git a/.inline-snapshot/external/a346213bec7a572810bd1ffe290e08ddfad221d6632fdb200a95ca6c996238e2.bin b/.inline-snapshot/external/a346213bec7a572810bd1ffe290e08ddfad221d6632fdb200a95ca6c996238e2.bin deleted file mode 100644 index 2ceced2f1c..0000000000 --- a/.inline-snapshot/external/a346213bec7a572810bd1ffe290e08ddfad221d6632fdb200a95ca6c996238e2.bin +++ /dev/null @@ -1,52 +0,0 @@ -data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"role":"assistant","content":null},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_g4Q1vRbE0CaHGOs5if8mHsBq","type":"function","function":{"name":"GetWeatherArgs","arguments":""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"ci"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"ty\": "}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"Edinb"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"urgh"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\", \"c"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"ountry"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\": \""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"UK\", "}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"units"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\": \""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"c\"}"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"id":"call_gWj3HQxZEHnFvyJLEHIiJKBV","type":"function","function":{"name":"get_stock_price","arguments":""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"{\"ti"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"cker\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":": \"AAP"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"L\", "}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"\"exch"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"ange\":"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":" \"NA"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"SDAQ\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"}"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"tool_calls"}]} - -data: {"id":"chatcmpl-9tAC9cJXpJZ5tGpOa9thAumwSCcmm","object":"chat.completion.chunk","created":1722934257,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[],"usage":{"prompt_tokens":149,"completion_tokens":60,"total_tokens":209}} - -data: [DONE] - diff --git a/.inline-snapshot/external/a7097cae6a1f8dea453977a1784b7ca16b9fadc5c4551ea066d305eb1607e1c6.bin b/.inline-snapshot/external/a7097cae6a1f8dea453977a1784b7ca16b9fadc5c4551ea066d305eb1607e1c6.bin deleted file mode 100644 index de0efe6bab..0000000000 --- a/.inline-snapshot/external/a7097cae6a1f8dea453977a1784b7ca16b9fadc5c4551ea066d305eb1607e1c6.bin +++ /dev/null @@ -1,28 +0,0 @@ -data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"role":"assistant","content":null,"tool_calls":[{"index":0,"id":"call_rQe3kzGnTr2epjx8HREg3F2a","type":"function","function":{"name":"get_weather","arguments":""}}],"refusal":null},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"city"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"San"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":" Francisco"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\",\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"state"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"CA"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"}"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"tool_calls"}]} - -data: {"id":"chatcmpl-9tACAMQt1guB31uPOzbyivps8944W","object":"chat.completion.chunk","created":1722934258,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[],"usage":{"prompt_tokens":48,"completion_tokens":19,"total_tokens":67}} - -data: [DONE] - diff --git a/.inline-snapshot/external/ae070a447e1ded1ad4819f7608abc40785d712248f65c8595c99879080d0eeb9.bin b/.inline-snapshot/external/ae070a447e1ded1ad4819f7608abc40785d712248f65c8595c99879080d0eeb9.bin deleted file mode 100644 index af003a8120..0000000000 --- a/.inline-snapshot/external/ae070a447e1ded1ad4819f7608abc40785d712248f65c8595c99879080d0eeb9.bin +++ /dev/null @@ -1,36 +0,0 @@ -data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"role":"assistant","content":null,"tool_calls":[{"index":0,"id":"call_Vz6ZXciy6Y0PYfT4d9W7fYB4","type":"function","function":{"name":"GetWeatherArgs","arguments":""}}],"refusal":null},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"city"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"Ed"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"inburgh"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\",\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"country"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"UK"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\",\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"units"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"c"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"}"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"tool_calls"}]} - -data: {"id":"chatcmpl-9tAC85ZjzRlx3OkdUgSGiR9aBLyL8","object":"chat.completion.chunk","created":1722934256,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[],"usage":{"prompt_tokens":76,"completion_tokens":24,"total_tokens":100}} - -data: [DONE] - diff --git a/.inline-snapshot/external/b9d6bee9f9b8ee5bdea06cd6955521e0258cc2cef0528a17fbdadb9cc76695f0.bin b/.inline-snapshot/external/b9d6bee9f9b8ee5bdea06cd6955521e0258cc2cef0528a17fbdadb9cc76695f0.bin deleted file mode 100644 index b4337f886a..0000000000 --- a/.inline-snapshot/external/b9d6bee9f9b8ee5bdea06cd6955521e0258cc2cef0528a17fbdadb9cc76695f0.bin +++ /dev/null @@ -1,72 +0,0 @@ -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"I'm"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" unable"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" to"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" provide"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" real"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"-time"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" updates"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" To"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" get"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" the"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" latest"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" information"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" for"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" San"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":","},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" I"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" recommend"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" checking"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" a"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" reliable"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" website"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" or"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" using"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" a"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" app"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} - -data: {"id":"chatcmpl-9tAC1e8N6ADc0gjWIhrsjjo4gddxQ","object":"chat.completion.chunk","created":1722934249,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":32,"total_tokens":46}} - -data: [DONE] - diff --git a/.inline-snapshot/external/be1089999ca5f1e63b149447f1613bdb9c4a2ad8262027d158cc94e6f9765164.bin b/.inline-snapshot/external/be1089999ca5f1e63b149447f1613bdb9c4a2ad8262027d158cc94e6f9765164.bin new file mode 100644 index 0000000000..f2a8158310 --- /dev/null +++ b/.inline-snapshot/external/be1089999ca5f1e63b149447f1613bdb9c4a2ad8262027d158cc94e6f9765164.bin @@ -0,0 +1,12 @@ +data: {"id":"chatcmpl-9tXjliCPGY1wrAHNJ4DBnWJxKYyuf","object":"chat.completion.chunk","created":1723024753,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":{"content":[],"refusal":null},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjliCPGY1wrAHNJ4DBnWJxKYyuf","object":"chat.completion.chunk","created":1723024753,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"Foo"},"logprobs":{"content":[{"token":"Foo","logprob":-0.0067602484,"bytes":[70,111,111],"top_logprobs":[]}],"refusal":null},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjliCPGY1wrAHNJ4DBnWJxKYyuf","object":"chat.completion.chunk","created":1723024753,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"."},"logprobs":{"content":[{"token":".","logprob":-2.4962392,"bytes":[46],"top_logprobs":[]}],"refusal":null},"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjliCPGY1wrAHNJ4DBnWJxKYyuf","object":"chat.completion.chunk","created":1723024753,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-9tXjliCPGY1wrAHNJ4DBnWJxKYyuf","object":"chat.completion.chunk","created":1723024753,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[],"usage":{"prompt_tokens":9,"completion_tokens":2,"total_tokens":11}} + +data: [DONE] + diff --git a/.inline-snapshot/external/ca015b8b1ebaac98be76f2f855f8694b77f608de5e2a3799276be06ce3fbb15b.bin b/.inline-snapshot/external/ca015b8b1ebaac98be76f2f855f8694b77f608de5e2a3799276be06ce3fbb15b.bin new file mode 100644 index 0000000000..c0a355f9d1 --- /dev/null +++ b/.inline-snapshot/external/ca015b8b1ebaac98be76f2f855f8694b77f608de5e2a3799276be06ce3fbb15b.bin @@ -0,0 +1,30 @@ +data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"role":"assistant","content":null,"refusal":""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":"I'm"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" sorry"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":","},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" but"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" I"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" can't"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" assist"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" with"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" that"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" request"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":"."},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[],"usage":{"prompt_tokens":17,"completion_tokens":12,"total_tokens":29}} + +data: [DONE] + diff --git a/.inline-snapshot/external/cb77dc69b6c8289a6f1e88fa24f05bd963fe093622e5bf9a95a3ebede64714bc.bin b/.inline-snapshot/external/cb77dc69b6c8289a6f1e88fa24f05bd963fe093622e5bf9a95a3ebede64714bc.bin deleted file mode 100644 index a95f28a54b..0000000000 --- a/.inline-snapshot/external/cb77dc69b6c8289a6f1e88fa24f05bd963fe093622e5bf9a95a3ebede64714bc.bin +++ /dev/null @@ -1,30 +0,0 @@ -data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"role":"assistant","content":null,"refusal":""},"logprobs":{"content":null,"refusal":[]},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":"I'm"},"logprobs":{"content":null,"refusal":[{"token":"I'm","logprob":-0.0010472201,"bytes":[73,39,109],"top_logprobs":[]}]},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" very"},"logprobs":{"content":null,"refusal":[{"token":" very","logprob":-0.7292482,"bytes":[32,118,101,114,121],"top_logprobs":[]}]},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" sorry"},"logprobs":{"content":null,"refusal":[{"token":" sorry","logprob":-5.080963e-6,"bytes":[32,115,111,114,114,121],"top_logprobs":[]}]},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":","},"logprobs":{"content":null,"refusal":[{"token":",","logprob":-0.00004048445,"bytes":[44],"top_logprobs":[]}]},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" but"},"logprobs":{"content":null,"refusal":[{"token":" but","logprob":-0.038046427,"bytes":[32,98,117,116],"top_logprobs":[]}]},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" I"},"logprobs":{"content":null,"refusal":[{"token":" I","logprob":-0.0019351852,"bytes":[32,73],"top_logprobs":[]}]},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" can't"},"logprobs":{"content":null,"refusal":[{"token":" can't","logprob":-0.008995773,"bytes":[32,99,97,110,39,116],"top_logprobs":[]}]},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" assist"},"logprobs":{"content":null,"refusal":[{"token":" assist","logprob":-0.0033510819,"bytes":[32,97,115,115,105,115,116],"top_logprobs":[]}]},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" with"},"logprobs":{"content":null,"refusal":[{"token":" with","logprob":-0.0036033941,"bytes":[32,119,105,116,104],"top_logprobs":[]}]},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" that"},"logprobs":{"content":null,"refusal":[{"token":" that","logprob":-0.0015974608,"bytes":[32,116,104,97,116],"top_logprobs":[]}]},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":"."},"logprobs":{"content":null,"refusal":[{"token":".","logprob":-0.6339823,"bytes":[46],"top_logprobs":[]}]},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} - -data: {"id":"chatcmpl-9tDU0lrTPa5PKPJIVzOxKYl2LTTg4","object":"chat.completion.chunk","created":1722946896,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[],"usage":{"prompt_tokens":17,"completion_tokens":12,"total_tokens":29}} - -data: [DONE] - diff --git a/.inline-snapshot/external/d79326933c1586e731a8235998194b58fc759adc3685170e0a61033241d2eda5.bin b/.inline-snapshot/external/d79326933c1586e731a8235998194b58fc759adc3685170e0a61033241d2eda5.bin deleted file mode 100644 index 895e4828ef..0000000000 --- a/.inline-snapshot/external/d79326933c1586e731a8235998194b58fc759adc3685170e0a61033241d2eda5.bin +++ /dev/null @@ -1,32 +0,0 @@ -data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"role":"assistant","content":null,"refusal":""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":"I'm"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" very"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" sorry"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":","},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" but"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" I"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" can't"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" assist"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" with"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" that"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":" request"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"refusal":"."},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} - -data: {"id":"chatcmpl-9tAC6sKqquyhW1Ql3Jaj6KGNDLGNZ","object":"chat.completion.chunk","created":1722934254,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[],"usage":{"prompt_tokens":17,"completion_tokens":13,"total_tokens":30}} - -data: [DONE] - diff --git a/.inline-snapshot/external/dae1b261f19722801adc82a13181772c3010c10b37e8af3996fbdbbecb3c32a2.bin b/.inline-snapshot/external/dae1b261f19722801adc82a13181772c3010c10b37e8af3996fbdbbecb3c32a2.bin new file mode 100644 index 0000000000..f0911c575d --- /dev/null +++ b/.inline-snapshot/external/dae1b261f19722801adc82a13181772c3010c10b37e8af3996fbdbbecb3c32a2.bin @@ -0,0 +1,22 @@ +data: {"id":"chatcmpl-9tXjtfxZZh2FYaFVxXKf2jiqNDiSo","object":"chat.completion.chunk","created":1723024761,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"role":"assistant","content":null,"tool_calls":[{"index":0,"id":"call_5uxEBMFySqqQGu02I5QHA8k6","type":"function","function":{"name":"get_weather","arguments":""}}],"refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjtfxZZh2FYaFVxXKf2jiqNDiSo","object":"chat.completion.chunk","created":1723024761,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjtfxZZh2FYaFVxXKf2jiqNDiSo","object":"chat.completion.chunk","created":1723024761,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"city"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjtfxZZh2FYaFVxXKf2jiqNDiSo","object":"chat.completion.chunk","created":1723024761,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjtfxZZh2FYaFVxXKf2jiqNDiSo","object":"chat.completion.chunk","created":1723024761,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"New"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjtfxZZh2FYaFVxXKf2jiqNDiSo","object":"chat.completion.chunk","created":1723024761,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":" York"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjtfxZZh2FYaFVxXKf2jiqNDiSo","object":"chat.completion.chunk","created":1723024761,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":" City"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjtfxZZh2FYaFVxXKf2jiqNDiSo","object":"chat.completion.chunk","created":1723024761,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"}"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-9tXjtfxZZh2FYaFVxXKf2jiqNDiSo","object":"chat.completion.chunk","created":1723024761,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"tool_calls"}]} + +data: {"id":"chatcmpl-9tXjtfxZZh2FYaFVxXKf2jiqNDiSo","object":"chat.completion.chunk","created":1723024761,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[],"usage":{"prompt_tokens":44,"completion_tokens":16,"total_tokens":60}} + +data: [DONE] + diff --git a/.inline-snapshot/external/ea9a417d533b9adfece02608f2ca00f3a963d785c6fe78c35d60d038cd7a8ba0.bin b/.inline-snapshot/external/ea9a417d533b9adfece02608f2ca00f3a963d785c6fe78c35d60d038cd7a8ba0.bin deleted file mode 100644 index 869b94de1a..0000000000 --- a/.inline-snapshot/external/ea9a417d533b9adfece02608f2ca00f3a963d785c6fe78c35d60d038cd7a8ba0.bin +++ /dev/null @@ -1,36 +0,0 @@ -data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"{\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"city"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"San"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\",\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"temperature"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"63"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":",\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"units"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"f"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"content":"\"}"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} - -data: {"id":"chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv","object":"chat.completion.chunk","created":1722934250,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[],"usage":{"prompt_tokens":17,"completion_tokens":14,"total_tokens":31}} - -data: [DONE] - diff --git a/.inline-snapshot/external/fb75060ede89cac360ce8baf1513a82f959a175ec05ce3c07412bbc9fd436234.bin b/.inline-snapshot/external/fb75060ede89cac360ce8baf1513a82f959a175ec05ce3c07412bbc9fd436234.bin deleted file mode 100644 index 970b1adf80..0000000000 --- a/.inline-snapshot/external/fb75060ede89cac360ce8baf1513a82f959a175ec05ce3c07412bbc9fd436234.bin +++ /dev/null @@ -1,22 +0,0 @@ -data: {"id":"chatcmpl-9tACC99384oWbk9upfFD1gITJehjE","object":"chat.completion.chunk","created":1722934260,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"role":"assistant","content":null,"tool_calls":[{"index":0,"id":"call_9rqjEc1DQRADTYGVV45LbZwL","type":"function","function":{"name":"get_weather","arguments":""}}],"refusal":null},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACC99384oWbk9upfFD1gITJehjE","object":"chat.completion.chunk","created":1722934260,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACC99384oWbk9upfFD1gITJehjE","object":"chat.completion.chunk","created":1722934260,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"city"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACC99384oWbk9upfFD1gITJehjE","object":"chat.completion.chunk","created":1722934260,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACC99384oWbk9upfFD1gITJehjE","object":"chat.completion.chunk","created":1722934260,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"New"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACC99384oWbk9upfFD1gITJehjE","object":"chat.completion.chunk","created":1722934260,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":" York"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACC99384oWbk9upfFD1gITJehjE","object":"chat.completion.chunk","created":1722934260,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":" City"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACC99384oWbk9upfFD1gITJehjE","object":"chat.completion.chunk","created":1722934260,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"}"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tACC99384oWbk9upfFD1gITJehjE","object":"chat.completion.chunk","created":1722934260,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} - -data: {"id":"chatcmpl-9tACC99384oWbk9upfFD1gITJehjE","object":"chat.completion.chunk","created":1722934260,"model":"gpt-4o-so","system_fingerprint":"fp_e1a05a1dce","choices":[],"usage":{"prompt_tokens":44,"completion_tokens":16,"total_tokens":60}} - -data: [DONE] - diff --git a/tests/lib/chat/test_completions.py b/tests/lib/chat/test_completions.py index db370e4332..e406a5a3bc 100644 --- a/tests/lib/chat/test_completions.py +++ b/tests/lib/chat/test_completions.py @@ -41,7 +41,7 @@ def test_parse_nothing(client: OpenAI, respx_mock: MockRouter, monkeypatch: pyte ], ), content_snapshot=snapshot( - '{"id": "chatcmpl-9tABLlmqdEOYnmmWATUI3dNKlfXa3", "object": "chat.completion", "created": 1722934207, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "I\'m unable to provide real-time weather updates. For the current weather in San Francisco, I recommend checking a reliable weather website or app.", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 14, "completion_tokens": 27, "total_tokens": 41}, "system_fingerprint": "fp_e1a05a1dce"}' + '{"id": "chatcmpl-9tXjSozlYq8oGdlRH3vgLsiUNRg8c", "object": "chat.completion", "created": 1723024734, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "I\'m unable to provide real-time weather updates. To find out the current weather in San Francisco, please check a reliable weather website or app.", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 14, "completion_tokens": 28, "total_tokens": 42}, "system_fingerprint": "fp_845eaabc1f"}' ), mock_client=client, respx_mock=respx_mock, @@ -56,8 +56,8 @@ def test_parse_nothing(client: OpenAI, respx_mock: MockRouter, monkeypatch: pyte index=0, logprobs=None, message=ParsedChatCompletionMessage[NoneType]( - content="I'm unable to provide real-time weather updates. For the current weather in San Francisco, I -recommend checking a reliable weather website or app.", + content="I'm unable to provide real-time weather updates. To find out the current weather in San +Francisco, please check a reliable weather website or app.", function_call=None, parsed=None, refusal=None, @@ -66,13 +66,13 @@ def test_parse_nothing(client: OpenAI, respx_mock: MockRouter, monkeypatch: pyte ) ) ], - created=1722934207, - id='chatcmpl-9tABLlmqdEOYnmmWATUI3dNKlfXa3', + created=1723024734, + id='chatcmpl-9tXjSozlYq8oGdlRH3vgLsiUNRg8c', model='gpt-4o-2024-08-06', object='chat.completion', service_tier=None, - system_fingerprint='fp_e1a05a1dce', - usage=CompletionUsage(completion_tokens=27, prompt_tokens=14, total_tokens=41) + system_fingerprint='fp_845eaabc1f', + usage=CompletionUsage(completion_tokens=28, prompt_tokens=14, total_tokens=42) ) """ ) @@ -97,7 +97,7 @@ class Location(BaseModel): response_format=Location, ), content_snapshot=snapshot( - '{"id": "chatcmpl-9tABUwdw3Kbe3VPRnMofh9lJkFkLV", "object": "chat.completion", "created": 1722934216, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"city\\":\\"San Francisco\\",\\"temperature\\":65,\\"units\\":\\"f\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 17, "completion_tokens": 14, "total_tokens": 31}, "system_fingerprint": "fp_e1a05a1dce"}' + '{"id": "chatcmpl-9tXjTNupyDe7nL1Z8eOO6BdSyrHAD", "object": "chat.completion", "created": 1723024735, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"city\\":\\"San Francisco\\",\\"temperature\\":56,\\"units\\":\\"f\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 17, "completion_tokens": 14, "total_tokens": 31}, "system_fingerprint": "fp_2a322c9ffc"}' ), mock_client=client, respx_mock=respx_mock, @@ -112,21 +112,21 @@ class Location(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( - content='{"city":"San Francisco","temperature":65,"units":"f"}', + content='{"city":"San Francisco","temperature":56,"units":"f"}', function_call=None, - parsed=Location(city='San Francisco', temperature=65.0, units='f'), + parsed=Location(city='San Francisco', temperature=56.0, units='f'), refusal=None, role='assistant', tool_calls=[] ) ) ], - created=1722934216, - id='chatcmpl-9tABUwdw3Kbe3VPRnMofh9lJkFkLV', + created=1723024735, + id='chatcmpl-9tXjTNupyDe7nL1Z8eOO6BdSyrHAD', model='gpt-4o-2024-08-06', object='chat.completion', service_tier=None, - system_fingerprint='fp_e1a05a1dce', + system_fingerprint='fp_2a322c9ffc', usage=CompletionUsage(completion_tokens=14, prompt_tokens=17, total_tokens=31) ) """ @@ -155,7 +155,7 @@ class Location(BaseModel): response_format=Location, ), content_snapshot=snapshot( - '{"id": "chatcmpl-9tABVfBu4ZdyQFKe8RgsWsyL7UoIj", "object": "chat.completion", "created": 1722934217, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"city\\":\\"San Francisco\\",\\"temperature\\":58.0,\\"units\\":\\"f\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}, {"index": 1, "message": {"role": "assistant", "content": "{\\"city\\":\\"San Francisco\\",\\"temperature\\":61,\\"units\\":\\"f\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}, {"index": 2, "message": {"role": "assistant", "content": "{\\"city\\":\\"San Francisco\\",\\"temperature\\":65,\\"units\\":\\"f\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 17, "completion_tokens": 44, "total_tokens": 61}, "system_fingerprint": "fp_e1a05a1dce"}' + '{"id": "chatcmpl-9tXjUrNFyyjSB2FJ842TMDNRM6Gen", "object": "chat.completion", "created": 1723024736, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"city\\":\\"San Francisco\\",\\"temperature\\":58,\\"units\\":\\"f\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}, {"index": 1, "message": {"role": "assistant", "content": "{\\"city\\":\\"San Francisco\\",\\"temperature\\":58,\\"units\\":\\"f\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}, {"index": 2, "message": {"role": "assistant", "content": "{\\"city\\":\\"San Francisco\\",\\"temperature\\":63,\\"units\\":\\"f\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 17, "completion_tokens": 42, "total_tokens": 59}, "system_fingerprint": "fp_845eaabc1f"}' ), mock_client=client, respx_mock=respx_mock, @@ -169,7 +169,7 @@ class Location(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( - content='{"city":"San Francisco","temperature":58.0,"units":"f"}', + content='{"city":"San Francisco","temperature":58,"units":"f"}', function_call=None, parsed=Location(city='San Francisco', temperature=58.0, units='f'), refusal=None, @@ -182,9 +182,9 @@ class Location(BaseModel): index=1, logprobs=None, message=ParsedChatCompletionMessage[Location]( - content='{"city":"San Francisco","temperature":61,"units":"f"}', + content='{"city":"San Francisco","temperature":58,"units":"f"}', function_call=None, - parsed=Location(city='San Francisco', temperature=61.0, units='f'), + parsed=Location(city='San Francisco', temperature=58.0, units='f'), refusal=None, role='assistant', tool_calls=[] @@ -195,9 +195,9 @@ class Location(BaseModel): index=2, logprobs=None, message=ParsedChatCompletionMessage[Location]( - content='{"city":"San Francisco","temperature":65,"units":"f"}', + content='{"city":"San Francisco","temperature":63,"units":"f"}', function_call=None, - parsed=Location(city='San Francisco', temperature=65.0, units='f'), + parsed=Location(city='San Francisco', temperature=63.0, units='f'), refusal=None, role='assistant', tool_calls=[] @@ -223,7 +223,7 @@ def test_pydantic_tool_model_all_types(client: OpenAI, respx_mock: MockRouter, m response_format=Query, ), content_snapshot=snapshot( - '{"id": "chatcmpl-9tABVRLORZbby5zZjZhyrUdDU1XhB", "object": "chat.completion", "created": 1722934217, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "tool_calls": [{"id": "call_VcgQcA1C047fQnXDG0PQXG7O", "type": "function", "function": {"name": "Query", "arguments": "{\\"table_name\\":\\"orders\\",\\"columns\\":[\\"id\\",\\"status\\",\\"expected_delivery_date\\",\\"delivered_at\\"],\\"conditions\\":[{\\"column\\":\\"ordered_at\\",\\"operator\\":\\"=\\",\\"value\\":\\"2022-05\\"},{\\"column\\":\\"status\\",\\"operator\\":\\"=\\",\\"value\\":\\"fulfilled\\"},{\\"column\\":\\"delivered_at\\",\\"operator\\":\\">\\",\\"value\\":{\\"column_name\\":\\"expected_delivery_date\\"}}],\\"order_by\\":\\"asc\\"}"}}], "refusal": null}, "logprobs": null, "finish_reason": "tool_calls"}], "usage": {"prompt_tokens": 195, "completion_tokens": 85, "total_tokens": 280}, "system_fingerprint": "fp_e1a05a1dce"}' + '{"id": "chatcmpl-9tXjVJVCLTn7CWFhpjETixvvApCk3", "object": "chat.completion", "created": 1723024737, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "tool_calls": [{"id": "call_Un4g0IXeQGOyqKBS3zhqNCox", "type": "function", "function": {"name": "Query", "arguments": "{\\"table_name\\":\\"orders\\",\\"columns\\":[\\"id\\",\\"status\\",\\"expected_delivery_date\\",\\"delivered_at\\",\\"shipped_at\\",\\"ordered_at\\"],\\"conditions\\":[{\\"column\\":\\"ordered_at\\",\\"operator\\":\\">=\\",\\"value\\":\\"2022-05-01\\"},{\\"column\\":\\"ordered_at\\",\\"operator\\":\\"<=\\",\\"value\\":\\"2022-05-31\\"},{\\"column\\":\\"status\\",\\"operator\\":\\"=\\",\\"value\\":\\"fulfilled\\"},{\\"column\\":\\"delivered_at\\",\\"operator\\":\\">\\",\\"value\\":{\\"column_name\\":\\"expected_delivery_date\\"}}],\\"order_by\\":\\"asc\\"}"}}], "refusal": null}, "logprobs": null, "finish_reason": "tool_calls"}], "usage": {"prompt_tokens": 195, "completion_tokens": 114, "total_tokens": 309}, "system_fingerprint": "fp_845eaabc1f"}' ), mock_client=client, respx_mock=respx_mock, @@ -244,19 +244,23 @@ def test_pydantic_tool_model_all_types(client: OpenAI, respx_mock: MockRouter, m tool_calls=[ ParsedFunctionToolCall( function=ParsedFunction( - arguments='{"table_name":"orders","columns":["id","status","expected_delivery_date","delivered_at"], -"conditions":[{"column":"ordered_at","operator":"=","value":"2022-05"},{"column":"status","operator":"=","value":"fulfil -led"},{"column":"delivered_at","operator":">","value":{"column_name":"expected_delivery_date"}}],"order_by":"asc"}', + arguments='{"table_name":"orders","columns":["id","status","expected_delivery_date","delivered_at"," +shipped_at","ordered_at"],"conditions":[{"column":"ordered_at","operator":">=","value":"2022-05-01"},{"column":"ordered_ +at","operator":"<=","value":"2022-05-31"},{"column":"status","operator":"=","value":"fulfilled"},{"column":"delivered_at +","operator":">","value":{"column_name":"expected_delivery_date"}}],"order_by":"asc"}', name='Query', parsed_arguments=Query( columns=[ , , , - + , + , + ], conditions=[ - Condition(column='ordered_at', operator=='>, value='2022-05-01'), + Condition(column='ordered_at', operator= ) ), - id='call_VcgQcA1C047fQnXDG0PQXG7O', + id='call_Un4g0IXeQGOyqKBS3zhqNCox', type='function' ) ] @@ -299,7 +303,7 @@ class Location(BaseModel): response_format=Location, ), content_snapshot=snapshot( - '{"id": "chatcmpl-9tABXbi3qast6oJvdaqQcK9C7k9fn", "object": "chat.completion", "created": 1722934219, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"", "refusal": null}, "logprobs": null, "finish_reason": "length"}], "usage": {"prompt_tokens": 17, "completion_tokens": 1, "total_tokens": 18}, "system_fingerprint": "fp_e1a05a1dce"}' + '{"id": "chatcmpl-9tXjYACgVKixKdMv2nVQqDVELkdSF", "object": "chat.completion", "created": 1723024740, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"", "refusal": null}, "logprobs": null, "finish_reason": "length"}], "usage": {"prompt_tokens": 17, "completion_tokens": 1, "total_tokens": 18}, "system_fingerprint": "fp_2a322c9ffc"}' ), mock_client=client, respx_mock=respx_mock, @@ -325,7 +329,7 @@ class Location(BaseModel): response_format=Location, ), content_snapshot=snapshot( - '{"id": "chatcmpl-9tABXJEffhEWxp24MeLxkDJCMtWmx", "object": "chat.completion", "created": 1722934219, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "refusal": "I\'m very sorry, but I can\'t assist with that."}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 17, "completion_tokens": 12, "total_tokens": 29}, "system_fingerprint": "fp_e1a05a1dce"}' + '{"id": "chatcmpl-9tXm7FnIj3hSot5xM4c954MIePle0", "object": "chat.completion", "created": 1723024899, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "refusal": "I\'m very sorry, but I can\'t assist with that request."}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 17, "completion_tokens": 13, "total_tokens": 30}, "system_fingerprint": "fp_845eaabc1f"}' ), mock_client=client, respx_mock=respx_mock, @@ -342,7 +346,7 @@ class Location(BaseModel): content=None, function_call=None, parsed=None, - refusal="I'm very sorry, but I can't assist with that.", + refusal="I'm very sorry, but I can't assist with that request.", role='assistant', tool_calls=[] ) @@ -373,7 +377,7 @@ class GetWeatherArgs(BaseModel): ], ), content_snapshot=snapshot( - '{"id": "chatcmpl-9tABgtKnF7Gbri4CmpOocmhg0UgBF", "object": "chat.completion", "created": 1722934228, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "tool_calls": [{"id": "call_9rqjEc1DQRADTYGVV45LbZwL", "type": "function", "function": {"name": "GetWeatherArgs", "arguments": "{\\"city\\":\\"Edinburgh\\",\\"country\\":\\"UK\\",\\"units\\":\\"c\\"}"}}], "refusal": null}, "logprobs": null, "finish_reason": "tool_calls"}], "usage": {"prompt_tokens": 76, "completion_tokens": 24, "total_tokens": 100}, "system_fingerprint": "fp_e1a05a1dce"}' + '{"id": "chatcmpl-9tXjbQ9V0l5XPlynOJHKvrWsJQymO", "object": "chat.completion", "created": 1723024743, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "tool_calls": [{"id": "call_EEaIYq8aTdiDWro8jILNl3XK", "type": "function", "function": {"name": "GetWeatherArgs", "arguments": "{\\"city\\":\\"Edinburgh\\",\\"country\\":\\"GB\\",\\"units\\":\\"c\\"}"}}], "refusal": null}, "logprobs": null, "finish_reason": "tool_calls"}], "usage": {"prompt_tokens": 76, "completion_tokens": 24, "total_tokens": 100}, "system_fingerprint": "fp_2a322c9ffc"}' ), mock_client=client, respx_mock=respx_mock, @@ -395,11 +399,11 @@ class GetWeatherArgs(BaseModel): tool_calls=[ ParsedFunctionToolCall( function=ParsedFunction( - arguments='{"city":"Edinburgh","country":"UK","units":"c"}', + arguments='{"city":"Edinburgh","country":"GB","units":"c"}', name='GetWeatherArgs', - parsed_arguments=GetWeatherArgs(city='Edinburgh', country='UK', units='c') + parsed_arguments=GetWeatherArgs(city='Edinburgh', country='GB', units='c') ), - id='call_9rqjEc1DQRADTYGVV45LbZwL', + id='call_EEaIYq8aTdiDWro8jILNl3XK', type='function' ) ] @@ -444,7 +448,7 @@ class GetStockPrice(BaseModel): ], ), content_snapshot=snapshot( - '{"id": "chatcmpl-9tABqDpvDTi0Cg8PHtKdNSFoh4UJv", "object": "chat.completion", "created": 1722934238, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "tool_calls": [{"id": "call_Yeg67XmQbMcohm3NGj0g12ty", "type": "function", "function": {"name": "GetWeatherArgs", "arguments": "{\\"city\\": \\"Edinburgh\\", \\"country\\": \\"GB\\", \\"units\\": \\"c\\"}"}}, {"id": "call_OGg3UZC2ksjAg7yrLXy8t1MO", "type": "function", "function": {"name": "get_stock_price", "arguments": "{\\"ticker\\": \\"AAPL\\", \\"exchange\\": \\"NASDAQ\\"}"}}], "refusal": null}, "logprobs": null, "finish_reason": "tool_calls"}], "usage": {"prompt_tokens": 149, "completion_tokens": 60, "total_tokens": 209}, "system_fingerprint": "fp_e1a05a1dce"}' + '{"id": "chatcmpl-9tXjcnIvzZDXRfLfbVTPNL5963GWw", "object": "chat.completion", "created": 1723024744, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "tool_calls": [{"id": "call_ECSuZ8gcNPPwgt24me91jHsJ", "type": "function", "function": {"name": "GetWeatherArgs", "arguments": "{\\"city\\": \\"Edinburgh\\", \\"country\\": \\"UK\\", \\"units\\": \\"c\\"}"}}, {"id": "call_Z3fM2sNBBGILhMtimk5Y3RQk", "type": "function", "function": {"name": "get_stock_price", "arguments": "{\\"ticker\\": \\"AAPL\\", \\"exchange\\": \\"NASDAQ\\"}"}}], "refusal": null}, "logprobs": null, "finish_reason": "tool_calls"}], "usage": {"prompt_tokens": 149, "completion_tokens": 60, "total_tokens": 209}, "system_fingerprint": "fp_845eaabc1f"}' ), mock_client=client, respx_mock=respx_mock, @@ -466,11 +470,11 @@ class GetStockPrice(BaseModel): tool_calls=[ ParsedFunctionToolCall( function=ParsedFunction( - arguments='{"city": "Edinburgh", "country": "GB", "units": "c"}', + arguments='{"city": "Edinburgh", "country": "UK", "units": "c"}', name='GetWeatherArgs', - parsed_arguments=GetWeatherArgs(city='Edinburgh', country='GB', units='c') + parsed_arguments=GetWeatherArgs(city='Edinburgh', country='UK', units='c') ), - id='call_Yeg67XmQbMcohm3NGj0g12ty', + id='call_ECSuZ8gcNPPwgt24me91jHsJ', type='function' ), ParsedFunctionToolCall( @@ -479,7 +483,7 @@ class GetStockPrice(BaseModel): name='get_stock_price', parsed_arguments=GetStockPrice(exchange='NASDAQ', ticker='AAPL') ), - id='call_OGg3UZC2ksjAg7yrLXy8t1MO', + id='call_Z3fM2sNBBGILhMtimk5Y3RQk', type='function' ) ] @@ -524,7 +528,7 @@ def test_parse_strict_tools(client: OpenAI, respx_mock: MockRouter, monkeypatch: ], ), content_snapshot=snapshot( - '{"id": "chatcmpl-9tAC0vDx3MfupXmsduSZavLVaLcrA", "object": "chat.completion", "created": 1722934248, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "tool_calls": [{"id": "call_iNznvWR4R81mizFFHjgh7o4i", "type": "function", "function": {"name": "get_weather", "arguments": "{\\"city\\":\\"San Francisco\\",\\"state\\":\\"CA\\"}"}}], "refusal": null}, "logprobs": null, "finish_reason": "tool_calls"}], "usage": {"prompt_tokens": 48, "completion_tokens": 19, "total_tokens": 67}, "system_fingerprint": "fp_e1a05a1dce"}' + '{"id": "chatcmpl-9tXjfjETDIqeYvDjsuGACbwdY0xsr", "object": "chat.completion", "created": 1723024747, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "tool_calls": [{"id": "call_7ZZPctBXQWexQlIHSrIHMVUq", "type": "function", "function": {"name": "get_weather", "arguments": "{\\"city\\":\\"San Francisco\\",\\"state\\":\\"CA\\"}"}}], "refusal": null}, "logprobs": null, "finish_reason": "tool_calls"}], "usage": {"prompt_tokens": 48, "completion_tokens": 19, "total_tokens": 67}, "system_fingerprint": "fp_2a322c9ffc"}' ), mock_client=client, respx_mock=respx_mock, @@ -550,7 +554,7 @@ def test_parse_strict_tools(client: OpenAI, respx_mock: MockRouter, monkeypatch: name='get_weather', parsed_arguments={'city': 'San Francisco', 'state': 'CA'} ), - id='call_iNznvWR4R81mizFFHjgh7o4i', + id='call_7ZZPctBXQWexQlIHSrIHMVUq', type='function' ) ] diff --git a/tests/lib/chat/test_completions_streaming.py b/tests/lib/chat/test_completions_streaming.py index 3aaa9a0f38..c3dd69ad57 100644 --- a/tests/lib/chat/test_completions_streaming.py +++ b/tests/lib/chat/test_completions_streaming.py @@ -48,7 +48,7 @@ def test_parse_nothing(client: OpenAI, respx_mock: MockRouter, monkeypatch: pyte }, ], ), - content_snapshot=snapshot(external("b9d6bee9f9b8*.bin")), + content_snapshot=snapshot(external("038a5c69c34c*.bin")), mock_client=client, respx_mock=respx_mock, ) @@ -61,8 +61,9 @@ def test_parse_nothing(client: OpenAI, respx_mock: MockRouter, monkeypatch: pyte index=0, logprobs=None, message=ParsedChatCompletionMessage[NoneType]( - content="I'm unable to provide real-time weather updates. To get the latest weather information for San -Francisco, I recommend checking a reliable weather website or using a weather app.", + content="I'm unable to provide real-time updates, including current weather information. For the latest +weather in San Francisco, I recommend checking a reliable weather website or app such as the Weather Channel, BBC +Weather, or a local San Francisco news station.", function_call=None, parsed=None, refusal=None, @@ -76,8 +77,9 @@ def test_parse_nothing(client: OpenAI, respx_mock: MockRouter, monkeypatch: pyte assert print_obj(listener.get_event_by_type("content.done"), monkeypatch) == snapshot( """\ ContentDoneEvent[NoneType]( - content="I'm unable to provide real-time weather updates. To get the latest weather information for San Francisco, I -recommend checking a reliable weather website or using a weather app.", + content="I'm unable to provide real-time updates, including current weather information. For the latest weather in +San Francisco, I recommend checking a reliable weather website or app such as the Weather Channel, BBC Weather, or a +local San Francisco news station.", parsed=None, type='content.done' ) @@ -109,7 +111,7 @@ def on_event(stream: ChatCompletionStream[Location], event: ChatCompletionStream ], response_format=Location, ), - content_snapshot=snapshot(external("ea9a417d533b*.bin")), + content_snapshot=snapshot(external("15ae68f793c7*.bin")), mock_client=client, respx_mock=respx_mock, on_event=on_event, @@ -138,21 +140,21 @@ def on_event(stream: ChatCompletionStream[Location], event: ChatCompletionStream index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( - content='{"city":"San Francisco","temperature":63,"units":"f"}', + content='{"city":"San Francisco","temperature":68,"units":"f"}', function_call=None, - parsed=Location(city='San Francisco', temperature=63.0, units='f'), + parsed=Location(city='San Francisco', temperature=68.0, units='f'), refusal=None, role='assistant', tool_calls=[] ) ) ], - created=1722934250, - id='chatcmpl-9tAC2Fr44W8e4GakwKuKSSsFPhISv', - model='gpt-4o-so', + created=1723024750, + id='chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD', + model='gpt-4o-2024-08-06', object='chat.completion', service_tier=None, - system_fingerprint='fp_e1a05a1dce', + system_fingerprint='fp_845eaabc1f', usage=CompletionUsage(completion_tokens=14, prompt_tokens=17, total_tokens=31) ) """ @@ -160,8 +162,8 @@ def on_event(stream: ChatCompletionStream[Location], event: ChatCompletionStream assert print_obj(listener.get_event_by_type("content.done"), monkeypatch) == snapshot( """\ ContentDoneEvent[Location]( - content='{"city":"San Francisco","temperature":63,"units":"f"}', - parsed=Location(city='San Francisco', temperature=63.0, units='f'), + content='{"city":"San Francisco","temperature":68,"units":"f"}', + parsed=Location(city='San Francisco', temperature=68.0, units='f'), type='content.done' ) """ @@ -189,7 +191,7 @@ class Location(BaseModel): n=3, response_format=Location, ), - content_snapshot=snapshot(external("1437bd06a9d5*.bin")), + content_snapshot=snapshot(external("a0c4f0be184e*.bin")), mock_client=client, respx_mock=respx_mock, ) @@ -209,35 +211,35 @@ class Location(BaseModel): "chunk", "content.delta", "chunk", - "content.delta", + "refusal.delta", "chunk", - "content.delta", + "refusal.delta", "chunk", "content.delta", "chunk", "content.delta", "chunk", - "content.delta", + "refusal.delta", "chunk", "content.delta", "chunk", "content.delta", "chunk", - "content.delta", + "refusal.delta", "chunk", "content.delta", "chunk", "content.delta", "chunk", - "content.delta", + "refusal.delta", "chunk", "content.delta", "chunk", "content.delta", "chunk", - "content.delta", + "refusal.delta", "chunk", - "content.delta", + "refusal.delta", "chunk", "content.delta", "chunk", @@ -247,9 +249,9 @@ class Location(BaseModel): "chunk", "content.delta", "chunk", - "content.delta", + "refusal.delta", "chunk", - "content.delta", + "refusal.delta", "chunk", "content.delta", "chunk", @@ -259,40 +261,96 @@ class Location(BaseModel): "chunk", "content.delta", "chunk", - "content.delta", + "refusal.delta", "chunk", "content.delta", "chunk", "content.delta", "chunk", - "content.delta", + "refusal.delta", "chunk", "content.delta", "chunk", "content.delta", "chunk", - "content.delta", + "refusal.delta", "chunk", "content.delta", "chunk", "content.delta", "chunk", - "content.delta", + "refusal.delta", "chunk", "content.delta", "chunk", "content.delta", "chunk", + "refusal.delta", + "chunk", "content.delta", "chunk", + "refusal.delta", + "chunk", "content.delta", "chunk", - "content.done", + "refusal.delta", + "chunk", + "refusal.delta", + "chunk", + "refusal.delta", + "chunk", + "refusal.delta", + "chunk", + "refusal.delta", + "chunk", + "refusal.delta", + "chunk", + "refusal.delta", + "chunk", + "refusal.delta", + "chunk", + "refusal.delta", + "chunk", + "refusal.delta", + "chunk", + "refusal.delta", + "chunk", + "refusal.delta", + "chunk", + "refusal.delta", + "chunk", + "refusal.delta", + "chunk", + "refusal.delta", + "chunk", + "refusal.delta", + "chunk", + "refusal.delta", + "chunk", + "refusal.delta", + "chunk", + "refusal.delta", + "chunk", + "refusal.delta", + "chunk", + "refusal.delta", + "chunk", + "refusal.delta", + "chunk", + "refusal.delta", + "chunk", + "refusal.delta", + "chunk", + "refusal.delta", + "chunk", + "refusal.delta", "chunk", "content.done", "chunk", "content.done", "chunk", + "refusal.done", + "chunk", ] ) assert print_obj(listener.stream.get_final_completion().choices, monkeypatch) == snapshot( @@ -303,9 +361,9 @@ class Location(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( - content='{"city":"San Francisco","temperature":64,"units":"f"}', + content='{"city":"San Francisco","temperature":63,"units":"f"}', function_call=None, - parsed=Location(city='San Francisco', temperature=64.0, units='f'), + parsed=Location(city='San Francisco', temperature=63.0, units='f'), refusal=None, role='assistant', tool_calls=[] @@ -316,9 +374,9 @@ class Location(BaseModel): index=1, logprobs=None, message=ParsedChatCompletionMessage[Location]( - content='{"city":"San Francisco","temperature":68,"units":"f"}', + content='{"city":"San Francisco","temperature":58.6,"units":"f"}', function_call=None, - parsed=Location(city='San Francisco', temperature=68.0, units='f'), + parsed=Location(city='San Francisco', temperature=58.6, units='f'), refusal=None, role='assistant', tool_calls=[] @@ -329,10 +387,11 @@ class Location(BaseModel): index=2, logprobs=None, message=ParsedChatCompletionMessage[Location]( - content='{"city":"San Francisco","temperature":64,"units":"f"}', + content=None, function_call=None, - parsed=Location(city='San Francisco', temperature=64.0, units='f'), - refusal=None, + parsed=None, + refusal="I'm sorry, but I can't accurately provide the current weather for San Francisco as my data is up to +October 2023. You can try checking a reliable weather website or app for real-time updates.", role='assistant', tool_calls=[] ) @@ -362,7 +421,7 @@ class Location(BaseModel): max_tokens=1, response_format=Location, ), - content_snapshot=snapshot(external("7ae6c1a2631b*.bin")), + content_snapshot=snapshot(external("69363a555f8e*.bin")), mock_client=client, respx_mock=respx_mock, ) @@ -386,13 +445,13 @@ class Location(BaseModel): ], response_format=Location, ), - content_snapshot=snapshot(external("d79326933c15*.bin")), + content_snapshot=snapshot(external("ca015b8b1eba*.bin")), mock_client=client, respx_mock=respx_mock, ) assert print_obj(listener.get_event_by_type("refusal.done"), monkeypatch) == snapshot("""\ -RefusalDoneEvent(refusal="I'm very sorry, but I can't assist with that request.", type='refusal.done') +RefusalDoneEvent(refusal="I'm sorry, but I can't assist with that request.", type='refusal.done') """) assert print_obj(listener.stream.get_final_completion().choices, monkeypatch) == snapshot( @@ -406,7 +465,7 @@ class Location(BaseModel): content=None, function_call=None, parsed=None, - refusal="I'm very sorry, but I can't assist with that request.", + refusal="I'm sorry, but I can't assist with that request.", role='assistant', tool_calls=[] ) @@ -429,7 +488,7 @@ def test_content_logprobs_events(client: OpenAI, respx_mock: MockRouter, monkeyp ], logprobs=True, ), - content_snapshot=snapshot(external("70c7df71ce72*.bin")), + content_snapshot=snapshot(external("be1089999ca5*.bin")), mock_client=client, respx_mock=respx_mock, ) @@ -437,24 +496,26 @@ def test_content_logprobs_events(client: OpenAI, respx_mock: MockRouter, monkeyp assert print_obj([e for e in listener.events if e.type.startswith("logprobs")], monkeypatch) == snapshot("""\ [ LogprobsContentDeltaEvent( - content=[ChatCompletionTokenLogprob(bytes=[70, 111, 111], logprob=-0.006764991, token='Foo', top_logprobs=[])], + content=[ + ChatCompletionTokenLogprob(bytes=[70, 111, 111], logprob=-0.0067602484, token='Foo', top_logprobs=[]) + ], snapshot=[ - ChatCompletionTokenLogprob(bytes=[70, 111, 111], logprob=-0.006764991, token='Foo', top_logprobs=[]) + ChatCompletionTokenLogprob(bytes=[70, 111, 111], logprob=-0.0067602484, token='Foo', top_logprobs=[]) ], type='logprobs.content.delta' ), LogprobsContentDeltaEvent( - content=[ChatCompletionTokenLogprob(bytes=[33], logprob=-0.31380808, token='!', top_logprobs=[])], + content=[ChatCompletionTokenLogprob(bytes=[46], logprob=-2.4962392, token='.', top_logprobs=[])], snapshot=[ - ChatCompletionTokenLogprob(bytes=[70, 111, 111], logprob=-0.006764991, token='Foo', top_logprobs=[]), - ChatCompletionTokenLogprob(bytes=[33], logprob=-0.31380808, token='!', top_logprobs=[]) + ChatCompletionTokenLogprob(bytes=[70, 111, 111], logprob=-0.0067602484, token='Foo', top_logprobs=[]), + ChatCompletionTokenLogprob(bytes=[46], logprob=-2.4962392, token='.', top_logprobs=[]) ], type='logprobs.content.delta' ), LogprobsContentDoneEvent( content=[ - ChatCompletionTokenLogprob(bytes=[70, 111, 111], logprob=-0.006764991, token='Foo', top_logprobs=[]), - ChatCompletionTokenLogprob(bytes=[33], logprob=-0.31380808, token='!', top_logprobs=[]) + ChatCompletionTokenLogprob(bytes=[70, 111, 111], logprob=-0.0067602484, token='Foo', top_logprobs=[]), + ChatCompletionTokenLogprob(bytes=[46], logprob=-2.4962392, token='.', top_logprobs=[]) ], type='logprobs.content.done' ) @@ -468,13 +529,13 @@ def test_content_logprobs_events(client: OpenAI, respx_mock: MockRouter, monkeyp index=0, logprobs=ChoiceLogprobs( content=[ - ChatCompletionTokenLogprob(bytes=[70, 111, 111], logprob=-0.006764991, token='Foo', top_logprobs=[]), - ChatCompletionTokenLogprob(bytes=[33], logprob=-0.31380808, token='!', top_logprobs=[]) + ChatCompletionTokenLogprob(bytes=[70, 111, 111], logprob=-0.0067602484, token='Foo', top_logprobs=[]), + ChatCompletionTokenLogprob(bytes=[46], logprob=-2.4962392, token='.', top_logprobs=[]) ], refusal=None ), message=ParsedChatCompletionMessage[NoneType]( - content='Foo!', + content='Foo.', function_call=None, parsed=None, refusal=None, @@ -505,7 +566,7 @@ class Location(BaseModel): logprobs=True, response_format=Location, ), - content_snapshot=snapshot(external("cb77dc69b6c8*.bin")), + content_snapshot=snapshot(external("0a00cd46c610*.bin")), mock_client=client, respx_mock=respx_mock, ) @@ -522,7 +583,6 @@ class Location(BaseModel): 'logprobs.refusal.delta', 'logprobs.refusal.delta', 'logprobs.refusal.delta', - 'logprobs.refusal.delta', 'logprobs.refusal.done' ] """) @@ -535,59 +595,53 @@ class Location(BaseModel): logprobs=ChoiceLogprobs( content=None, refusal=[ - ChatCompletionTokenLogprob(bytes=[73, 39, 109], logprob=-0.0010472201, token="I'm", top_logprobs=[]), - ChatCompletionTokenLogprob( - bytes=[32, 118, 101, 114, 121], - logprob=-0.7292482, - token=' very', - top_logprobs=[] - ), + ChatCompletionTokenLogprob(bytes=[73, 39, 109], logprob=-0.0016157961, token="I'm", top_logprobs=[]), ChatCompletionTokenLogprob( bytes=[32, 115, 111, 114, 114, 121], - logprob=-5.080963e-06, + logprob=-0.78663874, token=' sorry', top_logprobs=[] ), - ChatCompletionTokenLogprob(bytes=[44], logprob=-4.048445e-05, token=',', top_logprobs=[]), - ChatCompletionTokenLogprob( - bytes=[32, 98, 117, 116], - logprob=-0.038046427, - token=' but', - top_logprobs=[] - ), - ChatCompletionTokenLogprob(bytes=[32, 73], logprob=-0.0019351852, token=' I', top_logprobs=[]), + ChatCompletionTokenLogprob(bytes=[44], logprob=-7.79144e-05, token=',', top_logprobs=[]), + ChatCompletionTokenLogprob(bytes=[32, 73], logprob=-0.5234622, token=' I', top_logprobs=[]), ChatCompletionTokenLogprob( - bytes=[32, 99, 97, 110, 39, 116], - logprob=-0.008995773, - token=" can't", + bytes=[32, 99, 97, 110, 110, 111, 116], + logprob=-0.52499557, + token=' cannot', top_logprobs=[] ), ChatCompletionTokenLogprob( bytes=[32, 97, 115, 115, 105, 115, 116], - logprob=-0.0033510819, + logprob=-0.015198289, token=' assist', top_logprobs=[] ), ChatCompletionTokenLogprob( bytes=[32, 119, 105, 116, 104], - logprob=-0.0036033941, + logprob=-0.00071648485, token=' with', top_logprobs=[] ), ChatCompletionTokenLogprob( bytes=[32, 116, 104, 97, 116], - logprob=-0.0015974608, + logprob=-0.008114983, token=' that', top_logprobs=[] ), - ChatCompletionTokenLogprob(bytes=[46], logprob=-0.6339823, token='.', top_logprobs=[]) + ChatCompletionTokenLogprob( + bytes=[32, 114, 101, 113, 117, 101, 115, 116], + logprob=-0.0013802331, + token=' request', + top_logprobs=[] + ), + ChatCompletionTokenLogprob(bytes=[46], logprob=-3.4121115e-06, token='.', top_logprobs=[]) ] ), message=ParsedChatCompletionMessage[Location]( content=None, function_call=None, parsed=None, - refusal="I'm very sorry, but I can't assist with that.", + refusal="I'm sorry, I cannot assist with that request.", role='assistant', tool_calls=[] ) @@ -616,7 +670,7 @@ class GetWeatherArgs(BaseModel): openai.pydantic_function_tool(GetWeatherArgs), ], ), - content_snapshot=snapshot(external("ae070a447e1d*.bin")), + content_snapshot=snapshot(external("24aaf30663f9*.bin")), mock_client=client, respx_mock=respx_mock, ) @@ -637,11 +691,11 @@ class GetWeatherArgs(BaseModel): tool_calls=[ ParsedFunctionToolCall( function=ParsedFunction( - arguments='{"city":"Edinburgh","country":"UK","units":"c"}', + arguments='{"city":"Edinburgh","country":"GB","units":"c"}', name='GetWeatherArgs', - parsed_arguments=GetWeatherArgs(city='Edinburgh', country='UK', units='c') + parsed_arguments=GetWeatherArgs(city='Edinburgh', country='GB', units='c') ), - id='call_Vz6ZXciy6Y0PYfT4d9W7fYB4', + id='call_7PhhveOvvpPK53s1fV8TWhoV', index=0, type='function' ) @@ -668,11 +722,11 @@ class GetWeatherArgs(BaseModel): tool_calls=[ ParsedFunctionToolCall( function=ParsedFunction( - arguments='{"city":"Edinburgh","country":"UK","units":"c"}', + arguments='{"city":"Edinburgh","country":"GB","units":"c"}', name='GetWeatherArgs', - parsed_arguments=GetWeatherArgs(city='Edinburgh', country='UK', units='c') + parsed_arguments=GetWeatherArgs(city='Edinburgh', country='GB', units='c') ), - id='call_Vz6ZXciy6Y0PYfT4d9W7fYB4', + id='call_7PhhveOvvpPK53s1fV8TWhoV', index=0, type='function' ) @@ -717,7 +771,7 @@ class GetStockPrice(BaseModel): ), ], ), - content_snapshot=snapshot(external("a346213bec7a*.bin")), + content_snapshot=snapshot(external("453df473e962*.bin")), mock_client=client, respx_mock=respx_mock, ) @@ -742,7 +796,7 @@ class GetStockPrice(BaseModel): name='GetWeatherArgs', parsed_arguments=GetWeatherArgs(city='Edinburgh', country='UK', units='c') ), - id='call_g4Q1vRbE0CaHGOs5if8mHsBq', + id='call_lQnnsesjFMWMQ5IeWPHzR4th', index=0, type='function' ), @@ -752,7 +806,7 @@ class GetStockPrice(BaseModel): name='get_stock_price', parsed_arguments=GetStockPrice(exchange='NASDAQ', ticker='AAPL') ), - id='call_gWj3HQxZEHnFvyJLEHIiJKBV', + id='call_2xjOUgaCdiwAcl9ZBL9LyMUU', index=1, type='function' ) @@ -772,7 +826,7 @@ class GetStockPrice(BaseModel): name='GetWeatherArgs', parsed_arguments=GetWeatherArgs(city='Edinburgh', country='UK', units='c') ), - id='call_g4Q1vRbE0CaHGOs5if8mHsBq', + id='call_lQnnsesjFMWMQ5IeWPHzR4th', index=0, type='function' ), @@ -782,7 +836,7 @@ class GetStockPrice(BaseModel): name='get_stock_price', parsed_arguments=GetStockPrice(exchange='NASDAQ', ticker='AAPL') ), - id='call_gWj3HQxZEHnFvyJLEHIiJKBV', + id='call_2xjOUgaCdiwAcl9ZBL9LyMUU', index=1, type='function' ) @@ -824,7 +878,7 @@ def test_parse_strict_tools(client: OpenAI, respx_mock: MockRouter, monkeypatch: } ], ), - content_snapshot=snapshot(external("a7097cae6a1f*.bin")), + content_snapshot=snapshot(external("83d3d003e6fd*.bin")), mock_client=client, respx_mock=respx_mock, ) @@ -849,7 +903,7 @@ def test_parse_strict_tools(client: OpenAI, respx_mock: MockRouter, monkeypatch: name='get_weather', parsed_arguments={'city': 'San Francisco', 'state': 'CA'} ), - id='call_rQe3kzGnTr2epjx8HREg3F2a', + id='call_pVHYsU0gmSfX5TqxOyVbB2ma', index=0, type='function' ) @@ -874,7 +928,7 @@ def test_non_pydantic_response_format(client: OpenAI, respx_mock: MockRouter, mo ], response_format={"type": "json_object"}, ), - content_snapshot=snapshot(external("3e0df46f250d*.bin")), + content_snapshot=snapshot(external("0898f3d1651e*.bin")), mock_client=client, respx_mock=respx_mock, ) @@ -887,9 +941,10 @@ def test_non_pydantic_response_format(client: OpenAI, respx_mock: MockRouter, mo index=0, logprobs=None, message=ParsedChatCompletionMessage[NoneType]( - content='{\\n "location": "San Francisco, CA",\\n "temperature": "N/A",\\n "conditions": "N/A",\\n -"humidity": "N/A",\\n "wind_speed": "N/A",\\n "timestamp": "N/A",\\n "note": "Real-time weather data is not available. -Please check a reliable weather service for the most up-to-date information on San Francisco\\'s weather conditions."}', + content='\\n {\\n "location": "San Francisco, CA",\\n "forecast_date": "2023-11-02",\\n "weather": {\\n +"temperature": {\\n "current": "N/A",\\n "high": "N/A",\\n "low": "N/A"\\n },\\n "condition": +"N/A",\\n "humidity": "N/A",\\n "wind_speed": "N/A"\\n },\\n "note": "Please check a reliable weather +service for the most current information."\\n }', function_call=None, parsed=None, refusal=None, @@ -920,7 +975,7 @@ def test_allows_non_strict_tools_but_no_parsing( } ], ), - content_snapshot=snapshot(external("fb75060ede89*.bin")), + content_snapshot=snapshot(external("dae1b261f197*.bin")), mock_client=client, respx_mock=respx_mock, ) @@ -939,7 +994,7 @@ def test_allows_non_strict_tools_but_no_parsing( """\ [ ParsedChoice[NoneType]( - finish_reason='stop', + finish_reason='tool_calls', index=0, logprobs=None, message=ParsedChatCompletionMessage[NoneType]( @@ -955,7 +1010,7 @@ def test_allows_non_strict_tools_but_no_parsing( name='get_weather', parsed_arguments=None ), - id='call_9rqjEc1DQRADTYGVV45LbZwL', + id='call_5uxEBMFySqqQGu02I5QHA8k6', index=0, type='function' ) From 631a2a7156299351874f37c4769308a104ce19ed Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 7 Aug 2024 10:04:38 +0000 Subject: [PATCH 450/816] release: 1.40.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 9 +++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 0c37ae42ca..4b272115e4 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.40.0" + ".": "1.40.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 2454a9a6cc..95b51e8a03 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 1.40.1 (2024-08-07) + +Full Changelog: [v1.40.0...v1.40.1](https://github.com/openai/openai-python/compare/v1.40.0...v1.40.1) + +### Chores + +* **internal:** update OpenAPI spec url ([#1608](https://github.com/openai/openai-python/issues/1608)) ([5392753](https://github.com/openai/openai-python/commit/53927531fc101e96b9e3f5d44f34b298055f496a)) +* **internal:** update test snapshots ([a11d1cb](https://github.com/openai/openai-python/commit/a11d1cb5d04aac0bf69dc10a3a21fa95575c0aa0)) + ## 1.40.0 (2024-08-06) Full Changelog: [v1.39.0...v1.40.0](https://github.com/openai/openai-python/compare/v1.39.0...v1.40.0) diff --git a/pyproject.toml b/pyproject.toml index 1e86c44706..af661cbad7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.40.0" +version = "1.40.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 73cd42e5ea..f88b8dead1 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.40.0" # x-release-please-version +__version__ = "1.40.1" # x-release-please-version From 5f52e473a9c08dd30e3e956f81b5e7a3d6a802f5 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Wed, 7 Aug 2024 10:13:08 +0100 Subject: [PATCH 451/816] fix(client): raise helpful error message for response_format misuse --- src/openai/resources/chat/completions.py | 11 ++++++ tests/api_resources/chat/test_completions.py | 35 ++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index 3dcd3774d7..fb4c71ba99 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -2,10 +2,12 @@ from __future__ import annotations +import inspect from typing import Dict, List, Union, Iterable, Optional, overload from typing_extensions import Literal import httpx +import pydantic from ... import _legacy_response from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven @@ -647,6 +649,7 @@ def create( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ChatCompletion | Stream[ChatCompletionChunk]: + validate_response_format(response_format) return self._post( "/chat/completions", body=maybe_transform( @@ -1302,6 +1305,7 @@ async def create( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ChatCompletion | AsyncStream[ChatCompletionChunk]: + validate_response_format(response_format) return await self._post( "/chat/completions", body=await async_maybe_transform( @@ -1375,3 +1379,10 @@ def __init__(self, completions: AsyncCompletions) -> None: self.create = async_to_streamed_response_wrapper( completions.create, ) + + +def validate_response_format(response_format: object) -> None: + if inspect.isclass(response_format) and issubclass(response_format, pydantic.BaseModel): + raise TypeError( + "You tried to pass a `BaseModel` class to `chat.completions.create()`; You must use `beta.chat.completions.parse()` instead" + ) diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index d744dfe6ea..9fa3cc8284 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -6,6 +6,7 @@ from typing import Any, cast import pytest +import pydantic from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type @@ -257,6 +258,23 @@ def test_streaming_response_create_overload_2(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_method_create_disallows_pydantic(self, client: OpenAI) -> None: + class MyModel(pydantic.BaseModel): + a: str + + with pytest.raises(TypeError, match=r"You tried to pass a `BaseModel` class"): + client.chat.completions.create( + messages=[ + { + "content": "string", + "role": "system", + } + ], + model="gpt-4o", + response_format=cast(Any, MyModel), + ) + class TestAsyncCompletions: parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) @@ -498,3 +516,20 @@ async def test_streaming_response_create_overload_2(self, async_client: AsyncOpe await stream.close() assert cast(Any, response.is_closed) is True + + @parametrize + async def test_method_create_disallows_pydantic(self, async_client: AsyncOpenAI) -> None: + class MyModel(pydantic.BaseModel): + a: str + + with pytest.raises(TypeError, match=r"You tried to pass a `BaseModel` class"): + await async_client.chat.completions.create( + messages=[ + { + "content": "string", + "role": "system", + } + ], + model="gpt-4o", + response_format=cast(Any, MyModel), + ) From a9b8aa8e1812762ae1d30e1f893d4be1bc825a05 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Wed, 7 Aug 2024 10:13:24 +0100 Subject: [PATCH 452/816] chore(internal): format some docstrings --- src/openai/resources/beta/chat/completions.py | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/openai/resources/beta/chat/completions.py b/src/openai/resources/beta/chat/completions.py index 88ea2c0572..aee88c3c0f 100644 --- a/src/openai/resources/beta/chat/completions.py +++ b/src/openai/resources/beta/chat/completions.py @@ -78,14 +78,17 @@ def parse( from pydantic import BaseModel from openai import OpenAI + class Step(BaseModel): explanation: str output: str + class MathResponse(BaseModel): steps: List[Step] final_answer: str + client = OpenAI() completion = client.beta.chat.completions.parse( model="gpt-4o-2024-08-06", @@ -184,12 +187,12 @@ def stream( ```py with client.beta.chat.completions.stream( - model='gpt-4o-2024-08-06', + model="gpt-4o-2024-08-06", messages=[...], ) as stream: for event in stream: - if event.type == 'content.delta': - print(event.content, flush=True, end='') + if event.type == "content.delta": + print(event.content, flush=True, end="") ``` When the context manager is entered, a `ChatCompletionStream` instance is returned which, like `.create(stream=True)` is an iterator. The full list of events that are yielded by the iterator are outlined in [these docs](https://github.com/openai/openai-python/blob/main/helpers.md#chat-completions-events). @@ -287,14 +290,17 @@ async def parse( from pydantic import BaseModel from openai import AsyncOpenAI + class Step(BaseModel): explanation: str output: str + class MathResponse(BaseModel): steps: List[Step] final_answer: str + client = AsyncOpenAI() completion = await client.beta.chat.completions.parse( model="gpt-4o-2024-08-06", @@ -393,12 +399,12 @@ def stream( ```py async with client.beta.chat.completions.stream( - model='gpt-4o-2024-08-06', + model="gpt-4o-2024-08-06", messages=[...], ) as stream: async for event in stream: - if event.type == 'content.delta': - print(event.content, flush=True, end='') + if event.type == "content.delta": + print(event.content, flush=True, end="") ``` When the context manager is entered, an `AsyncChatCompletionStream` instance is returned which, like `.create(stream=True)` is an async iterator. The full list of events that are yielded by the iterator are outlined in [these docs](https://github.com/openai/openai-python/blob/main/helpers.md#chat-completions-events). From ef859c889df8a0e715377ea560a09b5ed1f3c40a Mon Sep 17 00:00:00 2001 From: Alex Protsyk Date: Thu, 8 Aug 2024 15:33:53 +0200 Subject: [PATCH 453/816] fix(json schema): support recursive BaseModels in Pydantic v1 (#1623) --- src/openai/lib/_pydantic.py | 5 +++++ tests/lib/test_pydantic.py | 2 ++ 2 files changed, 7 insertions(+) diff --git a/src/openai/lib/_pydantic.py b/src/openai/lib/_pydantic.py index 967ad5de57..a90effdf1a 100644 --- a/src/openai/lib/_pydantic.py +++ b/src/openai/lib/_pydantic.py @@ -62,6 +62,11 @@ def _ensure_strict_json_schema( for def_name, def_schema in defs.items(): _ensure_strict_json_schema(def_schema, path=(*path, "$defs", def_name)) + definitions = json_schema.get("definitions") + if is_dict(definitions): + for definition_name, definition_schema in definitions.items(): + _ensure_strict_json_schema(definition_schema, path=(*path, "definitions", definition_name)) + return json_schema diff --git a/tests/lib/test_pydantic.py b/tests/lib/test_pydantic.py index dc09596da2..a8fe8f4570 100644 --- a/tests/lib/test_pydantic.py +++ b/tests/lib/test_pydantic.py @@ -130,6 +130,7 @@ def test_most_types() -> None: "type": "object", "properties": {"column_name": {"title": "Column Name", "type": "string"}}, "required": ["column_name"], + "additionalProperties": False, }, "Condition": { "title": "Condition", @@ -147,6 +148,7 @@ def test_most_types() -> None: }, }, "required": ["column", "operator", "value"], + "additionalProperties": False, }, "OrderBy": { "title": "OrderBy", From a7f4ba7e976f80fff7e6994df6470249a5f52eb8 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 8 Aug 2024 20:21:24 +0000 Subject: [PATCH 454/816] chore(internal): updates (#1624) --- .stats.yml | 2 +- pyproject.toml | 3 +- src/openai/resources/chat/completions.py | 30 +++++++++++++++++++ .../types/chat/completion_create_params.py | 5 ++++ src/openai/types/chat_model.py | 2 +- 5 files changed, 38 insertions(+), 4 deletions(-) diff --git a/.stats.yml b/.stats.yml index ac652c9271..cad2c64cd0 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-4097c2f86beb3f3bb021775cd1dfa240e960caf842aeefc2e08da4dc0851ea79.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-97797a9363b9960b5f2fbdc84426a2b91e75533ecd409fe99e37c231180a4339.yml diff --git a/pyproject.toml b/pyproject.toml index af661cbad7..037b63242a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -202,7 +202,6 @@ unfixable = [ "T201", "T203", ] -ignore-init-module-imports = true [tool.ruff.lint.flake8-tidy-imports.banned-api] "functools.lru_cache".msg = "This function does not retain type information for the wrapped function's arguments; The `lru_cache` function from `_utils` should be used instead" @@ -214,7 +213,7 @@ combine-as-imports = true extra-standard-library = ["typing_extensions"] known-first-party = ["openai", "tests"] -[tool.ruff.per-file-ignores] +[tool.ruff.lint.per-file-ignores] "bin/**.py" = ["T201", "T203"] "scripts/**.py" = ["T201", "T203"] "tests/**.py" = ["T201", "T203"] diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index fb4c71ba99..dc577d6251 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -149,6 +149,11 @@ def create( [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -347,6 +352,11 @@ def create( [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -538,6 +548,11 @@ def create( [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -805,6 +820,11 @@ async def create( [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -1003,6 +1023,11 @@ async def create( [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. @@ -1194,6 +1219,11 @@ async def create( [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index bf648a3858..61126b37ac 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -126,6 +126,11 @@ class CompletionCreateParamsBase(TypedDict, total=False): [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured + Outputs which guarantees the model will match your supplied JSON schema. Learn + more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON. diff --git a/src/openai/types/chat_model.py b/src/openai/types/chat_model.py index 686f26b783..09bc081f7a 100644 --- a/src/openai/types/chat_model.py +++ b/src/openai/types/chat_model.py @@ -6,8 +6,8 @@ ChatModel: TypeAlias = Literal[ "gpt-4o", - "gpt-4o-2024-08-06", "gpt-4o-2024-05-13", + "gpt-4o-2024-08-06", "gpt-4o-mini", "gpt-4o-mini-2024-07-18", "gpt-4-turbo", From 646fff04dbe9458f1c46753031546ccf6415eeef Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 8 Aug 2024 20:21:56 +0000 Subject: [PATCH 455/816] release: 1.40.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 15 +++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 18 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 4b272115e4..2b233c7b0d 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.40.1" + ".": "1.40.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 95b51e8a03..a6c65f0eb2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## 1.40.2 (2024-08-08) + +Full Changelog: [v1.40.1...v1.40.2](https://github.com/openai/openai-python/compare/v1.40.1...v1.40.2) + +### Bug Fixes + +* **client:** raise helpful error message for response_format misuse ([18191da](https://github.com/openai/openai-python/commit/18191dac8e1437a0f708525d474b7ecfe459d966)) +* **json schema:** support recursive BaseModels in Pydantic v1 ([#1623](https://github.com/openai/openai-python/issues/1623)) ([43e10c0](https://github.com/openai/openai-python/commit/43e10c0f251a42f1e6497f360c6c23d3058b3da3)) + + +### Chores + +* **internal:** format some docstrings ([d34a081](https://github.com/openai/openai-python/commit/d34a081c30f869646145919b2256ded115241eb5)) +* **internal:** updates ([#1624](https://github.com/openai/openai-python/issues/1624)) ([598e7a2](https://github.com/openai/openai-python/commit/598e7a23768e7addbe1319ada2e87caee3cf0d14)) + ## 1.40.1 (2024-08-07) Full Changelog: [v1.40.0...v1.40.1](https://github.com/openai/openai-python/compare/v1.40.0...v1.40.1) diff --git a/pyproject.toml b/pyproject.toml index 037b63242a..9600130ca3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.40.1" +version = "1.40.2" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index f88b8dead1..7e6783b6c6 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.40.1" # x-release-please-version +__version__ = "1.40.2" # x-release-please-version From 4373893397584308faba493cfb6d47195063e4a9 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 9 Aug 2024 16:32:50 +0000 Subject: [PATCH 456/816] chore(ci): codeowners file (#1627) --- .github/CODEOWNERS | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 3ce5f8d004..d58c8454c5 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1 +1,4 @@ +# This file is used to automatically assign reviewers to PRs +# For more information see: https://help.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners + * @openai/sdks-team From 2a8773659ea9292a75fcab96d72dd40b26b3a5ff Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 9 Aug 2024 17:43:42 +0000 Subject: [PATCH 457/816] chore(ci): bump prism mock server version (#1630) --- scripts/mock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/mock b/scripts/mock index f586157699..d2814ae6a0 100755 --- a/scripts/mock +++ b/scripts/mock @@ -21,7 +21,7 @@ echo "==> Starting mock server with URL ${URL}" # Run prism mock on the given spec if [ "$1" == "--daemon" ]; then - npm exec --package=@stainless-api/prism-cli@5.8.4 -- prism mock "$URL" &> .prism.log & + npm exec --package=@stainless-api/prism-cli@5.8.5 -- prism mock "$URL" &> .prism.log & # Wait for server to come online echo -n "Waiting for server" @@ -37,5 +37,5 @@ if [ "$1" == "--daemon" ]; then echo else - npm exec --package=@stainless-api/prism-cli@5.8.4 -- prism mock "$URL" + npm exec --package=@stainless-api/prism-cli@5.8.5 -- prism mock "$URL" fi From 1d88db0cd80ad10bc403ded04db975df99d9e0c0 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 9 Aug 2024 19:05:02 +0000 Subject: [PATCH 458/816] chore(internal): ensure package is importable in lint cmd (#1631) --- pyproject.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index 9600130ca3..12360cbab7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -83,10 +83,13 @@ format = { chain = [ "lint" = { chain = [ "check:ruff", "typecheck", + "check:importable", ]} "check:ruff" = "ruff check ." "fix:ruff" = "ruff check --fix ." +"check:importable" = "python -c 'import openai'" + typecheck = { chain = [ "typecheck:pyright", "typecheck:mypy" From 1a388a193f7484f685c6c03a997f7c193a3fcb94 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Sat, 10 Aug 2024 05:03:53 +0000 Subject: [PATCH 459/816] release: 1.40.3 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 10 ++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 13 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 2b233c7b0d..64a418cb06 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.40.2" + ".": "1.40.3" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index a6c65f0eb2..825e753924 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## 1.40.3 (2024-08-10) + +Full Changelog: [v1.40.2...v1.40.3](https://github.com/openai/openai-python/compare/v1.40.2...v1.40.3) + +### Chores + +* **ci:** bump prism mock server version ([#1630](https://github.com/openai/openai-python/issues/1630)) ([214d8fd](https://github.com/openai/openai-python/commit/214d8fd8d7d43c06c7dfe02680847a6a60988120)) +* **ci:** codeowners file ([#1627](https://github.com/openai/openai-python/issues/1627)) ([c059a20](https://github.com/openai/openai-python/commit/c059a20c8cd2124178641c9d8688e276b1cf1d59)) +* **internal:** ensure package is importable in lint cmd ([#1631](https://github.com/openai/openai-python/issues/1631)) ([779e6d0](https://github.com/openai/openai-python/commit/779e6d081eb55c158f2aa1962190079eb7f1335e)) + ## 1.40.2 (2024-08-08) Full Changelog: [v1.40.1...v1.40.2](https://github.com/openai/openai-python/compare/v1.40.1...v1.40.2) diff --git a/pyproject.toml b/pyproject.toml index 12360cbab7..09a11668a3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.40.2" +version = "1.40.3" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 7e6783b6c6..5eed512d7c 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.40.2" # x-release-please-version +__version__ = "1.40.3" # x-release-please-version From 09350cb5d042b6e20b3a647e55ce129c0530934e Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 12 Aug 2024 08:30:48 +0100 Subject: [PATCH 460/816] fix(json schema): unwrap `allOf`s with one entry --- src/openai/lib/_pydantic.py | 10 ++++-- tests/lib/test_pydantic.py | 63 +++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 3 deletions(-) diff --git a/src/openai/lib/_pydantic.py b/src/openai/lib/_pydantic.py index a90effdf1a..85f147c236 100644 --- a/src/openai/lib/_pydantic.py +++ b/src/openai/lib/_pydantic.py @@ -53,9 +53,13 @@ def _ensure_strict_json_schema( # intersections all_of = json_schema.get("allOf") if is_list(all_of): - json_schema["allOf"] = [ - _ensure_strict_json_schema(entry, path=(*path, "anyOf", str(i))) for i, entry in enumerate(all_of) - ] + if len(all_of) == 1: + json_schema.update(_ensure_strict_json_schema(all_of[0], path=(*path, "allOf", "0"))) + json_schema.pop("allOf") + else: + json_schema["allOf"] = [ + _ensure_strict_json_schema(entry, path=(*path, "allOf", str(i))) for i, entry in enumerate(all_of) + ] defs = json_schema.get("$defs") if is_dict(defs): diff --git a/tests/lib/test_pydantic.py b/tests/lib/test_pydantic.py index a8fe8f4570..568844eada 100644 --- a/tests/lib/test_pydantic.py +++ b/tests/lib/test_pydantic.py @@ -1,5 +1,8 @@ from __future__ import annotations +from enum import Enum + +from pydantic import Field, BaseModel from inline_snapshot import snapshot import openai @@ -161,3 +164,63 @@ def test_most_types() -> None: }, } ) + + +class Color(Enum): + RED = "red" + BLUE = "blue" + GREEN = "green" + + +class ColorDetection(BaseModel): + color: Color = Field(description="The detected color") + hex_color_code: str = Field(description="The hex color code of the detected color") + + +def test_enums() -> None: + if PYDANTIC_V2: + assert openai.pydantic_function_tool(ColorDetection)["function"] == snapshot( + { + "name": "ColorDetection", + "strict": True, + "parameters": { + "$defs": {"Color": {"enum": ["red", "blue", "green"], "title": "Color", "type": "string"}}, + "properties": { + "color": {"description": "The detected color", "$ref": "#/$defs/Color"}, + "hex_color_code": { + "description": "The hex color code of the detected color", + "title": "Hex Color Code", + "type": "string", + }, + }, + "required": ["color", "hex_color_code"], + "title": "ColorDetection", + "type": "object", + "additionalProperties": False, + }, + } + ) + else: + assert openai.pydantic_function_tool(ColorDetection)["function"] == snapshot( + { + "name": "ColorDetection", + "strict": True, + "parameters": { + "properties": { + "color": {"description": "The detected color", "$ref": "#/definitions/Color"}, + "hex_color_code": { + "description": "The hex color code of the detected color", + "title": "Hex Color Code", + "type": "string", + }, + }, + "required": ["color", "hex_color_code"], + "title": "ColorDetection", + "definitions": { + "Color": {"title": "Color", "description": "An enumeration.", "enum": ["red", "blue", "green"]} + }, + "type": "object", + "additionalProperties": False, + }, + } + ) From ad5ac9fc6222710bedca52016b2e7374d680c221 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 12 Aug 2024 08:48:17 +0100 Subject: [PATCH 461/816] fix(json schema): unravel `$ref`s alongside additional keys --- src/openai/lib/_pydantic.py | 73 ++++++++++++++++++++++++------ tests/lib/chat/test_completions.py | 50 +++++++++++++++++++- tests/lib/test_pydantic.py | 13 +++++- 3 files changed, 119 insertions(+), 17 deletions(-) diff --git a/src/openai/lib/_pydantic.py b/src/openai/lib/_pydantic.py index 85f147c236..ad3b6eb29f 100644 --- a/src/openai/lib/_pydantic.py +++ b/src/openai/lib/_pydantic.py @@ -10,12 +10,15 @@ def to_strict_json_schema(model: type[pydantic.BaseModel]) -> dict[str, Any]: - return _ensure_strict_json_schema(model_json_schema(model), path=()) + schema = model_json_schema(model) + return _ensure_strict_json_schema(schema, path=(), root=schema) def _ensure_strict_json_schema( json_schema: object, + *, path: tuple[str, ...], + root: dict[str, object], ) -> dict[str, Any]: """Mutates the given JSON schema to ensure it conforms to the `strict` standard that the API expects. @@ -23,6 +26,16 @@ def _ensure_strict_json_schema( if not is_dict(json_schema): raise TypeError(f"Expected {json_schema} to be a dictionary; path={path}") + defs = json_schema.get("$defs") + if is_dict(defs): + for def_name, def_schema in defs.items(): + _ensure_strict_json_schema(def_schema, path=(*path, "$defs", def_name), root=root) + + definitions = json_schema.get("definitions") + if is_dict(definitions): + for definition_name, definition_schema in definitions.items(): + _ensure_strict_json_schema(definition_schema, path=(*path, "definitions", definition_name), root=root) + typ = json_schema.get("type") if typ == "object" and "additionalProperties" not in json_schema: json_schema["additionalProperties"] = False @@ -33,7 +46,7 @@ def _ensure_strict_json_schema( if is_dict(properties): json_schema["required"] = [prop for prop in properties.keys()] json_schema["properties"] = { - key: _ensure_strict_json_schema(prop_schema, path=(*path, "properties", key)) + key: _ensure_strict_json_schema(prop_schema, path=(*path, "properties", key), root=root) for key, prop_schema in properties.items() } @@ -41,40 +54,72 @@ def _ensure_strict_json_schema( # { 'type': 'array', 'items': {...} } items = json_schema.get("items") if is_dict(items): - json_schema["items"] = _ensure_strict_json_schema(items, path=(*path, "items")) + json_schema["items"] = _ensure_strict_json_schema(items, path=(*path, "items"), root=root) # unions any_of = json_schema.get("anyOf") if is_list(any_of): json_schema["anyOf"] = [ - _ensure_strict_json_schema(variant, path=(*path, "anyOf", str(i))) for i, variant in enumerate(any_of) + _ensure_strict_json_schema(variant, path=(*path, "anyOf", str(i)), root=root) + for i, variant in enumerate(any_of) ] # intersections all_of = json_schema.get("allOf") if is_list(all_of): if len(all_of) == 1: - json_schema.update(_ensure_strict_json_schema(all_of[0], path=(*path, "allOf", "0"))) + json_schema.update(_ensure_strict_json_schema(all_of[0], path=(*path, "allOf", "0"), root=root)) json_schema.pop("allOf") else: json_schema["allOf"] = [ - _ensure_strict_json_schema(entry, path=(*path, "allOf", str(i))) for i, entry in enumerate(all_of) + _ensure_strict_json_schema(entry, path=(*path, "allOf", str(i)), root=root) + for i, entry in enumerate(all_of) ] - defs = json_schema.get("$defs") - if is_dict(defs): - for def_name, def_schema in defs.items(): - _ensure_strict_json_schema(def_schema, path=(*path, "$defs", def_name)) + # we can't use `$ref`s if there are also other properties defined, e.g. + # `{"$ref": "...", "description": "my description"}` + # + # so we unravel the ref + # `{"type": "string", "description": "my description"}` + ref = json_schema.get("$ref") + if ref and has_more_than_n_keys(json_schema, 1): + assert isinstance(ref, str), f"Received non-string $ref - {ref}" - definitions = json_schema.get("definitions") - if is_dict(definitions): - for definition_name, definition_schema in definitions.items(): - _ensure_strict_json_schema(definition_schema, path=(*path, "definitions", definition_name)) + resolved = resolve_ref(root=root, ref=ref) + if not is_dict(resolved): + raise ValueError(f"Expected `$ref: {ref}` to resolved to a dictionary but got {resolved}") + + # properties from the json schema take priority over the ones on the `$ref` + json_schema.update({**resolved, **json_schema}) + json_schema.pop("$ref") return json_schema +def resolve_ref(*, root: dict[str, object], ref: str) -> object: + if not ref.startswith("#/"): + raise ValueError(f"Unexpected $ref format {ref!r}; Does not start with #/") + + path = ref[2:].split("/") + resolved = root + for key in path: + value = resolved[key] + assert is_dict(value), f"encountered non-dictionary entry while resolving {ref} - {resolved}" + resolved = value + + return resolved + + def is_dict(obj: object) -> TypeGuard[dict[str, object]]: # just pretend that we know there are only `str` keys # as that check is not worth the performance cost return _is_dict(obj) + + +def has_more_than_n_keys(obj: dict[str, object], n: int) -> bool: + i = 0 + for _ in obj.keys(): + i += 1 + if i > n: + return True + return False diff --git a/tests/lib/chat/test_completions.py b/tests/lib/chat/test_completions.py index e406a5a3bc..d2189e7cb6 100644 --- a/tests/lib/chat/test_completions.py +++ b/tests/lib/chat/test_completions.py @@ -2,13 +2,14 @@ import os import json +from enum import Enum from typing import Any, Callable from typing_extensions import Literal, TypeVar import httpx import pytest from respx import MockRouter -from pydantic import BaseModel +from pydantic import Field, BaseModel from inline_snapshot import snapshot import openai @@ -133,6 +134,53 @@ class Location(BaseModel): ) +@pytest.mark.respx(base_url=base_url) +def test_parse_pydantic_model_enum(client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: + class Color(Enum): + """The detected color""" + + RED = "red" + BLUE = "blue" + GREEN = "green" + + class ColorDetection(BaseModel): + color: Color + hex_color_code: str = Field(description="The hex color code of the detected color") + + completion = _make_snapshot_request( + lambda c: c.beta.chat.completions.parse( + model="gpt-4o-2024-08-06", + messages=[ + {"role": "user", "content": "What color is a Coke can?"}, + ], + response_format=ColorDetection, + ), + content_snapshot=snapshot( + '{"id": "chatcmpl-9vK4UZVr385F2UgZlP1ShwPn2nFxG", "object": "chat.completion", "created": 1723448878, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"color\\":\\"red\\",\\"hex_color_code\\":\\"#FF0000\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 18, "completion_tokens": 14, "total_tokens": 32}, "system_fingerprint": "fp_845eaabc1f"}' + ), + mock_client=client, + respx_mock=respx_mock, + ) + + assert print_obj(completion.choices[0], monkeypatch) == snapshot( + """\ +ParsedChoice[ColorDetection]( + finish_reason='stop', + index=0, + logprobs=None, + message=ParsedChatCompletionMessage[ColorDetection]( + content='{"color":"red","hex_color_code":"#FF0000"}', + function_call=None, + parsed=ColorDetection(color=, hex_color_code='#FF0000'), + refusal=None, + role='assistant', + tool_calls=[] + ) +) +""" + ) + + @pytest.mark.respx(base_url=base_url) def test_parse_pydantic_model_multiple_choices( client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch diff --git a/tests/lib/test_pydantic.py b/tests/lib/test_pydantic.py index 568844eada..531a89df58 100644 --- a/tests/lib/test_pydantic.py +++ b/tests/lib/test_pydantic.py @@ -186,7 +186,12 @@ def test_enums() -> None: "parameters": { "$defs": {"Color": {"enum": ["red", "blue", "green"], "title": "Color", "type": "string"}}, "properties": { - "color": {"description": "The detected color", "$ref": "#/$defs/Color"}, + "color": { + "description": "The detected color", + "enum": ["red", "blue", "green"], + "title": "Color", + "type": "string", + }, "hex_color_code": { "description": "The hex color code of the detected color", "title": "Hex Color Code", @@ -207,7 +212,11 @@ def test_enums() -> None: "strict": True, "parameters": { "properties": { - "color": {"description": "The detected color", "$ref": "#/definitions/Color"}, + "color": { + "description": "The detected color", + "title": "Color", + "enum": ["red", "blue", "green"], + }, "hex_color_code": { "description": "The hex color code of the detected color", "title": "Hex Color Code", From 153e4a45edf2b01f86ea985519e03394e98f68de Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 12 Aug 2024 17:45:39 +0000 Subject: [PATCH 462/816] release: 1.40.4 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 9 +++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 64a418cb06..0c2e4f80a4 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.40.3" + ".": "1.40.4" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 825e753924..aaf31653a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 1.40.4 (2024-08-12) + +Full Changelog: [v1.40.3...v1.40.4](https://github.com/openai/openai-python/compare/v1.40.3...v1.40.4) + +### Bug Fixes + +* **json schema:** unravel `$ref`s alongside additional keys ([c7a3d29](https://github.com/openai/openai-python/commit/c7a3d2986acaf3b31844b39608d03265ad87bb04)) +* **json schema:** unwrap `allOf`s with one entry ([53d964d](https://github.com/openai/openai-python/commit/53d964defebdf385d7d832ec7f13111b4af13c27)) + ## 1.40.3 (2024-08-10) Full Changelog: [v1.40.2...v1.40.3](https://github.com/openai/openai-python/compare/v1.40.2...v1.40.3) diff --git a/pyproject.toml b/pyproject.toml index 09a11668a3..e7436330a5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.40.3" +version = "1.40.4" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 5eed512d7c..bbf4d8303c 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.40.3" # x-release-please-version +__version__ = "1.40.4" # x-release-please-version From b23980b0354b88a9f7a98bc9018406c3ce0dfa52 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 12 Aug 2024 14:38:38 -0400 Subject: [PATCH 463/816] docs(helpers): make async client usage more clear closes #1639 --- helpers.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/helpers.md b/helpers.md index 2e0d314b50..965dd6e23c 100644 --- a/helpers.md +++ b/helpers.md @@ -139,6 +139,10 @@ It also supports all aforementioned [parsing helpers](#parsing-helpers). Unlike `.create(stream=True)`, the `.stream()` method requires usage within a context manager to prevent accidental leakage of the response: ```py +from openai import AsyncOpenAI + +client = AsyncOpenAI() + async with client.beta.chat.completions.stream( model='gpt-4o-2024-08-06', messages=[...], From 22bbd4a092b5248a4a96a08750ca613117fc1a38 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 12 Aug 2024 18:39:04 +0000 Subject: [PATCH 464/816] release: 1.40.5 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 0c2e4f80a4..190c2adda3 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.40.4" + ".": "1.40.5" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index aaf31653a0..4ee946c4df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.40.5 (2024-08-12) + +Full Changelog: [v1.40.4...v1.40.5](https://github.com/openai/openai-python/compare/v1.40.4...v1.40.5) + +### Documentation + +* **helpers:** make async client usage more clear ([34e1edf](https://github.com/openai/openai-python/commit/34e1edf29d6008df7196aaebc45172fa536c6410)), closes [#1639](https://github.com/openai/openai-python/issues/1639) + ## 1.40.4 (2024-08-12) Full Changelog: [v1.40.3...v1.40.4](https://github.com/openai/openai-python/compare/v1.40.3...v1.40.4) diff --git a/pyproject.toml b/pyproject.toml index e7436330a5..1e094d14a6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.40.4" +version = "1.40.5" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index bbf4d8303c..d416db5cac 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.40.4" # x-release-please-version +__version__ = "1.40.5" # x-release-please-version From f1e1060ec8403a7ae56e3a9a1272842d858c60ff Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 12 Aug 2024 15:08:41 -0400 Subject: [PATCH 465/816] chore(tests): fix pydantic v1 tests --- tests/lib/chat/test_completions.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/lib/chat/test_completions.py b/tests/lib/chat/test_completions.py index d2189e7cb6..f003866653 100644 --- a/tests/lib/chat/test_completions.py +++ b/tests/lib/chat/test_completions.py @@ -15,6 +15,7 @@ import openai from openai import OpenAI, AsyncOpenAI from openai._utils import assert_signatures_in_sync +from openai._compat import PYDANTIC_V2 from ._utils import print_obj from ...conftest import base_url @@ -147,6 +148,9 @@ class ColorDetection(BaseModel): color: Color hex_color_code: str = Field(description="The hex color code of the detected color") + if not PYDANTIC_V2: + ColorDetection.update_forward_refs(**locals()) # type: ignore + completion = _make_snapshot_request( lambda c: c.beta.chat.completions.parse( model="gpt-4o-2024-08-06", From ab57d86d07daeab04ee122161f80e00b4b58e580 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 12 Aug 2024 19:21:15 +0000 Subject: [PATCH 466/816] chore(internal): update some imports (#1642) --- .../beta/assistant_response_format_option_param.py | 9 ++++----- src/openai/types/beta/function_tool_param.py | 4 ++-- src/openai/types/chat/chat_completion_tool_param.py | 4 ++-- src/openai/types/chat/completion_create_params.py | 11 ++++++----- src/openai/types/shared_params/function_definition.py | 4 ++-- 5 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/openai/types/beta/assistant_response_format_option_param.py b/src/openai/types/beta/assistant_response_format_option_param.py index 680a060c3c..5e724a4d98 100644 --- a/src/openai/types/beta/assistant_response_format_option_param.py +++ b/src/openai/types/beta/assistant_response_format_option_param.py @@ -5,13 +5,12 @@ from typing import Union from typing_extensions import Literal, TypeAlias -from ...types import shared_params +from ..shared_params.response_format_text import ResponseFormatText +from ..shared_params.response_format_json_object import ResponseFormatJSONObject +from ..shared_params.response_format_json_schema import ResponseFormatJSONSchema __all__ = ["AssistantResponseFormatOptionParam"] AssistantResponseFormatOptionParam: TypeAlias = Union[ - Literal["auto"], - shared_params.ResponseFormatText, - shared_params.ResponseFormatJSONObject, - shared_params.ResponseFormatJSONSchema, + Literal["auto"], ResponseFormatText, ResponseFormatJSONObject, ResponseFormatJSONSchema ] diff --git a/src/openai/types/beta/function_tool_param.py b/src/openai/types/beta/function_tool_param.py index b44c0d47ef..d906e02b88 100644 --- a/src/openai/types/beta/function_tool_param.py +++ b/src/openai/types/beta/function_tool_param.py @@ -4,13 +4,13 @@ from typing_extensions import Literal, Required, TypedDict -from ...types import shared_params +from ..shared_params.function_definition import FunctionDefinition __all__ = ["FunctionToolParam"] class FunctionToolParam(TypedDict, total=False): - function: Required[shared_params.FunctionDefinition] + function: Required[FunctionDefinition] type: Required[Literal["function"]] """The type of tool being defined: `function`""" diff --git a/src/openai/types/chat/chat_completion_tool_param.py b/src/openai/types/chat/chat_completion_tool_param.py index 0cf6ea7268..6c2b1a36f0 100644 --- a/src/openai/types/chat/chat_completion_tool_param.py +++ b/src/openai/types/chat/chat_completion_tool_param.py @@ -4,13 +4,13 @@ from typing_extensions import Literal, Required, TypedDict -from ...types import shared_params +from ..shared_params.function_definition import FunctionDefinition __all__ = ["ChatCompletionToolParam"] class ChatCompletionToolParam(TypedDict, total=False): - function: Required[shared_params.FunctionDefinition] + function: Required[FunctionDefinition] type: Required[Literal["function"]] """The type of the tool. Currently, only `function` is supported.""" diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 61126b37ac..91435dcedd 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -5,12 +5,15 @@ from typing import Dict, List, Union, Iterable, Optional from typing_extensions import Literal, Required, TypeAlias, TypedDict -from ...types import shared_params from ..chat_model import ChatModel from .chat_completion_tool_param import ChatCompletionToolParam from .chat_completion_message_param import ChatCompletionMessageParam +from ..shared_params.function_parameters import FunctionParameters +from ..shared_params.response_format_text import ResponseFormatText from .chat_completion_stream_options_param import ChatCompletionStreamOptionsParam from .chat_completion_tool_choice_option_param import ChatCompletionToolChoiceOptionParam +from ..shared_params.response_format_json_object import ResponseFormatJSONObject +from ..shared_params.response_format_json_schema import ResponseFormatJSONSchema from .chat_completion_function_call_option_param import ChatCompletionFunctionCallOptionParam __all__ = [ @@ -244,7 +247,7 @@ class Function(TypedDict, total=False): how to call the function. """ - parameters: shared_params.FunctionParameters + parameters: FunctionParameters """The parameters the functions accepts, described as a JSON Schema object. See the [guide](https://platform.openai.com/docs/guides/function-calling) for @@ -256,9 +259,7 @@ class Function(TypedDict, total=False): """ -ResponseFormat: TypeAlias = Union[ - shared_params.ResponseFormatText, shared_params.ResponseFormatJSONObject, shared_params.ResponseFormatJSONSchema -] +ResponseFormat: TypeAlias = Union[ResponseFormatText, ResponseFormatJSONObject, ResponseFormatJSONSchema] class CompletionCreateParamsNonStreaming(CompletionCreateParamsBase): diff --git a/src/openai/types/shared_params/function_definition.py b/src/openai/types/shared_params/function_definition.py index f41392f154..d45ec13f1e 100644 --- a/src/openai/types/shared_params/function_definition.py +++ b/src/openai/types/shared_params/function_definition.py @@ -5,7 +5,7 @@ from typing import Optional from typing_extensions import Required, TypedDict -from ...types import shared_params +from .function_parameters import FunctionParameters __all__ = ["FunctionDefinition"] @@ -24,7 +24,7 @@ class FunctionDefinition(TypedDict, total=False): how to call the function. """ - parameters: shared_params.FunctionParameters + parameters: FunctionParameters """The parameters the functions accepts, described as a JSON Schema object. See the [guide](https://platform.openai.com/docs/guides/function-calling) for From 092a8df7a46878c11f4c4fdea0fbc80e8d96d669 Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Mon, 12 Aug 2024 19:52:09 +0000 Subject: [PATCH 467/816] chore(examples): minor formatting changes (#1644) --- tests/api_resources/beta/test_assistants.py | 4 +- tests/api_resources/beta/test_threads.py | 56 ++++++------ tests/api_resources/beta/threads/test_runs.py | 48 +++++----- tests/api_resources/chat/test_completions.py | 88 +++++++++---------- tests/api_resources/fine_tuning/test_jobs.py | 24 ++--- tests/api_resources/test_images.py | 12 +-- 6 files changed, 116 insertions(+), 116 deletions(-) diff --git a/tests/api_resources/beta/test_assistants.py b/tests/api_resources/beta/test_assistants.py index fbd5ff0597..642935cdaf 100644 --- a/tests/api_resources/beta/test_assistants.py +++ b/tests/api_resources/beta/test_assistants.py @@ -44,8 +44,8 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "vector_store_ids": ["string"], "vector_stores": [ { - "file_ids": ["string", "string", "string"], "chunking_strategy": {"type": "auto"}, + "file_ids": ["string", "string", "string"], "metadata": {}, } ], @@ -276,8 +276,8 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "vector_store_ids": ["string"], "vector_stores": [ { - "file_ids": ["string", "string", "string"], "chunking_strategy": {"type": "auto"}, + "file_ids": ["string", "string", "string"], "metadata": {}, } ], diff --git a/tests/api_resources/beta/test_threads.py b/tests/api_resources/beta/test_threads.py index 67fff736dd..95bebd84f5 100644 --- a/tests/api_resources/beta/test_threads.py +++ b/tests/api_resources/beta/test_threads.py @@ -31,8 +31,8 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: thread = client.beta.threads.create( messages=[ { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -62,8 +62,8 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "metadata": {}, }, { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -93,8 +93,8 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "metadata": {}, }, { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -131,8 +131,8 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "vector_store_ids": ["string"], "vector_stores": [ { - "file_ids": ["string", "string", "string"], "chunking_strategy": {"type": "auto"}, + "file_ids": ["string", "string", "string"], "metadata": {}, } ], @@ -310,8 +310,8 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) thread={ "messages": [ { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -341,8 +341,8 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) "metadata": {}, }, { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -372,8 +372,8 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) "metadata": {}, }, { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -403,20 +403,20 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) "metadata": {}, }, ], + "metadata": {}, "tool_resources": { "code_interpreter": {"file_ids": ["string", "string", "string"]}, "file_search": { "vector_store_ids": ["string"], "vector_stores": [ { - "file_ids": ["string", "string", "string"], "chunking_strategy": {"type": "auto"}, + "file_ids": ["string", "string", "string"], "metadata": {}, } ], }, }, - "metadata": {}, }, tool_choice="none", tool_resources={ @@ -480,8 +480,8 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) thread={ "messages": [ { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -511,8 +511,8 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) "metadata": {}, }, { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -542,8 +542,8 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) "metadata": {}, }, { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -573,20 +573,20 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) "metadata": {}, }, ], + "metadata": {}, "tool_resources": { "code_interpreter": {"file_ids": ["string", "string", "string"]}, "file_search": { "vector_store_ids": ["string"], "vector_stores": [ { - "file_ids": ["string", "string", "string"], "chunking_strategy": {"type": "auto"}, + "file_ids": ["string", "string", "string"], "metadata": {}, } ], }, }, - "metadata": {}, }, tool_choice="none", tool_resources={ @@ -641,8 +641,8 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> thread = await async_client.beta.threads.create( messages=[ { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -672,8 +672,8 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "metadata": {}, }, { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -703,8 +703,8 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "metadata": {}, }, { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -741,8 +741,8 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "vector_store_ids": ["string"], "vector_stores": [ { - "file_ids": ["string", "string", "string"], "chunking_strategy": {"type": "auto"}, + "file_ids": ["string", "string", "string"], "metadata": {}, } ], @@ -920,8 +920,8 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie thread={ "messages": [ { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -951,8 +951,8 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie "metadata": {}, }, { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -982,8 +982,8 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie "metadata": {}, }, { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -1013,20 +1013,20 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie "metadata": {}, }, ], + "metadata": {}, "tool_resources": { "code_interpreter": {"file_ids": ["string", "string", "string"]}, "file_search": { "vector_store_ids": ["string"], "vector_stores": [ { - "file_ids": ["string", "string", "string"], "chunking_strategy": {"type": "auto"}, + "file_ids": ["string", "string", "string"], "metadata": {}, } ], }, }, - "metadata": {}, }, tool_choice="none", tool_resources={ @@ -1090,8 +1090,8 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie thread={ "messages": [ { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -1121,8 +1121,8 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie "metadata": {}, }, { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -1152,8 +1152,8 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie "metadata": {}, }, { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -1183,20 +1183,20 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie "metadata": {}, }, ], + "metadata": {}, "tool_resources": { "code_interpreter": {"file_ids": ["string", "string", "string"]}, "file_search": { "vector_store_ids": ["string"], "vector_stores": [ { - "file_ids": ["string", "string", "string"], "chunking_strategy": {"type": "auto"}, + "file_ids": ["string", "string", "string"], "metadata": {}, } ], }, }, - "metadata": {}, }, tool_choice="none", tool_resources={ diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index e21c6c2c77..5d16bdb364 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -38,8 +38,8 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: additional_instructions="string", additional_messages=[ { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -69,8 +69,8 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: "metadata": {}, }, { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -100,8 +100,8 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: "metadata": {}, }, { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -202,8 +202,8 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: additional_instructions="string", additional_messages=[ { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -233,8 +233,8 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: "metadata": {}, }, { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -264,8 +264,8 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: "metadata": {}, }, { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -567,16 +567,16 @@ def test_method_submit_tool_outputs_with_all_params_overload_1(self, client: Ope thread_id="string", tool_outputs=[ { - "tool_call_id": "string", - "output": "string", + "output": "output", + "tool_call_id": "tool_call_id", }, { - "tool_call_id": "string", - "output": "string", + "output": "output", + "tool_call_id": "tool_call_id", }, { - "tool_call_id": "string", - "output": "string", + "output": "output", + "tool_call_id": "tool_call_id", }, ], stream=False, @@ -704,8 +704,8 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn additional_instructions="string", additional_messages=[ { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -735,8 +735,8 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn "metadata": {}, }, { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -766,8 +766,8 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn "metadata": {}, }, { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -868,8 +868,8 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn additional_instructions="string", additional_messages=[ { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -899,8 +899,8 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn "metadata": {}, }, { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -930,8 +930,8 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn "metadata": {}, }, { - "role": "user", "content": "string", + "role": "user", "attachments": [ { "file_id": "string", @@ -1233,16 +1233,16 @@ async def test_method_submit_tool_outputs_with_all_params_overload_1(self, async thread_id="string", tool_outputs=[ { - "tool_call_id": "string", - "output": "string", + "output": "output", + "tool_call_id": "tool_call_id", }, { - "tool_call_id": "string", - "output": "string", + "output": "output", + "tool_call_id": "tool_call_id", }, { - "tool_call_id": "string", - "output": "string", + "output": "output", + "tool_call_id": "tool_call_id", }, ], stream=False, diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index 9fa3cc8284..0b89fbf9cd 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -48,8 +48,8 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: function_call="none", functions=[ { - "description": "string", - "name": "string", + "name": "name", + "description": "description", "parameters": {"foo": "bar"}, } ], @@ -69,31 +69,31 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: tool_choice="none", tools=[ { - "type": "function", "function": { - "description": "string", - "name": "string", + "name": "name", + "description": "description", "parameters": {"foo": "bar"}, "strict": True, }, + "type": "function", }, { - "type": "function", "function": { - "description": "string", - "name": "string", + "name": "name", + "description": "description", "parameters": {"foo": "bar"}, "strict": True, }, + "type": "function", }, { - "type": "function", "function": { - "description": "string", - "name": "string", + "name": "name", + "description": "description", "parameters": {"foo": "bar"}, "strict": True, }, + "type": "function", }, ], top_logprobs=0, @@ -168,8 +168,8 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: function_call="none", functions=[ { - "description": "string", - "name": "string", + "name": "name", + "description": "description", "parameters": {"foo": "bar"}, } ], @@ -188,31 +188,31 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: tool_choice="none", tools=[ { - "type": "function", "function": { - "description": "string", - "name": "string", + "name": "name", + "description": "description", "parameters": {"foo": "bar"}, "strict": True, }, + "type": "function", }, { - "type": "function", "function": { - "description": "string", - "name": "string", + "name": "name", + "description": "description", "parameters": {"foo": "bar"}, "strict": True, }, + "type": "function", }, { - "type": "function", "function": { - "description": "string", - "name": "string", + "name": "name", + "description": "description", "parameters": {"foo": "bar"}, "strict": True, }, + "type": "function", }, ], top_logprobs=0, @@ -307,8 +307,8 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn function_call="none", functions=[ { - "description": "string", - "name": "string", + "name": "name", + "description": "description", "parameters": {"foo": "bar"}, } ], @@ -328,31 +328,31 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn tool_choice="none", tools=[ { - "type": "function", "function": { - "description": "string", - "name": "string", + "name": "name", + "description": "description", "parameters": {"foo": "bar"}, "strict": True, }, + "type": "function", }, { - "type": "function", "function": { - "description": "string", - "name": "string", + "name": "name", + "description": "description", "parameters": {"foo": "bar"}, "strict": True, }, + "type": "function", }, { - "type": "function", "function": { - "description": "string", - "name": "string", + "name": "name", + "description": "description", "parameters": {"foo": "bar"}, "strict": True, }, + "type": "function", }, ], top_logprobs=0, @@ -427,8 +427,8 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn function_call="none", functions=[ { - "description": "string", - "name": "string", + "name": "name", + "description": "description", "parameters": {"foo": "bar"}, } ], @@ -447,31 +447,31 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn tool_choice="none", tools=[ { - "type": "function", "function": { - "description": "string", - "name": "string", + "name": "name", + "description": "description", "parameters": {"foo": "bar"}, "strict": True, }, + "type": "function", }, { - "type": "function", "function": { - "description": "string", - "name": "string", + "name": "name", + "description": "description", "parameters": {"foo": "bar"}, "strict": True, }, + "type": "function", }, { - "type": "function", "function": { - "description": "string", - "name": "string", + "name": "name", + "description": "description", "parameters": {"foo": "bar"}, "strict": True, }, + "type": "function", }, ], top_logprobs=0, diff --git a/tests/api_resources/fine_tuning/test_jobs.py b/tests/api_resources/fine_tuning/test_jobs.py index 68b3d73ac5..d1ad611219 100644 --- a/tests/api_resources/fine_tuning/test_jobs.py +++ b/tests/api_resources/fine_tuning/test_jobs.py @@ -44,8 +44,8 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "type": "wandb", "wandb": { "project": "my-wandb-project", - "name": "string", - "entity": "string", + "entity": "entity", + "name": "name", "tags": ["custom-tag", "custom-tag", "custom-tag"], }, }, @@ -53,8 +53,8 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "type": "wandb", "wandb": { "project": "my-wandb-project", - "name": "string", - "entity": "string", + "entity": "entity", + "name": "name", "tags": ["custom-tag", "custom-tag", "custom-tag"], }, }, @@ -62,8 +62,8 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "type": "wandb", "wandb": { "project": "my-wandb-project", - "name": "string", - "entity": "string", + "entity": "entity", + "name": "name", "tags": ["custom-tag", "custom-tag", "custom-tag"], }, }, @@ -283,8 +283,8 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "type": "wandb", "wandb": { "project": "my-wandb-project", - "name": "string", - "entity": "string", + "entity": "entity", + "name": "name", "tags": ["custom-tag", "custom-tag", "custom-tag"], }, }, @@ -292,8 +292,8 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "type": "wandb", "wandb": { "project": "my-wandb-project", - "name": "string", - "entity": "string", + "entity": "entity", + "name": "name", "tags": ["custom-tag", "custom-tag", "custom-tag"], }, }, @@ -301,8 +301,8 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "type": "wandb", "wandb": { "project": "my-wandb-project", - "name": "string", - "entity": "string", + "entity": "entity", + "name": "name", "tags": ["custom-tag", "custom-tag", "custom-tag"], }, }, diff --git a/tests/api_resources/test_images.py b/tests/api_resources/test_images.py index 2e31f3354a..9bc9719bc5 100644 --- a/tests/api_resources/test_images.py +++ b/tests/api_resources/test_images.py @@ -31,7 +31,7 @@ def test_method_create_variation_with_all_params(self, client: OpenAI) -> None: model="dall-e-2", n=1, response_format="url", - size="1024x1024", + size="256x256", user="user-1234", ) assert_matches_type(ImagesResponse, image, path=["response"]) @@ -77,7 +77,7 @@ def test_method_edit_with_all_params(self, client: OpenAI) -> None: model="dall-e-2", n=1, response_format="url", - size="1024x1024", + size="256x256", user="user-1234", ) assert_matches_type(ImagesResponse, image, path=["response"]) @@ -123,7 +123,7 @@ def test_method_generate_with_all_params(self, client: OpenAI) -> None: n=1, quality="standard", response_format="url", - size="1024x1024", + size="256x256", style="vivid", user="user-1234", ) @@ -171,7 +171,7 @@ async def test_method_create_variation_with_all_params(self, async_client: Async model="dall-e-2", n=1, response_format="url", - size="1024x1024", + size="256x256", user="user-1234", ) assert_matches_type(ImagesResponse, image, path=["response"]) @@ -217,7 +217,7 @@ async def test_method_edit_with_all_params(self, async_client: AsyncOpenAI) -> N model="dall-e-2", n=1, response_format="url", - size="1024x1024", + size="256x256", user="user-1234", ) assert_matches_type(ImagesResponse, image, path=["response"]) @@ -263,7 +263,7 @@ async def test_method_generate_with_all_params(self, async_client: AsyncOpenAI) n=1, quality="standard", response_format="url", - size="1024x1024", + size="256x256", style="vivid", user="user-1234", ) From 32677356f371fa86635c5216e8207835d96e2f3c Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 12 Aug 2024 21:25:41 +0000 Subject: [PATCH 468/816] chore: sync openapi url (#1646) --- .stats.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index cad2c64cd0..2371b7b8d4 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-97797a9363b9960b5f2fbdc84426a2b91e75533ecd409fe99e37c231180a4339.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-285bce7dcdae7eea5fe84a8d6e5af2c1473d65ea193109370fb2257851eef7eb.yml From 40f4cdb52a7494472c32e26c70f54bb41bb2bb57 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 12 Aug 2024 21:26:09 +0000 Subject: [PATCH 469/816] release: 1.40.6 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 11 +++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 14 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 190c2adda3..ae6438060f 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.40.5" + ".": "1.40.6" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ee946c4df..7dd2a34ef9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## 1.40.6 (2024-08-12) + +Full Changelog: [v1.40.5...v1.40.6](https://github.com/openai/openai-python/compare/v1.40.5...v1.40.6) + +### Chores + +* **examples:** minor formatting changes ([#1644](https://github.com/openai/openai-python/issues/1644)) ([e08acf1](https://github.com/openai/openai-python/commit/e08acf1c6edd1501ed70c4634cd884ab1658af0d)) +* **internal:** update some imports ([#1642](https://github.com/openai/openai-python/issues/1642)) ([fce1ea7](https://github.com/openai/openai-python/commit/fce1ea72a89ba2737bc77775fe04f3a21ecb28e7)) +* sync openapi url ([#1646](https://github.com/openai/openai-python/issues/1646)) ([8ae3801](https://github.com/openai/openai-python/commit/8ae380123ada0bfaca9961e222a0e9c8b585e2d4)) +* **tests:** fix pydantic v1 tests ([2623630](https://github.com/openai/openai-python/commit/26236303f0f6de5df887e8ee3e41d5bc39a3abb1)) + ## 1.40.5 (2024-08-12) Full Changelog: [v1.40.4...v1.40.5](https://github.com/openai/openai-python/compare/v1.40.4...v1.40.5) diff --git a/pyproject.toml b/pyproject.toml index 1e094d14a6..a92be494cd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.40.5" +version = "1.40.6" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index d416db5cac..d4083f4a69 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.40.5" # x-release-please-version +__version__ = "1.40.6" # x-release-please-version From 64b859505e5f28cef355a92bf786857e9e169ead Mon Sep 17 00:00:00 2001 From: Morgante Pell Date: Wed, 14 Aug 2024 04:33:15 -0700 Subject: [PATCH 470/816] fix(cli/migrate): change grit binaries download source (#1649) --- src/openai/cli/_tools/migrate.py | 66 +++++++++++--------------------- 1 file changed, 23 insertions(+), 43 deletions(-) diff --git a/src/openai/cli/_tools/migrate.py b/src/openai/cli/_tools/migrate.py index 7c10bb7f85..7a0b0f90f6 100644 --- a/src/openai/cli/_tools/migrate.py +++ b/src/openai/cli/_tools/migrate.py @@ -2,7 +2,6 @@ import os import sys -import json import shutil import tarfile import platform @@ -85,7 +84,9 @@ def install() -> Path: if sys.platform == "win32": raise CLIError("Windows is not supported yet in the migration CLI") - platform = "macos" if sys.platform == "darwin" else "linux" + _debug("Using Grit installer from GitHub") + + platform = "apple-darwin" if sys.platform == "darwin" else "unknown-linux-gnu" dir_name = _cache_dir() / "openai-python" install_dir = dir_name / ".install" @@ -109,27 +110,14 @@ def install() -> Path: arch = _get_arch() _debug(f"Using architecture {arch}") - file_name = f"marzano-{platform}-{arch}" - meta_url = f"https://api.keygen.sh/v1/accounts/%7BKEYGEN_ACCOUNT%7D/artifacts/%7Bfile_name%7D" + file_name = f"marzano-{arch}-{platform}" + download_url = f"https://github.com/getgrit/gritql/releases/latest/download/%7Bfile_name%7D.tar.gz" - sys.stdout.write(f"Retrieving Grit CLI metadata from {meta_url}\n") + sys.stdout.write(f"Downloading Grit CLI from {download_url}\n") with httpx.Client() as client: - response = client.get(meta_url) # pyright: ignore[reportUnknownMemberType] - - data = response.json() - errors = data.get("errors") - if errors: - for error in errors: - sys.stdout.write(f"{error}\n") - - raise CLIError("Could not locate Grit CLI binary - see above errors") - - write_manifest(install_dir, data["data"]["relationships"]["release"]["data"]["id"]) - - link = data["data"]["links"]["redirect"] - _debug(f"Redirect URL {link}") - - download_response = client.get(link) # pyright: ignore[reportUnknownMemberType] + download_response = client.get(download_url, follow_redirects=True) + if download_response.status_code != 200: + raise CLIError(f"Failed to download Grit CLI from {download_url}") with open(temp_file, "wb") as file: for chunk in download_response.iter_bytes(): file.write(chunk) @@ -143,8 +131,7 @@ def install() -> Path: else: archive.extractall(unpacked_dir) - for item in unpacked_dir.iterdir(): - item.rename(target_dir / item.name) + _move_files_recursively(unpacked_dir, target_dir) shutil.rmtree(unpacked_dir) os.remove(temp_file) @@ -155,30 +142,23 @@ def install() -> Path: return target_path +def _move_files_recursively(source_dir: Path, target_dir: Path) -> None: + for item in source_dir.iterdir(): + if item.is_file(): + item.rename(target_dir / item.name) + elif item.is_dir(): + _move_files_recursively(item, target_dir) + + def _get_arch() -> str: architecture = platform.machine().lower() - # Map the architecture names to Node.js equivalents + # Map the architecture names to Grit equivalents arch_map = { - "x86_64": "x64", - "amd64": "x64", - "armv7l": "arm", - "aarch64": "arm64", + "x86_64": "x86_64", + "amd64": "x86_64", + "armv7l": "aarch64", + "arm64": "aarch64", } return arch_map.get(architecture, architecture) - - -def write_manifest(install_path: Path, release: str) -> None: - manifest = { - "installPath": str(install_path), - "binaries": { - "marzano": { - "name": "marzano", - "release": release, - }, - }, - } - manifest_path = Path(install_path) / "manifests.json" - with open(manifest_path, "w") as f: - json.dump(manifest, f, indent=2) From c58a0a4bc4d9a70d40625110182216e557ccdff9 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Wed, 14 Aug 2024 13:10:09 -0400 Subject: [PATCH 471/816] chore(docs): fix typo in example snippet --- src/openai/resources/beta/chat/completions.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/openai/resources/beta/chat/completions.py b/src/openai/resources/beta/chat/completions.py index aee88c3c0f..07eda27b76 100644 --- a/src/openai/resources/beta/chat/completions.py +++ b/src/openai/resources/beta/chat/completions.py @@ -192,7 +192,7 @@ def stream( ) as stream: for event in stream: if event.type == "content.delta": - print(event.content, flush=True, end="") + print(event.delta, flush=True, end="") ``` When the context manager is entered, a `ChatCompletionStream` instance is returned which, like `.create(stream=True)` is an iterator. The full list of events that are yielded by the iterator are outlined in [these docs](https://github.com/openai/openai-python/blob/main/helpers.md#chat-completions-events). @@ -404,7 +404,7 @@ def stream( ) as stream: async for event in stream: if event.type == "content.delta": - print(event.content, flush=True, end="") + print(event.delta, flush=True, end="") ``` When the context manager is entered, an `AsyncChatCompletionStream` instance is returned which, like `.create(stream=True)` is an async iterator. The full list of events that are yielded by the iterator are outlined in [these docs](https://github.com/openai/openai-python/blob/main/helpers.md#chat-completions-events). From cd8c3a3d2129da28188c9c71cd77964287f18803 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 15 Aug 2024 20:19:37 +0000 Subject: [PATCH 472/816] chore(internal): use different 32bit detection method (#1652) --- src/openai/_base_client.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 3388d69fab..f374449dbc 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -1,5 +1,6 @@ from __future__ import annotations +import sys import json import time import uuid @@ -2012,7 +2013,6 @@ def get_python_version() -> str: def get_architecture() -> Arch: try: - python_bitness, _ = platform.architecture() machine = platform.machine().lower() except Exception: return "unknown" @@ -2028,7 +2028,7 @@ def get_architecture() -> Arch: return "x64" # TODO: untested - if python_bitness == "32bit": + if sys.maxsize <= 2**32: return "x32" if machine: From 3bf03f2f7ee1a9e214484524000774532d02cba7 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 15 Aug 2024 20:20:06 +0000 Subject: [PATCH 473/816] release: 1.40.7 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 14 ++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 17 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index ae6438060f..8e6933f44e 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.40.6" + ".": "1.40.7" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 7dd2a34ef9..dc07303148 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,19 @@ # Changelog +## 1.40.7 (2024-08-15) + +Full Changelog: [v1.40.6...v1.40.7](https://github.com/openai/openai-python/compare/v1.40.6...v1.40.7) + +### Bug Fixes + +* **cli/migrate:** change grit binaries download source ([#1649](https://github.com/openai/openai-python/issues/1649)) ([85e8935](https://github.com/openai/openai-python/commit/85e8935d9a123b92964d39a98334a975a06ab845)) + + +### Chores + +* **docs:** fix typo in example snippet ([4e83b57](https://github.com/openai/openai-python/commit/4e83b57ffbb64e1c98c19968557dc68a0b65d0b3)) +* **internal:** use different 32bit detection method ([#1652](https://github.com/openai/openai-python/issues/1652)) ([5831af6](https://github.com/openai/openai-python/commit/5831af65048af2a5df9e3ea4a48b8fff2e66dd8c)) + ## 1.40.6 (2024-08-12) Full Changelog: [v1.40.5...v1.40.6](https://github.com/openai/openai-python/compare/v1.40.5...v1.40.6) diff --git a/pyproject.toml b/pyproject.toml index a92be494cd..4ea6ceb539 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.40.6" +version = "1.40.7" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index d4083f4a69..bae8a44c96 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.40.6" # x-release-please-version +__version__ = "1.40.7" # x-release-please-version From 05f0132fb81580e94ca22baf68a804d635248815 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 15 Aug 2024 21:59:01 +0000 Subject: [PATCH 474/816] chore(types): define FilePurpose enum (#1653) --- .stats.yml | 2 +- api.md | 2 +- src/openai/resources/files.py | 8 ++++---- src/openai/resources/uploads/uploads.py | 8 ++++---- src/openai/types/__init__.py | 1 + src/openai/types/file_create_params.py | 5 +++-- src/openai/types/file_purpose.py | 7 +++++++ src/openai/types/upload_create_params.py | 6 ++++-- 8 files changed, 25 insertions(+), 14 deletions(-) create mode 100644 src/openai/types/file_purpose.py diff --git a/.stats.yml b/.stats.yml index 2371b7b8d4..185585b675 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-285bce7dcdae7eea5fe84a8d6e5af2c1473d65ea193109370fb2257851eef7eb.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-8ff62fa1091460d68fbd36d72c17d91b709917bebf2983c9c4de5784bc384a2e.yml diff --git a/api.md b/api.md index 1687476d86..648d0f3708 100644 --- a/api.md +++ b/api.md @@ -82,7 +82,7 @@ Methods: Types: ```python -from openai.types import FileContent, FileDeleted, FileObject +from openai.types import FileContent, FileDeleted, FileObject, FilePurpose ``` Methods: diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index 75c971a8bc..a240e1d886 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -5,12 +5,11 @@ import time import typing_extensions from typing import Mapping, cast -from typing_extensions import Literal import httpx from .. import _legacy_response -from ..types import file_list_params, file_create_params +from ..types import FilePurpose, file_list_params, file_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from .._utils import ( extract_files, @@ -35,6 +34,7 @@ ) from ..types.file_object import FileObject from ..types.file_deleted import FileDeleted +from ..types.file_purpose import FilePurpose __all__ = ["Files", "AsyncFiles"] @@ -52,7 +52,7 @@ def create( self, *, file: FileTypes, - purpose: Literal["assistants", "batch", "fine-tune", "vision"], + purpose: FilePurpose, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -334,7 +334,7 @@ async def create( self, *, file: FileTypes, - purpose: Literal["assistants", "batch", "fine-tune", "vision"], + purpose: FilePurpose, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, diff --git a/src/openai/resources/uploads/uploads.py b/src/openai/resources/uploads/uploads.py index 4100423d3e..3590a3843f 100644 --- a/src/openai/resources/uploads/uploads.py +++ b/src/openai/resources/uploads/uploads.py @@ -3,7 +3,6 @@ from __future__ import annotations from typing import List -from typing_extensions import Literal import httpx @@ -16,7 +15,7 @@ PartsWithStreamingResponse, AsyncPartsWithStreamingResponse, ) -from ...types import upload_create_params, upload_complete_params +from ...types import FilePurpose, upload_create_params, upload_complete_params from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ..._utils import ( maybe_transform, @@ -27,6 +26,7 @@ from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ..._base_client import make_request_options from ...types.upload import Upload +from ...types.file_purpose import FilePurpose __all__ = ["Uploads", "AsyncUploads"] @@ -50,7 +50,7 @@ def create( bytes: int, filename: str, mime_type: str, - purpose: Literal["assistants", "batch", "fine-tune", "vision"], + purpose: FilePurpose, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -233,7 +233,7 @@ async def create( bytes: int, filename: str, mime_type: str, - purpose: Literal["assistants", "batch", "fine-tune", "vision"], + purpose: FilePurpose, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index f621fb67c5..ad9284fbd5 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -24,6 +24,7 @@ from .image_model import ImageModel as ImageModel from .file_content import FileContent as FileContent from .file_deleted import FileDeleted as FileDeleted +from .file_purpose import FilePurpose as FilePurpose from .model_deleted import ModelDeleted as ModelDeleted from .images_response import ImagesResponse as ImagesResponse from .completion_usage import CompletionUsage as CompletionUsage diff --git a/src/openai/types/file_create_params.py b/src/openai/types/file_create_params.py index 8b1c296f39..ecf7503358 100644 --- a/src/openai/types/file_create_params.py +++ b/src/openai/types/file_create_params.py @@ -2,9 +2,10 @@ from __future__ import annotations -from typing_extensions import Literal, Required, TypedDict +from typing_extensions import Required, TypedDict from .._types import FileTypes +from .file_purpose import FilePurpose __all__ = ["FileCreateParams"] @@ -13,7 +14,7 @@ class FileCreateParams(TypedDict, total=False): file: Required[FileTypes] """The File object (not file name) to be uploaded.""" - purpose: Required[Literal["assistants", "batch", "fine-tune", "vision"]] + purpose: Required[FilePurpose] """The intended purpose of the uploaded file. Use "assistants" for diff --git a/src/openai/types/file_purpose.py b/src/openai/types/file_purpose.py new file mode 100644 index 0000000000..32dc352c62 --- /dev/null +++ b/src/openai/types/file_purpose.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["FilePurpose"] + +FilePurpose: TypeAlias = Literal["assistants", "batch", "fine-tune", "vision"] diff --git a/src/openai/types/upload_create_params.py b/src/openai/types/upload_create_params.py index 3165ebcc7a..2ebabe6c66 100644 --- a/src/openai/types/upload_create_params.py +++ b/src/openai/types/upload_create_params.py @@ -2,7 +2,9 @@ from __future__ import annotations -from typing_extensions import Literal, Required, TypedDict +from typing_extensions import Required, TypedDict + +from .file_purpose import FilePurpose __all__ = ["UploadCreateParams"] @@ -21,7 +23,7 @@ class UploadCreateParams(TypedDict, total=False): supported MIME types for assistants and vision. """ - purpose: Required[Literal["assistants", "batch", "fine-tune", "vision"]] + purpose: Required[FilePurpose] """The intended purpose of the uploaded file. See the From b143c164678ad7579161448846ce67be62e7f21f Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 15 Aug 2024 21:59:28 +0000 Subject: [PATCH 475/816] release: 1.40.8 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 8e6933f44e..5d3167d511 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.40.7" + ".": "1.40.8" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index dc07303148..28fdd36aa6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.40.8 (2024-08-15) + +Full Changelog: [v1.40.7...v1.40.8](https://github.com/openai/openai-python/compare/v1.40.7...v1.40.8) + +### Chores + +* **types:** define FilePurpose enum ([#1653](https://github.com/openai/openai-python/issues/1653)) ([3c2eeae](https://github.com/openai/openai-python/commit/3c2eeae32adf5d4ab6bc622be6f9a95a1a298dd3)) + ## 1.40.7 (2024-08-15) Full Changelog: [v1.40.6...v1.40.7](https://github.com/openai/openai-python/compare/v1.40.6...v1.40.7) diff --git a/pyproject.toml b/pyproject.toml index 4ea6ceb539..388d63cc09 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.40.7" +version = "1.40.8" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index bae8a44c96..4c087bdf11 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.40.7" # x-release-please-version +__version__ = "1.40.8" # x-release-please-version From 3bbb271927811194d3b17a4f9968b7fff2d79861 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Thu, 18 Jul 2024 13:56:56 +0100 Subject: [PATCH 476/816] feat(client): add uploads.upload_file helper --- examples/generate_file.sh | 10 ++ examples/uploads.py | 46 +++++ src/openai/resources/uploads/uploads.py | 225 +++++++++++++++++++++++- 3 files changed, 279 insertions(+), 2 deletions(-) create mode 100644 examples/generate_file.sh create mode 100644 examples/uploads.py diff --git a/examples/generate_file.sh b/examples/generate_file.sh new file mode 100644 index 0000000000..ff07d096be --- /dev/null +++ b/examples/generate_file.sh @@ -0,0 +1,10 @@ +# generate a text file with random data for testing file uploads +wanted_size=$((1024*2048*512)) +file_size=$(( ((wanted_size/12)+1)*12 )) +read_size=$((file_size*3/4)) + +echo "wanted=$wanted_size file=$file_size read=$read_size" + +dd if=/dev/urandom bs=$read_size count=1 | base64 > /tmp/small_test_file.txt + +truncate -s "$wanted_size" /tmp/big_test_file.txt diff --git a/examples/uploads.py b/examples/uploads.py new file mode 100644 index 0000000000..c3896b365b --- /dev/null +++ b/examples/uploads.py @@ -0,0 +1,46 @@ +import sys +from pathlib import Path + +import rich + +from openai import OpenAI + +# generate this file using `./generate_file.sh` +file = Path("/tmp/big_test_file.txt") + +client = OpenAI() + + +def from_disk() -> None: + print("uploading file from disk") + + upload = client.uploads.upload_file_chunked( + file=file, + mime_type="txt", + purpose="batch", + ) + rich.print(upload) + + +def from_in_memory() -> None: + print("uploading file from memory") + + # read the data into memory ourselves to simulate + # it coming from somewhere else + data = file.read_bytes() + filename = "my_file.txt" + + upload = client.uploads.upload_file_chunked( + file=data, + filename=filename, + bytes=len(data), + mime_type="txt", + purpose="batch", + ) + rich.print(upload) + + +if "memory" in sys.argv: + from_in_memory() +else: + from_disk() diff --git a/src/openai/resources/uploads/uploads.py b/src/openai/resources/uploads/uploads.py index 3590a3843f..5eecef4d4b 100644 --- a/src/openai/resources/uploads/uploads.py +++ b/src/openai/resources/uploads/uploads.py @@ -2,8 +2,14 @@ from __future__ import annotations -from typing import List - +import io +import os +import logging +import builtins +from typing import List, overload +from pathlib import Path + +import anyio import httpx from ... import _legacy_response @@ -31,6 +37,12 @@ __all__ = ["Uploads", "AsyncUploads"] +# 64MB +DEFAULT_PART_SIZE = 64 * 1024 * 1024 + +log: logging.Logger = logging.getLogger(__name__) + + class Uploads(SyncAPIResource): @cached_property def parts(self) -> Parts: @@ -44,6 +56,105 @@ def with_raw_response(self) -> UploadsWithRawResponse: def with_streaming_response(self) -> UploadsWithStreamingResponse: return UploadsWithStreamingResponse(self) + @overload + def upload_file_chunked( + self, + *, + file: os.PathLike[str], + mime_type: str, + purpose: FilePurpose, + bytes: int | None = None, + part_size: int | None = None, + md5: str | NotGiven = NOT_GIVEN, + ) -> Upload: + """Splits a file into multiple 64MB parts and uploads them sequentially.""" + + @overload + def upload_file_chunked( + self, + *, + file: bytes, + filename: str, + bytes: int, + mime_type: str, + purpose: FilePurpose, + part_size: int | None = None, + md5: str | NotGiven = NOT_GIVEN, + ) -> Upload: + """Splits an in-memory file into multiple 64MB parts and uploads them sequentially.""" + + def upload_file_chunked( + self, + *, + file: os.PathLike[str] | bytes, + mime_type: str, + purpose: FilePurpose, + filename: str | None = None, + bytes: int | None = None, + part_size: int | None = None, + md5: str | NotGiven = NOT_GIVEN, + ) -> Upload: + """Splits the given file into multiple parts and uploads them sequentially. + + ```py + from pathlib import Path + + client.uploads.upload_file( + file=Path("my-paper.pdf"), + mime_type="pdf", + purpose="assistants", + ) + ``` + """ + if isinstance(file, builtins.bytes): + if filename is None: + raise TypeError("The `filename` argument must be given for in-memory files") + + if bytes is None: + raise TypeError("The `bytes` argument must be given for in-memory files") + else: + if not isinstance(file, Path): + file = Path(file) + + if not filename: + filename = file.name + + if bytes is None: + bytes = file.stat().st_size + + upload = self.create( + bytes=bytes, + filename=filename, + mime_type=mime_type, + purpose=purpose, + ) + + part_ids: list[str] = [] + + if part_size is None: + part_size = DEFAULT_PART_SIZE + + if isinstance(file, builtins.bytes): + buf: io.FileIO | io.BytesIO = io.BytesIO(file) + else: + buf = io.FileIO(file) + + try: + while True: + data = buf.read(part_size) + if not data: + # EOF + break + + part = self.parts.create(upload_id=upload.id, data=data) + log.info("Uploaded part %s for upload %s", part.id, upload.id) + part_ids.append(part.id) + except Exception: + buf.close() + raise + + return self.complete(upload_id=upload.id, part_ids=part_ids, md5=md5) + def create( self, *, @@ -227,6 +338,116 @@ def with_raw_response(self) -> AsyncUploadsWithRawResponse: def with_streaming_response(self) -> AsyncUploadsWithStreamingResponse: return AsyncUploadsWithStreamingResponse(self) + @overload + async def upload_file_chunked( + self, + *, + file: os.PathLike[str], + mime_type: str, + purpose: FilePurpose, + bytes: int | None = None, + part_size: int | None = None, + md5: str | NotGiven = NOT_GIVEN, + ) -> Upload: + """Splits a file into multiple 64MB parts and uploads them sequentially.""" + + @overload + async def upload_file_chunked( + self, + *, + file: bytes, + filename: str, + bytes: int, + mime_type: str, + purpose: FilePurpose, + part_size: int | None = None, + md5: str | NotGiven = NOT_GIVEN, + ) -> Upload: + """Splits an in-memory file into multiple 64MB parts and uploads them sequentially.""" + + async def upload_file_chunked( + self, + *, + file: os.PathLike[str] | bytes, + mime_type: str, + purpose: FilePurpose, + filename: str | None = None, + bytes: int | None = None, + part_size: int | None = None, + md5: str | NotGiven = NOT_GIVEN, + ) -> Upload: + """Splits the given file into multiple parts and uploads them sequentially. + + ```py + from pathlib import Path + + client.uploads.upload_file( + file=Path("my-paper.pdf"), + mime_type="pdf", + purpose="assistants", + ) + ``` + """ + if isinstance(file, builtins.bytes): + if filename is None: + raise TypeError("The `filename` argument must be given for in-memory files") + + if bytes is None: + raise TypeError("The `bytes` argument must be given for in-memory files") + else: + if not isinstance(file, anyio.Path): + file = anyio.Path(file) + + if not filename: + filename = file.name + + if bytes is None: + stat = await file.stat() + bytes = stat.st_size + + upload = await self.create( + bytes=bytes, + filename=filename, + mime_type=mime_type, + purpose=purpose, + ) + + part_ids: list[str] = [] + + if part_size is None: + part_size = DEFAULT_PART_SIZE + + if isinstance(file, anyio.Path): + fd = await file.open("rb") + async with fd: + while True: + data = await fd.read(part_size) + if not data: + # EOF + break + + part = await self.parts.create(upload_id=upload.id, data=data) + log.info("Uploaded part %s for upload %s", part.id, upload.id) + part_ids.append(part.id) + else: + buf = io.BytesIO(file) + + try: + while True: + data = buf.read(part_size) + if not data: + # EOF + break + + part = await self.parts.create(upload_id=upload.id, data=data) + log.info("Uploaded part %s for upload %s", part.id, upload.id) + part_ids.append(part.id) + except Exception: + buf.close() + raise + + return await self.complete(upload_id=upload.id, part_ids=part_ids, md5=md5) + async def create( self, *, From 798c6cb8032f4568d0b23f762d479d68be62ce3e Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 16 Aug 2024 20:44:45 +0000 Subject: [PATCH 477/816] release: 1.41.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 5d3167d511..4bce58a11b 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.40.8" + ".": "1.41.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 28fdd36aa6..cfcfdfe3eb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.41.0 (2024-08-16) + +Full Changelog: [v1.40.8...v1.41.0](https://github.com/openai/openai-python/compare/v1.40.8...v1.41.0) + +### Features + +* **client:** add uploads.upload_file helper ([aae079d](https://github.com/openai/openai-python/commit/aae079daa3c1763ab0e46bad766ae5261b475806)) + ## 1.40.8 (2024-08-15) Full Changelog: [v1.40.7...v1.40.8](https://github.com/openai/openai-python/compare/v1.40.7...v1.40.8) diff --git a/pyproject.toml b/pyproject.toml index 388d63cc09..052afada08 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.40.8" +version = "1.41.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 4c087bdf11..c44c93d3e9 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.40.8" # x-release-please-version +__version__ = "1.41.0" # x-release-please-version From 54156ad1a7d3f24ff66c43bffc5a6325904c6137 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 19 Aug 2024 17:22:47 -0400 Subject: [PATCH 478/816] fix(json schema): remove `None` defaults (#1663) --- src/openai/lib/_pydantic.py | 7 ++++ tests/lib/chat/test_completions.py | 60 +++++++++++++++++++++++++++++- tests/lib/schema_types/query.py | 3 +- tests/lib/test_pydantic.py | 6 ++- 4 files changed, 72 insertions(+), 4 deletions(-) diff --git a/src/openai/lib/_pydantic.py b/src/openai/lib/_pydantic.py index ad3b6eb29f..f989ce3ed0 100644 --- a/src/openai/lib/_pydantic.py +++ b/src/openai/lib/_pydantic.py @@ -5,6 +5,7 @@ import pydantic +from .._types import NOT_GIVEN from .._utils import is_dict as _is_dict, is_list from .._compat import model_json_schema @@ -76,6 +77,12 @@ def _ensure_strict_json_schema( for i, entry in enumerate(all_of) ] + # strip `None` defaults as there's no meaningful distinction here + # the schema will still be `nullable` and the model will default + # to using `None` anyway + if json_schema.get("default", NOT_GIVEN) is None: + json_schema.pop("default") + # we can't use `$ref`s if there are also other properties defined, e.g. # `{"$ref": "...", "description": "my description"}` # diff --git a/tests/lib/chat/test_completions.py b/tests/lib/chat/test_completions.py index f003866653..aea449b097 100644 --- a/tests/lib/chat/test_completions.py +++ b/tests/lib/chat/test_completions.py @@ -3,7 +3,7 @@ import os import json from enum import Enum -from typing import Any, Callable +from typing import Any, Callable, Optional from typing_extensions import Literal, TypeVar import httpx @@ -135,6 +135,63 @@ class Location(BaseModel): ) +@pytest.mark.respx(base_url=base_url) +def test_parse_pydantic_model_optional_default( + client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch +) -> None: + class Location(BaseModel): + city: str + temperature: float + units: Optional[Literal["c", "f"]] = None + + completion = _make_snapshot_request( + lambda c: c.beta.chat.completions.parse( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "user", + "content": "What's the weather like in SF?", + }, + ], + response_format=Location, + ), + content_snapshot=snapshot( + '{"id": "chatcmpl-9y39Q2jGzWmeEZlm5CoNVOuQzcxP4", "object": "chat.completion", "created": 1724098820, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"city\\":\\"San Francisco\\",\\"temperature\\":62,\\"units\\":\\"f\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 17, "completion_tokens": 14, "total_tokens": 31}, "system_fingerprint": "fp_2a322c9ffc"}' + ), + mock_client=client, + respx_mock=respx_mock, + ) + + assert print_obj(completion, monkeypatch) == snapshot( + """\ +ParsedChatCompletion[Location]( + choices=[ + ParsedChoice[Location]( + finish_reason='stop', + index=0, + logprobs=None, + message=ParsedChatCompletionMessage[Location]( + content='{"city":"San Francisco","temperature":62,"units":"f"}', + function_call=None, + parsed=Location(city='San Francisco', temperature=62.0, units='f'), + refusal=None, + role='assistant', + tool_calls=[] + ) + ) + ], + created=1724098820, + id='chatcmpl-9y39Q2jGzWmeEZlm5CoNVOuQzcxP4', + model='gpt-4o-2024-08-06', + object='chat.completion', + service_tier=None, + system_fingerprint='fp_2a322c9ffc', + usage=CompletionUsage(completion_tokens=14, prompt_tokens=17, total_tokens=31) +) +""" + ) + + @pytest.mark.respx(base_url=base_url) def test_parse_pydantic_model_enum(client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: class Color(Enum): @@ -320,6 +377,7 @@ def test_pydantic_tool_model_all_types(client: OpenAI, respx_mock: MockRouter, m value=DynamicValue(column_name='expected_delivery_date') ) ], + name=None, order_by=, table_name= ) diff --git a/tests/lib/schema_types/query.py b/tests/lib/schema_types/query.py index d2284424f0..03439fb17f 100644 --- a/tests/lib/schema_types/query.py +++ b/tests/lib/schema_types/query.py @@ -1,5 +1,5 @@ from enum import Enum -from typing import List, Union +from typing import List, Union, Optional from pydantic import BaseModel @@ -45,6 +45,7 @@ class Condition(BaseModel): class Query(BaseModel): + name: Optional[str] = None table_name: Table columns: List[Column] conditions: List[Condition] diff --git a/tests/lib/test_pydantic.py b/tests/lib/test_pydantic.py index 531a89df58..99b9e96d21 100644 --- a/tests/lib/test_pydantic.py +++ b/tests/lib/test_pydantic.py @@ -62,6 +62,7 @@ def test_most_types() -> None: "Table": {"enum": ["orders", "customers", "products"], "title": "Table", "type": "string"}, }, "properties": { + "name": {"anyOf": [{"type": "string"}, {"type": "null"}], "title": "Name"}, "table_name": {"$ref": "#/$defs/Table"}, "columns": { "items": {"$ref": "#/$defs/Column"}, @@ -75,7 +76,7 @@ def test_most_types() -> None: }, "order_by": {"$ref": "#/$defs/OrderBy"}, }, - "required": ["table_name", "columns", "conditions", "order_by"], + "required": ["name", "table_name", "columns", "conditions", "order_by"], "title": "Query", "type": "object", "additionalProperties": False, @@ -91,6 +92,7 @@ def test_most_types() -> None: "title": "Query", "type": "object", "properties": { + "name": {"title": "Name", "type": "string"}, "table_name": {"$ref": "#/definitions/Table"}, "columns": {"type": "array", "items": {"$ref": "#/definitions/Column"}}, "conditions": { @@ -100,7 +102,7 @@ def test_most_types() -> None: }, "order_by": {"$ref": "#/definitions/OrderBy"}, }, - "required": ["table_name", "columns", "conditions", "order_by"], + "required": ["name", "table_name", "columns", "conditions", "order_by"], "definitions": { "Table": { "title": "Table", From fb5e53efa9670aaaba7db40ce331417df05d049e Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 19 Aug 2024 21:25:16 +0000 Subject: [PATCH 479/816] chore(client): fix parsing union responses when non-json is returned (#1665) --- src/openai/_models.py | 2 ++ tests/test_legacy_response.py | 22 +++++++++++++++++++- tests/test_response.py | 39 ++++++++++++++++++++++++++++++++++- 3 files changed, 61 insertions(+), 2 deletions(-) diff --git a/src/openai/_models.py b/src/openai/_models.py index 5148d5a7b3..d386eaa3a4 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -380,6 +380,8 @@ def is_basemodel(type_: type) -> bool: def is_basemodel_type(type_: type) -> TypeGuard[type[BaseModel] | type[GenericModel]]: origin = get_origin(type_) or type_ + if not inspect.isclass(origin): + return False return issubclass(origin, BaseModel) or issubclass(origin, GenericModel) diff --git a/tests/test_legacy_response.py b/tests/test_legacy_response.py index 3659ee12c1..3c2df53e58 100644 --- a/tests/test_legacy_response.py +++ b/tests/test_legacy_response.py @@ -1,5 +1,5 @@ import json -from typing import cast +from typing import Any, Union, cast from typing_extensions import Annotated import httpx @@ -81,3 +81,23 @@ def test_response_parse_annotated_type(client: OpenAI) -> None: ) assert obj.foo == "hello!" assert obj.bar == 2 + + +class OtherModel(pydantic.BaseModel): + a: str + + +@pytest.mark.parametrize("client", [False], indirect=True) # loose validation +def test_response_parse_expect_model_union_non_json_content(client: OpenAI) -> None: + response = LegacyAPIResponse( + raw=httpx.Response(200, content=b"foo", headers={"Content-Type": "application/text"}), + client=client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + obj = response.parse(to=cast(Any, Union[CustomModel, OtherModel])) + assert isinstance(obj, str) + assert obj == "foo" diff --git a/tests/test_response.py b/tests/test_response.py index 6ea1be1a1a..b7d88bdbde 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -1,5 +1,5 @@ import json -from typing import List, cast +from typing import Any, List, Union, cast from typing_extensions import Annotated import httpx @@ -188,3 +188,40 @@ async def test_async_response_parse_annotated_type(async_client: AsyncOpenAI) -> ) assert obj.foo == "hello!" assert obj.bar == 2 + + +class OtherModel(BaseModel): + a: str + + +@pytest.mark.parametrize("client", [False], indirect=True) # loose validation +def test_response_parse_expect_model_union_non_json_content(client: OpenAI) -> None: + response = APIResponse( + raw=httpx.Response(200, content=b"foo", headers={"Content-Type": "application/text"}), + client=client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + obj = response.parse(to=cast(Any, Union[CustomModel, OtherModel])) + assert isinstance(obj, str) + assert obj == "foo" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("async_client", [False], indirect=True) # loose validation +async def test_async_response_parse_expect_model_union_non_json_content(async_client: AsyncOpenAI) -> None: + response = AsyncAPIResponse( + raw=httpx.Response(200, content=b"foo", headers={"Content-Type": "application/text"}), + client=async_client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + obj = await response.parse(to=cast(Any, Union[CustomModel, OtherModel])) + assert isinstance(obj, str) + assert obj == "foo" From 3d780f260a1d26ab612dde0f870db114a42273bd Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 19 Aug 2024 21:25:45 +0000 Subject: [PATCH 480/816] release: 1.41.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 4bce58a11b..5a1b26c33e 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.41.0" + ".": "1.41.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index cfcfdfe3eb..e80a4fcc8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.41.1 (2024-08-19) + +Full Changelog: [v1.41.0...v1.41.1](https://github.com/openai/openai-python/compare/v1.41.0...v1.41.1) + +### Bug Fixes + +* **json schema:** remove `None` defaults ([#1663](https://github.com/openai/openai-python/issues/1663)) ([30215c1](https://github.com/openai/openai-python/commit/30215c15df613cf9c36cafd717af79158c9db3e5)) + + +### Chores + +* **client:** fix parsing union responses when non-json is returned ([#1665](https://github.com/openai/openai-python/issues/1665)) ([822c37d](https://github.com/openai/openai-python/commit/822c37de49eb2ffe8c05122f7520ba87bd76e30b)) + ## 1.41.0 (2024-08-16) Full Changelog: [v1.40.8...v1.41.0](https://github.com/openai/openai-python/compare/v1.40.8...v1.41.0) diff --git a/pyproject.toml b/pyproject.toml index 052afada08..b6530b8523 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.41.0" +version = "1.41.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index c44c93d3e9..22ed2bff90 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.41.0" # x-release-please-version +__version__ = "1.41.1" # x-release-please-version From e8c28f2ec93063bf73c53e6c8d19bae935a135be Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 20 Aug 2024 01:49:10 +0000 Subject: [PATCH 481/816] chore(ci): also run pydantic v1 tests (#1666) --- scripts/test | 3 +++ 1 file changed, 3 insertions(+) diff --git a/scripts/test b/scripts/test index b3ace9013b..4fa5698b8f 100755 --- a/scripts/test +++ b/scripts/test @@ -54,3 +54,6 @@ fi echo "==> Running tests" rye run pytest "$@" + +echo "==> Running Pydantic v1 tests" +rye run nox -s test-pydantic-v1 -- "$@" From ecd6e922b540948c117b26380d63be4148699bf4 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Tue, 20 Aug 2024 11:09:41 -0400 Subject: [PATCH 482/816] feat(parsing): add support for pydantic dataclasses (#1655) --- src/openai/lib/_parsing/_completions.py | 28 ++++++++---- src/openai/lib/_pydantic.py | 26 +++++++++-- tests/lib/chat/test_completions.py | 59 ++++++++++++++++++++++++- 3 files changed, 99 insertions(+), 14 deletions(-) diff --git a/src/openai/lib/_parsing/_completions.py b/src/openai/lib/_parsing/_completions.py index f9d1d6b351..2ef1bf3553 100644 --- a/src/openai/lib/_parsing/_completions.py +++ b/src/openai/lib/_parsing/_completions.py @@ -9,9 +9,9 @@ from .._tools import PydanticFunctionTool from ..._types import NOT_GIVEN, NotGiven from ..._utils import is_dict, is_given -from ..._compat import model_parse_json +from ..._compat import PYDANTIC_V2, model_parse_json from ..._models import construct_type_unchecked -from .._pydantic import to_strict_json_schema +from .._pydantic import is_basemodel_type, to_strict_json_schema, is_dataclass_like_type from ...types.chat import ( ParsedChoice, ChatCompletion, @@ -216,14 +216,16 @@ def is_parseable_tool(input_tool: ChatCompletionToolParam) -> bool: return cast(FunctionDefinition, input_fn).get("strict") or False -def is_basemodel_type(typ: type) -> TypeGuard[type[pydantic.BaseModel]]: - return issubclass(typ, pydantic.BaseModel) - - def _parse_content(response_format: type[ResponseFormatT], content: str) -> ResponseFormatT: if is_basemodel_type(response_format): return cast(ResponseFormatT, model_parse_json(response_format, content)) + if is_dataclass_like_type(response_format): + if not PYDANTIC_V2: + raise TypeError(f"Non BaseModel types are only supported with Pydantic v2 - {response_format}") + + return pydantic.TypeAdapter(response_format).validate_json(content) + raise TypeError(f"Unable to automatically parse response format type {response_format}") @@ -241,14 +243,22 @@ def type_to_response_format_param( # can only be a `type` response_format = cast(type, response_format) - if not is_basemodel_type(response_format): + json_schema_type: type[pydantic.BaseModel] | pydantic.TypeAdapter[Any] | None = None + + if is_basemodel_type(response_format): + name = response_format.__name__ + json_schema_type = response_format + elif is_dataclass_like_type(response_format): + name = response_format.__name__ + json_schema_type = pydantic.TypeAdapter(response_format) + else: raise TypeError(f"Unsupported response_format type - {response_format}") return { "type": "json_schema", "json_schema": { - "schema": to_strict_json_schema(response_format), - "name": response_format.__name__, + "schema": to_strict_json_schema(json_schema_type), + "name": name, "strict": True, }, } diff --git a/src/openai/lib/_pydantic.py b/src/openai/lib/_pydantic.py index f989ce3ed0..22c7a1f3cd 100644 --- a/src/openai/lib/_pydantic.py +++ b/src/openai/lib/_pydantic.py @@ -1,17 +1,26 @@ from __future__ import annotations -from typing import Any +import inspect +from typing import Any, TypeVar from typing_extensions import TypeGuard import pydantic from .._types import NOT_GIVEN from .._utils import is_dict as _is_dict, is_list -from .._compat import model_json_schema +from .._compat import PYDANTIC_V2, model_json_schema +_T = TypeVar("_T") + + +def to_strict_json_schema(model: type[pydantic.BaseModel] | pydantic.TypeAdapter[Any]) -> dict[str, Any]: + if inspect.isclass(model) and is_basemodel_type(model): + schema = model_json_schema(model) + elif PYDANTIC_V2 and isinstance(model, pydantic.TypeAdapter): + schema = model.json_schema() + else: + raise TypeError(f"Non BaseModel types are only supported with Pydantic v2 - {model}") -def to_strict_json_schema(model: type[pydantic.BaseModel]) -> dict[str, Any]: - schema = model_json_schema(model) return _ensure_strict_json_schema(schema, path=(), root=schema) @@ -117,6 +126,15 @@ def resolve_ref(*, root: dict[str, object], ref: str) -> object: return resolved +def is_basemodel_type(typ: type) -> TypeGuard[type[pydantic.BaseModel]]: + return issubclass(typ, pydantic.BaseModel) + + +def is_dataclass_like_type(typ: type) -> bool: + """Returns True if the given type likely used `@pydantic.dataclass`""" + return hasattr(typ, "__pydantic_config__") + + def is_dict(obj: object) -> TypeGuard[dict[str, object]]: # just pretend that we know there are only `str` keys # as that check is not worth the performance cost diff --git a/tests/lib/chat/test_completions.py b/tests/lib/chat/test_completions.py index aea449b097..d67d5129cd 100644 --- a/tests/lib/chat/test_completions.py +++ b/tests/lib/chat/test_completions.py @@ -3,7 +3,7 @@ import os import json from enum import Enum -from typing import Any, Callable, Optional +from typing import Any, List, Callable, Optional from typing_extensions import Literal, TypeVar import httpx @@ -317,6 +317,63 @@ class Location(BaseModel): ) +@pytest.mark.respx(base_url=base_url) +@pytest.mark.skipif(not PYDANTIC_V2, reason="dataclasses only supported in v2") +def test_parse_pydantic_dataclass(client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: + from pydantic.dataclasses import dataclass + + @dataclass + class CalendarEvent: + name: str + date: str + participants: List[str] + + completion = _make_snapshot_request( + lambda c: c.beta.chat.completions.parse( + model="gpt-4o-2024-08-06", + messages=[ + {"role": "system", "content": "Extract the event information."}, + {"role": "user", "content": "Alice and Bob are going to a science fair on Friday."}, + ], + response_format=CalendarEvent, + ), + content_snapshot=snapshot( + '{"id": "chatcmpl-9wdGqXkJJARAz7rOrLH5u5FBwLjF3", "object": "chat.completion", "created": 1723761008, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"name\\":\\"Science Fair\\",\\"date\\":\\"Friday\\",\\"participants\\":[\\"Alice\\",\\"Bob\\"]}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 32, "completion_tokens": 17, "total_tokens": 49}, "system_fingerprint": "fp_2a322c9ffc"}' + ), + mock_client=client, + respx_mock=respx_mock, + ) + + assert print_obj(completion, monkeypatch) == snapshot( + """\ +ParsedChatCompletion[CalendarEvent]( + choices=[ + ParsedChoice[CalendarEvent]( + finish_reason='stop', + index=0, + logprobs=None, + message=ParsedChatCompletionMessage[CalendarEvent]( + content='{"name":"Science Fair","date":"Friday","participants":["Alice","Bob"]}', + function_call=None, + parsed=CalendarEvent(name='Science Fair', date='Friday', participants=['Alice', 'Bob']), + refusal=None, + role='assistant', + tool_calls=[] + ) + ) + ], + created=1723761008, + id='chatcmpl-9wdGqXkJJARAz7rOrLH5u5FBwLjF3', + model='gpt-4o-2024-08-06', + object='chat.completion', + service_tier=None, + system_fingerprint='fp_2a322c9ffc', + usage=CompletionUsage(completion_tokens=17, prompt_tokens=32, total_tokens=49) +) +""" + ) + + @pytest.mark.respx(base_url=base_url) def test_pydantic_tool_model_all_types(client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: completion = _make_snapshot_request( From 05fa732c024b55ddda1f5f8b107ce78233acd3ce Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 20 Aug 2024 15:10:05 +0000 Subject: [PATCH 483/816] release: 1.42.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 5a1b26c33e..507912c504 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.41.1" + ".": "1.42.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index e80a4fcc8a..6daddd33fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.42.0 (2024-08-20) + +Full Changelog: [v1.41.1...v1.42.0](https://github.com/openai/openai-python/compare/v1.41.1...v1.42.0) + +### Features + +* **parsing:** add support for pydantic dataclasses ([#1655](https://github.com/openai/openai-python/issues/1655)) ([101bee9](https://github.com/openai/openai-python/commit/101bee9844f725d2174796c3d09a58d3aa079fad)) + + +### Chores + +* **ci:** also run pydantic v1 tests ([#1666](https://github.com/openai/openai-python/issues/1666)) ([af2a1ca](https://github.com/openai/openai-python/commit/af2a1ca408a406098c6c79837aa3561b822e08ec)) + ## 1.41.1 (2024-08-19) Full Changelog: [v1.41.0...v1.41.1](https://github.com/openai/openai-python/compare/v1.41.0...v1.41.1) diff --git a/pyproject.toml b/pyproject.toml index b6530b8523..526e46e063 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.41.1" +version = "1.42.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 22ed2bff90..b89e3df342 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.41.1" # x-release-please-version +__version__ = "1.42.0" # x-release-please-version From 5d3111a85b34e369adf76263b3b8ba7447702459 Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Thu, 29 Aug 2024 16:27:45 +0000 Subject: [PATCH 484/816] feat(api): add file search result details to run steps (#1681) --- .stats.yml | 2 +- api.md | 3 +- .../resources/beta/threads/runs/runs.py | 83 ++++++++++++++++++- .../resources/beta/threads/runs/steps.py | 64 ++++++++++++-- src/openai/types/beta/file_search_tool.py | 26 +++++- .../types/beta/file_search_tool_param.py | 26 +++++- .../types/beta/threads/run_create_params.py | 15 +++- .../types/beta/threads/runs/__init__.py | 2 + .../threads/runs/file_search_tool_call.py | 58 ++++++++++++- .../beta/threads/runs/run_step_include.py | 7 ++ .../beta/threads/runs/step_list_params.py | 15 ++++ .../beta/threads/runs/step_retrieve_params.py | 28 +++++++ .../beta/threads/runs/test_steps.py | 38 +++++++-- tests/api_resources/beta/threads/test_runs.py | 20 +++-- 14 files changed, 351 insertions(+), 36 deletions(-) create mode 100644 src/openai/types/beta/threads/runs/run_step_include.py create mode 100644 src/openai/types/beta/threads/runs/step_retrieve_params.py diff --git a/.stats.yml b/.stats.yml index 185585b675..fd4f271361 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-8ff62fa1091460d68fbd36d72c17d91b709917bebf2983c9c4de5784bc384a2e.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-1dbac0e95bdb5a89a0dd3d93265475a378214551b7d8c22862928e0d87ace94b.yml diff --git a/api.md b/api.md index 648d0f3708..48778cc57c 100644 --- a/api.md +++ b/api.md @@ -365,6 +365,7 @@ from openai.types.beta.threads.runs import ( RunStepDelta, RunStepDeltaEvent, RunStepDeltaMessageDelta, + RunStepInclude, ToolCall, ToolCallDelta, ToolCallDeltaObject, @@ -374,7 +375,7 @@ from openai.types.beta.threads.runs import ( Methods: -- client.beta.threads.runs.steps.retrieve(step_id, \*, thread_id, run_id) -> RunStep +- client.beta.threads.runs.steps.retrieve(step_id, \*, thread_id, run_id, \*\*params) -> RunStep - client.beta.threads.runs.steps.list(run_id, \*, thread_id, \*\*params) -> SyncCursorPage[RunStep] ### Messages diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index cbfb9546f0..4f39912e62 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -3,7 +3,7 @@ from __future__ import annotations import typing_extensions -from typing import Union, Iterable, Optional, overload +from typing import List, Union, Iterable, Optional, overload from functools import partial from typing_extensions import Literal @@ -49,6 +49,7 @@ from .....types.beta.threads.run import Run from .....types.beta.assistant_tool_param import AssistantToolParam from .....types.beta.assistant_stream_event import AssistantStreamEvent +from .....types.beta.threads.runs.run_step_include import RunStepInclude from .....types.beta.assistant_tool_choice_option_param import AssistantToolChoiceOptionParam from .....types.beta.assistant_response_format_option_param import AssistantResponseFormatOptionParam @@ -74,6 +75,7 @@ def create( thread_id: str, *, assistant_id: str, + include: List[RunStepInclude] | NotGiven = NOT_GIVEN, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, @@ -104,6 +106,14 @@ def create( [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run. + include: A list of additional fields to include in the response. Currently the only + supported value is `step_details.tool_calls[*].file_search.results[*].content` + to fetch the file search result content. + + See the + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + for more information. + additional_instructions: Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions. @@ -206,6 +216,7 @@ def create( *, assistant_id: str, stream: Literal[True], + include: List[RunStepInclude] | NotGiven = NOT_GIVEN, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, @@ -239,6 +250,14 @@ def create( events, terminating when the Run enters a terminal state with a `data: [DONE]` message. + include: A list of additional fields to include in the response. Currently the only + supported value is `step_details.tool_calls[*].file_search.results[*].content` + to fetch the file search result content. + + See the + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + for more information. + additional_instructions: Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions. @@ -337,6 +356,7 @@ def create( *, assistant_id: str, stream: bool, + include: List[RunStepInclude] | NotGiven = NOT_GIVEN, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, @@ -370,6 +390,14 @@ def create( events, terminating when the Run enters a terminal state with a `data: [DONE]` message. + include: A list of additional fields to include in the response. Currently the only + supported value is `step_details.tool_calls[*].file_search.results[*].content` + to fetch the file search result content. + + See the + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + for more information. + additional_instructions: Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions. @@ -467,6 +495,7 @@ def create( thread_id: str, *, assistant_id: str, + include: List[RunStepInclude] | NotGiven = NOT_GIVEN, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, @@ -516,7 +545,11 @@ def create( run_create_params.RunCreateParams, ), options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform({"include": include}, run_create_params.RunCreateParams), ), cast_to=Run, stream=stream or False, @@ -712,6 +745,7 @@ def create_and_poll( self, *, assistant_id: str, + include: List[RunStepInclude] | NotGiven = NOT_GIVEN, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, @@ -743,6 +777,7 @@ def create_and_poll( run = self.create( thread_id=thread_id, assistant_id=assistant_id, + include=include, additional_instructions=additional_instructions, additional_messages=additional_messages, instructions=instructions, @@ -958,6 +993,7 @@ def stream( self, *, assistant_id: str, + include: List[RunStepInclude] | NotGiven = NOT_GIVEN, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, @@ -988,6 +1024,7 @@ def stream( self, *, assistant_id: str, + include: List[RunStepInclude] | NotGiven = NOT_GIVEN, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, @@ -1018,6 +1055,7 @@ def stream( self, *, assistant_id: str, + include: List[RunStepInclude] | NotGiven = NOT_GIVEN, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, @@ -1057,6 +1095,7 @@ def stream( body=maybe_transform( { "assistant_id": assistant_id, + "include": include, "additional_instructions": additional_instructions, "additional_messages": additional_messages, "instructions": instructions, @@ -1387,6 +1426,7 @@ async def create( thread_id: str, *, assistant_id: str, + include: List[RunStepInclude] | NotGiven = NOT_GIVEN, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, @@ -1417,6 +1457,14 @@ async def create( [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run. + include: A list of additional fields to include in the response. Currently the only + supported value is `step_details.tool_calls[*].file_search.results[*].content` + to fetch the file search result content. + + See the + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + for more information. + additional_instructions: Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions. @@ -1519,6 +1567,7 @@ async def create( *, assistant_id: str, stream: Literal[True], + include: List[RunStepInclude] | NotGiven = NOT_GIVEN, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, @@ -1552,6 +1601,14 @@ async def create( events, terminating when the Run enters a terminal state with a `data: [DONE]` message. + include: A list of additional fields to include in the response. Currently the only + supported value is `step_details.tool_calls[*].file_search.results[*].content` + to fetch the file search result content. + + See the + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + for more information. + additional_instructions: Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions. @@ -1650,6 +1707,7 @@ async def create( *, assistant_id: str, stream: bool, + include: List[RunStepInclude] | NotGiven = NOT_GIVEN, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, @@ -1683,6 +1741,14 @@ async def create( events, terminating when the Run enters a terminal state with a `data: [DONE]` message. + include: A list of additional fields to include in the response. Currently the only + supported value is `step_details.tool_calls[*].file_search.results[*].content` + to fetch the file search result content. + + See the + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + for more information. + additional_instructions: Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions. @@ -1780,6 +1846,7 @@ async def create( thread_id: str, *, assistant_id: str, + include: List[RunStepInclude] | NotGiven = NOT_GIVEN, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, @@ -1810,6 +1877,7 @@ async def create( body=await async_maybe_transform( { "assistant_id": assistant_id, + "include": include, "additional_instructions": additional_instructions, "additional_messages": additional_messages, "instructions": instructions, @@ -1829,7 +1897,11 @@ async def create( run_create_params.RunCreateParams, ), options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform({"include": include}, run_create_params.RunCreateParams), ), cast_to=Run, stream=stream or False, @@ -2025,6 +2097,7 @@ async def create_and_poll( self, *, assistant_id: str, + include: List[RunStepInclude] | NotGiven = NOT_GIVEN, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, @@ -2056,6 +2129,7 @@ async def create_and_poll( run = await self.create( thread_id=thread_id, assistant_id=assistant_id, + include=include, additional_instructions=additional_instructions, additional_messages=additional_messages, instructions=instructions, @@ -2303,6 +2377,7 @@ def stream( self, *, assistant_id: str, + include: List[RunStepInclude] | NotGiven = NOT_GIVEN, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, @@ -2333,6 +2408,7 @@ def stream( self, *, assistant_id: str, + include: List[RunStepInclude] | NotGiven = NOT_GIVEN, additional_instructions: Optional[str] | NotGiven = NOT_GIVEN, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, @@ -2374,6 +2450,7 @@ def stream( body=maybe_transform( { "assistant_id": assistant_id, + "include": include, "additional_instructions": additional_instructions, "additional_messages": additional_messages, "instructions": instructions, diff --git a/src/openai/resources/beta/threads/runs/steps.py b/src/openai/resources/beta/threads/runs/steps.py index 512008939c..3d2d40a3fb 100644 --- a/src/openai/resources/beta/threads/runs/steps.py +++ b/src/openai/resources/beta/threads/runs/steps.py @@ -2,23 +2,25 @@ from __future__ import annotations +from typing import List from typing_extensions import Literal import httpx from ..... import _legacy_response from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ....._utils import maybe_transform +from ....._utils import ( + maybe_transform, + async_maybe_transform, +) from ....._compat import cached_property from ....._resource import SyncAPIResource, AsyncAPIResource from ....._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from .....pagination import SyncCursorPage, AsyncCursorPage -from ....._base_client import ( - AsyncPaginator, - make_request_options, -) -from .....types.beta.threads.runs import step_list_params +from ....._base_client import AsyncPaginator, make_request_options +from .....types.beta.threads.runs import step_list_params, step_retrieve_params from .....types.beta.threads.runs.run_step import RunStep +from .....types.beta.threads.runs.run_step_include import RunStepInclude __all__ = ["Steps", "AsyncSteps"] @@ -38,6 +40,7 @@ def retrieve( *, thread_id: str, run_id: str, + include: List[RunStepInclude] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -49,6 +52,14 @@ def retrieve( Retrieves a run step. Args: + include: A list of additional fields to include in the response. Currently the only + supported value is `step_details.tool_calls[*].file_search.results[*].content` + to fetch the file search result content. + + See the + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + for more information. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -67,7 +78,11 @@ def retrieve( return self._get( f"/threads/{thread_id}/runs/{run_id}/steps/{step_id}", options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform({"include": include}, step_retrieve_params.StepRetrieveParams), ), cast_to=RunStep, ) @@ -79,6 +94,7 @@ def list( thread_id: str, after: str | NotGiven = NOT_GIVEN, before: str | NotGiven = NOT_GIVEN, + include: List[RunStepInclude] | NotGiven = NOT_GIVEN, limit: int | NotGiven = NOT_GIVEN, order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -102,6 +118,14 @@ def list( ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + include: A list of additional fields to include in the response. Currently the only + supported value is `step_details.tool_calls[*].file_search.results[*].content` + to fetch the file search result content. + + See the + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + for more information. + limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. @@ -133,6 +157,7 @@ def list( { "after": after, "before": before, + "include": include, "limit": limit, "order": order, }, @@ -158,6 +183,7 @@ async def retrieve( *, thread_id: str, run_id: str, + include: List[RunStepInclude] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -169,6 +195,14 @@ async def retrieve( Retrieves a run step. Args: + include: A list of additional fields to include in the response. Currently the only + supported value is `step_details.tool_calls[*].file_search.results[*].content` + to fetch the file search result content. + + See the + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + for more information. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -187,7 +221,11 @@ async def retrieve( return await self._get( f"/threads/{thread_id}/runs/{run_id}/steps/{step_id}", options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform({"include": include}, step_retrieve_params.StepRetrieveParams), ), cast_to=RunStep, ) @@ -199,6 +237,7 @@ def list( thread_id: str, after: str | NotGiven = NOT_GIVEN, before: str | NotGiven = NOT_GIVEN, + include: List[RunStepInclude] | NotGiven = NOT_GIVEN, limit: int | NotGiven = NOT_GIVEN, order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -222,6 +261,14 @@ def list( ending with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. + include: A list of additional fields to include in the response. Currently the only + supported value is `step_details.tool_calls[*].file_search.results[*].content` + to fetch the file search result content. + + See the + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + for more information. + limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. @@ -253,6 +300,7 @@ def list( { "after": after, "before": before, + "include": include, "limit": limit, "order": order, }, diff --git a/src/openai/types/beta/file_search_tool.py b/src/openai/types/beta/file_search_tool.py index 26ab1cb83f..4015b3da09 100644 --- a/src/openai/types/beta/file_search_tool.py +++ b/src/openai/types/beta/file_search_tool.py @@ -5,7 +5,21 @@ from ..._models import BaseModel -__all__ = ["FileSearchTool", "FileSearch"] +__all__ = ["FileSearchTool", "FileSearch", "FileSearchRankingOptions"] + + +class FileSearchRankingOptions(BaseModel): + ranker: Optional[Literal["auto", "default_2024_08_21"]] = None + """The ranker to use for the file search. + + If not specified will use the `auto` ranker. + """ + + score_threshold: Optional[float] = None + """The score threshold for the file search. + + All values must be a floating point number between 0 and 1. + """ class FileSearch(BaseModel): @@ -17,7 +31,15 @@ class FileSearch(BaseModel): Note that the file search tool may output fewer than `max_num_results` results. See the - [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/number-of-chunks-returned) + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + for more information. + """ + + ranking_options: Optional[FileSearchRankingOptions] = None + """The ranking options for the file search. + + See the + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) for more information. """ diff --git a/src/openai/types/beta/file_search_tool_param.py b/src/openai/types/beta/file_search_tool_param.py index 666719f8cd..97e651b0da 100644 --- a/src/openai/types/beta/file_search_tool_param.py +++ b/src/openai/types/beta/file_search_tool_param.py @@ -4,7 +4,21 @@ from typing_extensions import Literal, Required, TypedDict -__all__ = ["FileSearchToolParam", "FileSearch"] +__all__ = ["FileSearchToolParam", "FileSearch", "FileSearchRankingOptions"] + + +class FileSearchRankingOptions(TypedDict, total=False): + ranker: Literal["auto", "default_2024_08_21"] + """The ranker to use for the file search. + + If not specified will use the `auto` ranker. + """ + + score_threshold: float + """The score threshold for the file search. + + All values must be a floating point number between 0 and 1. + """ class FileSearch(TypedDict, total=False): @@ -16,7 +30,15 @@ class FileSearch(TypedDict, total=False): Note that the file search tool may output fewer than `max_num_results` results. See the - [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/number-of-chunks-returned) + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + for more information. + """ + + ranking_options: FileSearchRankingOptions + """The ranking options for the file search. + + See the + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) for more information. """ diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index d3e6d9c476..8bb73ddc78 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -2,11 +2,12 @@ from __future__ import annotations -from typing import Union, Iterable, Optional +from typing import List, Union, Iterable, Optional from typing_extensions import Literal, Required, TypeAlias, TypedDict from ...chat_model import ChatModel from ..assistant_tool_param import AssistantToolParam +from .runs.run_step_include import RunStepInclude from .message_content_part_param import MessageContentPartParam from ..code_interpreter_tool_param import CodeInterpreterToolParam from ..assistant_tool_choice_option_param import AssistantToolChoiceOptionParam @@ -32,6 +33,18 @@ class RunCreateParamsBase(TypedDict, total=False): execute this run. """ + include: List[RunStepInclude] + """A list of additional fields to include in the response. + + Currently the only supported value is + `step_details.tool_calls[*].file_search.results[*].content` to fetch the file + search result content. + + See the + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + for more information. + """ + additional_instructions: Optional[str] """Appends additional instructions at the end of the instructions for the run. diff --git a/src/openai/types/beta/threads/runs/__init__.py b/src/openai/types/beta/threads/runs/__init__.py index a312ce3df2..467d5d793d 100644 --- a/src/openai/types/beta/threads/runs/__init__.py +++ b/src/openai/types/beta/threads/runs/__init__.py @@ -6,9 +6,11 @@ from .tool_call import ToolCall as ToolCall from .run_step_delta import RunStepDelta as RunStepDelta from .tool_call_delta import ToolCallDelta as ToolCallDelta +from .run_step_include import RunStepInclude as RunStepInclude from .step_list_params import StepListParams as StepListParams from .function_tool_call import FunctionToolCall as FunctionToolCall from .run_step_delta_event import RunStepDeltaEvent as RunStepDeltaEvent +from .step_retrieve_params import StepRetrieveParams as StepRetrieveParams from .code_interpreter_logs import CodeInterpreterLogs as CodeInterpreterLogs from .file_search_tool_call import FileSearchToolCall as FileSearchToolCall from .tool_call_delta_object import ToolCallDeltaObject as ToolCallDeltaObject diff --git a/src/openai/types/beta/threads/runs/file_search_tool_call.py b/src/openai/types/beta/threads/runs/file_search_tool_call.py index 57c0ca9a90..da4d58dc37 100644 --- a/src/openai/types/beta/threads/runs/file_search_tool_call.py +++ b/src/openai/types/beta/threads/runs/file_search_tool_call.py @@ -1,17 +1,71 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +from typing import List, Optional from typing_extensions import Literal from ....._models import BaseModel -__all__ = ["FileSearchToolCall"] +__all__ = [ + "FileSearchToolCall", + "FileSearch", + "FileSearchRankingOptions", + "FileSearchResult", + "FileSearchResultContent", +] + + +class FileSearchRankingOptions(BaseModel): + ranker: Literal["default_2024_08_21"] + """The ranker used for the file search.""" + + score_threshold: float + """The score threshold for the file search. + + All values must be a floating point number between 0 and 1. + """ + + +class FileSearchResultContent(BaseModel): + text: Optional[str] = None + """The text content of the file.""" + + type: Optional[Literal["text"]] = None + """The type of the content.""" + + +class FileSearchResult(BaseModel): + file_id: str + """The ID of the file that result was found in.""" + + file_name: str + """The name of the file that result was found in.""" + + score: float + """The score of the result. + + All values must be a floating point number between 0 and 1. + """ + + content: Optional[List[FileSearchResultContent]] = None + """The content of the result that was found. + + The content is only included if requested via the include query parameter. + """ + + +class FileSearch(BaseModel): + ranking_options: Optional[FileSearchRankingOptions] = None + """The ranking options for the file search.""" + + results: Optional[List[FileSearchResult]] = None + """The results of the file search.""" class FileSearchToolCall(BaseModel): id: str """The ID of the tool call object.""" - file_search: object + file_search: FileSearch """For now, this is always going to be an empty object.""" type: Literal["file_search"] diff --git a/src/openai/types/beta/threads/runs/run_step_include.py b/src/openai/types/beta/threads/runs/run_step_include.py new file mode 100644 index 0000000000..8e76c1b716 --- /dev/null +++ b/src/openai/types/beta/threads/runs/run_step_include.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["RunStepInclude"] + +RunStepInclude: TypeAlias = Literal["step_details.tool_calls[*].file_search.results[*].content"] diff --git a/src/openai/types/beta/threads/runs/step_list_params.py b/src/openai/types/beta/threads/runs/step_list_params.py index 606d444539..3931bd7e0c 100644 --- a/src/openai/types/beta/threads/runs/step_list_params.py +++ b/src/openai/types/beta/threads/runs/step_list_params.py @@ -2,8 +2,11 @@ from __future__ import annotations +from typing import List from typing_extensions import Literal, Required, TypedDict +from .run_step_include import RunStepInclude + __all__ = ["StepListParams"] @@ -28,6 +31,18 @@ class StepListParams(TypedDict, total=False): of the list. """ + include: List[RunStepInclude] + """A list of additional fields to include in the response. + + Currently the only supported value is + `step_details.tool_calls[*].file_search.results[*].content` to fetch the file + search result content. + + See the + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + for more information. + """ + limit: int """A limit on the number of objects to be returned. diff --git a/src/openai/types/beta/threads/runs/step_retrieve_params.py b/src/openai/types/beta/threads/runs/step_retrieve_params.py new file mode 100644 index 0000000000..22c1c049f4 --- /dev/null +++ b/src/openai/types/beta/threads/runs/step_retrieve_params.py @@ -0,0 +1,28 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List +from typing_extensions import Required, TypedDict + +from .run_step_include import RunStepInclude + +__all__ = ["StepRetrieveParams"] + + +class StepRetrieveParams(TypedDict, total=False): + thread_id: Required[str] + + run_id: Required[str] + + include: List[RunStepInclude] + """A list of additional fields to include in the response. + + Currently the only supported value is + `step_details.tool_calls[*].file_search.results[*].content` to fetch the file + search result content. + + See the + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + for more information. + """ diff --git a/tests/api_resources/beta/threads/runs/test_steps.py b/tests/api_resources/beta/threads/runs/test_steps.py index e6108d8dad..f5dc17e0b5 100644 --- a/tests/api_resources/beta/threads/runs/test_steps.py +++ b/tests/api_resources/beta/threads/runs/test_steps.py @@ -27,6 +27,16 @@ def test_method_retrieve(self, client: OpenAI) -> None: ) assert_matches_type(RunStep, step, path=["response"]) + @parametrize + def test_method_retrieve_with_all_params(self, client: OpenAI) -> None: + step = client.beta.threads.runs.steps.retrieve( + step_id="step_id", + thread_id="thread_id", + run_id="run_id", + include=["step_details.tool_calls[*].file_search.results[*].content"], + ) + assert_matches_type(RunStep, step, path=["response"]) + @parametrize def test_raw_response_retrieve(self, client: OpenAI) -> None: response = client.beta.threads.runs.steps.with_raw_response.retrieve( @@ -89,10 +99,11 @@ def test_method_list(self, client: OpenAI) -> None: @parametrize def test_method_list_with_all_params(self, client: OpenAI) -> None: step = client.beta.threads.runs.steps.list( - "string", - thread_id="string", - after="string", - before="string", + run_id="run_id", + thread_id="thread_id", + after="after", + before="before", + include=["step_details.tool_calls[*].file_search.results[*].content"], limit=0, order="asc", ) @@ -151,6 +162,16 @@ async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: ) assert_matches_type(RunStep, step, path=["response"]) + @parametrize + async def test_method_retrieve_with_all_params(self, async_client: AsyncOpenAI) -> None: + step = await async_client.beta.threads.runs.steps.retrieve( + step_id="step_id", + thread_id="thread_id", + run_id="run_id", + include=["step_details.tool_calls[*].file_search.results[*].content"], + ) + assert_matches_type(RunStep, step, path=["response"]) + @parametrize async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: response = await async_client.beta.threads.runs.steps.with_raw_response.retrieve( @@ -213,10 +234,11 @@ async def test_method_list(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: step = await async_client.beta.threads.runs.steps.list( - "string", - thread_id="string", - after="string", - before="string", + run_id="run_id", + thread_id="thread_id", + after="after", + before="before", + include=["step_details.tool_calls[*].file_search.results[*].content"], limit=0, order="asc", ) diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index 5d16bdb364..c8d70f5f89 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -33,9 +33,10 @@ def test_method_create_overload_1(self, client: OpenAI) -> None: @parametrize def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: run = client.beta.threads.runs.create( - "string", - assistant_id="string", - additional_instructions="string", + thread_id="thread_id", + assistant_id="assistant_id", + include=["step_details.tool_calls[*].file_search.results[*].content"], + additional_instructions="additional_instructions", additional_messages=[ { "content": "string", @@ -199,7 +200,8 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: "string", assistant_id="string", stream=True, - additional_instructions="string", + include=["step_details.tool_calls[*].file_search.results[*].content"], + additional_instructions="additional_instructions", additional_messages=[ { "content": "string", @@ -699,9 +701,10 @@ async def test_method_create_overload_1(self, async_client: AsyncOpenAI) -> None @parametrize async def test_method_create_with_all_params_overload_1(self, async_client: AsyncOpenAI) -> None: run = await async_client.beta.threads.runs.create( - "string", - assistant_id="string", - additional_instructions="string", + thread_id="thread_id", + assistant_id="assistant_id", + include=["step_details.tool_calls[*].file_search.results[*].content"], + additional_instructions="additional_instructions", additional_messages=[ { "content": "string", @@ -865,7 +868,8 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn "string", assistant_id="string", stream=True, - additional_instructions="string", + include=["step_details.tool_calls[*].file_search.results[*].content"], + additional_instructions="additional_instructions", additional_messages=[ { "content": "string", From 9850c169c4126fd04dc6796e4685f1b9e4924aa4 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 29 Aug 2024 16:43:50 +0000 Subject: [PATCH 485/816] release: 1.43.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 507912c504..b5fcdb93a4 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.42.0" + ".": "1.43.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 6daddd33fe..49403cc371 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.43.0 (2024-08-29) + +Full Changelog: [v1.42.0...v1.43.0](https://github.com/openai/openai-python/compare/v1.42.0...v1.43.0) + +### Features + +* **api:** add file search result details to run steps ([#1681](https://github.com/openai/openai-python/issues/1681)) ([f5449c0](https://github.com/openai/openai-python/commit/f5449c07580ac9707f0387f86f4772fbf0a874b6)) + ## 1.42.0 (2024-08-20) Full Changelog: [v1.41.1...v1.42.0](https://github.com/openai/openai-python/compare/v1.41.1...v1.42.0) diff --git a/pyproject.toml b/pyproject.toml index 526e46e063..54ae75de32 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.42.0" +version = "1.43.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index b89e3df342..b027b37a69 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.42.0" # x-release-please-version +__version__ = "1.43.0" # x-release-please-version From b2f58cba092cfb3083dc31de429fa19d89f739dc Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 5 Sep 2024 11:01:40 +0000 Subject: [PATCH 486/816] release: 1.43.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index b5fcdb93a4..5b3c8f9482 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.43.0" + ".": "1.43.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 49403cc371..7aa4280d4b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.43.1 (2024-09-05) + +Full Changelog: [v1.43.0...v1.43.1](https://github.com/openai/openai-python/compare/v1.43.0...v1.43.1) + +### Chores + +* pyproject.toml formatting changes ([#1687](https://github.com/openai/openai-python/issues/1687)) ([3387ede](https://github.com/openai/openai-python/commit/3387ede0b896788bf1197378b01941c75bd6e179)) + ## 1.43.0 (2024-08-29) Full Changelog: [v1.42.0...v1.43.0](https://github.com/openai/openai-python/compare/v1.42.0...v1.43.0) diff --git a/pyproject.toml b/pyproject.toml index 54ae75de32..04ecef16e9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.43.0" +version = "1.43.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index b027b37a69..ac6080b318 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.43.0" # x-release-please-version +__version__ = "1.43.1" # x-release-please-version From f161000ff0fe3153cbfaaf9160be0ca28f213871 Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Fri, 6 Sep 2024 09:27:05 +0000 Subject: [PATCH 487/816] feat(vector store): improve chunking strategy type names (#1690) --- .stats.yml | 2 +- api.md | 12 ++++- .../beta/vector_stores/file_batches.py | 23 ++++----- .../resources/beta/vector_stores/files.py | 27 +++++----- .../beta/vector_stores/vector_stores.py | 15 +++--- src/openai/types/beta/__init__.py | 7 +++ .../types/beta/assistant_create_params.py | 44 ++-------------- .../beta/auto_file_chunking_strategy_param.py | 12 +++++ .../types/beta/file_chunking_strategy.py | 14 +++++ .../beta/file_chunking_strategy_param.py | 13 +++++ .../other_file_chunking_strategy_object.py | 12 +++++ .../beta/static_file_chunking_strategy.py | 22 ++++++++ .../static_file_chunking_strategy_object.py | 15 ++++++ .../static_file_chunking_strategy_param.py | 22 ++++++++ .../beta/thread_create_and_run_params.py | 43 ++-------------- src/openai/types/beta/thread_create_params.py | 42 ++------------- .../types/beta/vector_store_create_params.py | 47 +++-------------- .../vector_stores/file_batch_create_params.py | 51 +++---------------- .../beta/vector_stores/file_create_params.py | 50 +++--------------- .../beta/vector_stores/vector_store_file.py | 49 ++---------------- 20 files changed, 201 insertions(+), 321 deletions(-) create mode 100644 src/openai/types/beta/auto_file_chunking_strategy_param.py create mode 100644 src/openai/types/beta/file_chunking_strategy.py create mode 100644 src/openai/types/beta/file_chunking_strategy_param.py create mode 100644 src/openai/types/beta/other_file_chunking_strategy_object.py create mode 100644 src/openai/types/beta/static_file_chunking_strategy.py create mode 100644 src/openai/types/beta/static_file_chunking_strategy_object.py create mode 100644 src/openai/types/beta/static_file_chunking_strategy_param.py diff --git a/.stats.yml b/.stats.yml index fd4f271361..903c159960 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-1dbac0e95bdb5a89a0dd3d93265475a378214551b7d8c22862928e0d87ace94b.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-85a85e0c08de456441431c0ae4e9c078cc8f9748c29430b9a9058340db6389ee.yml diff --git a/api.md b/api.md index 48778cc57c..32c0fb9efc 100644 --- a/api.md +++ b/api.md @@ -222,7 +222,17 @@ Methods: Types: ```python -from openai.types.beta import VectorStore, VectorStoreDeleted +from openai.types.beta import ( + AutoFileChunkingStrategyParam, + FileChunkingStrategy, + FileChunkingStrategyParam, + OtherFileChunkingStrategyObject, + StaticFileChunkingStrategy, + StaticFileChunkingStrategyObject, + StaticFileChunkingStrategyParam, + VectorStore, + VectorStoreDeleted, +) ``` Methods: diff --git a/src/openai/resources/beta/vector_stores/file_batches.py b/src/openai/resources/beta/vector_stores/file_batches.py index d6862c24ef..a350ed0bea 100644 --- a/src/openai/resources/beta/vector_stores/file_batches.py +++ b/src/openai/resources/beta/vector_stores/file_batches.py @@ -22,11 +22,10 @@ from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ....pagination import SyncCursorPage, AsyncCursorPage -from ...._base_client import ( - AsyncPaginator, - make_request_options, -) +from ....types.beta import FileChunkingStrategyParam +from ...._base_client import AsyncPaginator, make_request_options from ....types.beta.vector_stores import file_batch_create_params, file_batch_list_files_params +from ....types.beta.file_chunking_strategy_param import FileChunkingStrategyParam from ....types.beta.vector_stores.vector_store_file import VectorStoreFile from ....types.beta.vector_stores.vector_store_file_batch import VectorStoreFileBatch @@ -47,7 +46,7 @@ def create( vector_store_id: str, *, file_ids: List[str], - chunking_strategy: file_batch_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, + chunking_strategy: FileChunkingStrategyParam | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -64,7 +63,7 @@ def create( files. chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will use the `auto` - strategy. + strategy. Only applicable if `file_ids` is non-empty. extra_headers: Send extra headers @@ -174,7 +173,7 @@ def create_and_poll( *, file_ids: List[str], poll_interval_ms: int | NotGiven = NOT_GIVEN, - chunking_strategy: file_batch_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, + chunking_strategy: FileChunkingStrategyParam | NotGiven = NOT_GIVEN, ) -> VectorStoreFileBatch: """Create a vector store batch and poll until all files have been processed.""" batch = self.create( @@ -308,7 +307,7 @@ def upload_and_poll( max_concurrency: int = 5, file_ids: List[str] = [], poll_interval_ms: int | NotGiven = NOT_GIVEN, - chunking_strategy: file_batch_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, + chunking_strategy: FileChunkingStrategyParam | NotGiven = NOT_GIVEN, ) -> VectorStoreFileBatch: """Uploads the given files concurrently and then creates a vector store file batch. @@ -365,7 +364,7 @@ async def create( vector_store_id: str, *, file_ids: List[str], - chunking_strategy: file_batch_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, + chunking_strategy: FileChunkingStrategyParam | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -382,7 +381,7 @@ async def create( files. chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will use the `auto` - strategy. + strategy. Only applicable if `file_ids` is non-empty. extra_headers: Send extra headers @@ -492,7 +491,7 @@ async def create_and_poll( *, file_ids: List[str], poll_interval_ms: int | NotGiven = NOT_GIVEN, - chunking_strategy: file_batch_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, + chunking_strategy: FileChunkingStrategyParam | NotGiven = NOT_GIVEN, ) -> VectorStoreFileBatch: """Create a vector store batch and poll until all files have been processed.""" batch = await self.create( @@ -626,7 +625,7 @@ async def upload_and_poll( max_concurrency: int = 5, file_ids: List[str] = [], poll_interval_ms: int | NotGiven = NOT_GIVEN, - chunking_strategy: file_batch_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, + chunking_strategy: FileChunkingStrategyParam | NotGiven = NOT_GIVEN, ) -> VectorStoreFileBatch: """Uploads the given files concurrently and then creates a vector store file batch. diff --git a/src/openai/resources/beta/vector_stores/files.py b/src/openai/resources/beta/vector_stores/files.py index 35ca331cc0..ba43519c75 100644 --- a/src/openai/resources/beta/vector_stores/files.py +++ b/src/openai/resources/beta/vector_stores/files.py @@ -18,11 +18,10 @@ from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ....pagination import SyncCursorPage, AsyncCursorPage -from ...._base_client import ( - AsyncPaginator, - make_request_options, -) +from ....types.beta import FileChunkingStrategyParam +from ...._base_client import AsyncPaginator, make_request_options from ....types.beta.vector_stores import file_list_params, file_create_params +from ....types.beta.file_chunking_strategy_param import FileChunkingStrategyParam from ....types.beta.vector_stores.vector_store_file import VectorStoreFile from ....types.beta.vector_stores.vector_store_file_deleted import VectorStoreFileDeleted @@ -43,7 +42,7 @@ def create( vector_store_id: str, *, file_id: str, - chunking_strategy: file_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, + chunking_strategy: FileChunkingStrategyParam | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -62,7 +61,7 @@ def create( files. chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will use the `auto` - strategy. + strategy. Only applicable if `file_ids` is non-empty. extra_headers: Send extra headers @@ -245,7 +244,7 @@ def create_and_poll( *, vector_store_id: str, poll_interval_ms: int | NotGiven = NOT_GIVEN, - chunking_strategy: file_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, + chunking_strategy: FileChunkingStrategyParam | NotGiven = NOT_GIVEN, ) -> VectorStoreFile: """Attach a file to the given vector store and wait for it to be processed.""" self.create(vector_store_id=vector_store_id, file_id=file_id, chunking_strategy=chunking_strategy) @@ -302,7 +301,7 @@ def upload( *, vector_store_id: str, file: FileTypes, - chunking_strategy: file_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, + chunking_strategy: FileChunkingStrategyParam | NotGiven = NOT_GIVEN, ) -> VectorStoreFile: """Upload a file to the `files` API and then attach it to the given vector store. @@ -318,7 +317,7 @@ def upload_and_poll( vector_store_id: str, file: FileTypes, poll_interval_ms: int | NotGiven = NOT_GIVEN, - chunking_strategy: file_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, + chunking_strategy: FileChunkingStrategyParam | NotGiven = NOT_GIVEN, ) -> VectorStoreFile: """Add a file to a vector store and poll until processing is complete.""" file_obj = self._client.files.create(file=file, purpose="assistants") @@ -344,7 +343,7 @@ async def create( vector_store_id: str, *, file_id: str, - chunking_strategy: file_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, + chunking_strategy: FileChunkingStrategyParam | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -363,7 +362,7 @@ async def create( files. chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will use the `auto` - strategy. + strategy. Only applicable if `file_ids` is non-empty. extra_headers: Send extra headers @@ -546,7 +545,7 @@ async def create_and_poll( *, vector_store_id: str, poll_interval_ms: int | NotGiven = NOT_GIVEN, - chunking_strategy: file_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, + chunking_strategy: FileChunkingStrategyParam | NotGiven = NOT_GIVEN, ) -> VectorStoreFile: """Attach a file to the given vector store and wait for it to be processed.""" await self.create(vector_store_id=vector_store_id, file_id=file_id, chunking_strategy=chunking_strategy) @@ -603,7 +602,7 @@ async def upload( *, vector_store_id: str, file: FileTypes, - chunking_strategy: file_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, + chunking_strategy: FileChunkingStrategyParam | NotGiven = NOT_GIVEN, ) -> VectorStoreFile: """Upload a file to the `files` API and then attach it to the given vector store. @@ -621,7 +620,7 @@ async def upload_and_poll( vector_store_id: str, file: FileTypes, poll_interval_ms: int | NotGiven = NOT_GIVEN, - chunking_strategy: file_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, + chunking_strategy: FileChunkingStrategyParam | NotGiven = NOT_GIVEN, ) -> VectorStoreFile: """Add a file to a vector store and poll until processing is complete.""" file_obj = await self._client.files.create(file=file, purpose="assistants") diff --git a/src/openai/resources/beta/vector_stores/vector_stores.py b/src/openai/resources/beta/vector_stores/vector_stores.py index cbd56a0693..c93b3bc41f 100644 --- a/src/openai/resources/beta/vector_stores/vector_stores.py +++ b/src/openai/resources/beta/vector_stores/vector_stores.py @@ -33,13 +33,16 @@ AsyncFileBatchesWithStreamingResponse, ) from ....pagination import SyncCursorPage, AsyncCursorPage -from ....types.beta import vector_store_list_params, vector_store_create_params, vector_store_update_params -from ...._base_client import ( - AsyncPaginator, - make_request_options, +from ....types.beta import ( + FileChunkingStrategyParam, + vector_store_list_params, + vector_store_create_params, + vector_store_update_params, ) +from ...._base_client import AsyncPaginator, make_request_options from ....types.beta.vector_store import VectorStore from ....types.beta.vector_store_deleted import VectorStoreDeleted +from ....types.beta.file_chunking_strategy_param import FileChunkingStrategyParam __all__ = ["VectorStores", "AsyncVectorStores"] @@ -64,7 +67,7 @@ def with_streaming_response(self) -> VectorStoresWithStreamingResponse: def create( self, *, - chunking_strategy: vector_store_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, + chunking_strategy: FileChunkingStrategyParam | NotGiven = NOT_GIVEN, expires_after: vector_store_create_params.ExpiresAfter | NotGiven = NOT_GIVEN, file_ids: List[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, @@ -331,7 +334,7 @@ def with_streaming_response(self) -> AsyncVectorStoresWithStreamingResponse: async def create( self, *, - chunking_strategy: vector_store_create_params.ChunkingStrategy | NotGiven = NOT_GIVEN, + chunking_strategy: FileChunkingStrategyParam | NotGiven = NOT_GIVEN, expires_after: vector_store_create_params.ExpiresAfter | NotGiven = NOT_GIVEN, file_ids: List[str] | NotGiven = NOT_GIVEN, metadata: Optional[object] | NotGiven = NOT_GIVEN, diff --git a/src/openai/types/beta/__init__.py b/src/openai/types/beta/__init__.py index 9c5ddfdbe0..7f76fed0cd 100644 --- a/src/openai/types/beta/__init__.py +++ b/src/openai/types/beta/__init__.py @@ -19,6 +19,7 @@ from .assistant_tool_choice import AssistantToolChoice as AssistantToolChoice from .code_interpreter_tool import CodeInterpreterTool as CodeInterpreterTool from .assistant_stream_event import AssistantStreamEvent as AssistantStreamEvent +from .file_chunking_strategy import FileChunkingStrategy as FileChunkingStrategy from .file_search_tool_param import FileSearchToolParam as FileSearchToolParam from .assistant_create_params import AssistantCreateParams as AssistantCreateParams from .assistant_update_params import AssistantUpdateParams as AssistantUpdateParams @@ -28,11 +29,17 @@ from .assistant_tool_choice_param import AssistantToolChoiceParam as AssistantToolChoiceParam from .code_interpreter_tool_param import CodeInterpreterToolParam as CodeInterpreterToolParam from .assistant_tool_choice_option import AssistantToolChoiceOption as AssistantToolChoiceOption +from .file_chunking_strategy_param import FileChunkingStrategyParam as FileChunkingStrategyParam from .thread_create_and_run_params import ThreadCreateAndRunParams as ThreadCreateAndRunParams +from .static_file_chunking_strategy import StaticFileChunkingStrategy as StaticFileChunkingStrategy from .assistant_tool_choice_function import AssistantToolChoiceFunction as AssistantToolChoiceFunction from .assistant_response_format_option import AssistantResponseFormatOption as AssistantResponseFormatOption +from .auto_file_chunking_strategy_param import AutoFileChunkingStrategyParam as AutoFileChunkingStrategyParam from .assistant_tool_choice_option_param import AssistantToolChoiceOptionParam as AssistantToolChoiceOptionParam +from .other_file_chunking_strategy_object import OtherFileChunkingStrategyObject as OtherFileChunkingStrategyObject +from .static_file_chunking_strategy_param import StaticFileChunkingStrategyParam as StaticFileChunkingStrategyParam from .assistant_tool_choice_function_param import AssistantToolChoiceFunctionParam as AssistantToolChoiceFunctionParam +from .static_file_chunking_strategy_object import StaticFileChunkingStrategyObject as StaticFileChunkingStrategyObject from .assistant_response_format_option_param import ( AssistantResponseFormatOptionParam as AssistantResponseFormatOptionParam, ) diff --git a/src/openai/types/beta/assistant_create_params.py b/src/openai/types/beta/assistant_create_params.py index 84cd4425d1..c1360b5b66 100644 --- a/src/openai/types/beta/assistant_create_params.py +++ b/src/openai/types/beta/assistant_create_params.py @@ -3,10 +3,11 @@ from __future__ import annotations from typing import List, Union, Iterable, Optional -from typing_extensions import Literal, Required, TypeAlias, TypedDict +from typing_extensions import Required, TypedDict from ..chat_model import ChatModel from .assistant_tool_param import AssistantToolParam +from .file_chunking_strategy_param import FileChunkingStrategyParam from .assistant_response_format_option_param import AssistantResponseFormatOptionParam __all__ = [ @@ -15,10 +16,6 @@ "ToolResourcesCodeInterpreter", "ToolResourcesFileSearch", "ToolResourcesFileSearchVectorStore", - "ToolResourcesFileSearchVectorStoreChunkingStrategy", - "ToolResourcesFileSearchVectorStoreChunkingStrategyAuto", - "ToolResourcesFileSearchVectorStoreChunkingStrategyStatic", - "ToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic", ] @@ -118,43 +115,12 @@ class ToolResourcesCodeInterpreter(TypedDict, total=False): """ -class ToolResourcesFileSearchVectorStoreChunkingStrategyAuto(TypedDict, total=False): - type: Required[Literal["auto"]] - """Always `auto`.""" - - -class ToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic(TypedDict, total=False): - chunk_overlap_tokens: Required[int] - """The number of tokens that overlap between chunks. The default value is `400`. - - Note that the overlap must not exceed half of `max_chunk_size_tokens`. - """ - - max_chunk_size_tokens: Required[int] - """The maximum number of tokens in each chunk. - - The default value is `800`. The minimum value is `100` and the maximum value is - `4096`. - """ - - -class ToolResourcesFileSearchVectorStoreChunkingStrategyStatic(TypedDict, total=False): - static: Required[ToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic] - - type: Required[Literal["static"]] - """Always `static`.""" - - -ToolResourcesFileSearchVectorStoreChunkingStrategy: TypeAlias = Union[ - ToolResourcesFileSearchVectorStoreChunkingStrategyAuto, ToolResourcesFileSearchVectorStoreChunkingStrategyStatic -] - - class ToolResourcesFileSearchVectorStore(TypedDict, total=False): - chunking_strategy: ToolResourcesFileSearchVectorStoreChunkingStrategy + chunking_strategy: FileChunkingStrategyParam """The chunking strategy used to chunk the file(s). - If not set, will use the `auto` strategy. + If not set, will use the `auto` strategy. Only applicable if `file_ids` is + non-empty. """ file_ids: List[str] diff --git a/src/openai/types/beta/auto_file_chunking_strategy_param.py b/src/openai/types/beta/auto_file_chunking_strategy_param.py new file mode 100644 index 0000000000..6f17836bac --- /dev/null +++ b/src/openai/types/beta/auto_file_chunking_strategy_param.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["AutoFileChunkingStrategyParam"] + + +class AutoFileChunkingStrategyParam(TypedDict, total=False): + type: Required[Literal["auto"]] + """Always `auto`.""" diff --git a/src/openai/types/beta/file_chunking_strategy.py b/src/openai/types/beta/file_chunking_strategy.py new file mode 100644 index 0000000000..406d69dd0e --- /dev/null +++ b/src/openai/types/beta/file_chunking_strategy.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Annotated, TypeAlias + +from ..._utils import PropertyInfo +from .other_file_chunking_strategy_object import OtherFileChunkingStrategyObject +from .static_file_chunking_strategy_object import StaticFileChunkingStrategyObject + +__all__ = ["FileChunkingStrategy"] + +FileChunkingStrategy: TypeAlias = Annotated[ + Union[StaticFileChunkingStrategyObject, OtherFileChunkingStrategyObject], PropertyInfo(discriminator="type") +] diff --git a/src/openai/types/beta/file_chunking_strategy_param.py b/src/openai/types/beta/file_chunking_strategy_param.py new file mode 100644 index 0000000000..46383358e5 --- /dev/null +++ b/src/openai/types/beta/file_chunking_strategy_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import TypeAlias + +from .auto_file_chunking_strategy_param import AutoFileChunkingStrategyParam +from .static_file_chunking_strategy_param import StaticFileChunkingStrategyParam + +__all__ = ["FileChunkingStrategyParam"] + +FileChunkingStrategyParam: TypeAlias = Union[AutoFileChunkingStrategyParam, StaticFileChunkingStrategyParam] diff --git a/src/openai/types/beta/other_file_chunking_strategy_object.py b/src/openai/types/beta/other_file_chunking_strategy_object.py new file mode 100644 index 0000000000..89da560be4 --- /dev/null +++ b/src/openai/types/beta/other_file_chunking_strategy_object.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["OtherFileChunkingStrategyObject"] + + +class OtherFileChunkingStrategyObject(BaseModel): + type: Literal["other"] + """Always `other`.""" diff --git a/src/openai/types/beta/static_file_chunking_strategy.py b/src/openai/types/beta/static_file_chunking_strategy.py new file mode 100644 index 0000000000..ba80e1a2b9 --- /dev/null +++ b/src/openai/types/beta/static_file_chunking_strategy.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +from ..._models import BaseModel + +__all__ = ["StaticFileChunkingStrategy"] + + +class StaticFileChunkingStrategy(BaseModel): + chunk_overlap_tokens: int + """The number of tokens that overlap between chunks. The default value is `400`. + + Note that the overlap must not exceed half of `max_chunk_size_tokens`. + """ + + max_chunk_size_tokens: int + """The maximum number of tokens in each chunk. + + The default value is `800`. The minimum value is `100` and the maximum value is + `4096`. + """ diff --git a/src/openai/types/beta/static_file_chunking_strategy_object.py b/src/openai/types/beta/static_file_chunking_strategy_object.py new file mode 100644 index 0000000000..896c4b8320 --- /dev/null +++ b/src/openai/types/beta/static_file_chunking_strategy_object.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel +from .static_file_chunking_strategy import StaticFileChunkingStrategy + +__all__ = ["StaticFileChunkingStrategyObject"] + + +class StaticFileChunkingStrategyObject(BaseModel): + static: StaticFileChunkingStrategy + + type: Literal["static"] + """Always `static`.""" diff --git a/src/openai/types/beta/static_file_chunking_strategy_param.py b/src/openai/types/beta/static_file_chunking_strategy_param.py new file mode 100644 index 0000000000..f917ac5647 --- /dev/null +++ b/src/openai/types/beta/static_file_chunking_strategy_param.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +__all__ = ["StaticFileChunkingStrategyParam"] + + +class StaticFileChunkingStrategyParam(TypedDict, total=False): + chunk_overlap_tokens: Required[int] + """The number of tokens that overlap between chunks. The default value is `400`. + + Note that the overlap must not exceed half of `max_chunk_size_tokens`. + """ + + max_chunk_size_tokens: Required[int] + """The maximum number of tokens in each chunk. + + The default value is `800`. The minimum value is `100` and the maximum value is + `4096`. + """ diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index 7490b25ef3..cd3d9f29d4 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -9,6 +9,7 @@ from .function_tool_param import FunctionToolParam from .file_search_tool_param import FileSearchToolParam from .code_interpreter_tool_param import CodeInterpreterToolParam +from .file_chunking_strategy_param import FileChunkingStrategyParam from .assistant_tool_choice_option_param import AssistantToolChoiceOptionParam from .threads.message_content_part_param import MessageContentPartParam from .assistant_response_format_option_param import AssistantResponseFormatOptionParam @@ -24,10 +25,6 @@ "ThreadToolResourcesCodeInterpreter", "ThreadToolResourcesFileSearch", "ThreadToolResourcesFileSearchVectorStore", - "ThreadToolResourcesFileSearchVectorStoreChunkingStrategy", - "ThreadToolResourcesFileSearchVectorStoreChunkingStrategyAuto", - "ThreadToolResourcesFileSearchVectorStoreChunkingStrategyStatic", - "ThreadToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic", "ToolResources", "ToolResourcesCodeInterpreter", "ToolResourcesFileSearch", @@ -218,44 +215,12 @@ class ThreadToolResourcesCodeInterpreter(TypedDict, total=False): """ -class ThreadToolResourcesFileSearchVectorStoreChunkingStrategyAuto(TypedDict, total=False): - type: Required[Literal["auto"]] - """Always `auto`.""" - - -class ThreadToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic(TypedDict, total=False): - chunk_overlap_tokens: Required[int] - """The number of tokens that overlap between chunks. The default value is `400`. - - Note that the overlap must not exceed half of `max_chunk_size_tokens`. - """ - - max_chunk_size_tokens: Required[int] - """The maximum number of tokens in each chunk. - - The default value is `800`. The minimum value is `100` and the maximum value is - `4096`. - """ - - -class ThreadToolResourcesFileSearchVectorStoreChunkingStrategyStatic(TypedDict, total=False): - static: Required[ThreadToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic] - - type: Required[Literal["static"]] - """Always `static`.""" - - -ThreadToolResourcesFileSearchVectorStoreChunkingStrategy: TypeAlias = Union[ - ThreadToolResourcesFileSearchVectorStoreChunkingStrategyAuto, - ThreadToolResourcesFileSearchVectorStoreChunkingStrategyStatic, -] - - class ThreadToolResourcesFileSearchVectorStore(TypedDict, total=False): - chunking_strategy: ThreadToolResourcesFileSearchVectorStoreChunkingStrategy + chunking_strategy: FileChunkingStrategyParam """The chunking strategy used to chunk the file(s). - If not set, will use the `auto` strategy. + If not set, will use the `auto` strategy. Only applicable if `file_ids` is + non-empty. """ file_ids: List[str] diff --git a/src/openai/types/beta/thread_create_params.py b/src/openai/types/beta/thread_create_params.py index f9561aa48c..729164b481 100644 --- a/src/openai/types/beta/thread_create_params.py +++ b/src/openai/types/beta/thread_create_params.py @@ -6,6 +6,7 @@ from typing_extensions import Literal, Required, TypeAlias, TypedDict from .code_interpreter_tool_param import CodeInterpreterToolParam +from .file_chunking_strategy_param import FileChunkingStrategyParam from .threads.message_content_part_param import MessageContentPartParam __all__ = [ @@ -18,10 +19,6 @@ "ToolResourcesCodeInterpreter", "ToolResourcesFileSearch", "ToolResourcesFileSearchVectorStore", - "ToolResourcesFileSearchVectorStoreChunkingStrategy", - "ToolResourcesFileSearchVectorStoreChunkingStrategyAuto", - "ToolResourcesFileSearchVectorStoreChunkingStrategyStatic", - "ToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic", ] @@ -99,43 +96,12 @@ class ToolResourcesCodeInterpreter(TypedDict, total=False): """ -class ToolResourcesFileSearchVectorStoreChunkingStrategyAuto(TypedDict, total=False): - type: Required[Literal["auto"]] - """Always `auto`.""" - - -class ToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic(TypedDict, total=False): - chunk_overlap_tokens: Required[int] - """The number of tokens that overlap between chunks. The default value is `400`. - - Note that the overlap must not exceed half of `max_chunk_size_tokens`. - """ - - max_chunk_size_tokens: Required[int] - """The maximum number of tokens in each chunk. - - The default value is `800`. The minimum value is `100` and the maximum value is - `4096`. - """ - - -class ToolResourcesFileSearchVectorStoreChunkingStrategyStatic(TypedDict, total=False): - static: Required[ToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic] - - type: Required[Literal["static"]] - """Always `static`.""" - - -ToolResourcesFileSearchVectorStoreChunkingStrategy: TypeAlias = Union[ - ToolResourcesFileSearchVectorStoreChunkingStrategyAuto, ToolResourcesFileSearchVectorStoreChunkingStrategyStatic -] - - class ToolResourcesFileSearchVectorStore(TypedDict, total=False): - chunking_strategy: ToolResourcesFileSearchVectorStoreChunkingStrategy + chunking_strategy: FileChunkingStrategyParam """The chunking strategy used to chunk the file(s). - If not set, will use the `auto` strategy. + If not set, will use the `auto` strategy. Only applicable if `file_ids` is + non-empty. """ file_ids: List[str] diff --git a/src/openai/types/beta/vector_store_create_params.py b/src/openai/types/beta/vector_store_create_params.py index 4f74af49f8..a8f03a89b9 100644 --- a/src/openai/types/beta/vector_store_create_params.py +++ b/src/openai/types/beta/vector_store_create_params.py @@ -2,21 +2,16 @@ from __future__ import annotations -from typing import List, Union, Optional -from typing_extensions import Literal, Required, TypeAlias, TypedDict +from typing import List, Optional +from typing_extensions import Literal, Required, TypedDict -__all__ = [ - "VectorStoreCreateParams", - "ChunkingStrategy", - "ChunkingStrategyAuto", - "ChunkingStrategyStatic", - "ChunkingStrategyStaticStatic", - "ExpiresAfter", -] +from .file_chunking_strategy_param import FileChunkingStrategyParam + +__all__ = ["VectorStoreCreateParams", "ExpiresAfter"] class VectorStoreCreateParams(TypedDict, total=False): - chunking_strategy: ChunkingStrategy + chunking_strategy: FileChunkingStrategyParam """The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. Only applicable if `file_ids` is @@ -45,36 +40,6 @@ class VectorStoreCreateParams(TypedDict, total=False): """The name of the vector store.""" -class ChunkingStrategyAuto(TypedDict, total=False): - type: Required[Literal["auto"]] - """Always `auto`.""" - - -class ChunkingStrategyStaticStatic(TypedDict, total=False): - chunk_overlap_tokens: Required[int] - """The number of tokens that overlap between chunks. The default value is `400`. - - Note that the overlap must not exceed half of `max_chunk_size_tokens`. - """ - - max_chunk_size_tokens: Required[int] - """The maximum number of tokens in each chunk. - - The default value is `800`. The minimum value is `100` and the maximum value is - `4096`. - """ - - -class ChunkingStrategyStatic(TypedDict, total=False): - static: Required[ChunkingStrategyStaticStatic] - - type: Required[Literal["static"]] - """Always `static`.""" - - -ChunkingStrategy: TypeAlias = Union[ChunkingStrategyAuto, ChunkingStrategyStatic] - - class ExpiresAfter(TypedDict, total=False): anchor: Required[Literal["last_active_at"]] """Anchor timestamp after which the expiration policy applies. diff --git a/src/openai/types/beta/vector_stores/file_batch_create_params.py b/src/openai/types/beta/vector_stores/file_batch_create_params.py index e1c3303cf3..e42ea99cd1 100644 --- a/src/openai/types/beta/vector_stores/file_batch_create_params.py +++ b/src/openai/types/beta/vector_stores/file_batch_create_params.py @@ -2,16 +2,12 @@ from __future__ import annotations -from typing import List, Union -from typing_extensions import Literal, Required, TypeAlias, TypedDict +from typing import List +from typing_extensions import Required, TypedDict -__all__ = [ - "FileBatchCreateParams", - "ChunkingStrategy", - "ChunkingStrategyAutoChunkingStrategyRequestParam", - "ChunkingStrategyStaticChunkingStrategyRequestParam", - "ChunkingStrategyStaticChunkingStrategyRequestParamStatic", -] +from ..file_chunking_strategy_param import FileChunkingStrategyParam + +__all__ = ["FileBatchCreateParams"] class FileBatchCreateParams(TypedDict, total=False): @@ -22,40 +18,9 @@ class FileBatchCreateParams(TypedDict, total=False): files. """ - chunking_strategy: ChunkingStrategy + chunking_strategy: FileChunkingStrategyParam """The chunking strategy used to chunk the file(s). - If not set, will use the `auto` strategy. - """ - - -class ChunkingStrategyAutoChunkingStrategyRequestParam(TypedDict, total=False): - type: Required[Literal["auto"]] - """Always `auto`.""" - - -class ChunkingStrategyStaticChunkingStrategyRequestParamStatic(TypedDict, total=False): - chunk_overlap_tokens: Required[int] - """The number of tokens that overlap between chunks. The default value is `400`. - - Note that the overlap must not exceed half of `max_chunk_size_tokens`. + If not set, will use the `auto` strategy. Only applicable if `file_ids` is + non-empty. """ - - max_chunk_size_tokens: Required[int] - """The maximum number of tokens in each chunk. - - The default value is `800`. The minimum value is `100` and the maximum value is - `4096`. - """ - - -class ChunkingStrategyStaticChunkingStrategyRequestParam(TypedDict, total=False): - static: Required[ChunkingStrategyStaticChunkingStrategyRequestParamStatic] - - type: Required[Literal["static"]] - """Always `static`.""" - - -ChunkingStrategy: TypeAlias = Union[ - ChunkingStrategyAutoChunkingStrategyRequestParam, ChunkingStrategyStaticChunkingStrategyRequestParam -] diff --git a/src/openai/types/beta/vector_stores/file_create_params.py b/src/openai/types/beta/vector_stores/file_create_params.py index cfb80657c6..d074d766e6 100644 --- a/src/openai/types/beta/vector_stores/file_create_params.py +++ b/src/openai/types/beta/vector_stores/file_create_params.py @@ -2,16 +2,11 @@ from __future__ import annotations -from typing import Union -from typing_extensions import Literal, Required, TypeAlias, TypedDict +from typing_extensions import Required, TypedDict -__all__ = [ - "FileCreateParams", - "ChunkingStrategy", - "ChunkingStrategyAutoChunkingStrategyRequestParam", - "ChunkingStrategyStaticChunkingStrategyRequestParam", - "ChunkingStrategyStaticChunkingStrategyRequestParamStatic", -] +from ..file_chunking_strategy_param import FileChunkingStrategyParam + +__all__ = ["FileCreateParams"] class FileCreateParams(TypedDict, total=False): @@ -22,40 +17,9 @@ class FileCreateParams(TypedDict, total=False): files. """ - chunking_strategy: ChunkingStrategy + chunking_strategy: FileChunkingStrategyParam """The chunking strategy used to chunk the file(s). - If not set, will use the `auto` strategy. - """ - - -class ChunkingStrategyAutoChunkingStrategyRequestParam(TypedDict, total=False): - type: Required[Literal["auto"]] - """Always `auto`.""" - - -class ChunkingStrategyStaticChunkingStrategyRequestParamStatic(TypedDict, total=False): - chunk_overlap_tokens: Required[int] - """The number of tokens that overlap between chunks. The default value is `400`. - - Note that the overlap must not exceed half of `max_chunk_size_tokens`. + If not set, will use the `auto` strategy. Only applicable if `file_ids` is + non-empty. """ - - max_chunk_size_tokens: Required[int] - """The maximum number of tokens in each chunk. - - The default value is `800`. The minimum value is `100` and the maximum value is - `4096`. - """ - - -class ChunkingStrategyStaticChunkingStrategyRequestParam(TypedDict, total=False): - static: Required[ChunkingStrategyStaticChunkingStrategyRequestParamStatic] - - type: Required[Literal["static"]] - """Always `static`.""" - - -ChunkingStrategy: TypeAlias = Union[ - ChunkingStrategyAutoChunkingStrategyRequestParam, ChunkingStrategyStaticChunkingStrategyRequestParam -] diff --git a/src/openai/types/beta/vector_stores/vector_store_file.py b/src/openai/types/beta/vector_stores/vector_store_file.py index 65096e8dad..e4608e159c 100644 --- a/src/openai/types/beta/vector_stores/vector_store_file.py +++ b/src/openai/types/beta/vector_stores/vector_store_file.py @@ -1,19 +1,12 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing import Union, Optional -from typing_extensions import Literal, Annotated, TypeAlias +from typing import Optional +from typing_extensions import Literal -from ...._utils import PropertyInfo from ...._models import BaseModel +from ..file_chunking_strategy import FileChunkingStrategy -__all__ = [ - "VectorStoreFile", - "LastError", - "ChunkingStrategy", - "ChunkingStrategyStatic", - "ChunkingStrategyStaticStatic", - "ChunkingStrategyOther", -] +__all__ = ["VectorStoreFile", "LastError"] class LastError(BaseModel): @@ -24,38 +17,6 @@ class LastError(BaseModel): """A human-readable description of the error.""" -class ChunkingStrategyStaticStatic(BaseModel): - chunk_overlap_tokens: int - """The number of tokens that overlap between chunks. The default value is `400`. - - Note that the overlap must not exceed half of `max_chunk_size_tokens`. - """ - - max_chunk_size_tokens: int - """The maximum number of tokens in each chunk. - - The default value is `800`. The minimum value is `100` and the maximum value is - `4096`. - """ - - -class ChunkingStrategyStatic(BaseModel): - static: ChunkingStrategyStaticStatic - - type: Literal["static"] - """Always `static`.""" - - -class ChunkingStrategyOther(BaseModel): - type: Literal["other"] - """Always `other`.""" - - -ChunkingStrategy: TypeAlias = Annotated[ - Union[ChunkingStrategyStatic, ChunkingStrategyOther], PropertyInfo(discriminator="type") -] - - class VectorStoreFile(BaseModel): id: str """The identifier, which can be referenced in API endpoints.""" @@ -93,5 +54,5 @@ class VectorStoreFile(BaseModel): attached to. """ - chunking_strategy: Optional[ChunkingStrategy] = None + chunking_strategy: Optional[FileChunkingStrategy] = None """The strategy used to chunk the file.""" From 93aa548201af70646fe651cc01fd875f32b00202 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 6 Sep 2024 09:27:30 +0000 Subject: [PATCH 488/816] release: 1.44.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 5b3c8f9482..ba2c5854ee 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.43.1" + ".": "1.44.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 7aa4280d4b..849d7b5e0b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.44.0 (2024-09-06) + +Full Changelog: [v1.43.1...v1.44.0](https://github.com/openai/openai-python/compare/v1.43.1...v1.44.0) + +### Features + +* **vector store:** improve chunking strategy type names ([#1690](https://github.com/openai/openai-python/issues/1690)) ([e82cd85](https://github.com/openai/openai-python/commit/e82cd85ac4962e36cb3b139c503069b56918688f)) + ## 1.43.1 (2024-09-05) Full Changelog: [v1.43.0...v1.43.1](https://github.com/openai/openai-python/compare/v1.43.0...v1.43.1) diff --git a/pyproject.toml b/pyproject.toml index 04ecef16e9..5d9d09e7da 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.43.1" +version = "1.44.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index ac6080b318..6be1f93a0f 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.43.1" # x-release-please-version +__version__ = "1.44.0" # x-release-please-version From 38dd5348b37ce3086137c8126a9b22982115c020 Mon Sep 17 00:00:00 2001 From: Adrian Cole <64215+codefromthecrypt@users.noreply.github.com> Date: Mon, 9 Sep 2024 18:17:21 +0800 Subject: [PATCH 489/816] docs(readme): improve custom `base_url` example (#1694) OPENAI_BASE_URL defaults to https://api.openai.com/v1, so if you add a replacement and forget to append the /v1, it will result in 404s --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 525c1b5aaf..d0cc9040a5 100644 --- a/README.md +++ b/README.md @@ -567,7 +567,7 @@ from openai import OpenAI, DefaultHttpxClient client = OpenAI( # Or use the `OPENAI_BASE_URL` env var - base_url="http://my.test.server.example.com:8083/", + base_url="http://my.test.server.example.com:8083/v1", http_client=DefaultHttpxClient( proxies="http://my.test.proxy.example.com/", transport=httpx.HTTPTransport(local_address="0.0.0.0"), From 3cf4acc65466ae77cab9d622fe1b46cbfdf05d45 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 9 Sep 2024 14:31:32 +0000 Subject: [PATCH 490/816] chore: add docstrings to raw response properties (#1696) --- src/openai/resources/audio/audio.py | 22 +++++++++++++++++++ src/openai/resources/audio/speech.py | 22 +++++++++++++++++++ src/openai/resources/audio/transcriptions.py | 22 +++++++++++++++++++ src/openai/resources/audio/translations.py | 22 +++++++++++++++++++ src/openai/resources/batches.py | 22 +++++++++++++++++++ src/openai/resources/beta/assistants.py | 22 +++++++++++++++++++ src/openai/resources/beta/beta.py | 22 +++++++++++++++++++ src/openai/resources/beta/threads/messages.py | 22 +++++++++++++++++++ .../resources/beta/threads/runs/runs.py | 22 +++++++++++++++++++ .../resources/beta/threads/runs/steps.py | 22 +++++++++++++++++++ src/openai/resources/beta/threads/threads.py | 22 +++++++++++++++++++ .../beta/vector_stores/file_batches.py | 22 +++++++++++++++++++ .../resources/beta/vector_stores/files.py | 22 +++++++++++++++++++ .../beta/vector_stores/vector_stores.py | 22 +++++++++++++++++++ src/openai/resources/chat/chat.py | 22 +++++++++++++++++++ src/openai/resources/chat/completions.py | 22 +++++++++++++++++++ src/openai/resources/completions.py | 22 +++++++++++++++++++ src/openai/resources/embeddings.py | 22 +++++++++++++++++++ src/openai/resources/files.py | 22 +++++++++++++++++++ .../resources/fine_tuning/fine_tuning.py | 22 +++++++++++++++++++ .../resources/fine_tuning/jobs/checkpoints.py | 22 +++++++++++++++++++ src/openai/resources/fine_tuning/jobs/jobs.py | 22 +++++++++++++++++++ src/openai/resources/images.py | 22 +++++++++++++++++++ src/openai/resources/models.py | 22 +++++++++++++++++++ src/openai/resources/moderations.py | 22 +++++++++++++++++++ src/openai/resources/uploads/parts.py | 22 +++++++++++++++++++ src/openai/resources/uploads/uploads.py | 22 +++++++++++++++++++ 27 files changed, 594 insertions(+) diff --git a/src/openai/resources/audio/audio.py b/src/openai/resources/audio/audio.py index 537ad573d0..18bd7b812c 100644 --- a/src/openai/resources/audio/audio.py +++ b/src/openai/resources/audio/audio.py @@ -47,10 +47,21 @@ def speech(self) -> Speech: @cached_property def with_raw_response(self) -> AudioWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AudioWithRawResponse(self) @cached_property def with_streaming_response(self) -> AudioWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AudioWithStreamingResponse(self) @@ -69,10 +80,21 @@ def speech(self) -> AsyncSpeech: @cached_property def with_raw_response(self) -> AsyncAudioWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncAudioWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncAudioWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncAudioWithStreamingResponse(self) diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index a0df9ec487..6085ae8afe 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -31,10 +31,21 @@ class Speech(SyncAPIResource): @cached_property def with_raw_response(self) -> SpeechWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return SpeechWithRawResponse(self) @cached_property def with_streaming_response(self) -> SpeechWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return SpeechWithStreamingResponse(self) def create( @@ -104,10 +115,21 @@ def create( class AsyncSpeech(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncSpeechWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncSpeechWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncSpeechWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncSpeechWithStreamingResponse(self) async def create( diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index 1ee962411c..a6009143d4 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -29,10 +29,21 @@ class Transcriptions(SyncAPIResource): @cached_property def with_raw_response(self) -> TranscriptionsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return TranscriptionsWithRawResponse(self) @cached_property def with_streaming_response(self) -> TranscriptionsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return TranscriptionsWithStreamingResponse(self) def create( @@ -125,10 +136,21 @@ def create( class AsyncTranscriptions(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncTranscriptionsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncTranscriptionsWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncTranscriptionsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncTranscriptionsWithStreamingResponse(self) async def create( diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index ed97ccf840..7ec647fb6b 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -28,10 +28,21 @@ class Translations(SyncAPIResource): @cached_property def with_raw_response(self) -> TranslationsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return TranslationsWithRawResponse(self) @cached_property def with_streaming_response(self) -> TranslationsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return TranslationsWithStreamingResponse(self) def create( @@ -109,10 +120,21 @@ def create( class AsyncTranslations(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncTranslationsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncTranslationsWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncTranslationsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncTranslationsWithStreamingResponse(self) async def create( diff --git a/src/openai/resources/batches.py b/src/openai/resources/batches.py index 7152fac622..a8a0ba4bbc 100644 --- a/src/openai/resources/batches.py +++ b/src/openai/resources/batches.py @@ -30,10 +30,21 @@ class Batches(SyncAPIResource): @cached_property def with_raw_response(self) -> BatchesWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return BatchesWithRawResponse(self) @cached_property def with_streaming_response(self) -> BatchesWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return BatchesWithStreamingResponse(self) def create( @@ -224,10 +235,21 @@ def cancel( class AsyncBatches(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncBatchesWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncBatchesWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncBatchesWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncBatchesWithStreamingResponse(self) async def create( diff --git a/src/openai/resources/beta/assistants.py b/src/openai/resources/beta/assistants.py index 441390d24b..1e57944eb3 100644 --- a/src/openai/resources/beta/assistants.py +++ b/src/openai/resources/beta/assistants.py @@ -35,10 +35,21 @@ class Assistants(SyncAPIResource): @cached_property def with_raw_response(self) -> AssistantsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AssistantsWithRawResponse(self) @cached_property def with_streaming_response(self) -> AssistantsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AssistantsWithStreamingResponse(self) def create( @@ -410,10 +421,21 @@ def delete( class AsyncAssistants(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncAssistantsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncAssistantsWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncAssistantsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncAssistantsWithStreamingResponse(self) async def create( diff --git a/src/openai/resources/beta/beta.py b/src/openai/resources/beta/beta.py index 479c97c471..a7d3e707c8 100644 --- a/src/openai/resources/beta/beta.py +++ b/src/openai/resources/beta/beta.py @@ -54,10 +54,21 @@ def threads(self) -> Threads: @cached_property def with_raw_response(self) -> BetaWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return BetaWithRawResponse(self) @cached_property def with_streaming_response(self) -> BetaWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return BetaWithStreamingResponse(self) @@ -80,10 +91,21 @@ def threads(self) -> AsyncThreads: @cached_property def with_raw_response(self) -> AsyncBetaWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncBetaWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncBetaWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncBetaWithStreamingResponse(self) diff --git a/src/openai/resources/beta/threads/messages.py b/src/openai/resources/beta/threads/messages.py index f0832515ce..4901174329 100644 --- a/src/openai/resources/beta/threads/messages.py +++ b/src/openai/resources/beta/threads/messages.py @@ -32,10 +32,21 @@ class Messages(SyncAPIResource): @cached_property def with_raw_response(self) -> MessagesWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return MessagesWithRawResponse(self) @cached_property def with_streaming_response(self) -> MessagesWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return MessagesWithStreamingResponse(self) def create( @@ -295,10 +306,21 @@ def delete( class AsyncMessages(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncMessagesWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncMessagesWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncMessagesWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncMessagesWithStreamingResponse(self) async def create( diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 4f39912e62..807027a644 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -63,10 +63,21 @@ def steps(self) -> Steps: @cached_property def with_raw_response(self) -> RunsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return RunsWithRawResponse(self) @cached_property def with_streaming_response(self) -> RunsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return RunsWithStreamingResponse(self) @overload @@ -1414,10 +1425,21 @@ def steps(self) -> AsyncSteps: @cached_property def with_raw_response(self) -> AsyncRunsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncRunsWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncRunsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncRunsWithStreamingResponse(self) @overload diff --git a/src/openai/resources/beta/threads/runs/steps.py b/src/openai/resources/beta/threads/runs/steps.py index 3d2d40a3fb..5d6d55f9d9 100644 --- a/src/openai/resources/beta/threads/runs/steps.py +++ b/src/openai/resources/beta/threads/runs/steps.py @@ -28,10 +28,21 @@ class Steps(SyncAPIResource): @cached_property def with_raw_response(self) -> StepsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return StepsWithRawResponse(self) @cached_property def with_streaming_response(self) -> StepsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return StepsWithStreamingResponse(self) def retrieve( @@ -171,10 +182,21 @@ def list( class AsyncSteps(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncStepsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncStepsWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncStepsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncStepsWithStreamingResponse(self) async def retrieve( diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 4c95c484cc..031121e5cc 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -72,10 +72,21 @@ def messages(self) -> Messages: @cached_property def with_raw_response(self) -> ThreadsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return ThreadsWithRawResponse(self) @cached_property def with_streaming_response(self) -> ThreadsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return ThreadsWithStreamingResponse(self) def create( @@ -895,10 +906,21 @@ def messages(self) -> AsyncMessages: @cached_property def with_raw_response(self) -> AsyncThreadsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncThreadsWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncThreadsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncThreadsWithStreamingResponse(self) async def create( diff --git a/src/openai/resources/beta/vector_stores/file_batches.py b/src/openai/resources/beta/vector_stores/file_batches.py index a350ed0bea..d1f9c872e4 100644 --- a/src/openai/resources/beta/vector_stores/file_batches.py +++ b/src/openai/resources/beta/vector_stores/file_batches.py @@ -35,10 +35,21 @@ class FileBatches(SyncAPIResource): @cached_property def with_raw_response(self) -> FileBatchesWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return FileBatchesWithRawResponse(self) @cached_property def with_streaming_response(self) -> FileBatchesWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return FileBatchesWithStreamingResponse(self) def create( @@ -353,10 +364,21 @@ def upload_and_poll( class AsyncFileBatches(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncFileBatchesWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncFileBatchesWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncFileBatchesWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncFileBatchesWithStreamingResponse(self) async def create( diff --git a/src/openai/resources/beta/vector_stores/files.py b/src/openai/resources/beta/vector_stores/files.py index ba43519c75..fe43bb3488 100644 --- a/src/openai/resources/beta/vector_stores/files.py +++ b/src/openai/resources/beta/vector_stores/files.py @@ -31,10 +31,21 @@ class Files(SyncAPIResource): @cached_property def with_raw_response(self) -> FilesWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return FilesWithRawResponse(self) @cached_property def with_streaming_response(self) -> FilesWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return FilesWithStreamingResponse(self) def create( @@ -332,10 +343,21 @@ def upload_and_poll( class AsyncFiles(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncFilesWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncFilesWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncFilesWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncFilesWithStreamingResponse(self) async def create( diff --git a/src/openai/resources/beta/vector_stores/vector_stores.py b/src/openai/resources/beta/vector_stores/vector_stores.py index c93b3bc41f..06e26852b4 100644 --- a/src/openai/resources/beta/vector_stores/vector_stores.py +++ b/src/openai/resources/beta/vector_stores/vector_stores.py @@ -58,10 +58,21 @@ def file_batches(self) -> FileBatches: @cached_property def with_raw_response(self) -> VectorStoresWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return VectorStoresWithRawResponse(self) @cached_property def with_streaming_response(self) -> VectorStoresWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return VectorStoresWithStreamingResponse(self) def create( @@ -325,10 +336,21 @@ def file_batches(self) -> AsyncFileBatches: @cached_property def with_raw_response(self) -> AsyncVectorStoresWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncVectorStoresWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncVectorStoresWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncVectorStoresWithStreamingResponse(self) async def create( diff --git a/src/openai/resources/chat/chat.py b/src/openai/resources/chat/chat.py index d14d055506..dc23a15a8e 100644 --- a/src/openai/resources/chat/chat.py +++ b/src/openai/resources/chat/chat.py @@ -23,10 +23,21 @@ def completions(self) -> Completions: @cached_property def with_raw_response(self) -> ChatWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return ChatWithRawResponse(self) @cached_property def with_streaming_response(self) -> ChatWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return ChatWithStreamingResponse(self) @@ -37,10 +48,21 @@ def completions(self) -> AsyncCompletions: @cached_property def with_raw_response(self) -> AsyncChatWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncChatWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncChatWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncChatWithStreamingResponse(self) diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index dc577d6251..ec76bfdf52 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -36,10 +36,21 @@ class Completions(SyncAPIResource): @cached_property def with_raw_response(self) -> CompletionsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return CompletionsWithRawResponse(self) @cached_property def with_streaming_response(self) -> CompletionsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return CompletionsWithStreamingResponse(self) @overload @@ -707,10 +718,21 @@ def create( class AsyncCompletions(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncCompletionsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncCompletionsWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncCompletionsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncCompletionsWithStreamingResponse(self) @overload diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index 0812000f78..091fb5657a 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -31,10 +31,21 @@ class Completions(SyncAPIResource): @cached_property def with_raw_response(self) -> CompletionsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return CompletionsWithRawResponse(self) @cached_property def with_streaming_response(self) -> CompletionsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return CompletionsWithStreamingResponse(self) @overload @@ -562,10 +573,21 @@ def create( class AsyncCompletions(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncCompletionsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncCompletionsWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncCompletionsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncCompletionsWithStreamingResponse(self) @overload diff --git a/src/openai/resources/embeddings.py b/src/openai/resources/embeddings.py index 773b6f0968..71c2a18a24 100644 --- a/src/openai/resources/embeddings.py +++ b/src/openai/resources/embeddings.py @@ -27,10 +27,21 @@ class Embeddings(SyncAPIResource): @cached_property def with_raw_response(self) -> EmbeddingsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return EmbeddingsWithRawResponse(self) @cached_property def with_streaming_response(self) -> EmbeddingsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return EmbeddingsWithStreamingResponse(self) def create( @@ -128,10 +139,21 @@ def parser(obj: CreateEmbeddingResponse) -> CreateEmbeddingResponse: class AsyncEmbeddings(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncEmbeddingsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncEmbeddingsWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncEmbeddingsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncEmbeddingsWithStreamingResponse(self) async def create( diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index a240e1d886..e24eeec711 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -42,10 +42,21 @@ class Files(SyncAPIResource): @cached_property def with_raw_response(self) -> FilesWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return FilesWithRawResponse(self) @cached_property def with_streaming_response(self) -> FilesWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return FilesWithStreamingResponse(self) def create( @@ -324,10 +335,21 @@ def wait_for_processing( class AsyncFiles(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncFilesWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncFilesWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncFilesWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncFilesWithStreamingResponse(self) async def create( diff --git a/src/openai/resources/fine_tuning/fine_tuning.py b/src/openai/resources/fine_tuning/fine_tuning.py index 0404fed6ec..c386de3c2a 100644 --- a/src/openai/resources/fine_tuning/fine_tuning.py +++ b/src/openai/resources/fine_tuning/fine_tuning.py @@ -24,10 +24,21 @@ def jobs(self) -> Jobs: @cached_property def with_raw_response(self) -> FineTuningWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return FineTuningWithRawResponse(self) @cached_property def with_streaming_response(self) -> FineTuningWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return FineTuningWithStreamingResponse(self) @@ -38,10 +49,21 @@ def jobs(self) -> AsyncJobs: @cached_property def with_raw_response(self) -> AsyncFineTuningWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncFineTuningWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncFineTuningWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncFineTuningWithStreamingResponse(self) diff --git a/src/openai/resources/fine_tuning/jobs/checkpoints.py b/src/openai/resources/fine_tuning/jobs/checkpoints.py index 67f5739a02..8b5e905ea5 100644 --- a/src/openai/resources/fine_tuning/jobs/checkpoints.py +++ b/src/openai/resources/fine_tuning/jobs/checkpoints.py @@ -24,10 +24,21 @@ class Checkpoints(SyncAPIResource): @cached_property def with_raw_response(self) -> CheckpointsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return CheckpointsWithRawResponse(self) @cached_property def with_streaming_response(self) -> CheckpointsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return CheckpointsWithStreamingResponse(self) def list( @@ -84,10 +95,21 @@ def list( class AsyncCheckpoints(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncCheckpointsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncCheckpointsWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncCheckpointsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncCheckpointsWithStreamingResponse(self) def list( diff --git a/src/openai/resources/fine_tuning/jobs/jobs.py b/src/openai/resources/fine_tuning/jobs/jobs.py index 5cef7bcd22..ca4799e7ac 100644 --- a/src/openai/resources/fine_tuning/jobs/jobs.py +++ b/src/openai/resources/fine_tuning/jobs/jobs.py @@ -43,10 +43,21 @@ def checkpoints(self) -> Checkpoints: @cached_property def with_raw_response(self) -> JobsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return JobsWithRawResponse(self) @cached_property def with_streaming_response(self) -> JobsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return JobsWithStreamingResponse(self) def create( @@ -323,10 +334,21 @@ def checkpoints(self) -> AsyncCheckpoints: @cached_property def with_raw_response(self) -> AsyncJobsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncJobsWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncJobsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncJobsWithStreamingResponse(self) async def create( diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py index 0913b572cb..e9629d48fd 100644 --- a/src/openai/resources/images.py +++ b/src/openai/resources/images.py @@ -29,10 +29,21 @@ class Images(SyncAPIResource): @cached_property def with_raw_response(self) -> ImagesWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return ImagesWithRawResponse(self) @cached_property def with_streaming_response(self) -> ImagesWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return ImagesWithStreamingResponse(self) def create_variation( @@ -275,10 +286,21 @@ def generate( class AsyncImages(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncImagesWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncImagesWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncImagesWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncImagesWithStreamingResponse(self) async def create_variation( diff --git a/src/openai/resources/models.py b/src/openai/resources/models.py index e76c496ffa..d6062de230 100644 --- a/src/openai/resources/models.py +++ b/src/openai/resources/models.py @@ -23,10 +23,21 @@ class Models(SyncAPIResource): @cached_property def with_raw_response(self) -> ModelsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return ModelsWithRawResponse(self) @cached_property def with_streaming_response(self) -> ModelsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return ModelsWithStreamingResponse(self) def retrieve( @@ -125,10 +136,21 @@ def delete( class AsyncModels(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncModelsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncModelsWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncModelsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncModelsWithStreamingResponse(self) async def retrieve( diff --git a/src/openai/resources/moderations.py b/src/openai/resources/moderations.py index b9ad9972f0..5283554373 100644 --- a/src/openai/resources/moderations.py +++ b/src/openai/resources/moderations.py @@ -26,10 +26,21 @@ class Moderations(SyncAPIResource): @cached_property def with_raw_response(self) -> ModerationsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return ModerationsWithRawResponse(self) @cached_property def with_streaming_response(self) -> ModerationsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return ModerationsWithStreamingResponse(self) def create( @@ -86,10 +97,21 @@ def create( class AsyncModerations(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncModerationsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncModerationsWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncModerationsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncModerationsWithStreamingResponse(self) async def create( diff --git a/src/openai/resources/uploads/parts.py b/src/openai/resources/uploads/parts.py index 3ec2592b1e..d46e5ea1bb 100644 --- a/src/openai/resources/uploads/parts.py +++ b/src/openai/resources/uploads/parts.py @@ -27,10 +27,21 @@ class Parts(SyncAPIResource): @cached_property def with_raw_response(self) -> PartsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return PartsWithRawResponse(self) @cached_property def with_streaming_response(self) -> PartsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return PartsWithStreamingResponse(self) def create( @@ -91,10 +102,21 @@ def create( class AsyncParts(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncPartsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncPartsWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncPartsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncPartsWithStreamingResponse(self) async def create( diff --git a/src/openai/resources/uploads/uploads.py b/src/openai/resources/uploads/uploads.py index 5eecef4d4b..96a531a8e4 100644 --- a/src/openai/resources/uploads/uploads.py +++ b/src/openai/resources/uploads/uploads.py @@ -50,10 +50,21 @@ def parts(self) -> Parts: @cached_property def with_raw_response(self) -> UploadsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return UploadsWithRawResponse(self) @cached_property def with_streaming_response(self) -> UploadsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return UploadsWithStreamingResponse(self) @overload @@ -332,10 +343,21 @@ def parts(self) -> AsyncParts: @cached_property def with_raw_response(self) -> AsyncUploadsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ return AsyncUploadsWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncUploadsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ return AsyncUploadsWithStreamingResponse(self) @overload From fee1040459c4c7b2dbfd43fa2c85192cd3e2eae0 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 9 Sep 2024 14:41:46 +0000 Subject: [PATCH 491/816] docs(readme): add section on determining installed version (#1697) --- README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/README.md b/README.md index d0cc9040a5..8c73fdd82a 100644 --- a/README.md +++ b/README.md @@ -639,6 +639,17 @@ We take backwards-compatibility seriously and work hard to ensure you can rely o We are keen for your feedback; please open an [issue](https://www.github.com/openai/openai-python/issues) with questions, bugs, or suggestions. +### Determining the installed version + +If you've upgraded to the latest version but aren't seeing any new features you were expecting then your python environment is likely still using an older version. + +You can determine the version that is being used at runtime with: + +```py +import openai +print(openai.__version__) +``` + ## Requirements Python 3.7 or higher. From 6b07089ae031d64805c2e5eb6a33624ff0e64e84 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 9 Sep 2024 14:42:18 +0000 Subject: [PATCH 492/816] release: 1.44.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 14 ++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 17 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index ba2c5854ee..1ee5dee6dd 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.44.0" + ".": "1.44.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 849d7b5e0b..47fa2d9208 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,19 @@ # Changelog +## 1.44.1 (2024-09-09) + +Full Changelog: [v1.44.0...v1.44.1](https://github.com/openai/openai-python/compare/v1.44.0...v1.44.1) + +### Chores + +* add docstrings to raw response properties ([#1696](https://github.com/openai/openai-python/issues/1696)) ([1d2a19b](https://github.com/openai/openai-python/commit/1d2a19b0e8acab54c35ef2171d33321943488fdc)) + + +### Documentation + +* **readme:** add section on determining installed version ([#1697](https://github.com/openai/openai-python/issues/1697)) ([0255735](https://github.com/openai/openai-python/commit/0255735930d9c657c78e85e7f03fd1eb98a1e378)) +* **readme:** improve custom `base_url` example ([#1694](https://github.com/openai/openai-python/issues/1694)) ([05eec8a](https://github.com/openai/openai-python/commit/05eec8a0b7fcdc8651021f2e685214a353b861d1)) + ## 1.44.0 (2024-09-06) Full Changelog: [v1.43.1...v1.44.0](https://github.com/openai/openai-python/compare/v1.43.1...v1.44.0) diff --git a/pyproject.toml b/pyproject.toml index 5d9d09e7da..d4b7d2b210 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.44.0" +version = "1.44.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 6be1f93a0f..39c7f63e1e 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.44.0" # x-release-please-version +__version__ = "1.44.1" # x-release-please-version From 23b96159c080d6c9b413a69548d325aa40315b95 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Tue, 10 Sep 2024 16:46:51 +0100 Subject: [PATCH 493/816] feat(errors): include completion in LengthFinishReasonError (#1701) --- src/openai/_exceptions.py | 23 +++++++++++++++---- src/openai/lib/_parsing/_completions.py | 2 +- src/openai/lib/streaming/chat/_completions.py | 4 +++- 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/openai/_exceptions.py b/src/openai/_exceptions.py index f44f90b52f..e326ed9578 100644 --- a/src/openai/_exceptions.py +++ b/src/openai/_exceptions.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Any, Optional, cast +from typing import TYPE_CHECKING, Any, Optional, cast from typing_extensions import Literal import httpx @@ -10,6 +10,9 @@ from ._utils import is_dict from ._models import construct_type +if TYPE_CHECKING: + from .types.chat import ChatCompletion + __all__ = [ "BadRequestError", "AuthenticationError", @@ -130,10 +133,20 @@ class InternalServerError(APIStatusError): class LengthFinishReasonError(OpenAIError): - def __init__(self) -> None: - super().__init__( - f"Could not parse response content as the length limit was reached", - ) + completion: ChatCompletion + """The completion that caused this error. + + Note: this will *not* be a complete `ChatCompletion` object when streaming as `usage` + will not be included. + """ + + def __init__(self, *, completion: ChatCompletion) -> None: + msg = "Could not parse response content as the length limit was reached" + if completion.usage: + msg += f" - {completion.usage}" + + super().__init__(msg) + self.completion = completion class ContentFilterFinishReasonError(OpenAIError): diff --git a/src/openai/lib/_parsing/_completions.py b/src/openai/lib/_parsing/_completions.py index 2ef1bf3553..f1fa9f2b55 100644 --- a/src/openai/lib/_parsing/_completions.py +++ b/src/openai/lib/_parsing/_completions.py @@ -69,7 +69,7 @@ def parse_chat_completion( choices: list[ParsedChoice[ResponseFormatT]] = [] for choice in chat_completion.choices: if choice.finish_reason == "length": - raise LengthFinishReasonError() + raise LengthFinishReasonError(completion=chat_completion) if choice.finish_reason == "content_filter": raise ContentFilterFinishReasonError() diff --git a/src/openai/lib/streaming/chat/_completions.py b/src/openai/lib/streaming/chat/_completions.py index 342a5e2b95..a4b0f856f7 100644 --- a/src/openai/lib/streaming/chat/_completions.py +++ b/src/openai/lib/streaming/chat/_completions.py @@ -394,7 +394,9 @@ def _accumulate_chunk(self, chunk: ChatCompletionChunk) -> ParsedChatCompletionS if has_parseable_input(response_format=self._response_format, input_tools=self._input_tools): if choice.finish_reason == "length": - raise LengthFinishReasonError() + # at the time of writing, `.usage` will always be `None` but + # we include it here in case that is changed in the future + raise LengthFinishReasonError(completion=completion_snapshot) if choice.finish_reason == "content_filter": raise ContentFilterFinishReasonError() From a6e9db84c1952c856c8449536714b7a7daa22d2e Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 12 Sep 2024 14:11:58 +0000 Subject: [PATCH 494/816] fix(types): correctly mark stream discriminator as optional (#1706) --- src/openai/types/beta/thread_create_and_run_params.py | 2 +- src/openai/types/beta/threads/run_create_params.py | 2 +- src/openai/types/beta/threads/run_submit_tool_outputs_params.py | 2 +- src/openai/types/chat/completion_create_params.py | 2 +- src/openai/types/completion_create_params.py | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index cd3d9f29d4..370c2f9bce 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -332,7 +332,7 @@ class TruncationStrategy(TypedDict, total=False): """ -class ThreadCreateAndRunParamsNonStreaming(ThreadCreateAndRunParamsBase): +class ThreadCreateAndRunParamsNonStreaming(ThreadCreateAndRunParamsBase, total=False): stream: Optional[Literal[False]] """ If `true`, returns a stream of events that happen during the Run as server-sent diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index 8bb73ddc78..7c5f571d58 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -225,7 +225,7 @@ class TruncationStrategy(TypedDict, total=False): """ -class RunCreateParamsNonStreaming(RunCreateParamsBase): +class RunCreateParamsNonStreaming(RunCreateParamsBase, total=False): stream: Optional[Literal[False]] """ If `true`, returns a stream of events that happen during the Run as server-sent diff --git a/src/openai/types/beta/threads/run_submit_tool_outputs_params.py b/src/openai/types/beta/threads/run_submit_tool_outputs_params.py index ccb5e5e97e..147728603a 100644 --- a/src/openai/types/beta/threads/run_submit_tool_outputs_params.py +++ b/src/openai/types/beta/threads/run_submit_tool_outputs_params.py @@ -31,7 +31,7 @@ class ToolOutput(TypedDict, total=False): """ -class RunSubmitToolOutputsParamsNonStreaming(RunSubmitToolOutputsParamsBase): +class RunSubmitToolOutputsParamsNonStreaming(RunSubmitToolOutputsParamsBase, total=False): stream: Optional[Literal[False]] """ If `true`, returns a stream of events that happen during the Run as server-sent diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 91435dcedd..b86dab742b 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -262,7 +262,7 @@ class Function(TypedDict, total=False): ResponseFormat: TypeAlias = Union[ResponseFormatText, ResponseFormatJSONObject, ResponseFormatJSONSchema] -class CompletionCreateParamsNonStreaming(CompletionCreateParamsBase): +class CompletionCreateParamsNonStreaming(CompletionCreateParamsBase, total=False): stream: Optional[Literal[False]] """If set, partial message deltas will be sent, like in ChatGPT. diff --git a/src/openai/types/completion_create_params.py b/src/openai/types/completion_create_params.py index 9fe22fe3c9..6c112b3902 100644 --- a/src/openai/types/completion_create_params.py +++ b/src/openai/types/completion_create_params.py @@ -160,7 +160,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): """ -class CompletionCreateParamsNonStreaming(CompletionCreateParamsBase): +class CompletionCreateParamsNonStreaming(CompletionCreateParamsBase, total=False): stream: Optional[Literal[False]] """Whether to stream back partial progress. From 2bfec1a2f0be308053924ba673398cd18a038422 Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Thu, 12 Sep 2024 16:54:32 +0000 Subject: [PATCH 495/816] feat(api): add o1 models (#1708) See https://platform.openai.com/docs/guides/reasoning for details. --- .stats.yml | 2 +- src/openai/resources/beta/assistants.py | 24 +-- src/openai/resources/beta/chat/completions.py | 8 + .../resources/beta/threads/runs/runs.py | 36 ++-- src/openai/resources/beta/threads/threads.py | 36 ++-- src/openai/resources/chat/completions.py | 172 ++++++++++++------ src/openai/resources/fine_tuning/jobs/jobs.py | 4 +- src/openai/types/beta/assistant.py | 6 +- .../types/beta/assistant_create_params.py | 6 +- .../types/beta/assistant_update_params.py | 6 +- src/openai/types/beta/file_search_tool.py | 15 +- .../types/beta/file_search_tool_param.py | 15 +- .../beta/thread_create_and_run_params.py | 6 +- src/openai/types/beta/threads/run.py | 6 +- .../types/beta/threads/run_create_params.py | 6 +- .../types/chat/completion_create_params.py | 30 ++- src/openai/types/chat_model.py | 7 +- src/openai/types/completion_usage.py | 11 +- .../types/fine_tuning/job_create_params.py | 2 +- tests/api_resources/chat/test_completions.py | 4 + tests/lib/chat/test_completions.py | 8 +- tests/lib/chat/test_completions_streaming.py | 2 +- 22 files changed, 253 insertions(+), 159 deletions(-) diff --git a/.stats.yml b/.stats.yml index 903c159960..de3167f3a8 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-85a85e0c08de456441431c0ae4e9c078cc8f9748c29430b9a9058340db6389ee.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-501122aa32adaa2abb3d4487880ab9cdf2141addce2e6c3d1bd9bb6b44c318a8.yml diff --git a/src/openai/resources/beta/assistants.py b/src/openai/resources/beta/assistants.py index 1e57944eb3..5d8c6ec331 100644 --- a/src/openai/resources/beta/assistants.py +++ b/src/openai/resources/beta/assistants.py @@ -100,11 +100,11 @@ def create( and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to @@ -250,11 +250,11 @@ def update( and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to @@ -486,11 +486,11 @@ async def create( and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to @@ -636,11 +636,11 @@ async def update( and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to diff --git a/src/openai/resources/beta/chat/completions.py b/src/openai/resources/beta/chat/completions.py index 07eda27b76..ea3526778d 100644 --- a/src/openai/resources/beta/chat/completions.py +++ b/src/openai/resources/beta/chat/completions.py @@ -42,6 +42,7 @@ def parse( functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, @@ -121,6 +122,7 @@ class MathResponse(BaseModel): functions=functions, logit_bias=logit_bias, logprobs=logprobs, + max_completion_tokens=max_completion_tokens, max_tokens=max_tokens, n=n, parallel_tool_calls=parallel_tool_calls, @@ -157,6 +159,7 @@ def stream( functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, @@ -216,6 +219,7 @@ def stream( functions=functions, logit_bias=logit_bias, logprobs=logprobs, + max_completion_tokens=max_completion_tokens, max_tokens=max_tokens, n=n, parallel_tool_calls=parallel_tool_calls, @@ -254,6 +258,7 @@ async def parse( functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, @@ -333,6 +338,7 @@ class MathResponse(BaseModel): functions=functions, logit_bias=logit_bias, logprobs=logprobs, + max_completion_tokens=max_completion_tokens, max_tokens=max_tokens, n=n, parallel_tool_calls=parallel_tool_calls, @@ -369,6 +375,7 @@ def stream( functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, @@ -429,6 +436,7 @@ def stream( functions=functions, logit_bias=logit_bias, logprobs=logprobs, + max_completion_tokens=max_completion_tokens, max_tokens=max_tokens, n=n, parallel_tool_calls=parallel_tool_calls, diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 807027a644..3fb1cc77aa 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -167,11 +167,11 @@ def create( and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to @@ -311,11 +311,11 @@ def create( and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to @@ -451,11 +451,11 @@ def create( and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to @@ -1529,11 +1529,11 @@ async def create( and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to @@ -1673,11 +1673,11 @@ async def create( and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to @@ -1813,11 +1813,11 @@ async def create( and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 031121e5cc..49b0e4b37e 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -335,11 +335,11 @@ def create_and_run( and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to @@ -469,11 +469,11 @@ def create_and_run( and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to @@ -599,11 +599,11 @@ def create_and_run( and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to @@ -1169,11 +1169,11 @@ async def create_and_run( and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to @@ -1303,11 +1303,11 @@ async def create_and_run( and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to @@ -1433,11 +1433,11 @@ async def create_and_run( and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index ec76bfdf52..e9267b1f03 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -64,6 +64,7 @@ def create( functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, @@ -132,13 +133,17 @@ def create( returns the log probabilities of each output token returned in the `content` of `message`. + max_completion_tokens: An upper bound for the number of tokens that can be generated for a completion, + including visible output tokens and + [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). + max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the chat - completion. + completion. This value can be used to control + [costs](https://openai.com/api/pricing/) for text generated via API. - The total length of input tokens and generated tokens is limited by the model's - context length. - [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) - for counting tokens. + This value is now deprecated in favor of `max_completion_tokens`, and is not + compatible with + [o1 series models](https://platform.openai.com/docs/guides/reasoning). n: How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the @@ -161,11 +166,11 @@ def create( all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to @@ -185,8 +190,11 @@ def create( service_tier: Specifies the latency tier to use for processing the request. This parameter is relevant for customers subscribed to the scale tier service: - - If set to 'auto', the system will utilize scale tier credits until they are - exhausted. + - If set to 'auto', and the Project is Scale tier enabled, the system will + utilize scale tier credits until they are exhausted. + - If set to 'auto', and the Project is not Scale tier enabled, the request will + be processed using the default service tier with a lower uptime SLA and no + latency guarentee. - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. - When not set, the default behavior is 'auto'. @@ -261,6 +269,7 @@ def create( functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, @@ -335,13 +344,17 @@ def create( returns the log probabilities of each output token returned in the `content` of `message`. + max_completion_tokens: An upper bound for the number of tokens that can be generated for a completion, + including visible output tokens and + [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). + max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the chat - completion. + completion. This value can be used to control + [costs](https://openai.com/api/pricing/) for text generated via API. - The total length of input tokens and generated tokens is limited by the model's - context length. - [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) - for counting tokens. + This value is now deprecated in favor of `max_completion_tokens`, and is not + compatible with + [o1 series models](https://platform.openai.com/docs/guides/reasoning). n: How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the @@ -364,11 +377,11 @@ def create( all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to @@ -388,8 +401,11 @@ def create( service_tier: Specifies the latency tier to use for processing the request. This parameter is relevant for customers subscribed to the scale tier service: - - If set to 'auto', the system will utilize scale tier credits until they are - exhausted. + - If set to 'auto', and the Project is Scale tier enabled, the system will + utilize scale tier credits until they are exhausted. + - If set to 'auto', and the Project is not Scale tier enabled, the request will + be processed using the default service tier with a lower uptime SLA and no + latency guarentee. - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. - When not set, the default behavior is 'auto'. @@ -457,6 +473,7 @@ def create( functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, @@ -531,13 +548,17 @@ def create( returns the log probabilities of each output token returned in the `content` of `message`. + max_completion_tokens: An upper bound for the number of tokens that can be generated for a completion, + including visible output tokens and + [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). + max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the chat - completion. + completion. This value can be used to control + [costs](https://openai.com/api/pricing/) for text generated via API. - The total length of input tokens and generated tokens is limited by the model's - context length. - [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) - for counting tokens. + This value is now deprecated in favor of `max_completion_tokens`, and is not + compatible with + [o1 series models](https://platform.openai.com/docs/guides/reasoning). n: How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the @@ -560,11 +581,11 @@ def create( all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to @@ -584,8 +605,11 @@ def create( service_tier: Specifies the latency tier to use for processing the request. This parameter is relevant for customers subscribed to the scale tier service: - - If set to 'auto', the system will utilize scale tier credits until they are - exhausted. + - If set to 'auto', and the Project is Scale tier enabled, the system will + utilize scale tier credits until they are exhausted. + - If set to 'auto', and the Project is not Scale tier enabled, the request will + be processed using the default service tier with a lower uptime SLA and no + latency guarentee. - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. - When not set, the default behavior is 'auto'. @@ -652,6 +676,7 @@ def create( functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, @@ -687,6 +712,7 @@ def create( "functions": functions, "logit_bias": logit_bias, "logprobs": logprobs, + "max_completion_tokens": max_completion_tokens, "max_tokens": max_tokens, "n": n, "parallel_tool_calls": parallel_tool_calls, @@ -746,6 +772,7 @@ async def create( functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, @@ -814,13 +841,17 @@ async def create( returns the log probabilities of each output token returned in the `content` of `message`. + max_completion_tokens: An upper bound for the number of tokens that can be generated for a completion, + including visible output tokens and + [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). + max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the chat - completion. + completion. This value can be used to control + [costs](https://openai.com/api/pricing/) for text generated via API. - The total length of input tokens and generated tokens is limited by the model's - context length. - [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) - for counting tokens. + This value is now deprecated in favor of `max_completion_tokens`, and is not + compatible with + [o1 series models](https://platform.openai.com/docs/guides/reasoning). n: How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the @@ -843,11 +874,11 @@ async def create( all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to @@ -867,8 +898,11 @@ async def create( service_tier: Specifies the latency tier to use for processing the request. This parameter is relevant for customers subscribed to the scale tier service: - - If set to 'auto', the system will utilize scale tier credits until they are - exhausted. + - If set to 'auto', and the Project is Scale tier enabled, the system will + utilize scale tier credits until they are exhausted. + - If set to 'auto', and the Project is not Scale tier enabled, the request will + be processed using the default service tier with a lower uptime SLA and no + latency guarentee. - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. - When not set, the default behavior is 'auto'. @@ -943,6 +977,7 @@ async def create( functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, @@ -1017,13 +1052,17 @@ async def create( returns the log probabilities of each output token returned in the `content` of `message`. + max_completion_tokens: An upper bound for the number of tokens that can be generated for a completion, + including visible output tokens and + [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). + max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the chat - completion. + completion. This value can be used to control + [costs](https://openai.com/api/pricing/) for text generated via API. - The total length of input tokens and generated tokens is limited by the model's - context length. - [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) - for counting tokens. + This value is now deprecated in favor of `max_completion_tokens`, and is not + compatible with + [o1 series models](https://platform.openai.com/docs/guides/reasoning). n: How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the @@ -1046,11 +1085,11 @@ async def create( all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to @@ -1070,8 +1109,11 @@ async def create( service_tier: Specifies the latency tier to use for processing the request. This parameter is relevant for customers subscribed to the scale tier service: - - If set to 'auto', the system will utilize scale tier credits until they are - exhausted. + - If set to 'auto', and the Project is Scale tier enabled, the system will + utilize scale tier credits until they are exhausted. + - If set to 'auto', and the Project is not Scale tier enabled, the request will + be processed using the default service tier with a lower uptime SLA and no + latency guarentee. - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. - When not set, the default behavior is 'auto'. @@ -1139,6 +1181,7 @@ async def create( functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, @@ -1213,13 +1256,17 @@ async def create( returns the log probabilities of each output token returned in the `content` of `message`. + max_completion_tokens: An upper bound for the number of tokens that can be generated for a completion, + including visible output tokens and + [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). + max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the chat - completion. + completion. This value can be used to control + [costs](https://openai.com/api/pricing/) for text generated via API. - The total length of input tokens and generated tokens is limited by the model's - context length. - [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) - for counting tokens. + This value is now deprecated in favor of `max_completion_tokens`, and is not + compatible with + [o1 series models](https://platform.openai.com/docs/guides/reasoning). n: How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the @@ -1242,11 +1289,11 @@ async def create( all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to @@ -1266,8 +1313,11 @@ async def create( service_tier: Specifies the latency tier to use for processing the request. This parameter is relevant for customers subscribed to the scale tier service: - - If set to 'auto', the system will utilize scale tier credits until they are - exhausted. + - If set to 'auto', and the Project is Scale tier enabled, the system will + utilize scale tier credits until they are exhausted. + - If set to 'auto', and the Project is not Scale tier enabled, the request will + be processed using the default service tier with a lower uptime SLA and no + latency guarentee. - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. - When not set, the default behavior is 'auto'. @@ -1334,6 +1384,7 @@ async def create( functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN, logprobs: Optional[bool] | NotGiven = NOT_GIVEN, + max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, @@ -1369,6 +1420,7 @@ async def create( "functions": functions, "logit_bias": logit_bias, "logprobs": logprobs, + "max_completion_tokens": max_completion_tokens, "max_tokens": max_tokens, "n": n, "parallel_tool_calls": parallel_tool_calls, diff --git a/src/openai/resources/fine_tuning/jobs/jobs.py b/src/openai/resources/fine_tuning/jobs/jobs.py index ca4799e7ac..44abf1cfe1 100644 --- a/src/openai/resources/fine_tuning/jobs/jobs.py +++ b/src/openai/resources/fine_tuning/jobs/jobs.py @@ -114,7 +114,7 @@ def create( job parameters should produce the same results, but may differ in rare cases. If a seed is not specified, one will be generated for you. - suffix: A string of up to 18 characters that will be added to your fine-tuned model + suffix: A string of up to 64 characters that will be added to your fine-tuned model name. For example, a `suffix` of "custom-model-name" would produce a model name like @@ -405,7 +405,7 @@ async def create( job parameters should produce the same results, but may differ in rare cases. If a seed is not specified, one will be generated for you. - suffix: A string of up to 18 characters that will be added to your fine-tuned model + suffix: A string of up to 64 characters that will be added to your fine-tuned model name. For example, a `suffix` of "custom-model-name" would produce a model name like diff --git a/src/openai/types/beta/assistant.py b/src/openai/types/beta/assistant.py index c6a0a4cfcf..b4da08745d 100644 --- a/src/openai/types/beta/assistant.py +++ b/src/openai/types/beta/assistant.py @@ -90,11 +90,11 @@ class Assistant(BaseModel): and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to diff --git a/src/openai/types/beta/assistant_create_params.py b/src/openai/types/beta/assistant_create_params.py index c1360b5b66..eca4da0a2b 100644 --- a/src/openai/types/beta/assistant_create_params.py +++ b/src/openai/types/beta/assistant_create_params.py @@ -58,11 +58,11 @@ class AssistantCreateParams(TypedDict, total=False): and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to diff --git a/src/openai/types/beta/assistant_update_params.py b/src/openai/types/beta/assistant_update_params.py index ade565819f..5396233937 100644 --- a/src/openai/types/beta/assistant_update_params.py +++ b/src/openai/types/beta/assistant_update_params.py @@ -50,11 +50,11 @@ class AssistantUpdateParams(TypedDict, total=False): and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to diff --git a/src/openai/types/beta/file_search_tool.py b/src/openai/types/beta/file_search_tool.py index 4015b3da09..aee6593e89 100644 --- a/src/openai/types/beta/file_search_tool.py +++ b/src/openai/types/beta/file_search_tool.py @@ -9,16 +9,16 @@ class FileSearchRankingOptions(BaseModel): - ranker: Optional[Literal["auto", "default_2024_08_21"]] = None - """The ranker to use for the file search. + score_threshold: float + """The score threshold for the file search. - If not specified will use the `auto` ranker. + All values must be a floating point number between 0 and 1. """ - score_threshold: Optional[float] = None - """The score threshold for the file search. + ranker: Optional[Literal["auto", "default_2024_08_21"]] = None + """The ranker to use for the file search. - All values must be a floating point number between 0 and 1. + If not specified will use the `auto` ranker. """ @@ -38,6 +38,9 @@ class FileSearch(BaseModel): ranking_options: Optional[FileSearchRankingOptions] = None """The ranking options for the file search. + If not specified, the file search tool will use the `auto` ranker and a + score_threshold of 0. + See the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) for more information. diff --git a/src/openai/types/beta/file_search_tool_param.py b/src/openai/types/beta/file_search_tool_param.py index 97e651b0da..5ce91207ba 100644 --- a/src/openai/types/beta/file_search_tool_param.py +++ b/src/openai/types/beta/file_search_tool_param.py @@ -8,16 +8,16 @@ class FileSearchRankingOptions(TypedDict, total=False): - ranker: Literal["auto", "default_2024_08_21"] - """The ranker to use for the file search. + score_threshold: Required[float] + """The score threshold for the file search. - If not specified will use the `auto` ranker. + All values must be a floating point number between 0 and 1. """ - score_threshold: float - """The score threshold for the file search. + ranker: Literal["auto", "default_2024_08_21"] + """The ranker to use for the file search. - All values must be a floating point number between 0 and 1. + If not specified will use the `auto` ranker. """ @@ -37,6 +37,9 @@ class FileSearch(TypedDict, total=False): ranking_options: FileSearchRankingOptions """The ranking options for the file search. + If not specified, the file search tool will use the `auto` ranker and a + score_threshold of 0. + See the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) for more information. diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index 370c2f9bce..20d525fa1a 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -98,11 +98,11 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to diff --git a/src/openai/types/beta/threads/run.py b/src/openai/types/beta/threads/run.py index 0579e229d8..5abc1de295 100644 --- a/src/openai/types/beta/threads/run.py +++ b/src/openai/types/beta/threads/run.py @@ -172,11 +172,11 @@ class Run(BaseModel): and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index 7c5f571d58..824cb1a041 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -111,11 +111,11 @@ class RunCreateParamsBase(TypedDict, total=False): and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index b86dab742b..4ed89b00f5 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -87,15 +87,22 @@ class CompletionCreateParamsBase(TypedDict, total=False): `content` of `message`. """ + max_completion_tokens: Optional[int] + """ + An upper bound for the number of tokens that can be generated for a completion, + including visible output tokens and + [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). + """ + max_tokens: Optional[int] """ The maximum number of [tokens](/tokenizer) that can be generated in the chat - completion. + completion. This value can be used to control + [costs](https://openai.com/api/pricing/) for text generated via API. - The total length of input tokens and generated tokens is limited by the model's - context length. - [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) - for counting tokens. + This value is now deprecated in favor of `max_completion_tokens`, and is not + compatible with + [o1 series models](https://platform.openai.com/docs/guides/reasoning). """ n: Optional[int] @@ -130,11 +137,11 @@ class CompletionCreateParamsBase(TypedDict, total=False): all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured - Outputs which guarantees the model will match your supplied JSON schema. Learn - more in the + Outputs which ensures the model will match your supplied JSON schema. Learn more + in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to @@ -160,8 +167,11 @@ class CompletionCreateParamsBase(TypedDict, total=False): This parameter is relevant for customers subscribed to the scale tier service: - - If set to 'auto', the system will utilize scale tier credits until they are - exhausted. + - If set to 'auto', and the Project is Scale tier enabled, the system will + utilize scale tier credits until they are exhausted. + - If set to 'auto', and the Project is not Scale tier enabled, the request will + be processed using the default service tier with a lower uptime SLA and no + latency guarentee. - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. - When not set, the default behavior is 'auto'. diff --git a/src/openai/types/chat_model.py b/src/openai/types/chat_model.py index 09bc081f7a..f8438c75c8 100644 --- a/src/openai/types/chat_model.py +++ b/src/openai/types/chat_model.py @@ -5,9 +5,14 @@ __all__ = ["ChatModel"] ChatModel: TypeAlias = Literal[ + "o1-preview", + "o1-preview-2024-09-12", + "o1-mini", + "o1-mini-2024-09-12", "gpt-4o", - "gpt-4o-2024-05-13", "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "chatgpt-4o-latest", "gpt-4o-mini", "gpt-4o-mini-2024-07-18", "gpt-4-turbo", diff --git a/src/openai/types/completion_usage.py b/src/openai/types/completion_usage.py index ac09afd479..a4b9116e35 100644 --- a/src/openai/types/completion_usage.py +++ b/src/openai/types/completion_usage.py @@ -1,9 +1,15 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +from typing import Optional from .._models import BaseModel -__all__ = ["CompletionUsage"] +__all__ = ["CompletionUsage", "CompletionTokensDetails"] + + +class CompletionTokensDetails(BaseModel): + reasoning_tokens: Optional[int] = None + """Tokens generated by the model for reasoning.""" class CompletionUsage(BaseModel): @@ -15,3 +21,6 @@ class CompletionUsage(BaseModel): total_tokens: int """Total number of tokens used in the request (prompt + completion).""" + + completion_tokens_details: Optional[CompletionTokensDetails] = None + """Breakdown of tokens used in a completion.""" diff --git a/src/openai/types/fine_tuning/job_create_params.py b/src/openai/types/fine_tuning/job_create_params.py index e9be2ef1ca..8f5ea86274 100644 --- a/src/openai/types/fine_tuning/job_create_params.py +++ b/src/openai/types/fine_tuning/job_create_params.py @@ -50,7 +50,7 @@ class JobCreateParams(TypedDict, total=False): suffix: Optional[str] """ - A string of up to 18 characters that will be added to your fine-tuned model + A string of up to 64 characters that will be added to your fine-tuned model name. For example, a `suffix` of "custom-model-name" would produce a model name like diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index 0b89fbf9cd..c44703a434 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -55,6 +55,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: ], logit_bias={"foo": 0}, logprobs=True, + max_completion_tokens=0, max_tokens=0, n=1, parallel_tool_calls=True, @@ -175,6 +176,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: ], logit_bias={"foo": 0}, logprobs=True, + max_completion_tokens=0, max_tokens=0, n=1, parallel_tool_calls=True, @@ -314,6 +316,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn ], logit_bias={"foo": 0}, logprobs=True, + max_completion_tokens=0, max_tokens=0, n=1, parallel_tool_calls=True, @@ -434,6 +437,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn ], logit_bias={"foo": 0}, logprobs=True, + max_completion_tokens=0, max_tokens=0, n=1, parallel_tool_calls=True, diff --git a/tests/lib/chat/test_completions.py b/tests/lib/chat/test_completions.py index d67d5129cd..e7b9c4f1fd 100644 --- a/tests/lib/chat/test_completions.py +++ b/tests/lib/chat/test_completions.py @@ -74,7 +74,7 @@ def test_parse_nothing(client: OpenAI, respx_mock: MockRouter, monkeypatch: pyte object='chat.completion', service_tier=None, system_fingerprint='fp_845eaabc1f', - usage=CompletionUsage(completion_tokens=28, prompt_tokens=14, total_tokens=42) + usage=CompletionUsage(completion_tokens=28, completion_tokens_details=None, prompt_tokens=14, total_tokens=42) ) """ ) @@ -129,7 +129,7 @@ class Location(BaseModel): object='chat.completion', service_tier=None, system_fingerprint='fp_2a322c9ffc', - usage=CompletionUsage(completion_tokens=14, prompt_tokens=17, total_tokens=31) + usage=CompletionUsage(completion_tokens=14, completion_tokens_details=None, prompt_tokens=17, total_tokens=31) ) """ ) @@ -186,7 +186,7 @@ class Location(BaseModel): object='chat.completion', service_tier=None, system_fingerprint='fp_2a322c9ffc', - usage=CompletionUsage(completion_tokens=14, prompt_tokens=17, total_tokens=31) + usage=CompletionUsage(completion_tokens=14, completion_tokens_details=None, prompt_tokens=17, total_tokens=31) ) """ ) @@ -368,7 +368,7 @@ class CalendarEvent: object='chat.completion', service_tier=None, system_fingerprint='fp_2a322c9ffc', - usage=CompletionUsage(completion_tokens=17, prompt_tokens=32, total_tokens=49) + usage=CompletionUsage(completion_tokens=17, completion_tokens_details=None, prompt_tokens=32, total_tokens=49) ) """ ) diff --git a/tests/lib/chat/test_completions_streaming.py b/tests/lib/chat/test_completions_streaming.py index c3dd69ad57..5ad1f084d2 100644 --- a/tests/lib/chat/test_completions_streaming.py +++ b/tests/lib/chat/test_completions_streaming.py @@ -155,7 +155,7 @@ def on_event(stream: ChatCompletionStream[Location], event: ChatCompletionStream object='chat.completion', service_tier=None, system_fingerprint='fp_845eaabc1f', - usage=CompletionUsage(completion_tokens=14, prompt_tokens=17, total_tokens=31) + usage=CompletionUsage(completion_tokens=14, completion_tokens_details=None, prompt_tokens=17, total_tokens=31) ) """ ) From 48026f3a39b9e1423681ac7a35e68992d230d85a Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 12 Sep 2024 17:03:58 +0000 Subject: [PATCH 496/816] release: 1.45.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 14 ++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 17 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 1ee5dee6dd..6d2723c72a 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.44.1" + ".": "1.45.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 47fa2d9208..8382675b73 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,19 @@ # Changelog +## 1.45.0 (2024-09-12) + +Full Changelog: [v1.44.1...v1.45.0](https://github.com/openai/openai-python/compare/v1.44.1...v1.45.0) + +### Features + +* **api:** add o1 models ([#1708](https://github.com/openai/openai-python/issues/1708)) ([06bd42e](https://github.com/openai/openai-python/commit/06bd42e77121a6abd4826a79ce1848812d956576)) +* **errors:** include completion in LengthFinishReasonError ([#1701](https://github.com/openai/openai-python/issues/1701)) ([b0e3256](https://github.com/openai/openai-python/commit/b0e32562aff9aceafec994d3b047f7c2a9f11524)) + + +### Bug Fixes + +* **types:** correctly mark stream discriminator as optional ([#1706](https://github.com/openai/openai-python/issues/1706)) ([80f02f9](https://github.com/openai/openai-python/commit/80f02f9e5f83fac9cd2f4172b733a92ad01399b2)) + ## 1.44.1 (2024-09-09) Full Changelog: [v1.44.0...v1.44.1](https://github.com/openai/openai-python/compare/v1.44.0...v1.44.1) diff --git a/pyproject.toml b/pyproject.toml index d4b7d2b210..178c3db355 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.44.1" +version = "1.45.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 39c7f63e1e..0d8ebf418b 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.44.1" # x-release-please-version +__version__ = "1.45.0" # x-release-please-version From f63234732869d0511a7fc19c240ab19bec5de717 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 13 Sep 2024 15:30:06 +0000 Subject: [PATCH 497/816] docs: update CONTRIBUTING.md (#1710) --- CONTRIBUTING.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 354d21b2d2..5a6639b8fc 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -31,13 +31,13 @@ $ pip install -r requirements-dev.lock ## Modifying/Adding code -Most of the SDK is generated code, and any modified code will be overridden on the next generation. The -`src/openai/lib/` and `examples/` directories are exceptions and will never be overridden. +Most of the SDK is generated code. Modifications to code will be persisted between generations, but may +result in merge conflicts between manual patches and changes from the generator. The generator will never +modify the contents of the `src/openai/lib/` and `examples/` directories. ## Adding and running examples -All files in the `examples/` directory are not modified by the Stainless generator and can be freely edited or -added to. +All files in the `examples/` directory are not modified by the generator and can be freely edited or added to. ```bash # add an example to examples/.py From 803a7f3b16ec959fe04e1ae83ca3808faf8acffb Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Mon, 16 Sep 2024 12:05:27 +0000 Subject: [PATCH 498/816] chore(internal): bump ruff (#1714) --- requirements-dev.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.lock b/requirements-dev.lock index f4797f432b..e5e63ed037 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -141,7 +141,7 @@ requests==2.31.0 respx==0.20.2 rich==13.7.1 # via inline-snapshot -ruff==0.5.6 +ruff==0.6.5 setuptools==68.2.2 # via nodeenv six==1.16.0 From b5897bdf1fe3d300438b87c23d57611f3c2dad3a Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 16 Sep 2024 12:24:14 +0000 Subject: [PATCH 499/816] chore(internal): update spec link (#1716) --- .stats.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index de3167f3a8..2fc39385e9 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-501122aa32adaa2abb3d4487880ab9cdf2141addce2e6c3d1bd9bb6b44c318a8.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-ff407aa10917e62f2b0c12d1ad2c4f1258ed083bd45753c70eaaf5b1cf8356ae.yml From dbe51995f2f0431bba63e4422f61f09fddbe0375 Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Mon, 16 Sep 2024 12:46:46 +0000 Subject: [PATCH 500/816] chore(internal): bump pyright / mypy version (#1717) --- requirements-dev.lock | 4 ++-- src/openai/_utils/_utils.py | 7 ++++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/requirements-dev.lock b/requirements-dev.lock index e5e63ed037..a47de9656a 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -83,7 +83,7 @@ msal==1.29.0 # via msal-extensions msal-extensions==1.2.0 # via azure-identity -mypy==1.7.1 +mypy==1.11.2 mypy-extensions==1.0.0 # via black # via mypy @@ -125,7 +125,7 @@ pygments==2.18.0 # via rich pyjwt==2.8.0 # via msal -pyright==1.1.374 +pyright==1.1.380 pytest==7.1.1 # via pytest-asyncio pytest-asyncio==0.21.1 diff --git a/src/openai/_utils/_utils.py b/src/openai/_utils/_utils.py index 2fc5a1c65a..0bba17caad 100644 --- a/src/openai/_utils/_utils.py +++ b/src/openai/_utils/_utils.py @@ -363,12 +363,13 @@ def file_from_path(path: str) -> FileTypes: def get_required_header(headers: HeadersLike, header: str) -> str: lower_header = header.lower() - if isinstance(headers, Mapping): - for k, v in headers.items(): + if is_mapping_t(headers): + # mypy doesn't understand the type narrowing here + for k, v in headers.items(): # type: ignore if k.lower() == lower_header and isinstance(v, str): return v - """ to deal with the case where the header looks like Stainless-Event-Id """ + # to deal with the case where the header looks like Stainless-Event-Id intercaps_header = re.sub(r"([^\w])(\w)", lambda pat: pat.group(1) + pat.group(2).upper(), header.capitalize()) for normalized_header in [header, lower_header, header.upper(), intercaps_header]: From 73f9fda59561e35ae839c66dcc30b785e1629e58 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 16 Sep 2024 12:47:09 +0000 Subject: [PATCH 501/816] release: 1.45.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 15 +++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 18 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 6d2723c72a..c37d66f738 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.45.0" + ".": "1.45.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 8382675b73..b1f344cfb3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## 1.45.1 (2024-09-16) + +Full Changelog: [v1.45.0...v1.45.1](https://github.com/openai/openai-python/compare/v1.45.0...v1.45.1) + +### Chores + +* **internal:** bump pyright / mypy version ([#1717](https://github.com/openai/openai-python/issues/1717)) ([351af85](https://github.com/openai/openai-python/commit/351af85c5b813391910301a5049edddc8c9e70dd)) +* **internal:** bump ruff ([#1714](https://github.com/openai/openai-python/issues/1714)) ([aceaf64](https://github.com/openai/openai-python/commit/aceaf641eedd092ed42e4aaf031e8cfbf37e4212)) +* **internal:** update spec link ([#1716](https://github.com/openai/openai-python/issues/1716)) ([ca58c7f](https://github.com/openai/openai-python/commit/ca58c7f83a7cede0367dec2500127573c9b00d1f)) + + +### Documentation + +* update CONTRIBUTING.md ([#1710](https://github.com/openai/openai-python/issues/1710)) ([4d45eb5](https://github.com/openai/openai-python/commit/4d45eb5eb794bcc5076c022be09e06fae103abcc)) + ## 1.45.0 (2024-09-12) Full Changelog: [v1.44.1...v1.45.0](https://github.com/openai/openai-python/compare/v1.44.1...v1.45.0) diff --git a/pyproject.toml b/pyproject.toml index 178c3db355..7828d0f0e1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.45.0" +version = "1.45.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 0d8ebf418b..1b29a53bb6 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.45.0" # x-release-please-version +__version__ = "1.45.1" # x-release-please-version From 192b8f2b6a49f462e48c1442858931875524ab49 Mon Sep 17 00:00:00 2001 From: Dan Corin Date: Mon, 16 Sep 2024 09:52:22 -0400 Subject: [PATCH 502/816] docs(readme): add examples for chat with image content (#1703) --- README.md | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/README.md b/README.md index 8c73fdd82a..9e9628ff83 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,48 @@ we recommend using [python-dotenv](https://pypi.org/project/python-dotenv/) to add `OPENAI_API_KEY="My API Key"` to your `.env` file so that your API Key is not stored in source control. +### Vision + +With a hosted image: + +```python +response = client.chat.completions.create( + model="gpt-4o-mini", + messages=[ + { + "role": "user", + "content": [ + {"type": "text", "text": prompt}, + { + "type": "image_url", + "image_url": {"url": f"{img_url}"}, + }, + ], + } + ], +) +``` + +With the image as a base64 encoded string: + +```python +response = client.chat.completions.create( + model="gpt-4o-mini", + messages=[ + { + "role": "user", + "content": [ + {"type": "text", "text": prompt}, + { + "type": "image_url", + "image_url": {"url": f"data:{img_type};base64,{img_b64_str}"}, + }, + ], + } + ], +) +``` + ### Polling Helpers When interacting with the API some actions such as starting a Run and adding files to vector stores are asynchronous and take time to complete. The SDK includes From 4b3023466df27de4d19a93b4efbd14977254ecc0 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Tue, 17 Sep 2024 17:30:18 +0100 Subject: [PATCH 503/816] feat(client): add ._request_id property to object responses (#1707) --- README.md | 18 ++++++++++++++ src/openai/_legacy_response.py | 7 ++++-- src/openai/_models.py | 34 ++++++++++++++++++++++++++- src/openai/_response.py | 12 +++++++--- tests/test_legacy_response.py | 21 +++++++++++++++++ tests/test_response.py | 43 ++++++++++++++++++++++++++++++++++ 6 files changed, 129 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 9e9628ff83..c47bdd54c5 100644 --- a/README.md +++ b/README.md @@ -417,6 +417,24 @@ Error codes are as followed: | >=500 | `InternalServerError` | | N/A | `APIConnectionError` | +## Request IDs + +> For more information on debugging requests, see [these docs](https://platform.openai.com/docs/api-reference/debugging-requests) + +All object responses in the SDK provide a `_request_id` property which is added from the `x-request-id` response header so that you can quickly log failing requests and report them back to OpenAI. + +```python +completion = await client.chat.completions.create( + messages=[{"role": "user", "content": "Say this is a test"}], model="gpt-4" +) +print(completion._request_id) # req_123 +``` + +Note that unlike other properties that use an `_` prefix, the `_request_id` property +*is* public. Unless documented otherwise, *all* other `_` prefix properties, +methods and modules are *private*. + + ### Retries Certain errors are automatically retried 2 times by default, with a short exponential backoff. diff --git a/src/openai/_legacy_response.py b/src/openai/_legacy_response.py index c42fb8b83e..c7dbd54e23 100644 --- a/src/openai/_legacy_response.py +++ b/src/openai/_legacy_response.py @@ -25,7 +25,7 @@ from ._types import NoneType from ._utils import is_given, extract_type_arg, is_annotated_type -from ._models import BaseModel, is_basemodel +from ._models import BaseModel, is_basemodel, add_request_id from ._constants import RAW_RESPONSE_HEADER from ._streaming import Stream, AsyncStream, is_stream_class_type, extract_stream_chunk_type from ._exceptions import APIResponseValidationError @@ -138,8 +138,11 @@ class MyModel(BaseModel): if is_given(self._options.post_parser): parsed = self._options.post_parser(parsed) + if isinstance(parsed, BaseModel): + add_request_id(parsed, self.request_id) + self._parsed_by_type[cache_key] = parsed - return parsed + return cast(R, parsed) @property def headers(self) -> httpx.Headers: diff --git a/src/openai/_models.py b/src/openai/_models.py index d386eaa3a4..d6f42d3d4d 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -2,7 +2,7 @@ import os import inspect -from typing import TYPE_CHECKING, Any, Type, Union, Generic, TypeVar, Callable, cast +from typing import TYPE_CHECKING, Any, Type, Union, Generic, TypeVar, Callable, Optional, cast from datetime import date, datetime from typing_extensions import ( Unpack, @@ -94,6 +94,23 @@ def model_fields_set(self) -> set[str]: class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated] extra: Any = pydantic.Extra.allow # type: ignore + if TYPE_CHECKING: + _request_id: Optional[str] = None + """The ID of the request, returned via the X-Request-ID header. Useful for debugging requests and reporting issues to OpenAI. + + This will **only** be set for the top-level response object, it will not be defined for nested objects. For example: + + ```py + completion = await client.chat.completions.create(...) + completion._request_id # req_id_xxx + completion.usage._request_id # raises `AttributeError` + ``` + + Note: unlike other properties that use an `_` prefix, this property + *is* public. Unless documented otherwise, all other `_` prefix properties, + methods and modules are *private*. + """ + def to_dict( self, *, @@ -662,6 +679,21 @@ def set_pydantic_config(typ: Any, config: pydantic.ConfigDict) -> None: setattr(typ, "__pydantic_config__", config) # noqa: B010 +def add_request_id(obj: BaseModel, request_id: str | None) -> None: + obj._request_id = request_id + + # in Pydantic v1, using setattr like we do above causes the attribute + # to be included when serializing the model which we don't want in this + # case so we need to explicitly exclude it + if not PYDANTIC_V2: + try: + exclude_fields = obj.__exclude_fields__ # type: ignore + except AttributeError: + cast(Any, obj).__exclude_fields__ = {"_request_id", "__exclude_fields__"} + else: + cast(Any, obj).__exclude_fields__ = {*(exclude_fields or {}), "_request_id", "__exclude_fields__"} + + # our use of subclasssing here causes weirdness for type checkers, # so we just pretend that we don't subclass if TYPE_CHECKING: diff --git a/src/openai/_response.py b/src/openai/_response.py index f9d91786f6..20ce69ac8a 100644 --- a/src/openai/_response.py +++ b/src/openai/_response.py @@ -26,7 +26,7 @@ from ._types import NoneType from ._utils import is_given, extract_type_arg, is_annotated_type, extract_type_var_from_base -from ._models import BaseModel, is_basemodel +from ._models import BaseModel, is_basemodel, add_request_id from ._constants import RAW_RESPONSE_HEADER, OVERRIDE_CAST_TO_HEADER from ._streaming import Stream, AsyncStream, is_stream_class_type, extract_stream_chunk_type from ._exceptions import OpenAIError, APIResponseValidationError @@ -315,8 +315,11 @@ class MyModel(BaseModel): if is_given(self._options.post_parser): parsed = self._options.post_parser(parsed) + if isinstance(parsed, BaseModel): + add_request_id(parsed, self.request_id) + self._parsed_by_type[cache_key] = parsed - return parsed + return cast(R, parsed) def read(self) -> bytes: """Read and return the binary response content.""" @@ -419,8 +422,11 @@ class MyModel(BaseModel): if is_given(self._options.post_parser): parsed = self._options.post_parser(parsed) + if isinstance(parsed, BaseModel): + add_request_id(parsed, self.request_id) + self._parsed_by_type[cache_key] = parsed - return parsed + return cast(R, parsed) async def read(self) -> bytes: """Read and return the binary response content.""" diff --git a/tests/test_legacy_response.py b/tests/test_legacy_response.py index 3c2df53e58..a6fec9f2de 100644 --- a/tests/test_legacy_response.py +++ b/tests/test_legacy_response.py @@ -66,6 +66,27 @@ def test_response_parse_custom_model(client: OpenAI) -> None: assert obj.bar == 2 +def test_response_basemodel_request_id(client: OpenAI) -> None: + response = LegacyAPIResponse( + raw=httpx.Response( + 200, + headers={"x-request-id": "my-req-id"}, + content=json.dumps({"foo": "hello!", "bar": 2}), + ), + client=client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + obj = response.parse(to=CustomModel) + assert obj._request_id == "my-req-id" + assert obj.foo == "hello!" + assert obj.bar == 2 + assert obj.to_dict() == {"foo": "hello!", "bar": 2} + + def test_response_parse_annotated_type(client: OpenAI) -> None: response = LegacyAPIResponse( raw=httpx.Response(200, content=json.dumps({"foo": "hello!", "bar": 2})), diff --git a/tests/test_response.py b/tests/test_response.py index b7d88bdbde..97c56e0035 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -156,6 +156,49 @@ async def test_async_response_parse_custom_model(async_client: AsyncOpenAI) -> N assert obj.bar == 2 +def test_response_basemodel_request_id(client: OpenAI) -> None: + response = APIResponse( + raw=httpx.Response( + 200, + headers={"x-request-id": "my-req-id"}, + content=json.dumps({"foo": "hello!", "bar": 2}), + ), + client=client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + obj = response.parse(to=CustomModel) + assert obj._request_id == "my-req-id" + assert obj.foo == "hello!" + assert obj.bar == 2 + assert obj.to_dict() == {"foo": "hello!", "bar": 2} + + +@pytest.mark.asyncio +async def test_async_response_basemodel_request_id(client: OpenAI) -> None: + response = AsyncAPIResponse( + raw=httpx.Response( + 200, + headers={"x-request-id": "my-req-id"}, + content=json.dumps({"foo": "hello!", "bar": 2}), + ), + client=client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + obj = await response.parse(to=CustomModel) + assert obj._request_id == "my-req-id" + assert obj.foo == "hello!" + assert obj.bar == 2 + assert obj.to_dict() == {"foo": "hello!", "bar": 2} + + def test_response_parse_annotated_type(client: OpenAI) -> None: response = APIResponse( raw=httpx.Response(200, content=json.dumps({"foo": "hello!", "bar": 2})), From bcf9fcc36149921f216d49ac84ee1aa9c15c5a86 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 17 Sep 2024 16:34:47 +0000 Subject: [PATCH 504/816] release: 1.46.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index c37d66f738..4b6cc3c898 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.45.1" + ".": "1.46.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index b1f344cfb3..c1f852327c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.46.0 (2024-09-17) + +Full Changelog: [v1.45.1...v1.46.0](https://github.com/openai/openai-python/compare/v1.45.1...v1.46.0) + +### Features + +* **client:** add ._request_id property to object responses ([#1707](https://github.com/openai/openai-python/issues/1707)) ([8b3da05](https://github.com/openai/openai-python/commit/8b3da05a35b33245aec98693a0540ace6218a61b)) + + +### Documentation + +* **readme:** add examples for chat with image content ([#1703](https://github.com/openai/openai-python/issues/1703)) ([192b8f2](https://github.com/openai/openai-python/commit/192b8f2b6a49f462e48c1442858931875524ab49)) + ## 1.45.1 (2024-09-16) Full Changelog: [v1.45.0...v1.45.1](https://github.com/openai/openai-python/compare/v1.45.0...v1.45.1) diff --git a/pyproject.toml b/pyproject.toml index 7828d0f0e1..a3bd81cad5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.45.1" +version = "1.46.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 1b29a53bb6..ccd62dc230 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.45.1" # x-release-please-version +__version__ = "1.46.0" # x-release-please-version From 349b7f6c3bbe54bfe0c9e3652782f822ff2f1ab6 Mon Sep 17 00:00:00 2001 From: Krista Pratico Date: Wed, 18 Sep 2024 11:51:55 -0700 Subject: [PATCH 505/816] chore(streaming): silence pydantic model_dump warnings (#1722) --- src/openai/lib/streaming/_assistants.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/openai/lib/streaming/_assistants.py b/src/openai/lib/streaming/_assistants.py index 7445f9a96d..183754177a 100644 --- a/src/openai/lib/streaming/_assistants.py +++ b/src/openai/lib/streaming/_assistants.py @@ -906,11 +906,11 @@ def accumulate_run_step( merged = accumulate_delta( cast( "dict[object, object]", - snapshot.model_dump(exclude_unset=True), + snapshot.model_dump(exclude_unset=True, warnings=False), ), cast( "dict[object, object]", - data.delta.model_dump(exclude_unset=True), + data.delta.model_dump(exclude_unset=True, warnings=False), ), ) run_step_snapshots[snapshot.id] = cast(RunStep, construct_type(type_=RunStep, value=merged)) @@ -948,7 +948,7 @@ def accumulate_event( construct_type( # mypy doesn't allow Content for some reason type_=cast(Any, MessageContent), - value=content_delta.model_dump(exclude_unset=True), + value=content_delta.model_dump(exclude_unset=True, warnings=False), ), ), ) @@ -957,11 +957,11 @@ def accumulate_event( merged = accumulate_delta( cast( "dict[object, object]", - block.model_dump(exclude_unset=True), + block.model_dump(exclude_unset=True, warnings=False), ), cast( "dict[object, object]", - content_delta.model_dump(exclude_unset=True), + content_delta.model_dump(exclude_unset=True, warnings=False), ), ) current_message_snapshot.content[content_delta.index] = cast( From bd1e9e2fa7869c429f8ff727ba72b9675710edc9 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 19 Sep 2024 14:48:19 +0000 Subject: [PATCH 506/816] fix(client): handle domains with underscores (#1726) --- src/openai/_base_client.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index f374449dbc..2545ddf967 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -490,12 +490,17 @@ def _build_request( if not files: files = cast(HttpxRequestFiles, ForceMultipartDict()) + prepared_url = self._prepare_url(http://github.com/options.url) + if "_" in prepared_url.host: + # work around https://github.com/encode/httpx/discussions/2880 + kwargs["extensions"] = {"sni_hostname": prepared_url.host.replace("_", "-")} + # TODO: report this error to httpx return self._client.build_request( # pyright: ignore[reportUnknownMemberType] headers=headers, timeout=self.timeout if isinstance(options.timeout, NotGiven) else options.timeout, method=options.method, - url=self._prepare_url(http://github.com/options.url), + url=prepared_url, # the `Query` type that we use is incompatible with qs' # `Params` type as it needs to be typed as `Mapping[str, object]` # so that passing a `TypedDict` doesn't cause an error. From 6172976b16821b24194a05e3e3fe5cb2342a2b4b Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 19 Sep 2024 14:48:52 +0000 Subject: [PATCH 507/816] release: 1.46.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 4b6cc3c898..d89af66b28 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.46.0" + ".": "1.46.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index c1f852327c..3f1c96e6d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.46.1 (2024-09-19) + +Full Changelog: [v1.46.0...v1.46.1](https://github.com/openai/openai-python/compare/v1.46.0...v1.46.1) + +### Bug Fixes + +* **client:** handle domains with underscores ([#1726](https://github.com/openai/openai-python/issues/1726)) ([cd194df](https://github.com/openai/openai-python/commit/cd194dfdc418a84589bd903357cba349e9ad3e78)) + + +### Chores + +* **streaming:** silence pydantic model_dump warnings ([#1722](https://github.com/openai/openai-python/issues/1722)) ([30f84b9](https://github.com/openai/openai-python/commit/30f84b96081ac37f60e40a75d765dbbf563b61b3)) + ## 1.46.0 (2024-09-17) Full Changelog: [v1.45.1...v1.46.0](https://github.com/openai/openai-python/compare/v1.45.1...v1.46.0) diff --git a/pyproject.toml b/pyproject.toml index a3bd81cad5..b505880f11 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.46.0" +version = "1.46.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index ccd62dc230..197a24ea67 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.46.0" # x-release-please-version +__version__ = "1.46.1" # x-release-please-version From 3765cc2c6a8c90376a41d5daeb7f2f100f81f8a5 Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Thu, 19 Sep 2024 16:11:56 +0000 Subject: [PATCH 508/816] feat(client): send retry count header --- src/openai/_base_client.py | 102 ++++++++++++++++++++----------------- src/openai/lib/azure.py | 4 +- tests/test_client.py | 16 ++++++ 3 files changed, 74 insertions(+), 48 deletions(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 2545ddf967..77e82026ef 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -401,14 +401,7 @@ def _make_status_error( ) -> _exceptions.APIStatusError: raise NotImplementedError() - def _remaining_retries( - self, - remaining_retries: Optional[int], - options: FinalRequestOptions, - ) -> int: - return remaining_retries if remaining_retries is not None else options.get_max_retries(self.max_retries) - - def _build_headers(self, options: FinalRequestOptions) -> httpx.Headers: + def _build_headers(self, options: FinalRequestOptions, *, retries_taken: int = 0) -> httpx.Headers: custom_headers = options.headers or {} headers_dict = _merge_mappings(self.default_headers, custom_headers) self._validate_headers(headers_dict, custom_headers) @@ -420,6 +413,9 @@ def _build_headers(self, options: FinalRequestOptions) -> httpx.Headers: if idempotency_header and options.method.lower() != "get" and idempotency_header not in headers: headers[idempotency_header] = options.idempotency_key or self._idempotency_key() + if retries_taken > 0: + headers.setdefault("x-stainless-retry-count", str(retries_taken)) + return headers def _prepare_url(http://github.com/self,%20url:%20str) -> URL: @@ -441,6 +437,8 @@ def _make_sse_decoder(self) -> SSEDecoder | SSEBytesDecoder: def _build_request( self, options: FinalRequestOptions, + *, + retries_taken: int = 0, ) -> httpx.Request: if log.isEnabledFor(logging.DEBUG): log.debug("Request options: %s", model_dump(options, exclude_unset=True)) @@ -456,7 +454,7 @@ def _build_request( else: raise RuntimeError(f"Unexpected JSON data type, {type(json_data)}, cannot merge with `extra_body`") - headers = self._build_headers(options) + headers = self._build_headers(options, retries_taken=retries_taken) params = _merge_mappings(self.default_query, options.params) content_type = headers.get("Content-Type") files = options.files @@ -939,12 +937,17 @@ def request( stream: bool = False, stream_cls: type[_StreamT] | None = None, ) -> ResponseT | _StreamT: + if remaining_retries is not None: + retries_taken = options.get_max_retries(self.max_retries) - remaining_retries + else: + retries_taken = 0 + return self._request( cast_to=cast_to, options=options, stream=stream, stream_cls=stream_cls, - remaining_retries=remaining_retries, + retries_taken=retries_taken, ) def _request( @@ -952,7 +955,7 @@ def _request( *, cast_to: Type[ResponseT], options: FinalRequestOptions, - remaining_retries: int | None, + retries_taken: int, stream: bool, stream_cls: type[_StreamT] | None, ) -> ResponseT | _StreamT: @@ -964,8 +967,8 @@ def _request( cast_to = self._maybe_override_cast_to(cast_to, options) options = self._prepare_options(options) - retries = self._remaining_retries(remaining_retries, options) - request = self._build_request(options) + remaining_retries = options.get_max_retries(self.max_retries) - retries_taken + request = self._build_request(options, retries_taken=retries_taken) self._prepare_request(request) kwargs: HttpxSendArgs = {} @@ -983,11 +986,11 @@ def _request( except httpx.TimeoutException as err: log.debug("Encountered httpx.TimeoutException", exc_info=True) - if retries > 0: + if remaining_retries > 0: return self._retry_request( input_options, cast_to, - retries, + retries_taken=retries_taken, stream=stream, stream_cls=stream_cls, response_headers=None, @@ -998,11 +1001,11 @@ def _request( except Exception as err: log.debug("Encountered Exception", exc_info=True) - if retries > 0: + if remaining_retries > 0: return self._retry_request( input_options, cast_to, - retries, + retries_taken=retries_taken, stream=stream, stream_cls=stream_cls, response_headers=None, @@ -1026,13 +1029,13 @@ def _request( except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code log.debug("Encountered httpx.HTTPStatusError", exc_info=True) - if retries > 0 and self._should_retry(err.response): + if remaining_retries > 0 and self._should_retry(err.response): err.response.close() return self._retry_request( input_options, cast_to, - retries, - err.response.headers, + retries_taken=retries_taken, + response_headers=err.response.headers, stream=stream, stream_cls=stream_cls, ) @@ -1051,26 +1054,26 @@ def _request( response=response, stream=stream, stream_cls=stream_cls, - retries_taken=options.get_max_retries(self.max_retries) - retries, + retries_taken=retries_taken, ) def _retry_request( self, options: FinalRequestOptions, cast_to: Type[ResponseT], - remaining_retries: int, - response_headers: httpx.Headers | None, *, + retries_taken: int, + response_headers: httpx.Headers | None, stream: bool, stream_cls: type[_StreamT] | None, ) -> ResponseT | _StreamT: - remaining = remaining_retries - 1 - if remaining == 1: + remaining_retries = options.get_max_retries(self.max_retries) - retries_taken + if remaining_retries == 1: log.debug("1 retry left") else: - log.debug("%i retries left", remaining) + log.debug("%i retries left", remaining_retries) - timeout = self._calculate_retry_timeout(remaining, options, response_headers) + timeout = self._calculate_retry_timeout(remaining_retries, options, response_headers) log.info("Retrying request to %s in %f seconds", options.url, timeout) # In a synchronous context we are blocking the entire thread. Up to the library user to run the client in a @@ -1080,7 +1083,7 @@ def _retry_request( return self._request( options=options, cast_to=cast_to, - remaining_retries=remaining, + retries_taken=retries_taken + 1, stream=stream, stream_cls=stream_cls, ) @@ -1512,12 +1515,17 @@ async def request( stream_cls: type[_AsyncStreamT] | None = None, remaining_retries: Optional[int] = None, ) -> ResponseT | _AsyncStreamT: + if remaining_retries is not None: + retries_taken = options.get_max_retries(self.max_retries) - remaining_retries + else: + retries_taken = 0 + return await self._request( cast_to=cast_to, options=options, stream=stream, stream_cls=stream_cls, - remaining_retries=remaining_retries, + retries_taken=retries_taken, ) async def _request( @@ -1527,7 +1535,7 @@ async def _request( *, stream: bool, stream_cls: type[_AsyncStreamT] | None, - remaining_retries: int | None, + retries_taken: int, ) -> ResponseT | _AsyncStreamT: if self._platform is None: # `get_platform` can make blocking IO calls so we @@ -1542,8 +1550,8 @@ async def _request( cast_to = self._maybe_override_cast_to(cast_to, options) options = await self._prepare_options(options) - retries = self._remaining_retries(remaining_retries, options) - request = self._build_request(options) + remaining_retries = options.get_max_retries(self.max_retries) - retries_taken + request = self._build_request(options, retries_taken=retries_taken) await self._prepare_request(request) kwargs: HttpxSendArgs = {} @@ -1559,11 +1567,11 @@ async def _request( except httpx.TimeoutException as err: log.debug("Encountered httpx.TimeoutException", exc_info=True) - if retries > 0: + if remaining_retries > 0: return await self._retry_request( input_options, cast_to, - retries, + retries_taken=retries_taken, stream=stream, stream_cls=stream_cls, response_headers=None, @@ -1574,11 +1582,11 @@ async def _request( except Exception as err: log.debug("Encountered Exception", exc_info=True) - if retries > 0: + if retries_taken > 0: return await self._retry_request( input_options, cast_to, - retries, + retries_taken=retries_taken, stream=stream, stream_cls=stream_cls, response_headers=None, @@ -1596,13 +1604,13 @@ async def _request( except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code log.debug("Encountered httpx.HTTPStatusError", exc_info=True) - if retries > 0 and self._should_retry(err.response): + if remaining_retries > 0 and self._should_retry(err.response): await err.response.aclose() return await self._retry_request( input_options, cast_to, - retries, - err.response.headers, + retries_taken=retries_taken, + response_headers=err.response.headers, stream=stream, stream_cls=stream_cls, ) @@ -1621,26 +1629,26 @@ async def _request( response=response, stream=stream, stream_cls=stream_cls, - retries_taken=options.get_max_retries(self.max_retries) - retries, + retries_taken=retries_taken, ) async def _retry_request( self, options: FinalRequestOptions, cast_to: Type[ResponseT], - remaining_retries: int, - response_headers: httpx.Headers | None, *, + retries_taken: int, + response_headers: httpx.Headers | None, stream: bool, stream_cls: type[_AsyncStreamT] | None, ) -> ResponseT | _AsyncStreamT: - remaining = remaining_retries - 1 - if remaining == 1: + remaining_retries = options.get_max_retries(self.max_retries) - retries_taken + if remaining_retries == 1: log.debug("1 retry left") else: - log.debug("%i retries left", remaining) + log.debug("%i retries left", remaining_retries) - timeout = self._calculate_retry_timeout(remaining, options, response_headers) + timeout = self._calculate_retry_timeout(remaining_retries, options, response_headers) log.info("Retrying request to %s in %f seconds", options.url, timeout) await anyio.sleep(timeout) @@ -1648,7 +1656,7 @@ async def _retry_request( return await self._request( options=options, cast_to=cast_to, - remaining_retries=remaining, + retries_taken=retries_taken + 1, stream=stream, stream_cls=stream_cls, ) diff --git a/src/openai/lib/azure.py b/src/openai/lib/azure.py index ef64137de4..5d21f10b70 100644 --- a/src/openai/lib/azure.py +++ b/src/openai/lib/azure.py @@ -53,13 +53,15 @@ class BaseAzureClient(BaseClient[_HttpxClientT, _DefaultStreamT]): def _build_request( self, options: FinalRequestOptions, + *, + retries_taken: int = 0, ) -> httpx.Request: if options.url in _deployments_endpoints and is_mapping(options.json_data): model = options.json_data.get("model") if model is not None and not "/deployments" in str(self.base_url): options.url = f"/deployments/{model}{options.url}" - return super()._build_request(options) + return super()._build_request(options, retries_taken=retries_taken) class AzureOpenAI(BaseAzureClient[httpx.Client, Stream[Any]], OpenAI): diff --git a/tests/test_client.py b/tests/test_client.py index 054ae0ff4e..567a6ec59f 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -788,6 +788,10 @@ def retry_handler(_request: httpx.Request) -> httpx.Response: ) assert response.retries_taken == failures_before_success + if failures_before_success == 0: + assert "x-stainless-retry-count" not in response.http_request.headers + else: + assert int(response.http_request.headers.get("x-stainless-retry-count")) == failures_before_success @pytest.mark.parametrize("failures_before_success", [0, 2, 4]) @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) @@ -818,6 +822,10 @@ def retry_handler(_request: httpx.Request) -> httpx.Response: model="gpt-4o", ) as response: assert response.retries_taken == failures_before_success + if failures_before_success == 0: + assert "x-stainless-retry-count" not in response.http_request.headers + else: + assert int(response.http_request.headers.get("x-stainless-retry-count")) == failures_before_success class TestAsyncOpenAI: @@ -1582,6 +1590,10 @@ def retry_handler(_request: httpx.Request) -> httpx.Response: ) assert response.retries_taken == failures_before_success + if failures_before_success == 0: + assert "x-stainless-retry-count" not in response.http_request.headers + else: + assert int(response.http_request.headers.get("x-stainless-retry-count")) == failures_before_success @pytest.mark.parametrize("failures_before_success", [0, 2, 4]) @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) @@ -1613,3 +1625,7 @@ def retry_handler(_request: httpx.Request) -> httpx.Response: model="gpt-4o", ) as response: assert response.retries_taken == failures_before_success + if failures_before_success == 0: + assert "x-stainless-retry-count" not in response.http_request.headers + else: + assert int(response.http_request.headers.get("x-stainless-retry-count")) == failures_before_success From eab2e5a396ae5d114cf63cb26f30070ccad8b0b1 Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Thu, 19 Sep 2024 16:26:25 +0000 Subject: [PATCH 509/816] chore(types): improve type name for embedding models (#1730) --- .stats.yml | 2 +- api.md | 2 +- src/openai/resources/embeddings.py | 9 ++++----- src/openai/types/__init__.py | 1 + src/openai/types/embedding_create_params.py | 4 +++- src/openai/types/embedding_model.py | 7 +++++++ 6 files changed, 17 insertions(+), 8 deletions(-) create mode 100644 src/openai/types/embedding_model.py diff --git a/.stats.yml b/.stats.yml index 2fc39385e9..0151c5a105 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-ff407aa10917e62f2b0c12d1ad2c4f1258ed083bd45753c70eaaf5b1cf8356ae.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-de1981b64ac229493473670d618500c6362c195f1057eb7de00bd1bc9184fbd5.yml diff --git a/api.md b/api.md index 32c0fb9efc..2498340328 100644 --- a/api.md +++ b/api.md @@ -70,7 +70,7 @@ Methods: Types: ```python -from openai.types import CreateEmbeddingResponse, Embedding +from openai.types import CreateEmbeddingResponse, Embedding, EmbeddingModel ``` Methods: diff --git a/src/openai/resources/embeddings.py b/src/openai/resources/embeddings.py index 71c2a18a24..c91e6cc13a 100644 --- a/src/openai/resources/embeddings.py +++ b/src/openai/resources/embeddings.py @@ -16,9 +16,8 @@ from .._extras import numpy as np, has_numpy from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper -from .._base_client import ( - make_request_options, -) +from .._base_client import make_request_options +from ..types.embedding_model import EmbeddingModel from ..types.create_embedding_response import CreateEmbeddingResponse __all__ = ["Embeddings", "AsyncEmbeddings"] @@ -48,7 +47,7 @@ def create( self, *, input: Union[str, List[str], Iterable[int], Iterable[Iterable[int]]], - model: Union[str, Literal["text-embedding-ada-002", "text-embedding-3-small", "text-embedding-3-large"]], + model: Union[str, EmbeddingModel], dimensions: int | NotGiven = NOT_GIVEN, encoding_format: Literal["float", "base64"] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, @@ -160,7 +159,7 @@ async def create( self, *, input: Union[str, List[str], Iterable[int], Iterable[Iterable[int]]], - model: Union[str, Literal["text-embedding-ada-002", "text-embedding-3-small", "text-embedding-3-large"]], + model: Union[str, EmbeddingModel], dimensions: int | NotGiven = NOT_GIVEN, encoding_format: Literal["float", "base64"] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index ad9284fbd5..4dbc1b6b7b 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -26,6 +26,7 @@ from .file_deleted import FileDeleted as FileDeleted from .file_purpose import FilePurpose as FilePurpose from .model_deleted import ModelDeleted as ModelDeleted +from .embedding_model import EmbeddingModel as EmbeddingModel from .images_response import ImagesResponse as ImagesResponse from .completion_usage import CompletionUsage as CompletionUsage from .file_list_params import FileListParams as FileListParams diff --git a/src/openai/types/embedding_create_params.py b/src/openai/types/embedding_create_params.py index 930b3b7914..1548cdbd77 100644 --- a/src/openai/types/embedding_create_params.py +++ b/src/openai/types/embedding_create_params.py @@ -5,6 +5,8 @@ from typing import List, Union, Iterable from typing_extensions import Literal, Required, TypedDict +from .embedding_model import EmbeddingModel + __all__ = ["EmbeddingCreateParams"] @@ -20,7 +22,7 @@ class EmbeddingCreateParams(TypedDict, total=False): for counting tokens. """ - model: Required[Union[str, Literal["text-embedding-ada-002", "text-embedding-3-small", "text-embedding-3-large"]]] + model: Required[Union[str, EmbeddingModel]] """ID of the model to use. You can use the diff --git a/src/openai/types/embedding_model.py b/src/openai/types/embedding_model.py new file mode 100644 index 0000000000..075ff97644 --- /dev/null +++ b/src/openai/types/embedding_model.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["EmbeddingModel"] + +EmbeddingModel: TypeAlias = Literal["text-embedding-ada-002", "text-embedding-3-small", "text-embedding-3-large"] From 45315a7a7fef522a56b4c86558f2e07ebea4f71a Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 20 Sep 2024 05:04:20 +0000 Subject: [PATCH 510/816] release: 1.47.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index d89af66b28..dc9bcb375c 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.46.1" + ".": "1.47.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f1c96e6d5..021be7ef4c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.47.0 (2024-09-20) + +Full Changelog: [v1.46.1...v1.47.0](https://github.com/openai/openai-python/compare/v1.46.1...v1.47.0) + +### Features + +* **client:** send retry count header ([21b0c00](https://github.com/openai/openai-python/commit/21b0c0043406d81971f87455e5a48b17935dc346)) + + +### Chores + +* **types:** improve type name for embedding models ([#1730](https://github.com/openai/openai-python/issues/1730)) ([4b4eb2b](https://github.com/openai/openai-python/commit/4b4eb2b37877728d2124ad5651ceebf615c0ab28)) + ## 1.46.1 (2024-09-19) Full Changelog: [v1.46.0...v1.46.1](https://github.com/openai/openai-python/compare/v1.46.0...v1.46.1) diff --git a/pyproject.toml b/pyproject.toml index b505880f11..5288d5aa10 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.46.1" +version = "1.47.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 197a24ea67..509df1e880 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.46.1" # x-release-please-version +__version__ = "1.47.0" # x-release-please-version From 5b2dbcd9ba17a4cb897697d90e66175b640e5780 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 23 Sep 2024 11:18:41 +0100 Subject: [PATCH 511/816] fix(pydantic v1): avoid warnings error --- src/openai/_compat.py | 2 ++ src/openai/lib/streaming/_assistants.py | 11 ++++++----- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/openai/_compat.py b/src/openai/_compat.py index c0dd8c1ee5..78851277eb 100644 --- a/src/openai/_compat.py +++ b/src/openai/_compat.py @@ -136,12 +136,14 @@ def model_dump( exclude: IncEx = None, exclude_unset: bool = False, exclude_defaults: bool = False, + warnings: bool = True, ) -> dict[str, Any]: if PYDANTIC_V2: return model.model_dump( exclude=exclude, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, + warnings=warnings, ) return cast( "dict[str, Any]", diff --git a/src/openai/lib/streaming/_assistants.py b/src/openai/lib/streaming/_assistants.py index 183754177a..103e4c40aa 100644 --- a/src/openai/lib/streaming/_assistants.py +++ b/src/openai/lib/streaming/_assistants.py @@ -8,6 +8,7 @@ import httpx from ..._utils import is_dict, is_list, consume_sync_iterator, consume_async_iterator +from ..._compat import model_dump from ..._models import construct_type from ..._streaming import Stream, AsyncStream from ...types.beta import AssistantStreamEvent @@ -906,11 +907,11 @@ def accumulate_run_step( merged = accumulate_delta( cast( "dict[object, object]", - snapshot.model_dump(exclude_unset=True, warnings=False), + model_dump(snapshot, exclude_unset=True, warnings=False), ), cast( "dict[object, object]", - data.delta.model_dump(exclude_unset=True, warnings=False), + model_dump(data.delta, exclude_unset=True, warnings=False), ), ) run_step_snapshots[snapshot.id] = cast(RunStep, construct_type(type_=RunStep, value=merged)) @@ -948,7 +949,7 @@ def accumulate_event( construct_type( # mypy doesn't allow Content for some reason type_=cast(Any, MessageContent), - value=content_delta.model_dump(exclude_unset=True, warnings=False), + value=model_dump(content_delta, exclude_unset=True, warnings=False), ), ), ) @@ -957,11 +958,11 @@ def accumulate_event( merged = accumulate_delta( cast( "dict[object, object]", - block.model_dump(exclude_unset=True, warnings=False), + model_dump(block, exclude_unset=True, warnings=False), ), cast( "dict[object, object]", - content_delta.model_dump(exclude_unset=True, warnings=False), + model_dump(content_delta, exclude_unset=True, warnings=False), ), ) current_message_snapshot.content[content_delta.index] = cast( From 89e5a010b22136f0f16eff5ec33105f4d3e273eb Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 23 Sep 2024 10:20:25 +0000 Subject: [PATCH 512/816] release: 1.47.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index dc9bcb375c..fea051a9dd 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.47.0" + ".": "1.47.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 021be7ef4c..823e9886d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.47.1 (2024-09-23) + +Full Changelog: [v1.47.0...v1.47.1](https://github.com/openai/openai-python/compare/v1.47.0...v1.47.1) + +### Bug Fixes + +* **pydantic v1:** avoid warnings error ([1e8e7d1](https://github.com/openai/openai-python/commit/1e8e7d1f01a4ab4153085bc20484a19613d993b3)) + ## 1.47.0 (2024-09-20) Full Changelog: [v1.46.1...v1.47.0](https://github.com/openai/openai-python/compare/v1.46.1...v1.47.0) diff --git a/pyproject.toml b/pyproject.toml index 5288d5aa10..e4b8a967e0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.47.0" +version = "1.47.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 509df1e880..cad4b7f76c 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.47.0" # x-release-please-version +__version__ = "1.47.1" # x-release-please-version From fd1ed4b5e3828a14074018a30ce42d3960741ccd Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Tue, 24 Sep 2024 14:58:33 +0000 Subject: [PATCH 513/816] chore(internal): use `typing_extensions.overload` instead of `typing` (#1740) --- src/openai/resources/beta/threads/runs/runs.py | 4 ++-- src/openai/resources/beta/threads/threads.py | 4 ++-- src/openai/resources/chat/completions.py | 4 ++-- src/openai/resources/completions.py | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 3fb1cc77aa..a4cbcc57e4 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -3,9 +3,9 @@ from __future__ import annotations import typing_extensions -from typing import List, Union, Iterable, Optional, overload +from typing import List, Union, Iterable, Optional from functools import partial -from typing_extensions import Literal +from typing_extensions import Literal, overload import httpx diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 49b0e4b37e..acc0fe9bda 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -2,9 +2,9 @@ from __future__ import annotations -from typing import Union, Iterable, Optional, overload +from typing import Union, Iterable, Optional from functools import partial -from typing_extensions import Literal +from typing_extensions import Literal, overload import httpx diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index e9267b1f03..05cfaacd83 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -3,8 +3,8 @@ from __future__ import annotations import inspect -from typing import Dict, List, Union, Iterable, Optional, overload -from typing_extensions import Literal +from typing import Dict, List, Union, Iterable, Optional +from typing_extensions import Literal, overload import httpx import pydantic diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index 091fb5657a..49198d2687 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -2,8 +2,8 @@ from __future__ import annotations -from typing import Dict, List, Union, Iterable, Optional, overload -from typing_extensions import Literal +from typing import Dict, List, Union, Iterable, Optional +from typing_extensions import Literal, overload import httpx From 102fce4f363d9996ef40b81cbe79fd29c3e7ccc1 Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Wed, 25 Sep 2024 12:43:48 +0000 Subject: [PATCH 514/816] fix(audio): correct response_format translations type (#1743) --- .DS_Store | Bin 0 -> 6148 bytes .stats.yml | 2 +- api.md | 2 +- src/openai/resources/audio/transcriptions.py | 14 ++++++++------ src/openai/resources/audio/translations.py | 14 ++++++++------ src/openai/types/__init__.py | 1 + .../types/audio/transcription_create_params.py | 7 ++++--- .../types/audio/translation_create_params.py | 7 ++++--- src/openai/types/audio_response_format.py | 7 +++++++ tests/api_resources/audio/test_translations.py | 8 ++++---- 10 files changed, 38 insertions(+), 24 deletions(-) create mode 100644 .DS_Store create mode 100644 src/openai/types/audio_response_format.py diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..c88a062b05be4fd1d362b3e4c6a7481e718b69d0 GIT binary patch literal 6148 zcmeH~O$x$5422WzLU7Zi%h`AUZ!n0Spcima5J4*Vx1OW>k_m#k8KJGkN^pg011%5 z4-v3?8#bF)Wh4O-Ab}?V`#vPNX$~z_{nLTqBLK8P*$r!-C7{U)&>UK-q5{*H9yD6j z#}KP~J2b_)99pW@cF`C;crrWIXQgOGwy`I%~QMGk}L;X0y%TE9jyNVZZH|!@{KyzrRiVBQB0*--!1inh( E0rZ6u#{d8T literal 0 HcmV?d00001 diff --git a/.stats.yml b/.stats.yml index 0151c5a105..e8bca3c6d8 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-de1981b64ac229493473670d618500c6362c195f1057eb7de00bd1bc9184fbd5.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-073331021d48db6af646a3552ab0c682efe31b7fb4e59a109ed1ba539f9b89c5.yml diff --git a/api.md b/api.md index 2498340328..eae17d8d84 100644 --- a/api.md +++ b/api.md @@ -114,7 +114,7 @@ Methods: Types: ```python -from openai.types import AudioModel +from openai.types import AudioModel, AudioResponseFormat ``` ## Transcriptions diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index a6009143d4..fd042d1ac3 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -8,6 +8,7 @@ import httpx from ... import _legacy_response +from ...types import AudioResponseFormat from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from ..._utils import ( extract_files, @@ -22,6 +23,7 @@ from ..._base_client import make_request_options from ...types.audio_model import AudioModel from ...types.audio.transcription import Transcription +from ...types.audio_response_format import AudioResponseFormat __all__ = ["Transcriptions", "AsyncTranscriptions"] @@ -53,7 +55,7 @@ def create( model: Union[str, AudioModel], language: str | NotGiven = NOT_GIVEN, prompt: str | NotGiven = NOT_GIVEN, - response_format: Literal["json", "text", "srt", "verbose_json", "vtt"] | NotGiven = NOT_GIVEN, + response_format: AudioResponseFormat | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, timestamp_granularities: List[Literal["word", "segment"]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -83,8 +85,8 @@ def create( [prompt](https://platform.openai.com/docs/guides/speech-to-text/prompting) should match the audio language. - response_format: The format of the transcript output, in one of these options: `json`, `text`, - `srt`, `verbose_json`, or `vtt`. + response_format: The format of the output, in one of these options: `json`, `text`, `srt`, + `verbose_json`, or `vtt`. temperature: The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and @@ -160,7 +162,7 @@ async def create( model: Union[str, AudioModel], language: str | NotGiven = NOT_GIVEN, prompt: str | NotGiven = NOT_GIVEN, - response_format: Literal["json", "text", "srt", "verbose_json", "vtt"] | NotGiven = NOT_GIVEN, + response_format: AudioResponseFormat | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, timestamp_granularities: List[Literal["word", "segment"]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -190,8 +192,8 @@ async def create( [prompt](https://platform.openai.com/docs/guides/speech-to-text/prompting) should match the audio language. - response_format: The format of the transcript output, in one of these options: `json`, `text`, - `srt`, `verbose_json`, or `vtt`. + response_format: The format of the output, in one of these options: `json`, `text`, `srt`, + `verbose_json`, or `vtt`. temperature: The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index 7ec647fb6b..fe08dd550e 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -7,6 +7,7 @@ import httpx from ... import _legacy_response +from ...types import AudioResponseFormat from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from ..._utils import ( extract_files, @@ -21,6 +22,7 @@ from ..._base_client import make_request_options from ...types.audio_model import AudioModel from ...types.audio.translation import Translation +from ...types.audio_response_format import AudioResponseFormat __all__ = ["Translations", "AsyncTranslations"] @@ -51,7 +53,7 @@ def create( file: FileTypes, model: Union[str, AudioModel], prompt: str | NotGiven = NOT_GIVEN, - response_format: str | NotGiven = NOT_GIVEN, + response_format: AudioResponseFormat | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -75,8 +77,8 @@ def create( [prompt](https://platform.openai.com/docs/guides/speech-to-text/prompting) should be in English. - response_format: The format of the transcript output, in one of these options: `json`, `text`, - `srt`, `verbose_json`, or `vtt`. + response_format: The format of the output, in one of these options: `json`, `text`, `srt`, + `verbose_json`, or `vtt`. temperature: The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and @@ -143,7 +145,7 @@ async def create( file: FileTypes, model: Union[str, AudioModel], prompt: str | NotGiven = NOT_GIVEN, - response_format: str | NotGiven = NOT_GIVEN, + response_format: AudioResponseFormat | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -167,8 +169,8 @@ async def create( [prompt](https://platform.openai.com/docs/guides/speech-to-text/prompting) should be in English. - response_format: The format of the transcript output, in one of these options: `json`, `text`, - `srt`, `verbose_json`, or `vtt`. + response_format: The format of the output, in one of these options: `json`, `text`, `srt`, + `verbose_json`, or `vtt`. temperature: The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index 4dbc1b6b7b..6223be883d 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -38,6 +38,7 @@ from .batch_create_params import BatchCreateParams as BatchCreateParams from .batch_request_counts import BatchRequestCounts as BatchRequestCounts from .upload_create_params import UploadCreateParams as UploadCreateParams +from .audio_response_format import AudioResponseFormat as AudioResponseFormat from .image_generate_params import ImageGenerateParams as ImageGenerateParams from .upload_complete_params import UploadCompleteParams as UploadCompleteParams from .embedding_create_params import EmbeddingCreateParams as EmbeddingCreateParams diff --git a/src/openai/types/audio/transcription_create_params.py b/src/openai/types/audio/transcription_create_params.py index a825fefecb..5ac2bb91e5 100644 --- a/src/openai/types/audio/transcription_create_params.py +++ b/src/openai/types/audio/transcription_create_params.py @@ -7,6 +7,7 @@ from ..._types import FileTypes from ..audio_model import AudioModel +from ..audio_response_format import AudioResponseFormat __all__ = ["TranscriptionCreateParams"] @@ -41,10 +42,10 @@ class TranscriptionCreateParams(TypedDict, total=False): should match the audio language. """ - response_format: Literal["json", "text", "srt", "verbose_json", "vtt"] + response_format: AudioResponseFormat """ - The format of the transcript output, in one of these options: `json`, `text`, - `srt`, `verbose_json`, or `vtt`. + The format of the output, in one of these options: `json`, `text`, `srt`, + `verbose_json`, or `vtt`. """ temperature: float diff --git a/src/openai/types/audio/translation_create_params.py b/src/openai/types/audio/translation_create_params.py index 054996a134..6859ed9d30 100644 --- a/src/openai/types/audio/translation_create_params.py +++ b/src/openai/types/audio/translation_create_params.py @@ -7,6 +7,7 @@ from ..._types import FileTypes from ..audio_model import AudioModel +from ..audio_response_format import AudioResponseFormat __all__ = ["TranslationCreateParams"] @@ -33,10 +34,10 @@ class TranslationCreateParams(TypedDict, total=False): should be in English. """ - response_format: str + response_format: AudioResponseFormat """ - The format of the transcript output, in one of these options: `json`, `text`, - `srt`, `verbose_json`, or `vtt`. + The format of the output, in one of these options: `json`, `text`, `srt`, + `verbose_json`, or `vtt`. """ temperature: float diff --git a/src/openai/types/audio_response_format.py b/src/openai/types/audio_response_format.py new file mode 100644 index 0000000000..f8c8d45945 --- /dev/null +++ b/src/openai/types/audio_response_format.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["AudioResponseFormat"] + +AudioResponseFormat: TypeAlias = Literal["json", "text", "srt", "verbose_json", "vtt"] diff --git a/tests/api_resources/audio/test_translations.py b/tests/api_resources/audio/test_translations.py index f5c6c68f0b..b048a1af12 100644 --- a/tests/api_resources/audio/test_translations.py +++ b/tests/api_resources/audio/test_translations.py @@ -30,8 +30,8 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: translation = client.audio.translations.create( file=b"raw file contents", model="whisper-1", - prompt="string", - response_format="string", + prompt="prompt", + response_format="json", temperature=0, ) assert_matches_type(Translation, translation, path=["response"]) @@ -79,8 +79,8 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> translation = await async_client.audio.translations.create( file=b"raw file contents", model="whisper-1", - prompt="string", - response_format="string", + prompt="prompt", + response_format="json", temperature=0, ) assert_matches_type(Translation, translation, path=["response"]) From 5449e208bcf1bcf6c4a25a33f2144c7bfd8acdb3 Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Wed, 25 Sep 2024 12:45:37 +0000 Subject: [PATCH 515/816] feat(client): allow overriding retry count header (#1745) --- src/openai/_base_client.py | 6 +- tests/test_client.py | 150 +++++++++++++++++++++++++++++++++---- 2 files changed, 138 insertions(+), 18 deletions(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 77e82026ef..c4c9803e74 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -413,8 +413,10 @@ def _build_headers(self, options: FinalRequestOptions, *, retries_taken: int = 0 if idempotency_header and options.method.lower() != "get" and idempotency_header not in headers: headers[idempotency_header] = options.idempotency_key or self._idempotency_key() - if retries_taken > 0: - headers.setdefault("x-stainless-retry-count", str(retries_taken)) + # Don't set the retry count header if it was already set or removed by the caller. We check + # `custom_headers`, which can contain `Omit()`, instead of `headers` to account for the removal case. + if "x-stainless-retry-count" not in (header.lower() for header in custom_headers): + headers["x-stainless-retry-count"] = str(retries_taken) return headers diff --git a/tests/test_client.py b/tests/test_client.py index 567a6ec59f..463174465c 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -788,10 +788,71 @@ def retry_handler(_request: httpx.Request) -> httpx.Response: ) assert response.retries_taken == failures_before_success - if failures_before_success == 0: - assert "x-stainless-retry-count" not in response.http_request.headers - else: - assert int(response.http_request.headers.get("x-stainless-retry-count")) == failures_before_success + assert int(response.http_request.headers.get("x-stainless-retry-count")) == failures_before_success + + @pytest.mark.parametrize("failures_before_success", [0, 2, 4]) + @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) + @pytest.mark.respx(base_url=base_url) + def test_omit_retry_count_header( + self, client: OpenAI, failures_before_success: int, respx_mock: MockRouter + ) -> None: + client = client.with_options(max_retries=4) + + nb_retries = 0 + + def retry_handler(_request: httpx.Request) -> httpx.Response: + nonlocal nb_retries + if nb_retries < failures_before_success: + nb_retries += 1 + return httpx.Response(500) + return httpx.Response(200) + + respx_mock.post("/chat/completions").mock(side_effect=retry_handler) + + response = client.chat.completions.with_raw_response.create( + messages=[ + { + "content": "string", + "role": "system", + } + ], + model="gpt-4o", + extra_headers={"x-stainless-retry-count": Omit()}, + ) + + assert len(response.http_request.headers.get_list("x-stainless-retry-count")) == 0 + + @pytest.mark.parametrize("failures_before_success", [0, 2, 4]) + @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) + @pytest.mark.respx(base_url=base_url) + def test_overwrite_retry_count_header( + self, client: OpenAI, failures_before_success: int, respx_mock: MockRouter + ) -> None: + client = client.with_options(max_retries=4) + + nb_retries = 0 + + def retry_handler(_request: httpx.Request) -> httpx.Response: + nonlocal nb_retries + if nb_retries < failures_before_success: + nb_retries += 1 + return httpx.Response(500) + return httpx.Response(200) + + respx_mock.post("/chat/completions").mock(side_effect=retry_handler) + + response = client.chat.completions.with_raw_response.create( + messages=[ + { + "content": "string", + "role": "system", + } + ], + model="gpt-4o", + extra_headers={"x-stainless-retry-count": "42"}, + ) + + assert response.http_request.headers.get("x-stainless-retry-count") == "42" @pytest.mark.parametrize("failures_before_success", [0, 2, 4]) @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) @@ -822,10 +883,7 @@ def retry_handler(_request: httpx.Request) -> httpx.Response: model="gpt-4o", ) as response: assert response.retries_taken == failures_before_success - if failures_before_success == 0: - assert "x-stainless-retry-count" not in response.http_request.headers - else: - assert int(response.http_request.headers.get("x-stainless-retry-count")) == failures_before_success + assert int(response.http_request.headers.get("x-stainless-retry-count")) == failures_before_success class TestAsyncOpenAI: @@ -1590,10 +1648,73 @@ def retry_handler(_request: httpx.Request) -> httpx.Response: ) assert response.retries_taken == failures_before_success - if failures_before_success == 0: - assert "x-stainless-retry-count" not in response.http_request.headers - else: - assert int(response.http_request.headers.get("x-stainless-retry-count")) == failures_before_success + assert int(response.http_request.headers.get("x-stainless-retry-count")) == failures_before_success + + @pytest.mark.parametrize("failures_before_success", [0, 2, 4]) + @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) + @pytest.mark.respx(base_url=base_url) + @pytest.mark.asyncio + async def test_omit_retry_count_header( + self, async_client: AsyncOpenAI, failures_before_success: int, respx_mock: MockRouter + ) -> None: + client = async_client.with_options(max_retries=4) + + nb_retries = 0 + + def retry_handler(_request: httpx.Request) -> httpx.Response: + nonlocal nb_retries + if nb_retries < failures_before_success: + nb_retries += 1 + return httpx.Response(500) + return httpx.Response(200) + + respx_mock.post("/chat/completions").mock(side_effect=retry_handler) + + response = await client.chat.completions.with_raw_response.create( + messages=[ + { + "content": "string", + "role": "system", + } + ], + model="gpt-4o", + extra_headers={"x-stainless-retry-count": Omit()}, + ) + + assert len(response.http_request.headers.get_list("x-stainless-retry-count")) == 0 + + @pytest.mark.parametrize("failures_before_success", [0, 2, 4]) + @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) + @pytest.mark.respx(base_url=base_url) + @pytest.mark.asyncio + async def test_overwrite_retry_count_header( + self, async_client: AsyncOpenAI, failures_before_success: int, respx_mock: MockRouter + ) -> None: + client = async_client.with_options(max_retries=4) + + nb_retries = 0 + + def retry_handler(_request: httpx.Request) -> httpx.Response: + nonlocal nb_retries + if nb_retries < failures_before_success: + nb_retries += 1 + return httpx.Response(500) + return httpx.Response(200) + + respx_mock.post("/chat/completions").mock(side_effect=retry_handler) + + response = await client.chat.completions.with_raw_response.create( + messages=[ + { + "content": "string", + "role": "system", + } + ], + model="gpt-4o", + extra_headers={"x-stainless-retry-count": "42"}, + ) + + assert response.http_request.headers.get("x-stainless-retry-count") == "42" @pytest.mark.parametrize("failures_before_success", [0, 2, 4]) @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) @@ -1625,7 +1746,4 @@ def retry_handler(_request: httpx.Request) -> httpx.Response: model="gpt-4o", ) as response: assert response.retries_taken == failures_before_success - if failures_before_success == 0: - assert "x-stainless-retry-count" not in response.http_request.headers - else: - assert int(response.http_request.headers.get("x-stainless-retry-count")) == failures_before_success + assert int(response.http_request.headers.get("x-stainless-retry-count")) == failures_before_success From 864eafca8f9626c13a5864c133ca620d1cbecf89 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 25 Sep 2024 13:21:13 +0000 Subject: [PATCH 516/816] release: 1.48.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 18 ++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 21 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index fea051a9dd..3f47f4bc2b 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.47.1" + ".": "1.48.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 823e9886d8..d89151074b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,23 @@ # Changelog +## 1.48.0 (2024-09-25) + +Full Changelog: [v1.47.1...v1.48.0](https://github.com/openai/openai-python/compare/v1.47.1...v1.48.0) + +### Features + +* **client:** allow overriding retry count header ([#1745](https://github.com/openai/openai-python/issues/1745)) ([9f07d4d](https://github.com/openai/openai-python/commit/9f07d4dbd6f24108a1f5e0309037318858f5a229)) + + +### Bug Fixes + +* **audio:** correct response_format translations type ([#1743](https://github.com/openai/openai-python/issues/1743)) ([b912108](https://github.com/openai/openai-python/commit/b9121089c696bc943323e2e75d4706401d809aaa)) + + +### Chores + +* **internal:** use `typing_extensions.overload` instead of `typing` ([#1740](https://github.com/openai/openai-python/issues/1740)) ([2522bd5](https://github.com/openai/openai-python/commit/2522bd59f7b5e903e4fc856a4c5dbdbe66bba37f)) + ## 1.47.1 (2024-09-23) Full Changelog: [v1.47.0...v1.47.1](https://github.com/openai/openai-python/compare/v1.47.0...v1.47.1) diff --git a/pyproject.toml b/pyproject.toml index e4b8a967e0..05f957cac0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.47.1" +version = "1.48.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index cad4b7f76c..66109f354b 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.47.1" # x-release-please-version +__version__ = "1.48.0" # x-release-please-version From 9feadd8274809fff9ff1e36a0c90d45566ed46e2 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Thu, 26 Sep 2024 11:34:40 +0100 Subject: [PATCH 517/816] chore(internal): update test snapshots (#1749) --- ...661f4f5bea321c0aac9e164f2ed3e409aebc48.bin | 102 ----- ...2625e557f9e6763bd8c03bcd88e220149a3367.bin | 224 ----------- ...cf4aa41fc428937c231e17c3460f3237f6a018.bin | 28 -- ...6aea6d0356b63140161758a2e576d4e3092cfa.bin | 36 -- ...f8d591fb691ebac56f5ae39a22cc7d455c5353.bin | 28 ++ ...849decc68d3f63bd38172889367e1afb1e04f7.bin | 22 ++ ...fd3deafe041da94d541071009596234d8c84a6.bin | 36 -- ...3dfcc25dc2f57a5e05eb5cc46c70b51d8845c2.bin | 52 --- ...af1246f55edb6ad95fa24059f160996b68866d.bin | 10 + ...f7868df0b6d8a02dfcd23f6bc7196cf0eadb6e.bin | 28 -- ...6dd33878095c68badc6b6654a69769b391a1c1.bin | 30 ++ ...f0afcd22d4f0e85418ab38ee24d2a570a84ff0.bin | 10 - ...5e65923f182256b6e6b752950a3aaa2ad2320a.bin | 36 ++ ...542b954b37d9dfd1910b964ddebc9677e6ae85.bin | 12 + ...9d46ee41408a688758219f3f58ac1ee2084db3.bin | 28 -- ...5dfafc1d712c253b42bafe07991b3058541016.bin | 156 -------- ...6ad615ed8d8f649888ebfddfbc3ee151f44d46.bin | 28 ++ ...f60f7f745f1a56d82e62f58031cc2add502380.bin | 100 +++++ ...613bdb9c4a2ad8262027d158cc94e6f9765164.bin | 12 - ...05d4daf7e8ad6d61ffa406ab5361fe36a8d5b1.bin | 36 ++ ...f8694b77f608de5e2a3799276be06ce3fbb15b.bin | 30 -- ...8bb74642d23ac1ca13fe37cb6e889b66f759f6.bin | 362 ++++++++++++++++++ ...81772c3010c10b37e8af3996fbdbbecb3c32a2.bin | 22 -- ...47020a9d875eb7ce644a0ff355581690a4cbfd.bin | 68 ++++ ...7688be2f6ca0849a6e4f17851b517310841d9b.bin | 52 +++ tests/lib/chat/test_completions.py | 132 ++++--- tests/lib/chat/test_completions_streaming.py | 263 ++++++------- 27 files changed, 970 insertions(+), 973 deletions(-) delete mode 100644 .inline-snapshot/external/038a5c69c34c9513021b52aa61661f4f5bea321c0aac9e164f2ed3e409aebc48.bin delete mode 100644 .inline-snapshot/external/0898f3d1651e3244eeb3651d012625e557f9e6763bd8c03bcd88e220149a3367.bin delete mode 100644 .inline-snapshot/external/0a00cd46c61030ff70241d432dcf4aa41fc428937c231e17c3460f3237f6a018.bin delete mode 100644 .inline-snapshot/external/15ae68f793c7b390fc8af9e21a6aea6d0356b63140161758a2e576d4e3092cfa.bin create mode 100644 .inline-snapshot/external/173417d553406f034f643e5db3f8d591fb691ebac56f5ae39a22cc7d455c5353.bin create mode 100644 .inline-snapshot/external/2018feb66ae13fcf5333d61b95849decc68d3f63bd38172889367e1afb1e04f7.bin delete mode 100644 .inline-snapshot/external/24aaf30663f9a568a0e77970b4fd3deafe041da94d541071009596234d8c84a6.bin delete mode 100644 .inline-snapshot/external/453df473e96274dd8ab61ab4d13dfcc25dc2f57a5e05eb5cc46c70b51d8845c2.bin create mode 100644 .inline-snapshot/external/4cc50a6135d254573a502310e6af1246f55edb6ad95fa24059f160996b68866d.bin delete mode 100644 .inline-snapshot/external/4d75e4d7c3e0b532a67fb2114ff7868df0b6d8a02dfcd23f6bc7196cf0eadb6e.bin create mode 100644 .inline-snapshot/external/569c877e69429d4cbc1577d2cd6dd33878095c68badc6b6654a69769b391a1c1.bin delete mode 100644 .inline-snapshot/external/69363a555f8ea9b6eee0bb022af0afcd22d4f0e85418ab38ee24d2a570a84ff0.bin create mode 100644 .inline-snapshot/external/7e5ea4d12e7cc064399b6631415e65923f182256b6e6b752950a3aaa2ad2320a.bin create mode 100644 .inline-snapshot/external/83b060bae42eb41c4f1edbb7c1542b954b37d9dfd1910b964ddebc9677e6ae85.bin delete mode 100644 .inline-snapshot/external/83d3d003e6fdaa69b7a398440f9d46ee41408a688758219f3f58ac1ee2084db3.bin delete mode 100644 .inline-snapshot/external/a0c4f0be184e8234cdc0e3abae5dfafc1d712c253b42bafe07991b3058541016.bin create mode 100644 .inline-snapshot/external/a247c49c5fcd492bfb7a02a3306ad615ed8d8f649888ebfddfbc3ee151f44d46.bin create mode 100644 .inline-snapshot/external/a491adda08c3d4fde95f5b2ee3f60f7f745f1a56d82e62f58031cc2add502380.bin delete mode 100644 .inline-snapshot/external/be1089999ca5f1e63b149447f1613bdb9c4a2ad8262027d158cc94e6f9765164.bin create mode 100644 .inline-snapshot/external/c6aa7e397b7123c3501f25df3a05d4daf7e8ad6d61ffa406ab5361fe36a8d5b1.bin delete mode 100644 .inline-snapshot/external/ca015b8b1ebaac98be76f2f855f8694b77f608de5e2a3799276be06ce3fbb15b.bin create mode 100644 .inline-snapshot/external/d615580118391ee13492193e3a8bb74642d23ac1ca13fe37cb6e889b66f759f6.bin delete mode 100644 .inline-snapshot/external/dae1b261f19722801adc82a13181772c3010c10b37e8af3996fbdbbecb3c32a2.bin create mode 100644 .inline-snapshot/external/e2aad469b71d1d4894ff833ea147020a9d875eb7ce644a0ff355581690a4cbfd.bin create mode 100644 .inline-snapshot/external/f82268f2fefd5cfbc7eeb59c297688be2f6ca0849a6e4f17851b517310841d9b.bin diff --git a/.inline-snapshot/external/038a5c69c34c9513021b52aa61661f4f5bea321c0aac9e164f2ed3e409aebc48.bin b/.inline-snapshot/external/038a5c69c34c9513021b52aa61661f4f5bea321c0aac9e164f2ed3e409aebc48.bin deleted file mode 100644 index a5a0aeb4c0..0000000000 --- a/.inline-snapshot/external/038a5c69c34c9513021b52aa61661f4f5bea321c0aac9e164f2ed3e409aebc48.bin +++ /dev/null @@ -1,102 +0,0 @@ -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"I'm"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" unable"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" to"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" provide"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" real"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"-time"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" updates"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":","},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" including"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" current"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" information"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" For"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" the"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" latest"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" in"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" San"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":","},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" I"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" recommend"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" checking"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" a"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" reliable"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" website"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" or"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" app"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" such"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" as"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" the"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" Weather"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" Channel"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":","},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" BBC"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" Weather"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":","},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" or"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" a"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" local"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" San"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" news"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" station"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} - -data: {"id":"chatcmpl-9tXjg9DdaOfymTPDrSLfxslQEH0C2","object":"chat.completion.chunk","created":1723024748,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":47,"total_tokens":61}} - -data: [DONE] - diff --git a/.inline-snapshot/external/0898f3d1651e3244eeb3651d012625e557f9e6763bd8c03bcd88e220149a3367.bin b/.inline-snapshot/external/0898f3d1651e3244eeb3651d012625e557f9e6763bd8c03bcd88e220149a3367.bin deleted file mode 100644 index 4b42ada8d2..0000000000 --- a/.inline-snapshot/external/0898f3d1651e3244eeb3651d012625e557f9e6763bd8c03bcd88e220149a3367.bin +++ /dev/null @@ -1,224 +0,0 @@ -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\n"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" {\n"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"location"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"San"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":","},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" CA"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"forecast"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"_date"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"202"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"3"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"-"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"11"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"-"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"02"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"weather"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" {\n"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"temperature"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" {\n"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"current"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"N"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"/A"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"high"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"N"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"/A"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"low"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"N"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"/A"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\"\n"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" },\n"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"condition"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"N"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"/A"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"humidity"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"N"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"/A"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"wind"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"_speed"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"N"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"/A"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\"\n"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" },\n"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"note"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"Please"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" check"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" a"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" reliable"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" service"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" for"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" the"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" most"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" current"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" information"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":".\"\n"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" }"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} - -data: {"id":"chatcmpl-9tXjrL8ZwahfIfWjgwcnHRzZrzVL4","object":"chat.completion.chunk","created":1723024759,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[],"usage":{"prompt_tokens":19,"completion_tokens":108,"total_tokens":127}} - -data: [DONE] - diff --git a/.inline-snapshot/external/0a00cd46c61030ff70241d432dcf4aa41fc428937c231e17c3460f3237f6a018.bin b/.inline-snapshot/external/0a00cd46c61030ff70241d432dcf4aa41fc428937c231e17c3460f3237f6a018.bin deleted file mode 100644 index 73de9d6cbc..0000000000 --- a/.inline-snapshot/external/0a00cd46c61030ff70241d432dcf4aa41fc428937c231e17c3460f3237f6a018.bin +++ /dev/null @@ -1,28 +0,0 @@ -data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"role":"assistant","content":null,"refusal":""},"logprobs":{"content":null,"refusal":[]},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":"I'm"},"logprobs":{"content":null,"refusal":[{"token":"I'm","logprob":-0.0016157961,"bytes":[73,39,109],"top_logprobs":[]}]},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" sorry"},"logprobs":{"content":null,"refusal":[{"token":" sorry","logprob":-0.78663874,"bytes":[32,115,111,114,114,121],"top_logprobs":[]}]},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":","},"logprobs":{"content":null,"refusal":[{"token":",","logprob":-0.0000779144,"bytes":[44],"top_logprobs":[]}]},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" I"},"logprobs":{"content":null,"refusal":[{"token":" I","logprob":-0.5234622,"bytes":[32,73],"top_logprobs":[]}]},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" cannot"},"logprobs":{"content":null,"refusal":[{"token":" cannot","logprob":-0.52499557,"bytes":[32,99,97,110,110,111,116],"top_logprobs":[]}]},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" assist"},"logprobs":{"content":null,"refusal":[{"token":" assist","logprob":-0.015198289,"bytes":[32,97,115,115,105,115,116],"top_logprobs":[]}]},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" with"},"logprobs":{"content":null,"refusal":[{"token":" with","logprob":-0.00071648485,"bytes":[32,119,105,116,104],"top_logprobs":[]}]},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" that"},"logprobs":{"content":null,"refusal":[{"token":" that","logprob":-0.008114983,"bytes":[32,116,104,97,116],"top_logprobs":[]}]},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" request"},"logprobs":{"content":null,"refusal":[{"token":" request","logprob":-0.0013802331,"bytes":[32,114,101,113,117,101,115,116],"top_logprobs":[]}]},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":"."},"logprobs":{"content":null,"refusal":[{"token":".","logprob":-3.4121115e-6,"bytes":[46],"top_logprobs":[]}]},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} - -data: {"id":"chatcmpl-9tXjmhJIrvp7TBeVxzzxmx8pp2UGY","object":"chat.completion.chunk","created":1723024754,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[],"usage":{"prompt_tokens":17,"completion_tokens":11,"total_tokens":28}} - -data: [DONE] - diff --git a/.inline-snapshot/external/15ae68f793c7b390fc8af9e21a6aea6d0356b63140161758a2e576d4e3092cfa.bin b/.inline-snapshot/external/15ae68f793c7b390fc8af9e21a6aea6d0356b63140161758a2e576d4e3092cfa.bin deleted file mode 100644 index 1bcca1fceb..0000000000 --- a/.inline-snapshot/external/15ae68f793c7b390fc8af9e21a6aea6d0356b63140161758a2e576d4e3092cfa.bin +++ /dev/null @@ -1,36 +0,0 @@ -data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"{\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"city"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"San"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\",\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"temperature"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"68"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":",\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"units"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"f"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"\"}"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} - -data: {"id":"chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD","object":"chat.completion.chunk","created":1723024750,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[],"usage":{"prompt_tokens":17,"completion_tokens":14,"total_tokens":31}} - -data: [DONE] - diff --git a/.inline-snapshot/external/173417d553406f034f643e5db3f8d591fb691ebac56f5ae39a22cc7d455c5353.bin b/.inline-snapshot/external/173417d553406f034f643e5db3f8d591fb691ebac56f5ae39a22cc7d455c5353.bin new file mode 100644 index 0000000000..49c6dce93f --- /dev/null +++ b/.inline-snapshot/external/173417d553406f034f643e5db3f8d591fb691ebac56f5ae39a22cc7d455c5353.bin @@ -0,0 +1,28 @@ +data: {"id":"chatcmpl-ABfw4IfQfCCrcuybFm41wJyxjbkz7","object":"chat.completion.chunk","created":1727346172,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"role":"assistant","content":null,"refusal":""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw4IfQfCCrcuybFm41wJyxjbkz7","object":"chat.completion.chunk","created":1727346172,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"refusal":"I'm"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw4IfQfCCrcuybFm41wJyxjbkz7","object":"chat.completion.chunk","created":1727346172,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"refusal":" sorry"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw4IfQfCCrcuybFm41wJyxjbkz7","object":"chat.completion.chunk","created":1727346172,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"refusal":","},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw4IfQfCCrcuybFm41wJyxjbkz7","object":"chat.completion.chunk","created":1727346172,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"refusal":" I"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw4IfQfCCrcuybFm41wJyxjbkz7","object":"chat.completion.chunk","created":1727346172,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"refusal":" can't"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw4IfQfCCrcuybFm41wJyxjbkz7","object":"chat.completion.chunk","created":1727346172,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"refusal":" assist"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw4IfQfCCrcuybFm41wJyxjbkz7","object":"chat.completion.chunk","created":1727346172,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"refusal":" with"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw4IfQfCCrcuybFm41wJyxjbkz7","object":"chat.completion.chunk","created":1727346172,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"refusal":" that"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw4IfQfCCrcuybFm41wJyxjbkz7","object":"chat.completion.chunk","created":1727346172,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"refusal":" request"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw4IfQfCCrcuybFm41wJyxjbkz7","object":"chat.completion.chunk","created":1727346172,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"refusal":"."},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw4IfQfCCrcuybFm41wJyxjbkz7","object":"chat.completion.chunk","created":1727346172,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-ABfw4IfQfCCrcuybFm41wJyxjbkz7","object":"chat.completion.chunk","created":1727346172,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[],"usage":{"prompt_tokens":79,"completion_tokens":11,"total_tokens":90,"completion_tokens_details":{"reasoning_tokens":0}}} + +data: [DONE] + diff --git a/.inline-snapshot/external/2018feb66ae13fcf5333d61b95849decc68d3f63bd38172889367e1afb1e04f7.bin b/.inline-snapshot/external/2018feb66ae13fcf5333d61b95849decc68d3f63bd38172889367e1afb1e04f7.bin new file mode 100644 index 0000000000..871970676f --- /dev/null +++ b/.inline-snapshot/external/2018feb66ae13fcf5333d61b95849decc68d3f63bd38172889367e1afb1e04f7.bin @@ -0,0 +1,22 @@ +data: {"id":"chatcmpl-ABfwERreu9s99xXsVuOWtIB2UOx62","object":"chat.completion.chunk","created":1727346182,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_143bb8492c","choices":[{"index":0,"delta":{"role":"assistant","content":null,"tool_calls":[{"index":0,"id":"call_4XzlGBLtUe9dy3GVNV4jhq7h","type":"function","function":{"name":"get_weather","arguments":""}}],"refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwERreu9s99xXsVuOWtIB2UOx62","object":"chat.completion.chunk","created":1727346182,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_143bb8492c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwERreu9s99xXsVuOWtIB2UOx62","object":"chat.completion.chunk","created":1727346182,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_143bb8492c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"city"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwERreu9s99xXsVuOWtIB2UOx62","object":"chat.completion.chunk","created":1727346182,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_143bb8492c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwERreu9s99xXsVuOWtIB2UOx62","object":"chat.completion.chunk","created":1727346182,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_143bb8492c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"New"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwERreu9s99xXsVuOWtIB2UOx62","object":"chat.completion.chunk","created":1727346182,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_143bb8492c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":" York"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwERreu9s99xXsVuOWtIB2UOx62","object":"chat.completion.chunk","created":1727346182,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_143bb8492c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":" City"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwERreu9s99xXsVuOWtIB2UOx62","object":"chat.completion.chunk","created":1727346182,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_143bb8492c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"}"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwERreu9s99xXsVuOWtIB2UOx62","object":"chat.completion.chunk","created":1727346182,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_143bb8492c","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"tool_calls"}]} + +data: {"id":"chatcmpl-ABfwERreu9s99xXsVuOWtIB2UOx62","object":"chat.completion.chunk","created":1727346182,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_143bb8492c","choices":[],"usage":{"prompt_tokens":44,"completion_tokens":16,"total_tokens":60,"completion_tokens_details":{"reasoning_tokens":0}}} + +data: [DONE] + diff --git a/.inline-snapshot/external/24aaf30663f9a568a0e77970b4fd3deafe041da94d541071009596234d8c84a6.bin b/.inline-snapshot/external/24aaf30663f9a568a0e77970b4fd3deafe041da94d541071009596234d8c84a6.bin deleted file mode 100644 index 49962cff27..0000000000 --- a/.inline-snapshot/external/24aaf30663f9a568a0e77970b4fd3deafe041da94d541071009596234d8c84a6.bin +++ /dev/null @@ -1,36 +0,0 @@ -data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"role":"assistant","content":null,"tool_calls":[{"index":0,"id":"call_7PhhveOvvpPK53s1fV8TWhoV","type":"function","function":{"name":"GetWeatherArgs","arguments":""}}],"refusal":null},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"city"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"Ed"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"inburgh"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\",\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"country"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"GB"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\",\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"units"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"c"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"}"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"tool_calls"}]} - -data: {"id":"chatcmpl-9tXjnXkjzholyB3ceNegQC7g5zP57","object":"chat.completion.chunk","created":1723024755,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[],"usage":{"prompt_tokens":76,"completion_tokens":24,"total_tokens":100}} - -data: [DONE] - diff --git a/.inline-snapshot/external/453df473e96274dd8ab61ab4d13dfcc25dc2f57a5e05eb5cc46c70b51d8845c2.bin b/.inline-snapshot/external/453df473e96274dd8ab61ab4d13dfcc25dc2f57a5e05eb5cc46c70b51d8845c2.bin deleted file mode 100644 index adcdddd317..0000000000 --- a/.inline-snapshot/external/453df473e96274dd8ab61ab4d13dfcc25dc2f57a5e05eb5cc46c70b51d8845c2.bin +++ /dev/null @@ -1,52 +0,0 @@ -data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"role":"assistant","content":null},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_lQnnsesjFMWMQ5IeWPHzR4th","type":"function","function":{"name":"GetWeatherArgs","arguments":""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"ci"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"ty\": "}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"Edinb"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"urgh"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\", \"c"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"ountry"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\": \""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"UK\", "}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"units"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\": \""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"c\"}"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"id":"call_2xjOUgaCdiwAcl9ZBL9LyMUU","type":"function","function":{"name":"get_stock_price","arguments":""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"{\"ti"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"cker\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":": \"AAP"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"L\", "}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"\"exch"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"ange\":"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":" \"NA"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"SDAQ\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"}"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"tool_calls"}]} - -data: {"id":"chatcmpl-9tXjpPLJgivc9nyuBCCWX8HNg9L2J","object":"chat.completion.chunk","created":1723024757,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[],"usage":{"prompt_tokens":149,"completion_tokens":60,"total_tokens":209}} - -data: [DONE] - diff --git a/.inline-snapshot/external/4cc50a6135d254573a502310e6af1246f55edb6ad95fa24059f160996b68866d.bin b/.inline-snapshot/external/4cc50a6135d254573a502310e6af1246f55edb6ad95fa24059f160996b68866d.bin new file mode 100644 index 0000000000..c3392883be --- /dev/null +++ b/.inline-snapshot/external/4cc50a6135d254573a502310e6af1246f55edb6ad95fa24059f160996b68866d.bin @@ -0,0 +1,10 @@ +data: {"id":"chatcmpl-ABfw3Oqj8RD0z6aJiiX37oTjV2HFh","object":"chat.completion.chunk","created":1727346171,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_7568d46099","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw3Oqj8RD0z6aJiiX37oTjV2HFh","object":"chat.completion.chunk","created":1727346171,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_7568d46099","choices":[{"index":0,"delta":{"content":"{\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw3Oqj8RD0z6aJiiX37oTjV2HFh","object":"chat.completion.chunk","created":1727346171,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_7568d46099","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"length"}]} + +data: {"id":"chatcmpl-ABfw3Oqj8RD0z6aJiiX37oTjV2HFh","object":"chat.completion.chunk","created":1727346171,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_7568d46099","choices":[],"usage":{"prompt_tokens":79,"completion_tokens":1,"total_tokens":80,"completion_tokens_details":{"reasoning_tokens":0}}} + +data: [DONE] + diff --git a/.inline-snapshot/external/4d75e4d7c3e0b532a67fb2114ff7868df0b6d8a02dfcd23f6bc7196cf0eadb6e.bin b/.inline-snapshot/external/4d75e4d7c3e0b532a67fb2114ff7868df0b6d8a02dfcd23f6bc7196cf0eadb6e.bin deleted file mode 100644 index 008d5882ec..0000000000 --- a/.inline-snapshot/external/4d75e4d7c3e0b532a67fb2114ff7868df0b6d8a02dfcd23f6bc7196cf0eadb6e.bin +++ /dev/null @@ -1,28 +0,0 @@ -data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"role":"assistant","content":null,"refusal":""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":"I'm"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" sorry"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":","},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" I"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" cannot"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" assist"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" with"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" that"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" request"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":"."},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} - -data: {"id":"chatcmpl-9tXjkxJ4omrCOJoVbZIgaPWZS8TLD","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[],"usage":{"prompt_tokens":17,"completion_tokens":11,"total_tokens":28}} - -data: [DONE] - diff --git a/.inline-snapshot/external/569c877e69429d4cbc1577d2cd6dd33878095c68badc6b6654a69769b391a1c1.bin b/.inline-snapshot/external/569c877e69429d4cbc1577d2cd6dd33878095c68badc6b6654a69769b391a1c1.bin new file mode 100644 index 0000000000..47dd73151c --- /dev/null +++ b/.inline-snapshot/external/569c877e69429d4cbc1577d2cd6dd33878095c68badc6b6654a69769b391a1c1.bin @@ -0,0 +1,30 @@ +data: {"id":"chatcmpl-ABfw5GEVqPbLY576l46FZDQoNJ2KC","object":"chat.completion.chunk","created":1727346173,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"role":"assistant","content":null,"refusal":""},"logprobs":{"content":null,"refusal":[]},"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw5GEVqPbLY576l46FZDQoNJ2KC","object":"chat.completion.chunk","created":1727346173,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"refusal":"I'm"},"logprobs":{"content":null,"refusal":[{"token":"I'm","logprob":-0.0012038043,"bytes":[73,39,109],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw5GEVqPbLY576l46FZDQoNJ2KC","object":"chat.completion.chunk","created":1727346173,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"refusal":" very"},"logprobs":{"content":null,"refusal":[{"token":" very","logprob":-0.8438816,"bytes":[32,118,101,114,121],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw5GEVqPbLY576l46FZDQoNJ2KC","object":"chat.completion.chunk","created":1727346173,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"refusal":" sorry"},"logprobs":{"content":null,"refusal":[{"token":" sorry","logprob":-3.4121115e-6,"bytes":[32,115,111,114,114,121],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw5GEVqPbLY576l46FZDQoNJ2KC","object":"chat.completion.chunk","created":1727346173,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"refusal":","},"logprobs":{"content":null,"refusal":[{"token":",","logprob":-0.000033809047,"bytes":[44],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw5GEVqPbLY576l46FZDQoNJ2KC","object":"chat.completion.chunk","created":1727346173,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"refusal":" but"},"logprobs":{"content":null,"refusal":[{"token":" but","logprob":-0.038048144,"bytes":[32,98,117,116],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw5GEVqPbLY576l46FZDQoNJ2KC","object":"chat.completion.chunk","created":1727346173,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"refusal":" I"},"logprobs":{"content":null,"refusal":[{"token":" I","logprob":-0.0016109125,"bytes":[32,73],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw5GEVqPbLY576l46FZDQoNJ2KC","object":"chat.completion.chunk","created":1727346173,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"refusal":" can't"},"logprobs":{"content":null,"refusal":[{"token":" can't","logprob":-0.0073532974,"bytes":[32,99,97,110,39,116],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw5GEVqPbLY576l46FZDQoNJ2KC","object":"chat.completion.chunk","created":1727346173,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"refusal":" assist"},"logprobs":{"content":null,"refusal":[{"token":" assist","logprob":-0.0020837625,"bytes":[32,97,115,115,105,115,116],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw5GEVqPbLY576l46FZDQoNJ2KC","object":"chat.completion.chunk","created":1727346173,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"refusal":" with"},"logprobs":{"content":null,"refusal":[{"token":" with","logprob":-0.00318354,"bytes":[32,119,105,116,104],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw5GEVqPbLY576l46FZDQoNJ2KC","object":"chat.completion.chunk","created":1727346173,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"refusal":" that"},"logprobs":{"content":null,"refusal":[{"token":" that","logprob":-0.0017186158,"bytes":[32,116,104,97,116],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw5GEVqPbLY576l46FZDQoNJ2KC","object":"chat.completion.chunk","created":1727346173,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"refusal":"."},"logprobs":{"content":null,"refusal":[{"token":".","logprob":-0.57687104,"bytes":[46],"top_logprobs":[]}]},"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw5GEVqPbLY576l46FZDQoNJ2KC","object":"chat.completion.chunk","created":1727346173,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-ABfw5GEVqPbLY576l46FZDQoNJ2KC","object":"chat.completion.chunk","created":1727346173,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[],"usage":{"prompt_tokens":79,"completion_tokens":12,"total_tokens":91,"completion_tokens_details":{"reasoning_tokens":0}}} + +data: [DONE] + diff --git a/.inline-snapshot/external/69363a555f8ea9b6eee0bb022af0afcd22d4f0e85418ab38ee24d2a570a84ff0.bin b/.inline-snapshot/external/69363a555f8ea9b6eee0bb022af0afcd22d4f0e85418ab38ee24d2a570a84ff0.bin deleted file mode 100644 index 852a7758f9..0000000000 --- a/.inline-snapshot/external/69363a555f8ea9b6eee0bb022af0afcd22d4f0e85418ab38ee24d2a570a84ff0.bin +++ /dev/null @@ -1,10 +0,0 @@ -data: {"id":"chatcmpl-9tXjkSxyTVUSWZRJFSZJgWBHzh2c3","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjkSxyTVUSWZRJFSZJgWBHzh2c3","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"{\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjkSxyTVUSWZRJFSZJgWBHzh2c3","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"length"}]} - -data: {"id":"chatcmpl-9tXjkSxyTVUSWZRJFSZJgWBHzh2c3","object":"chat.completion.chunk","created":1723024752,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[],"usage":{"prompt_tokens":17,"completion_tokens":1,"total_tokens":18}} - -data: [DONE] - diff --git a/.inline-snapshot/external/7e5ea4d12e7cc064399b6631415e65923f182256b6e6b752950a3aaa2ad2320a.bin b/.inline-snapshot/external/7e5ea4d12e7cc064399b6631415e65923f182256b6e6b752950a3aaa2ad2320a.bin new file mode 100644 index 0000000000..801db2adf2 --- /dev/null +++ b/.inline-snapshot/external/7e5ea4d12e7cc064399b6631415e65923f182256b6e6b752950a3aaa2ad2320a.bin @@ -0,0 +1,36 @@ +data: {"id":"chatcmpl-ABfw1e5abtU8OwGr15vOreYVb2MiF","object":"chat.completion.chunk","created":1727346169,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw1e5abtU8OwGr15vOreYVb2MiF","object":"chat.completion.chunk","created":1727346169,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"{\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw1e5abtU8OwGr15vOreYVb2MiF","object":"chat.completion.chunk","created":1727346169,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"city"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw1e5abtU8OwGr15vOreYVb2MiF","object":"chat.completion.chunk","created":1727346169,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw1e5abtU8OwGr15vOreYVb2MiF","object":"chat.completion.chunk","created":1727346169,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"San"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw1e5abtU8OwGr15vOreYVb2MiF","object":"chat.completion.chunk","created":1727346169,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw1e5abtU8OwGr15vOreYVb2MiF","object":"chat.completion.chunk","created":1727346169,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\",\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw1e5abtU8OwGr15vOreYVb2MiF","object":"chat.completion.chunk","created":1727346169,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"temperature"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw1e5abtU8OwGr15vOreYVb2MiF","object":"chat.completion.chunk","created":1727346169,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw1e5abtU8OwGr15vOreYVb2MiF","object":"chat.completion.chunk","created":1727346169,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"61"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw1e5abtU8OwGr15vOreYVb2MiF","object":"chat.completion.chunk","created":1727346169,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":",\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw1e5abtU8OwGr15vOreYVb2MiF","object":"chat.completion.chunk","created":1727346169,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"units"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw1e5abtU8OwGr15vOreYVb2MiF","object":"chat.completion.chunk","created":1727346169,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw1e5abtU8OwGr15vOreYVb2MiF","object":"chat.completion.chunk","created":1727346169,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"f"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw1e5abtU8OwGr15vOreYVb2MiF","object":"chat.completion.chunk","created":1727346169,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\"}"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw1e5abtU8OwGr15vOreYVb2MiF","object":"chat.completion.chunk","created":1727346169,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-ABfw1e5abtU8OwGr15vOreYVb2MiF","object":"chat.completion.chunk","created":1727346169,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[],"usage":{"prompt_tokens":79,"completion_tokens":14,"total_tokens":93,"completion_tokens_details":{"reasoning_tokens":0}}} + +data: [DONE] + diff --git a/.inline-snapshot/external/83b060bae42eb41c4f1edbb7c1542b954b37d9dfd1910b964ddebc9677e6ae85.bin b/.inline-snapshot/external/83b060bae42eb41c4f1edbb7c1542b954b37d9dfd1910b964ddebc9677e6ae85.bin new file mode 100644 index 0000000000..e9f34b6334 --- /dev/null +++ b/.inline-snapshot/external/83b060bae42eb41c4f1edbb7c1542b954b37d9dfd1910b964ddebc9677e6ae85.bin @@ -0,0 +1,12 @@ +data: {"id":"chatcmpl-ABfw5EzoqmfXjnnsXY7Yd8OC6tb3c","object":"chat.completion.chunk","created":1727346173,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":{"content":[],"refusal":null},"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw5EzoqmfXjnnsXY7Yd8OC6tb3c","object":"chat.completion.chunk","created":1727346173,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"Foo"},"logprobs":{"content":[{"token":"Foo","logprob":-0.0025094282,"bytes":[70,111,111],"top_logprobs":[]}],"refusal":null},"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw5EzoqmfXjnnsXY7Yd8OC6tb3c","object":"chat.completion.chunk","created":1727346173,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"!"},"logprobs":{"content":[{"token":"!","logprob":-0.26638845,"bytes":[33],"top_logprobs":[]}],"refusal":null},"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw5EzoqmfXjnnsXY7Yd8OC6tb3c","object":"chat.completion.chunk","created":1727346173,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-ABfw5EzoqmfXjnnsXY7Yd8OC6tb3c","object":"chat.completion.chunk","created":1727346173,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[],"usage":{"prompt_tokens":9,"completion_tokens":2,"total_tokens":11,"completion_tokens_details":{"reasoning_tokens":0}}} + +data: [DONE] + diff --git a/.inline-snapshot/external/83d3d003e6fdaa69b7a398440f9d46ee41408a688758219f3f58ac1ee2084db3.bin b/.inline-snapshot/external/83d3d003e6fdaa69b7a398440f9d46ee41408a688758219f3f58ac1ee2084db3.bin deleted file mode 100644 index 05e08e3475..0000000000 --- a/.inline-snapshot/external/83d3d003e6fdaa69b7a398440f9d46ee41408a688758219f3f58ac1ee2084db3.bin +++ /dev/null @@ -1,28 +0,0 @@ -data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[{"index":0,"delta":{"role":"assistant","content":null,"tool_calls":[{"index":0,"id":"call_pVHYsU0gmSfX5TqxOyVbB2ma","type":"function","function":{"name":"get_weather","arguments":""}}],"refusal":null},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"city"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"San"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":" Francisco"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\",\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"state"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"CA"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"}"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"tool_calls"}]} - -data: {"id":"chatcmpl-9tXjq87CydgLGv4TnzV0EVDybqjCA","object":"chat.completion.chunk","created":1723024758,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_baa7103b2c","choices":[],"usage":{"prompt_tokens":48,"completion_tokens":19,"total_tokens":67}} - -data: [DONE] - diff --git a/.inline-snapshot/external/a0c4f0be184e8234cdc0e3abae5dfafc1d712c253b42bafe07991b3058541016.bin b/.inline-snapshot/external/a0c4f0be184e8234cdc0e3abae5dfafc1d712c253b42bafe07991b3058541016.bin deleted file mode 100644 index df20d6fda5..0000000000 --- a/.inline-snapshot/external/a0c4f0be184e8234cdc0e3abae5dfafc1d712c253b42bafe07991b3058541016.bin +++ /dev/null @@ -1,156 +0,0 @@ -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":"{\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"{\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":"city"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"city"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"role":"assistant","content":null,"refusal":""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":"I'm"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" sorry"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":"San"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"San"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":","},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" but"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":"\",\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"\",\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" I"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" can't"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":"temperature"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"temperature"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" accurately"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" provide"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":"63"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":",\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"58"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"."},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" the"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":"units"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"6"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" current"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":",\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" weather"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":"f"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"units"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" for"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{"content":"\"}"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" San"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"f"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" Francisco"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{"content":"\"}"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" as"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" my"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" data"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" is"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" up"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" to"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" October"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" "},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":"202"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":"3"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":"."},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" You"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" can"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" try"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" checking"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" a"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" reliable"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" weather"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" website"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" or"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" app"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" for"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" real"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":"-time"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":" updates"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{"refusal":"."},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":1,"delta":{},"logprobs":null,"finish_reason":"stop"}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[{"index":2,"delta":{},"logprobs":null,"finish_reason":"stop"}]} - -data: {"id":"chatcmpl-9tXjjpr5ZWilqbUE2tn3H1lwvMnDu","object":"chat.completion.chunk","created":1723024751,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_2a322c9ffc","choices":[],"usage":{"prompt_tokens":17,"completion_tokens":71,"total_tokens":88}} - -data: [DONE] - diff --git a/.inline-snapshot/external/a247c49c5fcd492bfb7a02a3306ad615ed8d8f649888ebfddfbc3ee151f44d46.bin b/.inline-snapshot/external/a247c49c5fcd492bfb7a02a3306ad615ed8d8f649888ebfddfbc3ee151f44d46.bin new file mode 100644 index 0000000000..b44d334ac5 --- /dev/null +++ b/.inline-snapshot/external/a247c49c5fcd492bfb7a02a3306ad615ed8d8f649888ebfddfbc3ee151f44d46.bin @@ -0,0 +1,28 @@ +data: {"id":"chatcmpl-ABfwCgi41eStOcARjZq97ohCEGBPO","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"role":"assistant","content":null,"tool_calls":[{"index":0,"id":"call_CTf1nWJLqSeRgDqaCG27xZ74","type":"function","function":{"name":"get_weather","arguments":""}}],"refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCgi41eStOcARjZq97ohCEGBPO","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCgi41eStOcARjZq97ohCEGBPO","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"city"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCgi41eStOcARjZq97ohCEGBPO","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCgi41eStOcARjZq97ohCEGBPO","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"San"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCgi41eStOcARjZq97ohCEGBPO","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":" Francisco"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCgi41eStOcARjZq97ohCEGBPO","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\",\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCgi41eStOcARjZq97ohCEGBPO","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"state"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCgi41eStOcARjZq97ohCEGBPO","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCgi41eStOcARjZq97ohCEGBPO","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"CA"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCgi41eStOcARjZq97ohCEGBPO","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"}"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCgi41eStOcARjZq97ohCEGBPO","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"tool_calls"}]} + +data: {"id":"chatcmpl-ABfwCgi41eStOcARjZq97ohCEGBPO","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[],"usage":{"prompt_tokens":48,"completion_tokens":19,"total_tokens":67,"completion_tokens_details":{"reasoning_tokens":0}}} + +data: [DONE] + diff --git a/.inline-snapshot/external/a491adda08c3d4fde95f5b2ee3f60f7f745f1a56d82e62f58031cc2add502380.bin b/.inline-snapshot/external/a491adda08c3d4fde95f5b2ee3f60f7f745f1a56d82e62f58031cc2add502380.bin new file mode 100644 index 0000000000..160e65de49 --- /dev/null +++ b/.inline-snapshot/external/a491adda08c3d4fde95f5b2ee3f60f7f745f1a56d82e62f58031cc2add502380.bin @@ -0,0 +1,100 @@ +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"content":"{\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":1,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":1,"delta":{"content":"{\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":2,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":2,"delta":{"content":"{\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"content":"city"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":1,"delta":{"content":"city"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":2,"delta":{"content":"city"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":1,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":2,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"content":"San"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":1,"delta":{"content":"San"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":2,"delta":{"content":"San"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":1,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":2,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"content":"\",\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":1,"delta":{"content":"\",\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":2,"delta":{"content":"\",\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"content":"temperature"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":1,"delta":{"content":"temperature"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":1,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":2,"delta":{"content":"temperature"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":2,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"content":"65"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"content":",\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":1,"delta":{"content":"61"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":1,"delta":{"content":",\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":2,"delta":{"content":"59"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":2,"delta":{"content":",\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"content":"units"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":1,"delta":{"content":"units"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":2,"delta":{"content":"units"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":1,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":2,"delta":{"content":"\":\""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"content":"f"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":1,"delta":{"content":"f"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":2,"delta":{"content":"f"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{"content":"\"}"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":1,"delta":{"content":"\"}"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":2,"delta":{"content":"\"}"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":1,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[{"index":2,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-ABfw2KKFuVXmEJgVwYfBvejMAdWtq","object":"chat.completion.chunk","created":1727346170,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_b40fb1c6fb","choices":[],"usage":{"prompt_tokens":79,"completion_tokens":42,"total_tokens":121,"completion_tokens_details":{"reasoning_tokens":0}}} + +data: [DONE] + diff --git a/.inline-snapshot/external/be1089999ca5f1e63b149447f1613bdb9c4a2ad8262027d158cc94e6f9765164.bin b/.inline-snapshot/external/be1089999ca5f1e63b149447f1613bdb9c4a2ad8262027d158cc94e6f9765164.bin deleted file mode 100644 index f2a8158310..0000000000 --- a/.inline-snapshot/external/be1089999ca5f1e63b149447f1613bdb9c4a2ad8262027d158cc94e6f9765164.bin +++ /dev/null @@ -1,12 +0,0 @@ -data: {"id":"chatcmpl-9tXjliCPGY1wrAHNJ4DBnWJxKYyuf","object":"chat.completion.chunk","created":1723024753,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":{"content":[],"refusal":null},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjliCPGY1wrAHNJ4DBnWJxKYyuf","object":"chat.completion.chunk","created":1723024753,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"Foo"},"logprobs":{"content":[{"token":"Foo","logprob":-0.0067602484,"bytes":[70,111,111],"top_logprobs":[]}],"refusal":null},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjliCPGY1wrAHNJ4DBnWJxKYyuf","object":"chat.completion.chunk","created":1723024753,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"content":"."},"logprobs":{"content":[{"token":".","logprob":-2.4962392,"bytes":[46],"top_logprobs":[]}],"refusal":null},"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjliCPGY1wrAHNJ4DBnWJxKYyuf","object":"chat.completion.chunk","created":1723024753,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} - -data: {"id":"chatcmpl-9tXjliCPGY1wrAHNJ4DBnWJxKYyuf","object":"chat.completion.chunk","created":1723024753,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[],"usage":{"prompt_tokens":9,"completion_tokens":2,"total_tokens":11}} - -data: [DONE] - diff --git a/.inline-snapshot/external/c6aa7e397b7123c3501f25df3a05d4daf7e8ad6d61ffa406ab5361fe36a8d5b1.bin b/.inline-snapshot/external/c6aa7e397b7123c3501f25df3a05d4daf7e8ad6d61ffa406ab5361fe36a8d5b1.bin new file mode 100644 index 0000000000..f20333fbef --- /dev/null +++ b/.inline-snapshot/external/c6aa7e397b7123c3501f25df3a05d4daf7e8ad6d61ffa406ab5361fe36a8d5b1.bin @@ -0,0 +1,36 @@ +data: {"id":"chatcmpl-ABfw8AOXnoa2kzy11vVTSjuQhHCQr","object":"chat.completion.chunk","created":1727346176,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_7568d46099","choices":[{"index":0,"delta":{"role":"assistant","content":null,"tool_calls":[{"index":0,"id":"call_c91SqDXlYFuETYv8mUHzz6pp","type":"function","function":{"name":"GetWeatherArgs","arguments":""}}],"refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw8AOXnoa2kzy11vVTSjuQhHCQr","object":"chat.completion.chunk","created":1727346176,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_7568d46099","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw8AOXnoa2kzy11vVTSjuQhHCQr","object":"chat.completion.chunk","created":1727346176,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_7568d46099","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"city"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw8AOXnoa2kzy11vVTSjuQhHCQr","object":"chat.completion.chunk","created":1727346176,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_7568d46099","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw8AOXnoa2kzy11vVTSjuQhHCQr","object":"chat.completion.chunk","created":1727346176,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_7568d46099","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"Ed"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw8AOXnoa2kzy11vVTSjuQhHCQr","object":"chat.completion.chunk","created":1727346176,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_7568d46099","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"inburgh"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw8AOXnoa2kzy11vVTSjuQhHCQr","object":"chat.completion.chunk","created":1727346176,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_7568d46099","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\",\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw8AOXnoa2kzy11vVTSjuQhHCQr","object":"chat.completion.chunk","created":1727346176,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_7568d46099","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"country"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw8AOXnoa2kzy11vVTSjuQhHCQr","object":"chat.completion.chunk","created":1727346176,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_7568d46099","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw8AOXnoa2kzy11vVTSjuQhHCQr","object":"chat.completion.chunk","created":1727346176,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_7568d46099","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"UK"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw8AOXnoa2kzy11vVTSjuQhHCQr","object":"chat.completion.chunk","created":1727346176,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_7568d46099","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\",\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw8AOXnoa2kzy11vVTSjuQhHCQr","object":"chat.completion.chunk","created":1727346176,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_7568d46099","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"units"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw8AOXnoa2kzy11vVTSjuQhHCQr","object":"chat.completion.chunk","created":1727346176,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_7568d46099","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw8AOXnoa2kzy11vVTSjuQhHCQr","object":"chat.completion.chunk","created":1727346176,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_7568d46099","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"c"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw8AOXnoa2kzy11vVTSjuQhHCQr","object":"chat.completion.chunk","created":1727346176,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_7568d46099","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"}"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw8AOXnoa2kzy11vVTSjuQhHCQr","object":"chat.completion.chunk","created":1727346176,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_7568d46099","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"tool_calls"}]} + +data: {"id":"chatcmpl-ABfw8AOXnoa2kzy11vVTSjuQhHCQr","object":"chat.completion.chunk","created":1727346176,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_7568d46099","choices":[],"usage":{"prompt_tokens":76,"completion_tokens":24,"total_tokens":100,"completion_tokens_details":{"reasoning_tokens":0}}} + +data: [DONE] + diff --git a/.inline-snapshot/external/ca015b8b1ebaac98be76f2f855f8694b77f608de5e2a3799276be06ce3fbb15b.bin b/.inline-snapshot/external/ca015b8b1ebaac98be76f2f855f8694b77f608de5e2a3799276be06ce3fbb15b.bin deleted file mode 100644 index c0a355f9d1..0000000000 --- a/.inline-snapshot/external/ca015b8b1ebaac98be76f2f855f8694b77f608de5e2a3799276be06ce3fbb15b.bin +++ /dev/null @@ -1,30 +0,0 @@ -data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"role":"assistant","content":null,"refusal":""},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":"I'm"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" sorry"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":","},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" but"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" I"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" can't"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" assist"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" with"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" that"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":" request"},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"refusal":"."},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} - -data: {"id":"chatcmpl-9tXmMGFPkLS0t0u0895fzYOblnfYa","object":"chat.completion.chunk","created":1723024914,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[],"usage":{"prompt_tokens":17,"completion_tokens":12,"total_tokens":29}} - -data: [DONE] - diff --git a/.inline-snapshot/external/d615580118391ee13492193e3a8bb74642d23ac1ca13fe37cb6e889b66f759f6.bin b/.inline-snapshot/external/d615580118391ee13492193e3a8bb74642d23ac1ca13fe37cb6e889b66f759f6.bin new file mode 100644 index 0000000000..aee8650c72 --- /dev/null +++ b/.inline-snapshot/external/d615580118391ee13492193e3a8bb74642d23ac1ca13fe37cb6e889b66f759f6.bin @@ -0,0 +1,362 @@ +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" {\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"location"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"San"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":","},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" CA"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"weather"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" {\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"temperature"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"18"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"°C"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"condition"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"Part"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"ly"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" Cloud"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"y"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"humidity"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"72"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"%\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"wind"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"Speed"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"15"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" km"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"/h"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"wind"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"Direction"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"NW"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\"\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" },\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"forecast"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" [\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" {\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"day"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"Monday"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"high"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"20"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"°C"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"low"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"14"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"°C"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"condition"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"Sunny"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\"\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" },\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" {\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"day"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"Tuesday"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"high"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"19"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"°C"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"low"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"15"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"°C"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"condition"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"Mostly"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" Cloud"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"y"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\"\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" },\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" {\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"day"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"Wednesday"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"high"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"18"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"°C"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"low"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"14"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"°C"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\",\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"condition"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\":"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" \""},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"Cloud"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"y"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"\"\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" }\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" ]\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" "},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" }\n"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-ABfwCjPMi0ubw56UyMIIeNfJzyogq","object":"chat.completion.chunk","created":1727346180,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[],"usage":{"prompt_tokens":19,"completion_tokens":177,"total_tokens":196,"completion_tokens_details":{"reasoning_tokens":0}}} + +data: [DONE] + diff --git a/.inline-snapshot/external/dae1b261f19722801adc82a13181772c3010c10b37e8af3996fbdbbecb3c32a2.bin b/.inline-snapshot/external/dae1b261f19722801adc82a13181772c3010c10b37e8af3996fbdbbecb3c32a2.bin deleted file mode 100644 index f0911c575d..0000000000 --- a/.inline-snapshot/external/dae1b261f19722801adc82a13181772c3010c10b37e8af3996fbdbbecb3c32a2.bin +++ /dev/null @@ -1,22 +0,0 @@ -data: {"id":"chatcmpl-9tXjtfxZZh2FYaFVxXKf2jiqNDiSo","object":"chat.completion.chunk","created":1723024761,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"role":"assistant","content":null,"tool_calls":[{"index":0,"id":"call_5uxEBMFySqqQGu02I5QHA8k6","type":"function","function":{"name":"get_weather","arguments":""}}],"refusal":null},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjtfxZZh2FYaFVxXKf2jiqNDiSo","object":"chat.completion.chunk","created":1723024761,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjtfxZZh2FYaFVxXKf2jiqNDiSo","object":"chat.completion.chunk","created":1723024761,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"city"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjtfxZZh2FYaFVxXKf2jiqNDiSo","object":"chat.completion.chunk","created":1723024761,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\":\""}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjtfxZZh2FYaFVxXKf2jiqNDiSo","object":"chat.completion.chunk","created":1723024761,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"New"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjtfxZZh2FYaFVxXKf2jiqNDiSo","object":"chat.completion.chunk","created":1723024761,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":" York"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjtfxZZh2FYaFVxXKf2jiqNDiSo","object":"chat.completion.chunk","created":1723024761,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":" City"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjtfxZZh2FYaFVxXKf2jiqNDiSo","object":"chat.completion.chunk","created":1723024761,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"}"}}]},"logprobs":null,"finish_reason":null}]} - -data: {"id":"chatcmpl-9tXjtfxZZh2FYaFVxXKf2jiqNDiSo","object":"chat.completion.chunk","created":1723024761,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"tool_calls"}]} - -data: {"id":"chatcmpl-9tXjtfxZZh2FYaFVxXKf2jiqNDiSo","object":"chat.completion.chunk","created":1723024761,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_845eaabc1f","choices":[],"usage":{"prompt_tokens":44,"completion_tokens":16,"total_tokens":60}} - -data: [DONE] - diff --git a/.inline-snapshot/external/e2aad469b71d1d4894ff833ea147020a9d875eb7ce644a0ff355581690a4cbfd.bin b/.inline-snapshot/external/e2aad469b71d1d4894ff833ea147020a9d875eb7ce644a0ff355581690a4cbfd.bin new file mode 100644 index 0000000000..b68ca8a3d9 --- /dev/null +++ b/.inline-snapshot/external/e2aad469b71d1d4894ff833ea147020a9d875eb7ce644a0ff355581690a4cbfd.bin @@ -0,0 +1,68 @@ +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"I'm"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" unable"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" to"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" provide"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" real"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"-time"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" updates"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" To"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" get"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" the"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" current"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" in"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" San"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" Francisco"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":","},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" I"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" recommend"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" checking"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" a"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" reliable"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" website"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" or"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" a"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" weather"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":" app"},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + +data: {"id":"chatcmpl-ABfw031mOJeYCSHe4yI2ZjOA6kMJL","object":"chat.completion.chunk","created":1727346168,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":30,"total_tokens":44,"completion_tokens_details":{"reasoning_tokens":0}}} + +data: [DONE] + diff --git a/.inline-snapshot/external/f82268f2fefd5cfbc7eeb59c297688be2f6ca0849a6e4f17851b517310841d9b.bin b/.inline-snapshot/external/f82268f2fefd5cfbc7eeb59c297688be2f6ca0849a6e4f17851b517310841d9b.bin new file mode 100644 index 0000000000..3b111d5e61 --- /dev/null +++ b/.inline-snapshot/external/f82268f2fefd5cfbc7eeb59c297688be2f6ca0849a6e4f17851b517310841d9b.bin @@ -0,0 +1,52 @@ +data: {"id":"chatcmpl-ABfwAwrNePHUgBBezonVC6MX3zd63","object":"chat.completion.chunk","created":1727346178,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"role":"assistant","content":null},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwAwrNePHUgBBezonVC6MX3zd63","object":"chat.completion.chunk","created":1727346178,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_JMW1whyEaYG438VE1OIflxA2","type":"function","function":{"name":"GetWeatherArgs","arguments":""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwAwrNePHUgBBezonVC6MX3zd63","object":"chat.completion.chunk","created":1727346178,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"ci"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwAwrNePHUgBBezonVC6MX3zd63","object":"chat.completion.chunk","created":1727346178,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"ty\": "}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwAwrNePHUgBBezonVC6MX3zd63","object":"chat.completion.chunk","created":1727346178,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"Edinb"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwAwrNePHUgBBezonVC6MX3zd63","object":"chat.completion.chunk","created":1727346178,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"urgh"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwAwrNePHUgBBezonVC6MX3zd63","object":"chat.completion.chunk","created":1727346178,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\", \"c"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwAwrNePHUgBBezonVC6MX3zd63","object":"chat.completion.chunk","created":1727346178,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"ountry"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwAwrNePHUgBBezonVC6MX3zd63","object":"chat.completion.chunk","created":1727346178,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\": \""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwAwrNePHUgBBezonVC6MX3zd63","object":"chat.completion.chunk","created":1727346178,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"GB\", "}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwAwrNePHUgBBezonVC6MX3zd63","object":"chat.completion.chunk","created":1727346178,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"units"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwAwrNePHUgBBezonVC6MX3zd63","object":"chat.completion.chunk","created":1727346178,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\": \""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwAwrNePHUgBBezonVC6MX3zd63","object":"chat.completion.chunk","created":1727346178,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"c\"}"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwAwrNePHUgBBezonVC6MX3zd63","object":"chat.completion.chunk","created":1727346178,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"id":"call_DNYTawLBoN8fj3KN6qU9N1Ou","type":"function","function":{"name":"get_stock_price","arguments":""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwAwrNePHUgBBezonVC6MX3zd63","object":"chat.completion.chunk","created":1727346178,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"{\"ti"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwAwrNePHUgBBezonVC6MX3zd63","object":"chat.completion.chunk","created":1727346178,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"cker\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwAwrNePHUgBBezonVC6MX3zd63","object":"chat.completion.chunk","created":1727346178,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":": \"AAP"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwAwrNePHUgBBezonVC6MX3zd63","object":"chat.completion.chunk","created":1727346178,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"L\", "}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwAwrNePHUgBBezonVC6MX3zd63","object":"chat.completion.chunk","created":1727346178,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"\"exch"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwAwrNePHUgBBezonVC6MX3zd63","object":"chat.completion.chunk","created":1727346178,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"ange\":"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwAwrNePHUgBBezonVC6MX3zd63","object":"chat.completion.chunk","created":1727346178,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":" \"NA"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwAwrNePHUgBBezonVC6MX3zd63","object":"chat.completion.chunk","created":1727346178,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"SDAQ\""}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwAwrNePHUgBBezonVC6MX3zd63","object":"chat.completion.chunk","created":1727346178,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"}"}}]},"logprobs":null,"finish_reason":null}]} + +data: {"id":"chatcmpl-ABfwAwrNePHUgBBezonVC6MX3zd63","object":"chat.completion.chunk","created":1727346178,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"tool_calls"}]} + +data: {"id":"chatcmpl-ABfwAwrNePHUgBBezonVC6MX3zd63","object":"chat.completion.chunk","created":1727346178,"model":"gpt-4o-2024-08-06","system_fingerprint":"fp_5050236cbd","choices":[],"usage":{"prompt_tokens":149,"completion_tokens":60,"total_tokens":209,"completion_tokens_details":{"reasoning_tokens":0}}} + +data: [DONE] + diff --git a/tests/lib/chat/test_completions.py b/tests/lib/chat/test_completions.py index e7b9c4f1fd..d66630fa3a 100644 --- a/tests/lib/chat/test_completions.py +++ b/tests/lib/chat/test_completions.py @@ -43,7 +43,7 @@ def test_parse_nothing(client: OpenAI, respx_mock: MockRouter, monkeypatch: pyte ], ), content_snapshot=snapshot( - '{"id": "chatcmpl-9tXjSozlYq8oGdlRH3vgLsiUNRg8c", "object": "chat.completion", "created": 1723024734, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "I\'m unable to provide real-time weather updates. To find out the current weather in San Francisco, please check a reliable weather website or app.", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 14, "completion_tokens": 28, "total_tokens": 42}, "system_fingerprint": "fp_845eaabc1f"}' + '{"id": "chatcmpl-ABfvaueLEMLNYbT8YzpJxsmiQ6HSY", "object": "chat.completion", "created": 1727346142, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "I\'m unable to provide real-time weather updates. To get the current weather in San Francisco, I recommend checking a reliable weather website or app like the Weather Channel or a local news station.", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 14, "completion_tokens": 37, "total_tokens": 51, "completion_tokens_details": {"reasoning_tokens": 0}}, "system_fingerprint": "fp_b40fb1c6fb"}' ), mock_client=client, respx_mock=respx_mock, @@ -58,8 +58,8 @@ def test_parse_nothing(client: OpenAI, respx_mock: MockRouter, monkeypatch: pyte index=0, logprobs=None, message=ParsedChatCompletionMessage[NoneType]( - content="I'm unable to provide real-time weather updates. To find out the current weather in San -Francisco, please check a reliable weather website or app.", + content="I'm unable to provide real-time weather updates. To get the current weather in San Francisco, I +recommend checking a reliable weather website or app like the Weather Channel or a local news station.", function_call=None, parsed=None, refusal=None, @@ -68,13 +68,18 @@ def test_parse_nothing(client: OpenAI, respx_mock: MockRouter, monkeypatch: pyte ) ) ], - created=1723024734, - id='chatcmpl-9tXjSozlYq8oGdlRH3vgLsiUNRg8c', + created=1727346142, + id='chatcmpl-ABfvaueLEMLNYbT8YzpJxsmiQ6HSY', model='gpt-4o-2024-08-06', object='chat.completion', service_tier=None, - system_fingerprint='fp_845eaabc1f', - usage=CompletionUsage(completion_tokens=28, completion_tokens_details=None, prompt_tokens=14, total_tokens=42) + system_fingerprint='fp_b40fb1c6fb', + usage=CompletionUsage( + completion_tokens=37, + completion_tokens_details=CompletionTokensDetails(reasoning_tokens=0), + prompt_tokens=14, + total_tokens=51 + ) ) """ ) @@ -99,7 +104,7 @@ class Location(BaseModel): response_format=Location, ), content_snapshot=snapshot( - '{"id": "chatcmpl-9tXjTNupyDe7nL1Z8eOO6BdSyrHAD", "object": "chat.completion", "created": 1723024735, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"city\\":\\"San Francisco\\",\\"temperature\\":56,\\"units\\":\\"f\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 17, "completion_tokens": 14, "total_tokens": 31}, "system_fingerprint": "fp_2a322c9ffc"}' + '{"id": "chatcmpl-ABfvbtVnTu5DeC4EFnRYj8mtfOM99", "object": "chat.completion", "created": 1727346143, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"city\\":\\"San Francisco\\",\\"temperature\\":65,\\"units\\":\\"f\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 79, "completion_tokens": 14, "total_tokens": 93, "completion_tokens_details": {"reasoning_tokens": 0}}, "system_fingerprint": "fp_5050236cbd"}' ), mock_client=client, respx_mock=respx_mock, @@ -114,22 +119,27 @@ class Location(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( - content='{"city":"San Francisco","temperature":56,"units":"f"}', + content='{"city":"San Francisco","temperature":65,"units":"f"}', function_call=None, - parsed=Location(city='San Francisco', temperature=56.0, units='f'), + parsed=Location(city='San Francisco', temperature=65.0, units='f'), refusal=None, role='assistant', tool_calls=[] ) ) ], - created=1723024735, - id='chatcmpl-9tXjTNupyDe7nL1Z8eOO6BdSyrHAD', + created=1727346143, + id='chatcmpl-ABfvbtVnTu5DeC4EFnRYj8mtfOM99', model='gpt-4o-2024-08-06', object='chat.completion', service_tier=None, - system_fingerprint='fp_2a322c9ffc', - usage=CompletionUsage(completion_tokens=14, completion_tokens_details=None, prompt_tokens=17, total_tokens=31) + system_fingerprint='fp_5050236cbd', + usage=CompletionUsage( + completion_tokens=14, + completion_tokens_details=CompletionTokensDetails(reasoning_tokens=0), + prompt_tokens=79, + total_tokens=93 + ) ) """ ) @@ -156,7 +166,7 @@ class Location(BaseModel): response_format=Location, ), content_snapshot=snapshot( - '{"id": "chatcmpl-9y39Q2jGzWmeEZlm5CoNVOuQzcxP4", "object": "chat.completion", "created": 1724098820, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"city\\":\\"San Francisco\\",\\"temperature\\":62,\\"units\\":\\"f\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 17, "completion_tokens": 14, "total_tokens": 31}, "system_fingerprint": "fp_2a322c9ffc"}' + '{"id": "chatcmpl-ABfvcC8grKYsRkSoMp9CCAhbXAd0b", "object": "chat.completion", "created": 1727346144, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"city\\":\\"San Francisco\\",\\"temperature\\":65,\\"units\\":\\"f\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 88, "completion_tokens": 14, "total_tokens": 102, "completion_tokens_details": {"reasoning_tokens": 0}}, "system_fingerprint": "fp_b40fb1c6fb"}' ), mock_client=client, respx_mock=respx_mock, @@ -171,22 +181,27 @@ class Location(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( - content='{"city":"San Francisco","temperature":62,"units":"f"}', + content='{"city":"San Francisco","temperature":65,"units":"f"}', function_call=None, - parsed=Location(city='San Francisco', temperature=62.0, units='f'), + parsed=Location(city='San Francisco', temperature=65.0, units='f'), refusal=None, role='assistant', tool_calls=[] ) ) ], - created=1724098820, - id='chatcmpl-9y39Q2jGzWmeEZlm5CoNVOuQzcxP4', + created=1727346144, + id='chatcmpl-ABfvcC8grKYsRkSoMp9CCAhbXAd0b', model='gpt-4o-2024-08-06', object='chat.completion', service_tier=None, - system_fingerprint='fp_2a322c9ffc', - usage=CompletionUsage(completion_tokens=14, completion_tokens_details=None, prompt_tokens=17, total_tokens=31) + system_fingerprint='fp_b40fb1c6fb', + usage=CompletionUsage( + completion_tokens=14, + completion_tokens_details=CompletionTokensDetails(reasoning_tokens=0), + prompt_tokens=88, + total_tokens=102 + ) ) """ ) @@ -217,7 +232,7 @@ class ColorDetection(BaseModel): response_format=ColorDetection, ), content_snapshot=snapshot( - '{"id": "chatcmpl-9vK4UZVr385F2UgZlP1ShwPn2nFxG", "object": "chat.completion", "created": 1723448878, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"color\\":\\"red\\",\\"hex_color_code\\":\\"#FF0000\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 18, "completion_tokens": 14, "total_tokens": 32}, "system_fingerprint": "fp_845eaabc1f"}' + '{"id": "chatcmpl-ABfvjIatz0zrZu50gRbMtlp0asZpz", "object": "chat.completion", "created": 1727346151, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"color\\":\\"red\\",\\"hex_color_code\\":\\"#FF0000\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 109, "completion_tokens": 14, "total_tokens": 123, "completion_tokens_details": {"reasoning_tokens": 0}}, "system_fingerprint": "fp_5050236cbd"}' ), mock_client=client, respx_mock=respx_mock, @@ -264,7 +279,7 @@ class Location(BaseModel): response_format=Location, ), content_snapshot=snapshot( - '{"id": "chatcmpl-9tXjUrNFyyjSB2FJ842TMDNRM6Gen", "object": "chat.completion", "created": 1723024736, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"city\\":\\"San Francisco\\",\\"temperature\\":58,\\"units\\":\\"f\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}, {"index": 1, "message": {"role": "assistant", "content": "{\\"city\\":\\"San Francisco\\",\\"temperature\\":58,\\"units\\":\\"f\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}, {"index": 2, "message": {"role": "assistant", "content": "{\\"city\\":\\"San Francisco\\",\\"temperature\\":63,\\"units\\":\\"f\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 17, "completion_tokens": 42, "total_tokens": 59}, "system_fingerprint": "fp_845eaabc1f"}' + '{"id": "chatcmpl-ABfvp8qzboW92q8ONDF4DPHlI7ckC", "object": "chat.completion", "created": 1727346157, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"city\\":\\"San Francisco\\",\\"temperature\\":64,\\"units\\":\\"f\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}, {"index": 1, "message": {"role": "assistant", "content": "{\\"city\\":\\"San Francisco\\",\\"temperature\\":65,\\"units\\":\\"f\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}, {"index": 2, "message": {"role": "assistant", "content": "{\\"city\\":\\"San Francisco\\",\\"temperature\\":63.0,\\"units\\":\\"f\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 79, "completion_tokens": 44, "total_tokens": 123, "completion_tokens_details": {"reasoning_tokens": 0}}, "system_fingerprint": "fp_b40fb1c6fb"}' ), mock_client=client, respx_mock=respx_mock, @@ -278,9 +293,9 @@ class Location(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( - content='{"city":"San Francisco","temperature":58,"units":"f"}', + content='{"city":"San Francisco","temperature":64,"units":"f"}', function_call=None, - parsed=Location(city='San Francisco', temperature=58.0, units='f'), + parsed=Location(city='San Francisco', temperature=64.0, units='f'), refusal=None, role='assistant', tool_calls=[] @@ -291,9 +306,9 @@ class Location(BaseModel): index=1, logprobs=None, message=ParsedChatCompletionMessage[Location]( - content='{"city":"San Francisco","temperature":58,"units":"f"}', + content='{"city":"San Francisco","temperature":65,"units":"f"}', function_call=None, - parsed=Location(city='San Francisco', temperature=58.0, units='f'), + parsed=Location(city='San Francisco', temperature=65.0, units='f'), refusal=None, role='assistant', tool_calls=[] @@ -304,7 +319,7 @@ class Location(BaseModel): index=2, logprobs=None, message=ParsedChatCompletionMessage[Location]( - content='{"city":"San Francisco","temperature":63,"units":"f"}', + content='{"city":"San Francisco","temperature":63.0,"units":"f"}', function_call=None, parsed=Location(city='San Francisco', temperature=63.0, units='f'), refusal=None, @@ -338,7 +353,7 @@ class CalendarEvent: response_format=CalendarEvent, ), content_snapshot=snapshot( - '{"id": "chatcmpl-9wdGqXkJJARAz7rOrLH5u5FBwLjF3", "object": "chat.completion", "created": 1723761008, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"name\\":\\"Science Fair\\",\\"date\\":\\"Friday\\",\\"participants\\":[\\"Alice\\",\\"Bob\\"]}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 32, "completion_tokens": 17, "total_tokens": 49}, "system_fingerprint": "fp_2a322c9ffc"}' + '{"id": "chatcmpl-ABfvqhz4uUUWsw8Ohw2Mp9B4sKKV8", "object": "chat.completion", "created": 1727346158, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"name\\":\\"Science Fair\\",\\"date\\":\\"Friday\\",\\"participants\\":[\\"Alice\\",\\"Bob\\"]}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 92, "completion_tokens": 17, "total_tokens": 109, "completion_tokens_details": {"reasoning_tokens": 0}}, "system_fingerprint": "fp_7568d46099"}' ), mock_client=client, respx_mock=respx_mock, @@ -362,13 +377,18 @@ class CalendarEvent: ) ) ], - created=1723761008, - id='chatcmpl-9wdGqXkJJARAz7rOrLH5u5FBwLjF3', + created=1727346158, + id='chatcmpl-ABfvqhz4uUUWsw8Ohw2Mp9B4sKKV8', model='gpt-4o-2024-08-06', object='chat.completion', service_tier=None, - system_fingerprint='fp_2a322c9ffc', - usage=CompletionUsage(completion_tokens=17, completion_tokens_details=None, prompt_tokens=32, total_tokens=49) + system_fingerprint='fp_7568d46099', + usage=CompletionUsage( + completion_tokens=17, + completion_tokens_details=CompletionTokensDetails(reasoning_tokens=0), + prompt_tokens=92, + total_tokens=109 + ) ) """ ) @@ -389,7 +409,7 @@ def test_pydantic_tool_model_all_types(client: OpenAI, respx_mock: MockRouter, m response_format=Query, ), content_snapshot=snapshot( - '{"id": "chatcmpl-9tXjVJVCLTn7CWFhpjETixvvApCk3", "object": "chat.completion", "created": 1723024737, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "tool_calls": [{"id": "call_Un4g0IXeQGOyqKBS3zhqNCox", "type": "function", "function": {"name": "Query", "arguments": "{\\"table_name\\":\\"orders\\",\\"columns\\":[\\"id\\",\\"status\\",\\"expected_delivery_date\\",\\"delivered_at\\",\\"shipped_at\\",\\"ordered_at\\"],\\"conditions\\":[{\\"column\\":\\"ordered_at\\",\\"operator\\":\\">=\\",\\"value\\":\\"2022-05-01\\"},{\\"column\\":\\"ordered_at\\",\\"operator\\":\\"<=\\",\\"value\\":\\"2022-05-31\\"},{\\"column\\":\\"status\\",\\"operator\\":\\"=\\",\\"value\\":\\"fulfilled\\"},{\\"column\\":\\"delivered_at\\",\\"operator\\":\\">\\",\\"value\\":{\\"column_name\\":\\"expected_delivery_date\\"}}],\\"order_by\\":\\"asc\\"}"}}], "refusal": null}, "logprobs": null, "finish_reason": "tool_calls"}], "usage": {"prompt_tokens": 195, "completion_tokens": 114, "total_tokens": 309}, "system_fingerprint": "fp_845eaabc1f"}' + '{"id": "chatcmpl-ABfvtNiaTNUF6OymZUnEFc9lPq9p1", "object": "chat.completion", "created": 1727346161, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "tool_calls": [{"id": "call_NKpApJybW1MzOjZO2FzwYw0d", "type": "function", "function": {"name": "Query", "arguments": "{\\"name\\":\\"May 2022 Fulfilled Orders Not Delivered on Time\\",\\"table_name\\":\\"orders\\",\\"columns\\":[\\"id\\",\\"status\\",\\"expected_delivery_date\\",\\"delivered_at\\",\\"shipped_at\\",\\"ordered_at\\",\\"canceled_at\\"],\\"conditions\\":[{\\"column\\":\\"ordered_at\\",\\"operator\\":\\">=\\",\\"value\\":\\"2022-05-01\\"},{\\"column\\":\\"ordered_at\\",\\"operator\\":\\"<=\\",\\"value\\":\\"2022-05-31\\"},{\\"column\\":\\"status\\",\\"operator\\":\\"=\\",\\"value\\":\\"fulfilled\\"},{\\"column\\":\\"delivered_at\\",\\"operator\\":\\">\\",\\"value\\":{\\"column_name\\":\\"expected_delivery_date\\"}}],\\"order_by\\":\\"asc\\"}"}}], "refusal": null}, "logprobs": null, "finish_reason": "tool_calls"}], "usage": {"prompt_tokens": 512, "completion_tokens": 132, "total_tokens": 644, "completion_tokens_details": {"reasoning_tokens": 0}}, "system_fingerprint": "fp_7568d46099"}' ), mock_client=client, respx_mock=respx_mock, @@ -410,10 +430,11 @@ def test_pydantic_tool_model_all_types(client: OpenAI, respx_mock: MockRouter, m tool_calls=[ ParsedFunctionToolCall( function=ParsedFunction( - arguments='{"table_name":"orders","columns":["id","status","expected_delivery_date","delivered_at"," -shipped_at","ordered_at"],"conditions":[{"column":"ordered_at","operator":">=","value":"2022-05-01"},{"column":"ordered_ -at","operator":"<=","value":"2022-05-31"},{"column":"status","operator":"=","value":"fulfilled"},{"column":"delivered_at -","operator":">","value":{"column_name":"expected_delivery_date"}}],"order_by":"asc"}', + arguments='{"name":"May 2022 Fulfilled Orders Not Delivered on +Time","table_name":"orders","columns":["id","status","expected_delivery_date","delivered_at","shipped_at","ordered_at"," +canceled_at"],"conditions":[{"column":"ordered_at","operator":">=","value":"2022-05-01"},{"column":"ordered_at","operato +r":"<=","value":"2022-05-31"},{"column":"status","operator":"=","value":"fulfilled"},{"column":"delivered_at","operator" +:">","value":{"column_name":"expected_delivery_date"}}],"order_by":"asc"}', name='Query', parsed_arguments=Query( columns=[ @@ -422,7 +443,8 @@ def test_pydantic_tool_model_all_types(client: OpenAI, respx_mock: MockRouter, m , , , - + , + ], conditions=[ Condition(column='ordered_at', operator=='>, value='2022-05-01'), @@ -434,12 +456,12 @@ def test_pydantic_tool_model_all_types(client: OpenAI, respx_mock: MockRouter, m value=DynamicValue(column_name='expected_delivery_date') ) ], - name=None, + name='May 2022 Fulfilled Orders Not Delivered on Time', order_by=, table_name= ) ), - id='call_Un4g0IXeQGOyqKBS3zhqNCox', + id='call_NKpApJybW1MzOjZO2FzwYw0d', type='function' ) ] @@ -470,7 +492,7 @@ class Location(BaseModel): response_format=Location, ), content_snapshot=snapshot( - '{"id": "chatcmpl-9tXjYACgVKixKdMv2nVQqDVELkdSF", "object": "chat.completion", "created": 1723024740, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"", "refusal": null}, "logprobs": null, "finish_reason": "length"}], "usage": {"prompt_tokens": 17, "completion_tokens": 1, "total_tokens": 18}, "system_fingerprint": "fp_2a322c9ffc"}' + '{"id": "chatcmpl-ABfvvX7eB1KsfeZj8VcF3z7G7SbaA", "object": "chat.completion", "created": 1727346163, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"", "refusal": null}, "logprobs": null, "finish_reason": "length"}], "usage": {"prompt_tokens": 79, "completion_tokens": 1, "total_tokens": 80, "completion_tokens_details": {"reasoning_tokens": 0}}, "system_fingerprint": "fp_7568d46099"}' ), mock_client=client, respx_mock=respx_mock, @@ -496,7 +518,7 @@ class Location(BaseModel): response_format=Location, ), content_snapshot=snapshot( - '{"id": "chatcmpl-9tXm7FnIj3hSot5xM4c954MIePle0", "object": "chat.completion", "created": 1723024899, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "refusal": "I\'m very sorry, but I can\'t assist with that request."}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 17, "completion_tokens": 13, "total_tokens": 30}, "system_fingerprint": "fp_845eaabc1f"}' + '{"id": "chatcmpl-ABfvwoKVWPQj2UPlAcAKM7s40GsRx", "object": "chat.completion", "created": 1727346164, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "refusal": "I\'m very sorry, but I can\'t assist with that."}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 79, "completion_tokens": 12, "total_tokens": 91, "completion_tokens_details": {"reasoning_tokens": 0}}, "system_fingerprint": "fp_5050236cbd"}' ), mock_client=client, respx_mock=respx_mock, @@ -513,7 +535,7 @@ class Location(BaseModel): content=None, function_call=None, parsed=None, - refusal="I'm very sorry, but I can't assist with that request.", + refusal="I'm very sorry, but I can't assist with that.", role='assistant', tool_calls=[] ) @@ -544,7 +566,7 @@ class GetWeatherArgs(BaseModel): ], ), content_snapshot=snapshot( - '{"id": "chatcmpl-9tXjbQ9V0l5XPlynOJHKvrWsJQymO", "object": "chat.completion", "created": 1723024743, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "tool_calls": [{"id": "call_EEaIYq8aTdiDWro8jILNl3XK", "type": "function", "function": {"name": "GetWeatherArgs", "arguments": "{\\"city\\":\\"Edinburgh\\",\\"country\\":\\"GB\\",\\"units\\":\\"c\\"}"}}], "refusal": null}, "logprobs": null, "finish_reason": "tool_calls"}], "usage": {"prompt_tokens": 76, "completion_tokens": 24, "total_tokens": 100}, "system_fingerprint": "fp_2a322c9ffc"}' + '{"id": "chatcmpl-ABfvx6Z4dchiW2nya1N8KMsHFrQRE", "object": "chat.completion", "created": 1727346165, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "tool_calls": [{"id": "call_Y6qJ7ofLgOrBnMD5WbVAeiRV", "type": "function", "function": {"name": "GetWeatherArgs", "arguments": "{\\"city\\":\\"Edinburgh\\",\\"country\\":\\"UK\\",\\"units\\":\\"c\\"}"}}], "refusal": null}, "logprobs": null, "finish_reason": "tool_calls"}], "usage": {"prompt_tokens": 76, "completion_tokens": 24, "total_tokens": 100, "completion_tokens_details": {"reasoning_tokens": 0}}, "system_fingerprint": "fp_e45dabd248"}' ), mock_client=client, respx_mock=respx_mock, @@ -566,11 +588,11 @@ class GetWeatherArgs(BaseModel): tool_calls=[ ParsedFunctionToolCall( function=ParsedFunction( - arguments='{"city":"Edinburgh","country":"GB","units":"c"}', + arguments='{"city":"Edinburgh","country":"UK","units":"c"}', name='GetWeatherArgs', - parsed_arguments=GetWeatherArgs(city='Edinburgh', country='GB', units='c') + parsed_arguments=GetWeatherArgs(city='Edinburgh', country='UK', units='c') ), - id='call_EEaIYq8aTdiDWro8jILNl3XK', + id='call_Y6qJ7ofLgOrBnMD5WbVAeiRV', type='function' ) ] @@ -615,7 +637,7 @@ class GetStockPrice(BaseModel): ], ), content_snapshot=snapshot( - '{"id": "chatcmpl-9tXjcnIvzZDXRfLfbVTPNL5963GWw", "object": "chat.completion", "created": 1723024744, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "tool_calls": [{"id": "call_ECSuZ8gcNPPwgt24me91jHsJ", "type": "function", "function": {"name": "GetWeatherArgs", "arguments": "{\\"city\\": \\"Edinburgh\\", \\"country\\": \\"UK\\", \\"units\\": \\"c\\"}"}}, {"id": "call_Z3fM2sNBBGILhMtimk5Y3RQk", "type": "function", "function": {"name": "get_stock_price", "arguments": "{\\"ticker\\": \\"AAPL\\", \\"exchange\\": \\"NASDAQ\\"}"}}], "refusal": null}, "logprobs": null, "finish_reason": "tool_calls"}], "usage": {"prompt_tokens": 149, "completion_tokens": 60, "total_tokens": 209}, "system_fingerprint": "fp_845eaabc1f"}' + '{"id": "chatcmpl-ABfvyvfNWKcl7Ohqos4UFrmMs1v4C", "object": "chat.completion", "created": 1727346166, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "tool_calls": [{"id": "call_fdNz3vOBKYgOIpMdWotB9MjY", "type": "function", "function": {"name": "GetWeatherArgs", "arguments": "{\\"city\\": \\"Edinburgh\\", \\"country\\": \\"GB\\", \\"units\\": \\"c\\"}"}}, {"id": "call_h1DWI1POMJLb0KwIyQHWXD4p", "type": "function", "function": {"name": "get_stock_price", "arguments": "{\\"ticker\\": \\"AAPL\\", \\"exchange\\": \\"NASDAQ\\"}"}}], "refusal": null}, "logprobs": null, "finish_reason": "tool_calls"}], "usage": {"prompt_tokens": 149, "completion_tokens": 60, "total_tokens": 209, "completion_tokens_details": {"reasoning_tokens": 0}}, "system_fingerprint": "fp_b40fb1c6fb"}' ), mock_client=client, respx_mock=respx_mock, @@ -637,11 +659,11 @@ class GetStockPrice(BaseModel): tool_calls=[ ParsedFunctionToolCall( function=ParsedFunction( - arguments='{"city": "Edinburgh", "country": "UK", "units": "c"}', + arguments='{"city": "Edinburgh", "country": "GB", "units": "c"}', name='GetWeatherArgs', - parsed_arguments=GetWeatherArgs(city='Edinburgh', country='UK', units='c') + parsed_arguments=GetWeatherArgs(city='Edinburgh', country='GB', units='c') ), - id='call_ECSuZ8gcNPPwgt24me91jHsJ', + id='call_fdNz3vOBKYgOIpMdWotB9MjY', type='function' ), ParsedFunctionToolCall( @@ -650,7 +672,7 @@ class GetStockPrice(BaseModel): name='get_stock_price', parsed_arguments=GetStockPrice(exchange='NASDAQ', ticker='AAPL') ), - id='call_Z3fM2sNBBGILhMtimk5Y3RQk', + id='call_h1DWI1POMJLb0KwIyQHWXD4p', type='function' ) ] @@ -695,7 +717,7 @@ def test_parse_strict_tools(client: OpenAI, respx_mock: MockRouter, monkeypatch: ], ), content_snapshot=snapshot( - '{"id": "chatcmpl-9tXjfjETDIqeYvDjsuGACbwdY0xsr", "object": "chat.completion", "created": 1723024747, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "tool_calls": [{"id": "call_7ZZPctBXQWexQlIHSrIHMVUq", "type": "function", "function": {"name": "get_weather", "arguments": "{\\"city\\":\\"San Francisco\\",\\"state\\":\\"CA\\"}"}}], "refusal": null}, "logprobs": null, "finish_reason": "tool_calls"}], "usage": {"prompt_tokens": 48, "completion_tokens": 19, "total_tokens": 67}, "system_fingerprint": "fp_2a322c9ffc"}' + '{"id": "chatcmpl-ABfvzdvCI6RaIkiEFNjqGXCSYnlzf", "object": "chat.completion", "created": 1727346167, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": null, "tool_calls": [{"id": "call_CUdUoJpsWWVdxXntucvnol1M", "type": "function", "function": {"name": "get_weather", "arguments": "{\\"city\\":\\"San Francisco\\",\\"state\\":\\"CA\\"}"}}], "refusal": null}, "logprobs": null, "finish_reason": "tool_calls"}], "usage": {"prompt_tokens": 48, "completion_tokens": 19, "total_tokens": 67, "completion_tokens_details": {"reasoning_tokens": 0}}, "system_fingerprint": "fp_5050236cbd"}' ), mock_client=client, respx_mock=respx_mock, @@ -721,7 +743,7 @@ def test_parse_strict_tools(client: OpenAI, respx_mock: MockRouter, monkeypatch: name='get_weather', parsed_arguments={'city': 'San Francisco', 'state': 'CA'} ), - id='call_7ZZPctBXQWexQlIHSrIHMVUq', + id='call_CUdUoJpsWWVdxXntucvnol1M', type='function' ) ] diff --git a/tests/lib/chat/test_completions_streaming.py b/tests/lib/chat/test_completions_streaming.py index 5ad1f084d2..ce402cd158 100644 --- a/tests/lib/chat/test_completions_streaming.py +++ b/tests/lib/chat/test_completions_streaming.py @@ -48,7 +48,7 @@ def test_parse_nothing(client: OpenAI, respx_mock: MockRouter, monkeypatch: pyte }, ], ), - content_snapshot=snapshot(external("038a5c69c34c*.bin")), + content_snapshot=snapshot(external("e2aad469b71d*.bin")), mock_client=client, respx_mock=respx_mock, ) @@ -61,9 +61,8 @@ def test_parse_nothing(client: OpenAI, respx_mock: MockRouter, monkeypatch: pyte index=0, logprobs=None, message=ParsedChatCompletionMessage[NoneType]( - content="I'm unable to provide real-time updates, including current weather information. For the latest -weather in San Francisco, I recommend checking a reliable weather website or app such as the Weather Channel, BBC -Weather, or a local San Francisco news station.", + content="I'm unable to provide real-time weather updates. To get the current weather in San Francisco, I +recommend checking a reliable weather website or a weather app.", function_call=None, parsed=None, refusal=None, @@ -77,9 +76,8 @@ def test_parse_nothing(client: OpenAI, respx_mock: MockRouter, monkeypatch: pyte assert print_obj(listener.get_event_by_type("content.done"), monkeypatch) == snapshot( """\ ContentDoneEvent[NoneType]( - content="I'm unable to provide real-time updates, including current weather information. For the latest weather in -San Francisco, I recommend checking a reliable weather website or app such as the Weather Channel, BBC Weather, or a -local San Francisco news station.", + content="I'm unable to provide real-time weather updates. To get the current weather in San Francisco, I recommend +checking a reliable weather website or a weather app.", parsed=None, type='content.done' ) @@ -111,7 +109,7 @@ def on_event(stream: ChatCompletionStream[Location], event: ChatCompletionStream ], response_format=Location, ), - content_snapshot=snapshot(external("15ae68f793c7*.bin")), + content_snapshot=snapshot(external("7e5ea4d12e7c*.bin")), mock_client=client, respx_mock=respx_mock, on_event=on_event, @@ -140,30 +138,35 @@ def on_event(stream: ChatCompletionStream[Location], event: ChatCompletionStream index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( - content='{"city":"San Francisco","temperature":68,"units":"f"}', + content='{"city":"San Francisco","temperature":61,"units":"f"}', function_call=None, - parsed=Location(city='San Francisco', temperature=68.0, units='f'), + parsed=Location(city='San Francisco', temperature=61.0, units='f'), refusal=None, role='assistant', tool_calls=[] ) ) ], - created=1723024750, - id='chatcmpl-9tXji2y8kKxlOO3muVvfdJ7ECJVlD', + created=1727346169, + id='chatcmpl-ABfw1e5abtU8OwGr15vOreYVb2MiF', model='gpt-4o-2024-08-06', object='chat.completion', service_tier=None, - system_fingerprint='fp_845eaabc1f', - usage=CompletionUsage(completion_tokens=14, completion_tokens_details=None, prompt_tokens=17, total_tokens=31) + system_fingerprint='fp_5050236cbd', + usage=CompletionUsage( + completion_tokens=14, + completion_tokens_details=CompletionTokensDetails(reasoning_tokens=0), + prompt_tokens=79, + total_tokens=93 + ) ) """ ) assert print_obj(listener.get_event_by_type("content.done"), monkeypatch) == snapshot( """\ ContentDoneEvent[Location]( - content='{"city":"San Francisco","temperature":68,"units":"f"}', - parsed=Location(city='San Francisco', temperature=68.0, units='f'), + content='{"city":"San Francisco","temperature":61,"units":"f"}', + parsed=Location(city='San Francisco', temperature=61.0, units='f'), type='content.done' ) """ @@ -191,7 +194,7 @@ class Location(BaseModel): n=3, response_format=Location, ), - content_snapshot=snapshot(external("a0c4f0be184e*.bin")), + content_snapshot=snapshot(external("a491adda08c3*.bin")), mock_client=client, respx_mock=respx_mock, ) @@ -211,36 +214,22 @@ class Location(BaseModel): "chunk", "content.delta", "chunk", - "refusal.delta", - "chunk", - "refusal.delta", - "chunk", "content.delta", "chunk", "content.delta", "chunk", - "refusal.delta", - "chunk", "content.delta", "chunk", "content.delta", "chunk", - "refusal.delta", - "chunk", "content.delta", "chunk", "content.delta", "chunk", - "refusal.delta", - "chunk", "content.delta", "chunk", "content.delta", "chunk", - "refusal.delta", - "chunk", - "refusal.delta", - "chunk", "content.delta", "chunk", "content.delta", @@ -249,10 +238,6 @@ class Location(BaseModel): "chunk", "content.delta", "chunk", - "refusal.delta", - "chunk", - "refusal.delta", - "chunk", "content.delta", "chunk", "content.delta", @@ -261,95 +246,57 @@ class Location(BaseModel): "chunk", "content.delta", "chunk", - "refusal.delta", - "chunk", "content.delta", "chunk", "content.delta", "chunk", - "refusal.delta", - "chunk", "content.delta", "chunk", "content.delta", "chunk", - "refusal.delta", - "chunk", "content.delta", "chunk", "content.delta", "chunk", - "refusal.delta", - "chunk", "content.delta", "chunk", "content.delta", "chunk", - "refusal.delta", - "chunk", "content.delta", "chunk", - "refusal.delta", - "chunk", "content.delta", "chunk", - "refusal.delta", - "chunk", - "refusal.delta", - "chunk", - "refusal.delta", - "chunk", - "refusal.delta", - "chunk", - "refusal.delta", - "chunk", - "refusal.delta", - "chunk", - "refusal.delta", - "chunk", - "refusal.delta", - "chunk", - "refusal.delta", - "chunk", - "refusal.delta", - "chunk", - "refusal.delta", - "chunk", - "refusal.delta", - "chunk", - "refusal.delta", - "chunk", - "refusal.delta", + "content.delta", "chunk", - "refusal.delta", + "content.delta", "chunk", - "refusal.delta", + "content.delta", "chunk", - "refusal.delta", + "content.delta", "chunk", - "refusal.delta", + "content.delta", "chunk", - "refusal.delta", + "content.delta", "chunk", - "refusal.delta", + "content.delta", "chunk", - "refusal.delta", + "content.delta", "chunk", - "refusal.delta", + "content.delta", "chunk", - "refusal.delta", + "content.delta", "chunk", - "refusal.delta", + "content.delta", "chunk", - "refusal.delta", + "content.delta", "chunk", - "refusal.delta", + "content.delta", "chunk", "content.done", "chunk", "content.done", "chunk", - "refusal.done", + "content.done", "chunk", ] ) @@ -361,9 +308,9 @@ class Location(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( - content='{"city":"San Francisco","temperature":63,"units":"f"}', + content='{"city":"San Francisco","temperature":65,"units":"f"}', function_call=None, - parsed=Location(city='San Francisco', temperature=63.0, units='f'), + parsed=Location(city='San Francisco', temperature=65.0, units='f'), refusal=None, role='assistant', tool_calls=[] @@ -374,9 +321,9 @@ class Location(BaseModel): index=1, logprobs=None, message=ParsedChatCompletionMessage[Location]( - content='{"city":"San Francisco","temperature":58.6,"units":"f"}', + content='{"city":"San Francisco","temperature":61,"units":"f"}', function_call=None, - parsed=Location(city='San Francisco', temperature=58.6, units='f'), + parsed=Location(city='San Francisco', temperature=61.0, units='f'), refusal=None, role='assistant', tool_calls=[] @@ -387,11 +334,10 @@ class Location(BaseModel): index=2, logprobs=None, message=ParsedChatCompletionMessage[Location]( - content=None, + content='{"city":"San Francisco","temperature":59,"units":"f"}', function_call=None, - parsed=None, - refusal="I'm sorry, but I can't accurately provide the current weather for San Francisco as my data is up to -October 2023. You can try checking a reliable weather website or app for real-time updates.", + parsed=Location(city='San Francisco', temperature=59.0, units='f'), + refusal=None, role='assistant', tool_calls=[] ) @@ -421,7 +367,7 @@ class Location(BaseModel): max_tokens=1, response_format=Location, ), - content_snapshot=snapshot(external("69363a555f8e*.bin")), + content_snapshot=snapshot(external("4cc50a6135d2*.bin")), mock_client=client, respx_mock=respx_mock, ) @@ -445,13 +391,13 @@ class Location(BaseModel): ], response_format=Location, ), - content_snapshot=snapshot(external("ca015b8b1eba*.bin")), + content_snapshot=snapshot(external("173417d55340*.bin")), mock_client=client, respx_mock=respx_mock, ) assert print_obj(listener.get_event_by_type("refusal.done"), monkeypatch) == snapshot("""\ -RefusalDoneEvent(refusal="I'm sorry, but I can't assist with that request.", type='refusal.done') +RefusalDoneEvent(refusal="I'm sorry, I can't assist with that request.", type='refusal.done') """) assert print_obj(listener.stream.get_final_completion().choices, monkeypatch) == snapshot( @@ -465,7 +411,7 @@ class Location(BaseModel): content=None, function_call=None, parsed=None, - refusal="I'm sorry, but I can't assist with that request.", + refusal="I'm sorry, I can't assist with that request.", role='assistant', tool_calls=[] ) @@ -488,7 +434,7 @@ def test_content_logprobs_events(client: OpenAI, respx_mock: MockRouter, monkeyp ], logprobs=True, ), - content_snapshot=snapshot(external("be1089999ca5*.bin")), + content_snapshot=snapshot(external("83b060bae42e*.bin")), mock_client=client, respx_mock=respx_mock, ) @@ -497,25 +443,25 @@ def test_content_logprobs_events(client: OpenAI, respx_mock: MockRouter, monkeyp [ LogprobsContentDeltaEvent( content=[ - ChatCompletionTokenLogprob(bytes=[70, 111, 111], logprob=-0.0067602484, token='Foo', top_logprobs=[]) + ChatCompletionTokenLogprob(bytes=[70, 111, 111], logprob=-0.0025094282, token='Foo', top_logprobs=[]) ], snapshot=[ - ChatCompletionTokenLogprob(bytes=[70, 111, 111], logprob=-0.0067602484, token='Foo', top_logprobs=[]) + ChatCompletionTokenLogprob(bytes=[70, 111, 111], logprob=-0.0025094282, token='Foo', top_logprobs=[]) ], type='logprobs.content.delta' ), LogprobsContentDeltaEvent( - content=[ChatCompletionTokenLogprob(bytes=[46], logprob=-2.4962392, token='.', top_logprobs=[])], + content=[ChatCompletionTokenLogprob(bytes=[33], logprob=-0.26638845, token='!', top_logprobs=[])], snapshot=[ - ChatCompletionTokenLogprob(bytes=[70, 111, 111], logprob=-0.0067602484, token='Foo', top_logprobs=[]), - ChatCompletionTokenLogprob(bytes=[46], logprob=-2.4962392, token='.', top_logprobs=[]) + ChatCompletionTokenLogprob(bytes=[70, 111, 111], logprob=-0.0025094282, token='Foo', top_logprobs=[]), + ChatCompletionTokenLogprob(bytes=[33], logprob=-0.26638845, token='!', top_logprobs=[]) ], type='logprobs.content.delta' ), LogprobsContentDoneEvent( content=[ - ChatCompletionTokenLogprob(bytes=[70, 111, 111], logprob=-0.0067602484, token='Foo', top_logprobs=[]), - ChatCompletionTokenLogprob(bytes=[46], logprob=-2.4962392, token='.', top_logprobs=[]) + ChatCompletionTokenLogprob(bytes=[70, 111, 111], logprob=-0.0025094282, token='Foo', top_logprobs=[]), + ChatCompletionTokenLogprob(bytes=[33], logprob=-0.26638845, token='!', top_logprobs=[]) ], type='logprobs.content.done' ) @@ -529,13 +475,13 @@ def test_content_logprobs_events(client: OpenAI, respx_mock: MockRouter, monkeyp index=0, logprobs=ChoiceLogprobs( content=[ - ChatCompletionTokenLogprob(bytes=[70, 111, 111], logprob=-0.0067602484, token='Foo', top_logprobs=[]), - ChatCompletionTokenLogprob(bytes=[46], logprob=-2.4962392, token='.', top_logprobs=[]) + ChatCompletionTokenLogprob(bytes=[70, 111, 111], logprob=-0.0025094282, token='Foo', top_logprobs=[]), + ChatCompletionTokenLogprob(bytes=[33], logprob=-0.26638845, token='!', top_logprobs=[]) ], refusal=None ), message=ParsedChatCompletionMessage[NoneType]( - content='Foo.', + content='Foo!', function_call=None, parsed=None, refusal=None, @@ -566,7 +512,7 @@ class Location(BaseModel): logprobs=True, response_format=Location, ), - content_snapshot=snapshot(external("0a00cd46c610*.bin")), + content_snapshot=snapshot(external("569c877e6942*.bin")), mock_client=client, respx_mock=respx_mock, ) @@ -583,6 +529,7 @@ class Location(BaseModel): 'logprobs.refusal.delta', 'logprobs.refusal.delta', 'logprobs.refusal.delta', + 'logprobs.refusal.delta', 'logprobs.refusal.done' ] """) @@ -595,53 +542,59 @@ class Location(BaseModel): logprobs=ChoiceLogprobs( content=None, refusal=[ - ChatCompletionTokenLogprob(bytes=[73, 39, 109], logprob=-0.0016157961, token="I'm", top_logprobs=[]), + ChatCompletionTokenLogprob(bytes=[73, 39, 109], logprob=-0.0012038043, token="I'm", top_logprobs=[]), + ChatCompletionTokenLogprob( + bytes=[32, 118, 101, 114, 121], + logprob=-0.8438816, + token=' very', + top_logprobs=[] + ), ChatCompletionTokenLogprob( bytes=[32, 115, 111, 114, 114, 121], - logprob=-0.78663874, + logprob=-3.4121115e-06, token=' sorry', top_logprobs=[] ), - ChatCompletionTokenLogprob(bytes=[44], logprob=-7.79144e-05, token=',', top_logprobs=[]), - ChatCompletionTokenLogprob(bytes=[32, 73], logprob=-0.5234622, token=' I', top_logprobs=[]), + ChatCompletionTokenLogprob(bytes=[44], logprob=-3.3809047e-05, token=',', top_logprobs=[]), + ChatCompletionTokenLogprob( + bytes=[32, 98, 117, 116], + logprob=-0.038048144, + token=' but', + top_logprobs=[] + ), + ChatCompletionTokenLogprob(bytes=[32, 73], logprob=-0.0016109125, token=' I', top_logprobs=[]), ChatCompletionTokenLogprob( - bytes=[32, 99, 97, 110, 110, 111, 116], - logprob=-0.52499557, - token=' cannot', + bytes=[32, 99, 97, 110, 39, 116], + logprob=-0.0073532974, + token=" can't", top_logprobs=[] ), ChatCompletionTokenLogprob( bytes=[32, 97, 115, 115, 105, 115, 116], - logprob=-0.015198289, + logprob=-0.0020837625, token=' assist', top_logprobs=[] ), ChatCompletionTokenLogprob( bytes=[32, 119, 105, 116, 104], - logprob=-0.00071648485, + logprob=-0.00318354, token=' with', top_logprobs=[] ), ChatCompletionTokenLogprob( bytes=[32, 116, 104, 97, 116], - logprob=-0.008114983, + logprob=-0.0017186158, token=' that', top_logprobs=[] ), - ChatCompletionTokenLogprob( - bytes=[32, 114, 101, 113, 117, 101, 115, 116], - logprob=-0.0013802331, - token=' request', - top_logprobs=[] - ), - ChatCompletionTokenLogprob(bytes=[46], logprob=-3.4121115e-06, token='.', top_logprobs=[]) + ChatCompletionTokenLogprob(bytes=[46], logprob=-0.57687104, token='.', top_logprobs=[]) ] ), message=ParsedChatCompletionMessage[Location]( content=None, function_call=None, parsed=None, - refusal="I'm sorry, I cannot assist with that request.", + refusal="I'm very sorry, but I can't assist with that.", role='assistant', tool_calls=[] ) @@ -670,7 +623,7 @@ class GetWeatherArgs(BaseModel): openai.pydantic_function_tool(GetWeatherArgs), ], ), - content_snapshot=snapshot(external("24aaf30663f9*.bin")), + content_snapshot=snapshot(external("c6aa7e397b71*.bin")), mock_client=client, respx_mock=respx_mock, ) @@ -691,11 +644,11 @@ class GetWeatherArgs(BaseModel): tool_calls=[ ParsedFunctionToolCall( function=ParsedFunction( - arguments='{"city":"Edinburgh","country":"GB","units":"c"}', + arguments='{"city":"Edinburgh","country":"UK","units":"c"}', name='GetWeatherArgs', - parsed_arguments=GetWeatherArgs(city='Edinburgh', country='GB', units='c') + parsed_arguments=GetWeatherArgs(city='Edinburgh', country='UK', units='c') ), - id='call_7PhhveOvvpPK53s1fV8TWhoV', + id='call_c91SqDXlYFuETYv8mUHzz6pp', index=0, type='function' ) @@ -722,11 +675,11 @@ class GetWeatherArgs(BaseModel): tool_calls=[ ParsedFunctionToolCall( function=ParsedFunction( - arguments='{"city":"Edinburgh","country":"GB","units":"c"}', + arguments='{"city":"Edinburgh","country":"UK","units":"c"}', name='GetWeatherArgs', - parsed_arguments=GetWeatherArgs(city='Edinburgh', country='GB', units='c') + parsed_arguments=GetWeatherArgs(city='Edinburgh', country='UK', units='c') ), - id='call_7PhhveOvvpPK53s1fV8TWhoV', + id='call_c91SqDXlYFuETYv8mUHzz6pp', index=0, type='function' ) @@ -771,7 +724,7 @@ class GetStockPrice(BaseModel): ), ], ), - content_snapshot=snapshot(external("453df473e962*.bin")), + content_snapshot=snapshot(external("f82268f2fefd*.bin")), mock_client=client, respx_mock=respx_mock, ) @@ -792,11 +745,11 @@ class GetStockPrice(BaseModel): tool_calls=[ ParsedFunctionToolCall( function=ParsedFunction( - arguments='{"city": "Edinburgh", "country": "UK", "units": "c"}', + arguments='{"city": "Edinburgh", "country": "GB", "units": "c"}', name='GetWeatherArgs', - parsed_arguments=GetWeatherArgs(city='Edinburgh', country='UK', units='c') + parsed_arguments=GetWeatherArgs(city='Edinburgh', country='GB', units='c') ), - id='call_lQnnsesjFMWMQ5IeWPHzR4th', + id='call_JMW1whyEaYG438VE1OIflxA2', index=0, type='function' ), @@ -806,7 +759,7 @@ class GetStockPrice(BaseModel): name='get_stock_price', parsed_arguments=GetStockPrice(exchange='NASDAQ', ticker='AAPL') ), - id='call_2xjOUgaCdiwAcl9ZBL9LyMUU', + id='call_DNYTawLBoN8fj3KN6qU9N1Ou', index=1, type='function' ) @@ -822,11 +775,11 @@ class GetStockPrice(BaseModel): [ ParsedFunctionToolCall( function=ParsedFunction( - arguments='{"city": "Edinburgh", "country": "UK", "units": "c"}', + arguments='{"city": "Edinburgh", "country": "GB", "units": "c"}', name='GetWeatherArgs', - parsed_arguments=GetWeatherArgs(city='Edinburgh', country='UK', units='c') + parsed_arguments=GetWeatherArgs(city='Edinburgh', country='GB', units='c') ), - id='call_lQnnsesjFMWMQ5IeWPHzR4th', + id='call_JMW1whyEaYG438VE1OIflxA2', index=0, type='function' ), @@ -836,7 +789,7 @@ class GetStockPrice(BaseModel): name='get_stock_price', parsed_arguments=GetStockPrice(exchange='NASDAQ', ticker='AAPL') ), - id='call_2xjOUgaCdiwAcl9ZBL9LyMUU', + id='call_DNYTawLBoN8fj3KN6qU9N1Ou', index=1, type='function' ) @@ -878,7 +831,7 @@ def test_parse_strict_tools(client: OpenAI, respx_mock: MockRouter, monkeypatch: } ], ), - content_snapshot=snapshot(external("83d3d003e6fd*.bin")), + content_snapshot=snapshot(external("a247c49c5fcd*.bin")), mock_client=client, respx_mock=respx_mock, ) @@ -903,7 +856,7 @@ def test_parse_strict_tools(client: OpenAI, respx_mock: MockRouter, monkeypatch: name='get_weather', parsed_arguments={'city': 'San Francisco', 'state': 'CA'} ), - id='call_pVHYsU0gmSfX5TqxOyVbB2ma', + id='call_CTf1nWJLqSeRgDqaCG27xZ74', index=0, type='function' ) @@ -928,7 +881,7 @@ def test_non_pydantic_response_format(client: OpenAI, respx_mock: MockRouter, mo ], response_format={"type": "json_object"}, ), - content_snapshot=snapshot(external("0898f3d1651e*.bin")), + content_snapshot=snapshot(external("d61558011839*.bin")), mock_client=client, respx_mock=respx_mock, ) @@ -941,10 +894,12 @@ def test_non_pydantic_response_format(client: OpenAI, respx_mock: MockRouter, mo index=0, logprobs=None, message=ParsedChatCompletionMessage[NoneType]( - content='\\n {\\n "location": "San Francisco, CA",\\n "forecast_date": "2023-11-02",\\n "weather": {\\n -"temperature": {\\n "current": "N/A",\\n "high": "N/A",\\n "low": "N/A"\\n },\\n "condition": -"N/A",\\n "humidity": "N/A",\\n "wind_speed": "N/A"\\n },\\n "note": "Please check a reliable weather -service for the most current information."\\n }', + content='\\n {\\n "location": "San Francisco, CA",\\n "weather": {\\n "temperature": "18°C",\\n +"condition": "Partly Cloudy",\\n "humidity": "72%",\\n "windSpeed": "15 km/h",\\n "windDirection": "NW"\\n +},\\n "forecast": [\\n {\\n "day": "Monday",\\n "high": "20°C",\\n "low": "14°C",\\n +"condition": "Sunny"\\n },\\n {\\n "day": "Tuesday",\\n "high": "19°C",\\n "low": "15°C",\\n +"condition": "Mostly Cloudy"\\n },\\n {\\n "day": "Wednesday",\\n "high": "18°C",\\n "low": +"14°C",\\n "condition": "Cloudy"\\n }\\n ]\\n }\\n', function_call=None, parsed=None, refusal=None, @@ -975,7 +930,7 @@ def test_allows_non_strict_tools_but_no_parsing( } ], ), - content_snapshot=snapshot(external("dae1b261f197*.bin")), + content_snapshot=snapshot(external("2018feb66ae1*.bin")), mock_client=client, respx_mock=respx_mock, ) @@ -1010,7 +965,7 @@ def test_allows_non_strict_tools_but_no_parsing( name='get_weather', parsed_arguments=None ), - id='call_5uxEBMFySqqQGu02I5QHA8k6', + id='call_4XzlGBLtUe9dy3GVNV4jhq7h', index=0, type='function' ) From 56e64d9a17024f8ffcaee7172d4d6c6e1614f60c Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 26 Sep 2024 17:25:28 +0000 Subject: [PATCH 518/816] feat(api): add omni-moderation model (#1750) --- .stats.yml | 2 +- api.md | 9 ++- src/openai/resources/moderations.py | 49 +++++++------ src/openai/types/__init__.py | 3 + src/openai/types/moderation.py | 70 ++++++++++++++++++- src/openai/types/moderation_create_params.py | 26 +++---- .../types/moderation_image_url_input_param.py | 20 ++++++ src/openai/types/moderation_model.py | 4 +- .../moderation_multi_modal_input_param.py | 13 ++++ .../types/moderation_text_input_param.py | 15 ++++ tests/api_resources/test_moderations.py | 4 +- 11 files changed, 172 insertions(+), 43 deletions(-) create mode 100644 src/openai/types/moderation_image_url_input_param.py create mode 100644 src/openai/types/moderation_multi_modal_input_param.py create mode 100644 src/openai/types/moderation_text_input_param.py diff --git a/.stats.yml b/.stats.yml index e8bca3c6d8..0998368a4c 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-073331021d48db6af646a3552ab0c682efe31b7fb4e59a109ed1ba539f9b89c5.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-17ddd746c775ca4d4fbe64e5621ac30756ef09c061ff6313190b6ec162222d4c.yml diff --git a/api.md b/api.md index eae17d8d84..29db54f0fd 100644 --- a/api.md +++ b/api.md @@ -158,7 +158,14 @@ Methods: Types: ```python -from openai.types import Moderation, ModerationModel, ModerationCreateResponse +from openai.types import ( + Moderation, + ModerationImageURLInput, + ModerationModel, + ModerationMultiModalInput, + ModerationTextInput, + ModerationCreateResponse, +) ``` Methods: diff --git a/src/openai/resources/moderations.py b/src/openai/resources/moderations.py index 5283554373..8b73da57b2 100644 --- a/src/openai/resources/moderations.py +++ b/src/openai/resources/moderations.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import List, Union +from typing import List, Union, Iterable import httpx @@ -19,6 +19,7 @@ from .._base_client import make_request_options from ..types.moderation_model import ModerationModel from ..types.moderation_create_response import ModerationCreateResponse +from ..types.moderation_multi_modal_input_param import ModerationMultiModalInputParam __all__ = ["Moderations", "AsyncModerations"] @@ -46,7 +47,7 @@ def with_streaming_response(self) -> ModerationsWithStreamingResponse: def create( self, *, - input: Union[str, List[str]], + input: Union[str, List[str], Iterable[ModerationMultiModalInputParam]], model: Union[str, ModerationModel] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -55,20 +56,19 @@ def create( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ModerationCreateResponse: - """ - Classifies if text is potentially harmful. + """Classifies if text and/or image inputs are potentially harmful. - Args: - input: The input text to classify + Learn more in + the [moderation guide](https://platform.openai.com/docs/guides/moderation). - model: Two content moderations models are available: `text-moderation-stable` and - `text-moderation-latest`. + Args: + input: Input (or inputs) to classify. Can be a single string, an array of strings, or + an array of multi-modal input objects similar to other models. - The default is `text-moderation-latest` which will be automatically upgraded - over time. This ensures you are always using our most accurate model. If you use - `text-moderation-stable`, we will provide advanced notice before updating the - model. Accuracy of `text-moderation-stable` may be slightly lower than for - `text-moderation-latest`. + model: The content moderation model you would like to use. Learn more in + [the moderation guide](https://platform.openai.com/docs/guides/moderation), and + learn about available models + [here](https://platform.openai.com/docs/models/moderation). extra_headers: Send extra headers @@ -117,7 +117,7 @@ def with_streaming_response(self) -> AsyncModerationsWithStreamingResponse: async def create( self, *, - input: Union[str, List[str]], + input: Union[str, List[str], Iterable[ModerationMultiModalInputParam]], model: Union[str, ModerationModel] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -126,20 +126,19 @@ async def create( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ModerationCreateResponse: - """ - Classifies if text is potentially harmful. + """Classifies if text and/or image inputs are potentially harmful. - Args: - input: The input text to classify + Learn more in + the [moderation guide](https://platform.openai.com/docs/guides/moderation). - model: Two content moderations models are available: `text-moderation-stable` and - `text-moderation-latest`. + Args: + input: Input (or inputs) to classify. Can be a single string, an array of strings, or + an array of multi-modal input objects similar to other models. - The default is `text-moderation-latest` which will be automatically upgraded - over time. This ensures you are always using our most accurate model. If you use - `text-moderation-stable`, we will provide advanced notice before updating the - model. Accuracy of `text-moderation-stable` may be slightly lower than for - `text-moderation-latest`. + model: The content moderation model you would like to use. Learn more in + [the moderation guide](https://platform.openai.com/docs/guides/moderation), and + learn about available models + [here](https://platform.openai.com/docs/models/moderation). extra_headers: Send extra headers diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index 6223be883d..7677be01b2 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -46,4 +46,7 @@ from .moderation_create_params import ModerationCreateParams as ModerationCreateParams from .create_embedding_response import CreateEmbeddingResponse as CreateEmbeddingResponse from .moderation_create_response import ModerationCreateResponse as ModerationCreateResponse +from .moderation_text_input_param import ModerationTextInputParam as ModerationTextInputParam from .image_create_variation_params import ImageCreateVariationParams as ImageCreateVariationParams +from .moderation_image_url_input_param import ModerationImageURLInputParam as ModerationImageURLInputParam +from .moderation_multi_modal_input_param import ModerationMultiModalInputParam as ModerationMultiModalInputParam diff --git a/src/openai/types/moderation.py b/src/openai/types/moderation.py index 5aa691823a..e4ec182ce2 100644 --- a/src/openai/types/moderation.py +++ b/src/openai/types/moderation.py @@ -1,11 +1,13 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +from typing import List +from typing_extensions import Literal from pydantic import Field as FieldInfo from .._models import BaseModel -__all__ = ["Moderation", "Categories", "CategoryScores"] +__all__ = ["Moderation", "Categories", "CategoryAppliedInputTypes", "CategoryScores"] class Categories(BaseModel): @@ -36,6 +38,20 @@ class Categories(BaseModel): orientation, disability status, or caste. """ + illicit: bool + """ + Content that includes instructions or advice that facilitate the planning or + execution of wrongdoing, or that gives advice or instruction on how to commit + illicit acts. For example, "how to shoplift" would fit this category. + """ + + illicit_violent: bool = FieldInfo(alias="illicit/violent") + """ + Content that includes instructions or advice that facilitate the planning or + execution of wrongdoing that also includes violence, or that gives advice or + instruction on the procurement of any weapon. + """ + self_harm: bool = FieldInfo(alias="self-harm") """ Content that promotes, encourages, or depicts acts of self-harm, such as @@ -72,6 +88,47 @@ class Categories(BaseModel): """Content that depicts death, violence, or physical injury in graphic detail.""" +class CategoryAppliedInputTypes(BaseModel): + harassment: List[Literal["text"]] + """The applied input type(s) for the category 'harassment'.""" + + harassment_threatening: List[Literal["text"]] = FieldInfo(alias="harassment/threatening") + """The applied input type(s) for the category 'harassment/threatening'.""" + + hate: List[Literal["text"]] + """The applied input type(s) for the category 'hate'.""" + + hate_threatening: List[Literal["text"]] = FieldInfo(alias="hate/threatening") + """The applied input type(s) for the category 'hate/threatening'.""" + + illicit: List[Literal["text"]] + """The applied input type(s) for the category 'illicit'.""" + + illicit_violent: List[Literal["text"]] = FieldInfo(alias="illicit/violent") + """The applied input type(s) for the category 'illicit/violent'.""" + + self_harm: List[Literal["text", "image"]] = FieldInfo(alias="self-harm") + """The applied input type(s) for the category 'self-harm'.""" + + self_harm_instructions: List[Literal["text", "image"]] = FieldInfo(alias="self-harm/instructions") + """The applied input type(s) for the category 'self-harm/instructions'.""" + + self_harm_intent: List[Literal["text", "image"]] = FieldInfo(alias="self-harm/intent") + """The applied input type(s) for the category 'self-harm/intent'.""" + + sexual: List[Literal["text", "image"]] + """The applied input type(s) for the category 'sexual'.""" + + sexual_minors: List[Literal["text"]] = FieldInfo(alias="sexual/minors") + """The applied input type(s) for the category 'sexual/minors'.""" + + violence: List[Literal["text", "image"]] + """The applied input type(s) for the category 'violence'.""" + + violence_graphic: List[Literal["text", "image"]] = FieldInfo(alias="violence/graphic") + """The applied input type(s) for the category 'violence/graphic'.""" + + class CategoryScores(BaseModel): harassment: float """The score for the category 'harassment'.""" @@ -85,6 +142,12 @@ class CategoryScores(BaseModel): hate_threatening: float = FieldInfo(alias="hate/threatening") """The score for the category 'hate/threatening'.""" + illicit: float + """The score for the category 'illicit'.""" + + illicit_violent: float = FieldInfo(alias="illicit/violent") + """The score for the category 'illicit/violent'.""" + self_harm: float = FieldInfo(alias="self-harm") """The score for the category 'self-harm'.""" @@ -111,6 +174,11 @@ class Moderation(BaseModel): categories: Categories """A list of the categories, and whether they are flagged or not.""" + category_applied_input_types: CategoryAppliedInputTypes + """ + A list of the categories along with the input type(s) that the score applies to. + """ + category_scores: CategoryScores """A list of the categories along with their scores as predicted by model.""" diff --git a/src/openai/types/moderation_create_params.py b/src/openai/types/moderation_create_params.py index 337682194d..3193fd9c2d 100644 --- a/src/openai/types/moderation_create_params.py +++ b/src/openai/types/moderation_create_params.py @@ -2,26 +2,28 @@ from __future__ import annotations -from typing import List, Union +from typing import List, Union, Iterable from typing_extensions import Required, TypedDict from .moderation_model import ModerationModel +from .moderation_multi_modal_input_param import ModerationMultiModalInputParam __all__ = ["ModerationCreateParams"] class ModerationCreateParams(TypedDict, total=False): - input: Required[Union[str, List[str]]] - """The input text to classify""" + input: Required[Union[str, List[str], Iterable[ModerationMultiModalInputParam]]] + """Input (or inputs) to classify. - model: Union[str, ModerationModel] + Can be a single string, an array of strings, or an array of multi-modal input + objects similar to other models. """ - Two content moderations models are available: `text-moderation-stable` and - `text-moderation-latest`. - - The default is `text-moderation-latest` which will be automatically upgraded - over time. This ensures you are always using our most accurate model. If you use - `text-moderation-stable`, we will provide advanced notice before updating the - model. Accuracy of `text-moderation-stable` may be slightly lower than for - `text-moderation-latest`. + + model: Union[str, ModerationModel] + """The content moderation model you would like to use. + + Learn more in + [the moderation guide](https://platform.openai.com/docs/guides/moderation), and + learn about available models + [here](https://platform.openai.com/docs/models/moderation). """ diff --git a/src/openai/types/moderation_image_url_input_param.py b/src/openai/types/moderation_image_url_input_param.py new file mode 100644 index 0000000000..9a69a6a257 --- /dev/null +++ b/src/openai/types/moderation_image_url_input_param.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ModerationImageURLInputParam", "ImageURL"] + + +class ImageURL(TypedDict, total=False): + url: Required[str] + """Either a URL of the image or the base64 encoded image data.""" + + +class ModerationImageURLInputParam(TypedDict, total=False): + image_url: Required[ImageURL] + """Contains either an image URL or a data URL for a base64 encoded image.""" + + type: Required[Literal["image_url"]] + """Always `image_url`.""" diff --git a/src/openai/types/moderation_model.py b/src/openai/types/moderation_model.py index f549aeeb7a..64954c4547 100644 --- a/src/openai/types/moderation_model.py +++ b/src/openai/types/moderation_model.py @@ -4,4 +4,6 @@ __all__ = ["ModerationModel"] -ModerationModel: TypeAlias = Literal["text-moderation-latest", "text-moderation-stable"] +ModerationModel: TypeAlias = Literal[ + "omni-moderation-latest", "omni-moderation-2024-09-26", "text-moderation-latest", "text-moderation-stable" +] diff --git a/src/openai/types/moderation_multi_modal_input_param.py b/src/openai/types/moderation_multi_modal_input_param.py new file mode 100644 index 0000000000..4314e7b031 --- /dev/null +++ b/src/openai/types/moderation_multi_modal_input_param.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import TypeAlias + +from .moderation_text_input_param import ModerationTextInputParam +from .moderation_image_url_input_param import ModerationImageURLInputParam + +__all__ = ["ModerationMultiModalInputParam"] + +ModerationMultiModalInputParam: TypeAlias = Union[ModerationImageURLInputParam, ModerationTextInputParam] diff --git a/src/openai/types/moderation_text_input_param.py b/src/openai/types/moderation_text_input_param.py new file mode 100644 index 0000000000..e5da53337b --- /dev/null +++ b/src/openai/types/moderation_text_input_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ModerationTextInputParam"] + + +class ModerationTextInputParam(TypedDict, total=False): + text: Required[str] + """A string of text to classify.""" + + type: Required[Literal["text"]] + """Always `text`.""" diff --git a/tests/api_resources/test_moderations.py b/tests/api_resources/test_moderations.py index 94b9ecd31b..bbdeb63e49 100644 --- a/tests/api_resources/test_moderations.py +++ b/tests/api_resources/test_moderations.py @@ -28,7 +28,7 @@ def test_method_create(self, client: OpenAI) -> None: def test_method_create_with_all_params(self, client: OpenAI) -> None: moderation = client.moderations.create( input="I want to kill them.", - model="text-moderation-stable", + model="omni-moderation-2024-09-26", ) assert_matches_type(ModerationCreateResponse, moderation, path=["response"]) @@ -71,7 +71,7 @@ async def test_method_create(self, async_client: AsyncOpenAI) -> None: async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: moderation = await async_client.moderations.create( input="I want to kill them.", - model="text-moderation-stable", + model="omni-moderation-2024-09-26", ) assert_matches_type(ModerationCreateResponse, moderation, path=["response"]) From 70edb2134913569677b40ed514a3520e31bd9f25 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 26 Sep 2024 17:26:01 +0000 Subject: [PATCH 519/816] release: 1.49.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 3f47f4bc2b..5153ca9d4c 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.48.0" + ".": "1.49.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index d89151074b..4a8156c611 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.49.0 (2024-09-26) + +Full Changelog: [v1.48.0...v1.49.0](https://github.com/openai/openai-python/compare/v1.48.0...v1.49.0) + +### Features + +* **api:** add omni-moderation model ([#1750](https://github.com/openai/openai-python/issues/1750)) ([05b50da](https://github.com/openai/openai-python/commit/05b50da5428d5c7b5ea09626bcd88f8423762bf8)) + + +### Chores + +* **internal:** update test snapshots ([#1749](https://github.com/openai/openai-python/issues/1749)) ([42f054e](https://github.com/openai/openai-python/commit/42f054ee7afa8ce8316c2ecd90608a0f7e13bfdd)) + ## 1.48.0 (2024-09-25) Full Changelog: [v1.47.1...v1.48.0](https://github.com/openai/openai-python/compare/v1.47.1...v1.48.0) diff --git a/pyproject.toml b/pyproject.toml index 05f957cac0..aa4c7c1d76 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.48.0" +version = "1.49.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 66109f354b..32d54fb9d0 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.48.0" # x-release-please-version +__version__ = "1.49.0" # x-release-please-version From e1aeeb0ee62965687c8d0dd00e9e39e54be9498c Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Thu, 26 Sep 2024 23:12:51 +0100 Subject: [PATCH 520/816] chore(pydantic v1): exclude specific properties when rich printing (#1751) --- src/openai/_models.py | 10 +++++++++- tests/lib/chat/_utils.py | 11 +++-------- tests/test_legacy_response.py | 4 ++++ tests/test_response.py | 4 ++++ tests/utils.py | 13 +++++++++++++ 5 files changed, 33 insertions(+), 9 deletions(-) diff --git a/src/openai/_models.py b/src/openai/_models.py index d6f42d3d4d..710401defd 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -2,7 +2,7 @@ import os import inspect -from typing import TYPE_CHECKING, Any, Type, Union, Generic, TypeVar, Callable, Optional, cast +from typing import TYPE_CHECKING, Any, Type, Tuple, Union, Generic, TypeVar, Callable, Optional, cast from datetime import date, datetime from typing_extensions import ( Unpack, @@ -10,6 +10,7 @@ ClassVar, Protocol, Required, + Sequence, ParamSpec, TypedDict, TypeGuard, @@ -72,6 +73,8 @@ P = ParamSpec("P") +ReprArgs = Sequence[Tuple[Optional[str], Any]] + @runtime_checkable class _ConfigProtocol(Protocol): @@ -94,6 +97,11 @@ def model_fields_set(self) -> set[str]: class Config(pydantic.BaseConfig): # pyright: ignore[reportDeprecated] extra: Any = pydantic.Extra.allow # type: ignore + @override + def __repr_args__(self) -> ReprArgs: + # we don't want these attributes to be included when something like `rich.print` is used + return [arg for arg in super().__repr_args__() if arg[0] not in {"_request_id", "__exclude_fields__"}] + if TYPE_CHECKING: _request_id: Optional[str] = None """The ID of the request, returned via the X-Request-ID header. Useful for debugging requests and reporting issues to OpenAI. diff --git a/tests/lib/chat/_utils.py b/tests/lib/chat/_utils.py index dcc32b17fd..af08db417c 100644 --- a/tests/lib/chat/_utils.py +++ b/tests/lib/chat/_utils.py @@ -1,14 +1,14 @@ from __future__ import annotations -import io import inspect from typing import Any, Iterable from typing_extensions import TypeAlias -import rich import pytest import pydantic +from ...utils import rich_print_str + ReprArgs: TypeAlias = "Iterable[tuple[str | None, Any]]" @@ -26,12 +26,7 @@ def __repr_args__(self: pydantic.BaseModel) -> ReprArgs: with monkeypatch.context() as m: m.setattr(pydantic.BaseModel, "__repr_args__", __repr_args__) - buf = io.StringIO() - - console = rich.console.Console(file=buf, width=120) - console.print(obj) - - string = buf.getvalue() + string = rich_print_str(obj) # we remove all `fn_name..` occurences # so that we can share the same snapshots between diff --git a/tests/test_legacy_response.py b/tests/test_legacy_response.py index a6fec9f2de..f50a77c24d 100644 --- a/tests/test_legacy_response.py +++ b/tests/test_legacy_response.py @@ -11,6 +11,8 @@ from openai._base_client import FinalRequestOptions from openai._legacy_response import LegacyAPIResponse +from .utils import rich_print_str + class PydanticModel(pydantic.BaseModel): ... @@ -85,6 +87,8 @@ def test_response_basemodel_request_id(client: OpenAI) -> None: assert obj.foo == "hello!" assert obj.bar == 2 assert obj.to_dict() == {"foo": "hello!", "bar": 2} + assert "_request_id" not in rich_print_str(obj) + assert "__exclude_fields__" not in rich_print_str(obj) def test_response_parse_annotated_type(client: OpenAI) -> None: diff --git a/tests/test_response.py b/tests/test_response.py index 97c56e0035..e1fe332f2f 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -18,6 +18,8 @@ from openai._streaming import Stream from openai._base_client import FinalRequestOptions +from .utils import rich_print_str + class ConcreteBaseAPIResponse(APIResponse[bytes]): ... @@ -175,6 +177,8 @@ def test_response_basemodel_request_id(client: OpenAI) -> None: assert obj.foo == "hello!" assert obj.bar == 2 assert obj.to_dict() == {"foo": "hello!", "bar": 2} + assert "_request_id" not in rich_print_str(obj) + assert "__exclude_fields__" not in rich_print_str(obj) @pytest.mark.asyncio diff --git a/tests/utils.py b/tests/utils.py index 165f4e5bfd..8d5397f28e 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -1,5 +1,6 @@ from __future__ import annotations +import io import os import inspect import traceback @@ -8,6 +9,8 @@ from datetime import date, datetime from typing_extensions import Literal, get_args, get_origin, assert_type +import rich + from openai._types import Omit, NoneType from openai._utils import ( is_dict, @@ -138,6 +141,16 @@ def _assert_list_type(type_: type[object], value: object) -> None: assert_type(inner_type, entry) # type: ignore +def rich_print_str(obj: object) -> str: + """Like `rich.print()` but returns the string instead""" + buf = io.StringIO() + + console = rich.console.Console(file=buf, width=120) + console.print(obj) + + return buf.getvalue() + + @contextlib.contextmanager def update_env(**new_env: str | Omit) -> Iterator[None]: old = os.environ.copy() From 152a8bda1b1db21377496b36ff26ab127a27b221 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Thu, 26 Sep 2024 23:32:48 +0100 Subject: [PATCH 521/816] feat(structured outputs): add support for accessing raw responses (#1748) --- src/openai/resources/beta/chat/completions.py | 246 +++++++++++++----- tests/lib/chat/test_completions.py | 177 ++++++++++++- 2 files changed, 355 insertions(+), 68 deletions(-) diff --git a/src/openai/resources/beta/chat/completions.py b/src/openai/resources/beta/chat/completions.py index ea3526778d..da6f189929 100644 --- a/src/openai/resources/beta/chat/completions.py +++ b/src/openai/resources/beta/chat/completions.py @@ -2,16 +2,21 @@ from __future__ import annotations -from typing import Dict, List, Union, Iterable, Optional +from typing import Dict, List, Type, Union, Iterable, Optional, cast from functools import partial from typing_extensions import Literal import httpx +from .... import _legacy_response from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ...._utils import maybe_transform, async_maybe_transform +from ...._compat import cached_property from ...._resource import SyncAPIResource, AsyncAPIResource +from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ...._streaming import Stream from ....types.chat import completion_create_params +from ...._base_client import make_request_options from ....lib._parsing import ( ResponseFormatT, validate_input_tools as _validate_input_tools, @@ -20,6 +25,7 @@ ) from ....types.chat_model import ChatModel from ....lib.streaming.chat import ChatCompletionStreamManager, AsyncChatCompletionStreamManager +from ....types.chat.chat_completion import ChatCompletion from ....types.chat.chat_completion_chunk import ChatCompletionChunk from ....types.chat.parsed_chat_completion import ParsedChatCompletion from ....types.chat.chat_completion_tool_param import ChatCompletionToolParam @@ -31,6 +37,25 @@ class Completions(SyncAPIResource): + @cached_property + def with_raw_response(self) -> CompletionsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return CompletionsWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> CompletionsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return CompletionsWithStreamingResponse(self) + def parse( self, *, @@ -113,39 +138,55 @@ class MathResponse(BaseModel): **(extra_headers or {}), } - raw_completion = self._client.chat.completions.create( - messages=messages, - model=model, - response_format=_type_to_response_format(response_format), - frequency_penalty=frequency_penalty, - function_call=function_call, - functions=functions, - logit_bias=logit_bias, - logprobs=logprobs, - max_completion_tokens=max_completion_tokens, - max_tokens=max_tokens, - n=n, - parallel_tool_calls=parallel_tool_calls, - presence_penalty=presence_penalty, - seed=seed, - service_tier=service_tier, - stop=stop, - stream_options=stream_options, - temperature=temperature, - tool_choice=tool_choice, - tools=tools, - top_logprobs=top_logprobs, - top_p=top_p, - user=user, - extra_headers=extra_headers, - extra_query=extra_query, - extra_body=extra_body, - timeout=timeout, - ) - return _parse_chat_completion( - response_format=response_format, - chat_completion=raw_completion, - input_tools=tools, + def parser(raw_completion: ChatCompletion) -> ParsedChatCompletion[ResponseFormatT]: + return _parse_chat_completion( + response_format=response_format, + chat_completion=raw_completion, + input_tools=tools, + ) + + return self._post( + "/chat/completions", + body=maybe_transform( + { + "messages": messages, + "model": model, + "frequency_penalty": frequency_penalty, + "function_call": function_call, + "functions": functions, + "logit_bias": logit_bias, + "logprobs": logprobs, + "max_completion_tokens": max_completion_tokens, + "max_tokens": max_tokens, + "n": n, + "parallel_tool_calls": parallel_tool_calls, + "presence_penalty": presence_penalty, + "response_format": _type_to_response_format(response_format), + "seed": seed, + "service_tier": service_tier, + "stop": stop, + "stream": False, + "stream_options": stream_options, + "temperature": temperature, + "tool_choice": tool_choice, + "tools": tools, + "top_logprobs": top_logprobs, + "top_p": top_p, + "user": user, + }, + completion_create_params.CompletionCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + post_parser=parser, + ), + # we turn the `ChatCompletion` instance into a `ParsedChatCompletion` + # in the `parser` function above + cast_to=cast(Type[ParsedChatCompletion[ResponseFormatT]], ChatCompletion), + stream=False, ) def stream( @@ -247,6 +288,25 @@ def stream( class AsyncCompletions(AsyncAPIResource): + @cached_property + def with_raw_response(self) -> AsyncCompletionsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return AsyncCompletionsWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncCompletionsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return AsyncCompletionsWithStreamingResponse(self) + async def parse( self, *, @@ -329,39 +389,55 @@ class MathResponse(BaseModel): **(extra_headers or {}), } - raw_completion = await self._client.chat.completions.create( - messages=messages, - model=model, - response_format=_type_to_response_format(response_format), - frequency_penalty=frequency_penalty, - function_call=function_call, - functions=functions, - logit_bias=logit_bias, - logprobs=logprobs, - max_completion_tokens=max_completion_tokens, - max_tokens=max_tokens, - n=n, - parallel_tool_calls=parallel_tool_calls, - presence_penalty=presence_penalty, - seed=seed, - service_tier=service_tier, - stop=stop, - stream_options=stream_options, - temperature=temperature, - tool_choice=tool_choice, - tools=tools, - top_logprobs=top_logprobs, - top_p=top_p, - user=user, - extra_headers=extra_headers, - extra_query=extra_query, - extra_body=extra_body, - timeout=timeout, - ) - return _parse_chat_completion( - response_format=response_format, - chat_completion=raw_completion, - input_tools=tools, + def parser(raw_completion: ChatCompletion) -> ParsedChatCompletion[ResponseFormatT]: + return _parse_chat_completion( + response_format=response_format, + chat_completion=raw_completion, + input_tools=tools, + ) + + return await self._post( + "/chat/completions", + body=await async_maybe_transform( + { + "messages": messages, + "model": model, + "frequency_penalty": frequency_penalty, + "function_call": function_call, + "functions": functions, + "logit_bias": logit_bias, + "logprobs": logprobs, + "max_completion_tokens": max_completion_tokens, + "max_tokens": max_tokens, + "n": n, + "parallel_tool_calls": parallel_tool_calls, + "presence_penalty": presence_penalty, + "response_format": _type_to_response_format(response_format), + "seed": seed, + "service_tier": service_tier, + "stop": stop, + "stream": False, + "stream_options": stream_options, + "temperature": temperature, + "tool_choice": tool_choice, + "tools": tools, + "top_logprobs": top_logprobs, + "top_p": top_p, + "user": user, + }, + completion_create_params.CompletionCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + post_parser=parser, + ), + # we turn the `ChatCompletion` instance into a `ParsedChatCompletion` + # in the `parser` function above + cast_to=cast(Type[ParsedChatCompletion[ResponseFormatT]], ChatCompletion), + stream=False, ) def stream( @@ -461,3 +537,39 @@ def stream( response_format=response_format, input_tools=tools, ) + + +class CompletionsWithRawResponse: + def __init__(self, completions: Completions) -> None: + self._completions = completions + + self.parse = _legacy_response.to_raw_response_wrapper( + completions.parse, + ) + + +class AsyncCompletionsWithRawResponse: + def __init__(self, completions: AsyncCompletions) -> None: + self._completions = completions + + self.parse = _legacy_response.async_to_raw_response_wrapper( + completions.parse, + ) + + +class CompletionsWithStreamingResponse: + def __init__(self, completions: Completions) -> None: + self._completions = completions + + self.parse = to_streamed_response_wrapper( + completions.parse, + ) + + +class AsyncCompletionsWithStreamingResponse: + def __init__(self, completions: AsyncCompletions) -> None: + self._completions = completions + + self.parse = async_to_streamed_response_wrapper( + completions.parse, + ) diff --git a/tests/lib/chat/test_completions.py b/tests/lib/chat/test_completions.py index d66630fa3a..7702a98d49 100644 --- a/tests/lib/chat/test_completions.py +++ b/tests/lib/chat/test_completions.py @@ -3,7 +3,7 @@ import os import json from enum import Enum -from typing import Any, List, Callable, Optional +from typing import Any, List, Callable, Optional, Awaitable from typing_extensions import Literal, TypeVar import httpx @@ -773,6 +773,139 @@ def test_parse_non_strict_tools(client: OpenAI) -> None: ) +@pytest.mark.respx(base_url=base_url) +def test_parse_pydantic_raw_response(client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: + class Location(BaseModel): + city: str + temperature: float + units: Literal["c", "f"] + + response = _make_snapshot_request( + lambda c: c.beta.chat.completions.with_raw_response.parse( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "user", + "content": "What's the weather like in SF?", + }, + ], + response_format=Location, + ), + content_snapshot=snapshot( + '{"id": "chatcmpl-ABrDYCa8W1w66eUxKDO8TQF1m6trT", "object": "chat.completion", "created": 1727389540, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"city\\":\\"San Francisco\\",\\"temperature\\":58,\\"units\\":\\"f\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 79, "completion_tokens": 14, "total_tokens": 93, "completion_tokens_details": {"reasoning_tokens": 0}}, "system_fingerprint": "fp_5050236cbd"}' + ), + mock_client=client, + respx_mock=respx_mock, + ) + assert response.http_request.headers.get("x-stainless-helper-method") == "beta.chat.completions.parse" + + completion = response.parse() + message = completion.choices[0].message + assert message.parsed is not None + assert isinstance(message.parsed.city, str) + assert print_obj(completion, monkeypatch) == snapshot( + """\ +ParsedChatCompletion[Location]( + choices=[ + ParsedChoice[Location]( + finish_reason='stop', + index=0, + logprobs=None, + message=ParsedChatCompletionMessage[Location]( + content='{"city":"San Francisco","temperature":58,"units":"f"}', + function_call=None, + parsed=Location(city='San Francisco', temperature=58.0, units='f'), + refusal=None, + role='assistant', + tool_calls=[] + ) + ) + ], + created=1727389540, + id='chatcmpl-ABrDYCa8W1w66eUxKDO8TQF1m6trT', + model='gpt-4o-2024-08-06', + object='chat.completion', + service_tier=None, + system_fingerprint='fp_5050236cbd', + usage=CompletionUsage( + completion_tokens=14, + completion_tokens_details=CompletionTokensDetails(reasoning_tokens=0), + prompt_tokens=79, + total_tokens=93 + ) +) +""" + ) + + +@pytest.mark.respx(base_url=base_url) +@pytest.mark.asyncio +async def test_async_parse_pydantic_raw_response( + async_client: AsyncOpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch +) -> None: + class Location(BaseModel): + city: str + temperature: float + units: Literal["c", "f"] + + response = await _make_async_snapshot_request( + lambda c: c.beta.chat.completions.with_raw_response.parse( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "user", + "content": "What's the weather like in SF?", + }, + ], + response_format=Location, + ), + content_snapshot=snapshot( + '{"id": "chatcmpl-ABrDQWOiw0PK5JOsxl1D9ooeQgznq", "object": "chat.completion", "created": 1727389532, "model": "gpt-4o-2024-08-06", "choices": [{"index": 0, "message": {"role": "assistant", "content": "{\\"city\\":\\"San Francisco\\",\\"temperature\\":65,\\"units\\":\\"f\\"}", "refusal": null}, "logprobs": null, "finish_reason": "stop"}], "usage": {"prompt_tokens": 79, "completion_tokens": 14, "total_tokens": 93, "completion_tokens_details": {"reasoning_tokens": 0}}, "system_fingerprint": "fp_5050236cbd"}' + ), + mock_client=async_client, + respx_mock=respx_mock, + ) + assert response.http_request.headers.get("x-stainless-helper-method") == "beta.chat.completions.parse" + + completion = response.parse() + message = completion.choices[0].message + assert message.parsed is not None + assert isinstance(message.parsed.city, str) + assert print_obj(completion, monkeypatch) == snapshot( + """\ +ParsedChatCompletion[Location]( + choices=[ + ParsedChoice[Location]( + finish_reason='stop', + index=0, + logprobs=None, + message=ParsedChatCompletionMessage[Location]( + content='{"city":"San Francisco","temperature":65,"units":"f"}', + function_call=None, + parsed=Location(city='San Francisco', temperature=65.0, units='f'), + refusal=None, + role='assistant', + tool_calls=[] + ) + ) + ], + created=1727389532, + id='chatcmpl-ABrDQWOiw0PK5JOsxl1D9ooeQgznq', + model='gpt-4o-2024-08-06', + object='chat.completion', + service_tier=None, + system_fingerprint='fp_5050236cbd', + usage=CompletionUsage( + completion_tokens=14, + completion_tokens_details=CompletionTokensDetails(reasoning_tokens=0), + prompt_tokens=79, + total_tokens=93 + ) +) +""" + ) + + @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) def test_parse_method_in_sync(sync: bool, client: OpenAI, async_client: AsyncOpenAI) -> None: checking_client: OpenAI | AsyncOpenAI = client if sync else async_client @@ -824,3 +957,45 @@ def _on_response(response: httpx.Response) -> None: client.close() return result + + +async def _make_async_snapshot_request( + func: Callable[[AsyncOpenAI], Awaitable[_T]], + *, + content_snapshot: Any, + respx_mock: MockRouter, + mock_client: AsyncOpenAI, +) -> _T: + live = os.environ.get("OPENAI_LIVE") == "1" + if live: + + async def _on_response(response: httpx.Response) -> None: + # update the content snapshot + assert json.dumps(json.loads(await response.aread())) == content_snapshot + + respx_mock.stop() + + client = AsyncOpenAI( + http_client=httpx.AsyncClient( + event_hooks={ + "response": [_on_response], + } + ) + ) + else: + respx_mock.post("/chat/completions").mock( + return_value=httpx.Response( + 200, + content=content_snapshot._old_value, + headers={"content-type": "application/json"}, + ) + ) + + client = mock_client + + result = await func(client) + + if live: + await client.close() + + return result From 37f5615da1f4360710f6f45920dbb81387d1a4c5 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 26 Sep 2024 22:33:11 +0000 Subject: [PATCH 522/816] release: 1.50.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 5153ca9d4c..97e4d742db 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.49.0" + ".": "1.50.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a8156c611..20be5b530b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.50.0 (2024-09-26) + +Full Changelog: [v1.49.0...v1.50.0](https://github.com/openai/openai-python/compare/v1.49.0...v1.50.0) + +### Features + +* **structured outputs:** add support for accessing raw responses ([#1748](https://github.com/openai/openai-python/issues/1748)) ([0189e28](https://github.com/openai/openai-python/commit/0189e28b0b062a28b16343da0460a4f0f4e17a9a)) + + +### Chores + +* **pydantic v1:** exclude specific properties when rich printing ([#1751](https://github.com/openai/openai-python/issues/1751)) ([af535ce](https://github.com/openai/openai-python/commit/af535ce6a523eca39438f117a3e55f16064567a9)) + ## 1.49.0 (2024-09-26) Full Changelog: [v1.48.0...v1.49.0](https://github.com/openai/openai-python/compare/v1.48.0...v1.49.0) diff --git a/pyproject.toml b/pyproject.toml index aa4c7c1d76..f7061c5059 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.49.0" +version = "1.50.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 32d54fb9d0..e05b612a12 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.49.0" # x-release-please-version +__version__ = "1.50.0" # x-release-please-version From 73fc3b9ce2cc94959bd4efde8cdd4896e3953dee Mon Sep 17 00:00:00 2001 From: Sam El-Borai Date: Fri, 27 Sep 2024 14:20:58 +0200 Subject: [PATCH 523/816] docs(helpers): fix chat completion anchor (#1753) --- helpers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/helpers.md b/helpers.md index 965dd6e23c..65515df973 100644 --- a/helpers.md +++ b/helpers.md @@ -128,7 +128,7 @@ The `beta.chat.completions.parse()` method imposes some additional restrictions # Streaming Helpers -OpenAI supports streaming responses when interacting with the [Chat Completion] & [Assistant](#assistant-streaming-api) APIs. +OpenAI supports streaming responses when interacting with the [Chat Completion](#chat-completions-api) & [Assistant](#assistant-streaming-api) APIs. ## Chat Completions API From 7a5632f6c9a64ce77083494ea7e2385e200373cc Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 27 Sep 2024 12:21:24 +0000 Subject: [PATCH 524/816] release: 1.50.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 97e4d742db..43515db369 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.50.0" + ".": "1.50.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 20be5b530b..c51de0481b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.50.1 (2024-09-27) + +Full Changelog: [v1.50.0...v1.50.1](https://github.com/openai/openai-python/compare/v1.50.0...v1.50.1) + +### Documentation + +* **helpers:** fix chat completion anchor ([#1753](https://github.com/openai/openai-python/issues/1753)) ([956d4e8](https://github.com/openai/openai-python/commit/956d4e8e32507fbce399f4619e06daa9d37a0532)) + ## 1.50.0 (2024-09-26) Full Changelog: [v1.49.0...v1.50.0](https://github.com/openai/openai-python/compare/v1.49.0...v1.50.0) diff --git a/pyproject.toml b/pyproject.toml index f7061c5059..7ebf741165 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.50.0" +version = "1.50.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index e05b612a12..2b0fd31d26 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.50.0" # x-release-please-version +__version__ = "1.50.1" # x-release-please-version From adb6da3aeebac792766bc4d11073e90116f55a47 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Fri, 27 Sep 2024 23:51:00 +0100 Subject: [PATCH 525/816] fix(audio): correct types for transcriptions / translations (#1755) fix --- .stats.yml | 2 +- api.md | 14 +- src/openai/_utils/_reflection.py | 5 +- src/openai/resources/audio/transcriptions.py | 155 +++++++++++++++++- src/openai/resources/audio/translations.py | 142 +++++++++++++++- src/openai/types/audio/__init__.py | 6 + .../audio/transcription_create_response.py | 11 ++ .../types/audio/transcription_segment.py | 49 ++++++ .../types/audio/transcription_verbose.py | 26 +++ src/openai/types/audio/transcription_word.py | 17 ++ .../audio/translation_create_response.py | 11 ++ src/openai/types/audio/translation_verbose.py | 22 +++ .../beta/static_file_chunking_strategy.py | 1 - .../audio/test_transcriptions.py | 18 +- .../api_resources/audio/test_translations.py | 18 +- tests/lib/test_audio.py | 83 ++++++++++ tests/utils.py | 6 +- 17 files changed, 543 insertions(+), 43 deletions(-) create mode 100644 src/openai/types/audio/transcription_create_response.py create mode 100644 src/openai/types/audio/transcription_segment.py create mode 100644 src/openai/types/audio/transcription_verbose.py create mode 100644 src/openai/types/audio/transcription_word.py create mode 100644 src/openai/types/audio/translation_create_response.py create mode 100644 src/openai/types/audio/translation_verbose.py create mode 100644 tests/lib/test_audio.py diff --git a/.stats.yml b/.stats.yml index 0998368a4c..68789976bf 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-17ddd746c775ca4d4fbe64e5621ac30756ef09c061ff6313190b6ec162222d4c.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-71e58a77027c67e003fdd1b1ac8ac11557d8bfabc7666d1a827c6b1ca8ab98b5.yml diff --git a/api.md b/api.md index 29db54f0fd..813c5cb615 100644 --- a/api.md +++ b/api.md @@ -122,24 +122,30 @@ from openai.types import AudioModel, AudioResponseFormat Types: ```python -from openai.types.audio import Transcription +from openai.types.audio import ( + Transcription, + TranscriptionSegment, + TranscriptionVerbose, + TranscriptionWord, + TranscriptionCreateResponse, +) ``` Methods: -- client.audio.transcriptions.create(\*\*params) -> Transcription +- client.audio.transcriptions.create(\*\*params) -> TranscriptionCreateResponse ## Translations Types: ```python -from openai.types.audio import Translation +from openai.types.audio import Translation, TranslationVerbose, TranslationCreateResponse ``` Methods: -- client.audio.translations.create(\*\*params) -> Translation +- client.audio.translations.create(\*\*params) -> TranslationCreateResponse ## Speech diff --git a/src/openai/_utils/_reflection.py b/src/openai/_utils/_reflection.py index 89aa712ac4..bdaca29e4a 100644 --- a/src/openai/_utils/_reflection.py +++ b/src/openai/_utils/_reflection.py @@ -15,6 +15,7 @@ def assert_signatures_in_sync( check_func: Callable[..., Any], *, exclude_params: set[str] = set(), + description: str = "", ) -> None: """Ensure that the signature of the second function matches the first.""" @@ -39,4 +40,6 @@ def assert_signatures_in_sync( continue if errors: - raise AssertionError(f"{len(errors)} errors encountered when comparing signatures:\n\n" + "\n\n".join(errors)) + raise AssertionError( + f"{len(errors)} errors encountered when comparing signatures{description}:\n\n" + "\n\n".join(errors) + ) diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index fd042d1ac3..e6596a480e 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -2,8 +2,9 @@ from __future__ import annotations -from typing import List, Union, Mapping, cast -from typing_extensions import Literal +import logging +from typing import TYPE_CHECKING, List, Union, Mapping, cast +from typing_extensions import Literal, overload, assert_never import httpx @@ -24,9 +25,12 @@ from ...types.audio_model import AudioModel from ...types.audio.transcription import Transcription from ...types.audio_response_format import AudioResponseFormat +from ...types.audio.transcription_verbose import TranscriptionVerbose __all__ = ["Transcriptions", "AsyncTranscriptions"] +log: logging.Logger = logging.getLogger("openai.audio.transcriptions") + class Transcriptions(SyncAPIResource): @cached_property @@ -48,14 +52,53 @@ def with_streaming_response(self) -> TranscriptionsWithStreamingResponse: """ return TranscriptionsWithStreamingResponse(self) + @overload + def create( + self, + *, + file: FileTypes, + model: Union[str, AudioModel], + response_format: Union[Literal["json"], NotGiven] = NOT_GIVEN, + language: str | NotGiven = NOT_GIVEN, + prompt: str | NotGiven = NOT_GIVEN, + temperature: float | NotGiven = NOT_GIVEN, + timestamp_granularities: List[Literal["word", "segment"]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Transcription: ... + + @overload + def create( + self, + *, + file: FileTypes, + model: Union[str, AudioModel], + response_format: Literal["verbose_json"], + language: str | NotGiven = NOT_GIVEN, + prompt: str | NotGiven = NOT_GIVEN, + temperature: float | NotGiven = NOT_GIVEN, + timestamp_granularities: List[Literal["word", "segment"]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> TranscriptionVerbose: ... + + @overload def create( self, *, file: FileTypes, model: Union[str, AudioModel], + response_format: Literal["text", "srt", "vtt"], language: str | NotGiven = NOT_GIVEN, prompt: str | NotGiven = NOT_GIVEN, - response_format: AudioResponseFormat | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, timestamp_granularities: List[Literal["word", "segment"]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -64,7 +107,25 @@ def create( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> Transcription: + ) -> str: ... + + def create( + self, + *, + file: FileTypes, + model: Union[str, AudioModel], + language: str | NotGiven = NOT_GIVEN, + prompt: str | NotGiven = NOT_GIVEN, + response_format: Union[AudioResponseFormat, NotGiven] = NOT_GIVEN, + temperature: float | NotGiven = NOT_GIVEN, + timestamp_granularities: List[Literal["word", "segment"]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Transcription | TranscriptionVerbose | str: """ Transcribes audio into the input language. @@ -124,14 +185,14 @@ def create( # sent to the server will contain a `boundary` parameter, e.g. # multipart/form-data; boundary=---abc-- extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} - return self._post( + return self._post( # type: ignore[return-value] "/audio/transcriptions", body=maybe_transform(body, transcription_create_params.TranscriptionCreateParams), files=files, options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), - cast_to=Transcription, + cast_to=_get_response_format_type(response_format), ) @@ -155,14 +216,15 @@ def with_streaming_response(self) -> AsyncTranscriptionsWithStreamingResponse: """ return AsyncTranscriptionsWithStreamingResponse(self) + @overload async def create( self, *, file: FileTypes, model: Union[str, AudioModel], + response_format: Union[Literal["json"], NotGiven] = NOT_GIVEN, language: str | NotGiven = NOT_GIVEN, prompt: str | NotGiven = NOT_GIVEN, - response_format: AudioResponseFormat | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, timestamp_granularities: List[Literal["word", "segment"]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -171,7 +233,63 @@ async def create( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> Transcription: + ) -> Transcription: ... + + @overload + async def create( + self, + *, + file: FileTypes, + model: Union[str, AudioModel], + response_format: Literal["verbose_json"], + language: str | NotGiven = NOT_GIVEN, + prompt: str | NotGiven = NOT_GIVEN, + temperature: float | NotGiven = NOT_GIVEN, + timestamp_granularities: List[Literal["word", "segment"]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> TranscriptionVerbose: ... + + @overload + async def create( + self, + *, + file: FileTypes, + model: Union[str, AudioModel], + response_format: Literal["text", "srt", "vtt"], + language: str | NotGiven = NOT_GIVEN, + prompt: str | NotGiven = NOT_GIVEN, + temperature: float | NotGiven = NOT_GIVEN, + timestamp_granularities: List[Literal["word", "segment"]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> str: ... + + async def create( + self, + *, + file: FileTypes, + model: Union[str, AudioModel], + language: str | NotGiven = NOT_GIVEN, + prompt: str | NotGiven = NOT_GIVEN, + response_format: Union[AudioResponseFormat, NotGiven] = NOT_GIVEN, + temperature: float | NotGiven = NOT_GIVEN, + timestamp_granularities: List[Literal["word", "segment"]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Transcription | TranscriptionVerbose | str: """ Transcribes audio into the input language. @@ -238,7 +356,7 @@ async def create( options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), - cast_to=Transcription, + cast_to=_get_response_format_type(response_format), ) @@ -276,3 +394,22 @@ def __init__(self, transcriptions: AsyncTranscriptions) -> None: self.create = async_to_streamed_response_wrapper( transcriptions.create, ) + + +def _get_response_format_type( + response_format: Literal["json", "text", "srt", "verbose_json", "vtt"] | NotGiven, +) -> type[Transcription | TranscriptionVerbose | str]: + if isinstance(response_format, NotGiven) or response_format is None: # pyright: ignore[reportUnnecessaryComparison] + return Transcription + + if response_format == "json": + return Transcription + elif response_format == "verbose_json": + return TranscriptionVerbose + elif response_format == "srt" or response_format == "text" or response_format == "vtt": + return str + elif TYPE_CHECKING: # type: ignore[unreachable] + assert_never(response_format) + else: + log.warn("Unexpected audio response format: %s", response_format) + return Transcription diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index fe08dd550e..53ab625873 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -2,7 +2,9 @@ from __future__ import annotations -from typing import Union, Mapping, cast +import logging +from typing import TYPE_CHECKING, Union, Mapping, cast +from typing_extensions import Literal, overload, assert_never import httpx @@ -23,9 +25,12 @@ from ...types.audio_model import AudioModel from ...types.audio.translation import Translation from ...types.audio_response_format import AudioResponseFormat +from ...types.audio.translation_verbose import TranslationVerbose __all__ = ["Translations", "AsyncTranslations"] +log: logging.Logger = logging.getLogger("openai.audio.transcriptions") + class Translations(SyncAPIResource): @cached_property @@ -47,13 +52,64 @@ def with_streaming_response(self) -> TranslationsWithStreamingResponse: """ return TranslationsWithStreamingResponse(self) + @overload + def create( + self, + *, + file: FileTypes, + model: Union[str, AudioModel], + response_format: Union[Literal["json"], NotGiven] = NOT_GIVEN, + prompt: str | NotGiven = NOT_GIVEN, + temperature: float | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Translation: ... + + @overload + def create( + self, + *, + file: FileTypes, + model: Union[str, AudioModel], + response_format: Literal["verbose_json"], + prompt: str | NotGiven = NOT_GIVEN, + temperature: float | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> TranslationVerbose: ... + + @overload + def create( + self, + *, + file: FileTypes, + model: Union[str, AudioModel], + response_format: Literal["text", "srt", "vtt"], + prompt: str | NotGiven = NOT_GIVEN, + temperature: float | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> str: ... + def create( self, *, file: FileTypes, model: Union[str, AudioModel], prompt: str | NotGiven = NOT_GIVEN, - response_format: AudioResponseFormat | NotGiven = NOT_GIVEN, + response_format: Union[AudioResponseFormat, NotGiven] = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -61,7 +117,7 @@ def create( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> Translation: + ) -> Translation | TranslationVerbose | str: """ Translates audio into English. @@ -108,14 +164,14 @@ def create( # sent to the server will contain a `boundary` parameter, e.g. # multipart/form-data; boundary=---abc-- extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} - return self._post( + return self._post( # type: ignore[return-value] "/audio/translations", body=maybe_transform(body, translation_create_params.TranslationCreateParams), files=files, options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), - cast_to=Translation, + cast_to=_get_response_format_type(response_format), ) @@ -139,13 +195,14 @@ def with_streaming_response(self) -> AsyncTranslationsWithStreamingResponse: """ return AsyncTranslationsWithStreamingResponse(self) + @overload async def create( self, *, file: FileTypes, model: Union[str, AudioModel], + response_format: Union[Literal["json"], NotGiven] = NOT_GIVEN, prompt: str | NotGiven = NOT_GIVEN, - response_format: AudioResponseFormat | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -153,7 +210,57 @@ async def create( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> Translation: + ) -> Translation: ... + + @overload + async def create( + self, + *, + file: FileTypes, + model: Union[str, AudioModel], + response_format: Literal["verbose_json"], + prompt: str | NotGiven = NOT_GIVEN, + temperature: float | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> TranslationVerbose: ... + + @overload + async def create( + self, + *, + file: FileTypes, + model: Union[str, AudioModel], + response_format: Literal["text", "srt", "vtt"], + prompt: str | NotGiven = NOT_GIVEN, + temperature: float | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> str: ... + + async def create( + self, + *, + file: FileTypes, + model: Union[str, AudioModel], + prompt: str | NotGiven = NOT_GIVEN, + response_format: Union[AudioResponseFormat, NotGiven] = NOT_GIVEN, + temperature: float | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Translation | TranslationVerbose | str: """ Translates audio into English. @@ -207,7 +314,7 @@ async def create( options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), - cast_to=Translation, + cast_to=_get_response_format_type(response_format), ) @@ -245,3 +352,22 @@ def __init__(self, translations: AsyncTranslations) -> None: self.create = async_to_streamed_response_wrapper( translations.create, ) + + +def _get_response_format_type( + response_format: Literal["json", "text", "srt", "verbose_json", "vtt"] | NotGiven, +) -> type[Translation | TranslationVerbose | str]: + if isinstance(response_format, NotGiven) or response_format is None: # pyright: ignore[reportUnnecessaryComparison] + return Translation + + if response_format == "json": + return Translation + elif response_format == "verbose_json": + return TranslationVerbose + elif response_format == "srt" or response_format == "text" or response_format == "vtt": + return str + elif TYPE_CHECKING: # type: ignore[unreachable] + assert_never(response_format) + else: + log.warn("Unexpected audio response format: %s", response_format) + return Transcription diff --git a/src/openai/types/audio/__init__.py b/src/openai/types/audio/__init__.py index 1de5c0ff82..822e0f3a8d 100644 --- a/src/openai/types/audio/__init__.py +++ b/src/openai/types/audio/__init__.py @@ -5,6 +5,12 @@ from .translation import Translation as Translation from .speech_model import SpeechModel as SpeechModel from .transcription import Transcription as Transcription +from .transcription_word import TranscriptionWord as TranscriptionWord +from .translation_verbose import TranslationVerbose as TranslationVerbose from .speech_create_params import SpeechCreateParams as SpeechCreateParams +from .transcription_segment import TranscriptionSegment as TranscriptionSegment +from .transcription_verbose import TranscriptionVerbose as TranscriptionVerbose from .translation_create_params import TranslationCreateParams as TranslationCreateParams from .transcription_create_params import TranscriptionCreateParams as TranscriptionCreateParams +from .translation_create_response import TranslationCreateResponse as TranslationCreateResponse +from .transcription_create_response import TranscriptionCreateResponse as TranscriptionCreateResponse diff --git a/src/openai/types/audio/transcription_create_response.py b/src/openai/types/audio/transcription_create_response.py new file mode 100644 index 0000000000..2f7bed8114 --- /dev/null +++ b/src/openai/types/audio/transcription_create_response.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import TypeAlias + +from .transcription import Transcription +from .transcription_verbose import TranscriptionVerbose + +__all__ = ["TranscriptionCreateResponse"] + +TranscriptionCreateResponse: TypeAlias = Union[Transcription, TranscriptionVerbose] diff --git a/src/openai/types/audio/transcription_segment.py b/src/openai/types/audio/transcription_segment.py new file mode 100644 index 0000000000..522c401ebb --- /dev/null +++ b/src/openai/types/audio/transcription_segment.py @@ -0,0 +1,49 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List + +from ..._models import BaseModel + +__all__ = ["TranscriptionSegment"] + + +class TranscriptionSegment(BaseModel): + id: int + """Unique identifier of the segment.""" + + avg_logprob: float + """Average logprob of the segment. + + If the value is lower than -1, consider the logprobs failed. + """ + + compression_ratio: float + """Compression ratio of the segment. + + If the value is greater than 2.4, consider the compression failed. + """ + + end: float + """End time of the segment in seconds.""" + + no_speech_prob: float + """Probability of no speech in the segment. + + If the value is higher than 1.0 and the `avg_logprob` is below -1, consider this + segment silent. + """ + + seek: int + """Seek offset of the segment.""" + + start: float + """Start time of the segment in seconds.""" + + temperature: float + """Temperature parameter used for generating the segment.""" + + text: str + """Text content of the segment.""" + + tokens: List[int] + """Array of token IDs for the text content.""" diff --git a/src/openai/types/audio/transcription_verbose.py b/src/openai/types/audio/transcription_verbose.py new file mode 100644 index 0000000000..3b18fa4871 --- /dev/null +++ b/src/openai/types/audio/transcription_verbose.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from ..._models import BaseModel +from .transcription_word import TranscriptionWord +from .transcription_segment import TranscriptionSegment + +__all__ = ["TranscriptionVerbose"] + + +class TranscriptionVerbose(BaseModel): + duration: str + """The duration of the input audio.""" + + language: str + """The language of the input audio.""" + + text: str + """The transcribed text.""" + + segments: Optional[List[TranscriptionSegment]] = None + """Segments of the transcribed text and their corresponding details.""" + + words: Optional[List[TranscriptionWord]] = None + """Extracted words and their corresponding timestamps.""" diff --git a/src/openai/types/audio/transcription_word.py b/src/openai/types/audio/transcription_word.py new file mode 100644 index 0000000000..969da32509 --- /dev/null +++ b/src/openai/types/audio/transcription_word.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +from ..._models import BaseModel + +__all__ = ["TranscriptionWord"] + + +class TranscriptionWord(BaseModel): + end: float + """End time of the word in seconds.""" + + start: float + """Start time of the word in seconds.""" + + word: str + """The text content of the word.""" diff --git a/src/openai/types/audio/translation_create_response.py b/src/openai/types/audio/translation_create_response.py new file mode 100644 index 0000000000..9953813c08 --- /dev/null +++ b/src/openai/types/audio/translation_create_response.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import TypeAlias + +from .translation import Translation +from .translation_verbose import TranslationVerbose + +__all__ = ["TranslationCreateResponse"] + +TranslationCreateResponse: TypeAlias = Union[Translation, TranslationVerbose] diff --git a/src/openai/types/audio/translation_verbose.py b/src/openai/types/audio/translation_verbose.py new file mode 100644 index 0000000000..5901ae7535 --- /dev/null +++ b/src/openai/types/audio/translation_verbose.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional + +from ..._models import BaseModel +from .transcription_segment import TranscriptionSegment + +__all__ = ["TranslationVerbose"] + + +class TranslationVerbose(BaseModel): + duration: str + """The duration of the input audio.""" + + language: str + """The language of the output translation (always `english`).""" + + text: str + """The translated text.""" + + segments: Optional[List[TranscriptionSegment]] = None + """Segments of the translated text and their corresponding details.""" diff --git a/src/openai/types/beta/static_file_chunking_strategy.py b/src/openai/types/beta/static_file_chunking_strategy.py index ba80e1a2b9..6080093517 100644 --- a/src/openai/types/beta/static_file_chunking_strategy.py +++ b/src/openai/types/beta/static_file_chunking_strategy.py @@ -1,7 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from ..._models import BaseModel __all__ = ["StaticFileChunkingStrategy"] diff --git a/tests/api_resources/audio/test_transcriptions.py b/tests/api_resources/audio/test_transcriptions.py index ba8e9e4099..0fa91eb152 100644 --- a/tests/api_resources/audio/test_transcriptions.py +++ b/tests/api_resources/audio/test_transcriptions.py @@ -9,7 +9,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai.types.audio import Transcription +from openai.types.audio import TranscriptionCreateResponse base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") @@ -23,7 +23,7 @@ def test_method_create(self, client: OpenAI) -> None: file=b"raw file contents", model="whisper-1", ) - assert_matches_type(Transcription, transcription, path=["response"]) + assert_matches_type(TranscriptionCreateResponse, transcription, path=["response"]) @parametrize def test_method_create_with_all_params(self, client: OpenAI) -> None: @@ -36,7 +36,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: temperature=0, timestamp_granularities=["word", "segment"], ) - assert_matches_type(Transcription, transcription, path=["response"]) + assert_matches_type(TranscriptionCreateResponse, transcription, path=["response"]) @parametrize def test_raw_response_create(self, client: OpenAI) -> None: @@ -48,7 +48,7 @@ def test_raw_response_create(self, client: OpenAI) -> None: assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" transcription = response.parse() - assert_matches_type(Transcription, transcription, path=["response"]) + assert_matches_type(TranscriptionCreateResponse, transcription, path=["response"]) @parametrize def test_streaming_response_create(self, client: OpenAI) -> None: @@ -60,7 +60,7 @@ def test_streaming_response_create(self, client: OpenAI) -> None: assert response.http_request.headers.get("X-Stainless-Lang") == "python" transcription = response.parse() - assert_matches_type(Transcription, transcription, path=["response"]) + assert_matches_type(TranscriptionCreateResponse, transcription, path=["response"]) assert cast(Any, response.is_closed) is True @@ -74,7 +74,7 @@ async def test_method_create(self, async_client: AsyncOpenAI) -> None: file=b"raw file contents", model="whisper-1", ) - assert_matches_type(Transcription, transcription, path=["response"]) + assert_matches_type(TranscriptionCreateResponse, transcription, path=["response"]) @parametrize async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: @@ -87,7 +87,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> temperature=0, timestamp_granularities=["word", "segment"], ) - assert_matches_type(Transcription, transcription, path=["response"]) + assert_matches_type(TranscriptionCreateResponse, transcription, path=["response"]) @parametrize async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: @@ -99,7 +99,7 @@ async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" transcription = response.parse() - assert_matches_type(Transcription, transcription, path=["response"]) + assert_matches_type(TranscriptionCreateResponse, transcription, path=["response"]) @parametrize async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: @@ -111,6 +111,6 @@ async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> Non assert response.http_request.headers.get("X-Stainless-Lang") == "python" transcription = await response.parse() - assert_matches_type(Transcription, transcription, path=["response"]) + assert_matches_type(TranscriptionCreateResponse, transcription, path=["response"]) assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/audio/test_translations.py b/tests/api_resources/audio/test_translations.py index b048a1af12..e12ab7e6c0 100644 --- a/tests/api_resources/audio/test_translations.py +++ b/tests/api_resources/audio/test_translations.py @@ -9,7 +9,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai.types.audio import Translation +from openai.types.audio import TranslationCreateResponse base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") @@ -23,7 +23,7 @@ def test_method_create(self, client: OpenAI) -> None: file=b"raw file contents", model="whisper-1", ) - assert_matches_type(Translation, translation, path=["response"]) + assert_matches_type(TranslationCreateResponse, translation, path=["response"]) @parametrize def test_method_create_with_all_params(self, client: OpenAI) -> None: @@ -34,7 +34,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: response_format="json", temperature=0, ) - assert_matches_type(Translation, translation, path=["response"]) + assert_matches_type(TranslationCreateResponse, translation, path=["response"]) @parametrize def test_raw_response_create(self, client: OpenAI) -> None: @@ -46,7 +46,7 @@ def test_raw_response_create(self, client: OpenAI) -> None: assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" translation = response.parse() - assert_matches_type(Translation, translation, path=["response"]) + assert_matches_type(TranslationCreateResponse, translation, path=["response"]) @parametrize def test_streaming_response_create(self, client: OpenAI) -> None: @@ -58,7 +58,7 @@ def test_streaming_response_create(self, client: OpenAI) -> None: assert response.http_request.headers.get("X-Stainless-Lang") == "python" translation = response.parse() - assert_matches_type(Translation, translation, path=["response"]) + assert_matches_type(TranslationCreateResponse, translation, path=["response"]) assert cast(Any, response.is_closed) is True @@ -72,7 +72,7 @@ async def test_method_create(self, async_client: AsyncOpenAI) -> None: file=b"raw file contents", model="whisper-1", ) - assert_matches_type(Translation, translation, path=["response"]) + assert_matches_type(TranslationCreateResponse, translation, path=["response"]) @parametrize async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: @@ -83,7 +83,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> response_format="json", temperature=0, ) - assert_matches_type(Translation, translation, path=["response"]) + assert_matches_type(TranslationCreateResponse, translation, path=["response"]) @parametrize async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: @@ -95,7 +95,7 @@ async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" translation = response.parse() - assert_matches_type(Translation, translation, path=["response"]) + assert_matches_type(TranslationCreateResponse, translation, path=["response"]) @parametrize async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: @@ -107,6 +107,6 @@ async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> Non assert response.http_request.headers.get("X-Stainless-Lang") == "python" translation = await response.parse() - assert_matches_type(Translation, translation, path=["response"]) + assert_matches_type(TranslationCreateResponse, translation, path=["response"]) assert cast(Any, response.is_closed) is True diff --git a/tests/lib/test_audio.py b/tests/lib/test_audio.py new file mode 100644 index 0000000000..0f53b316ba --- /dev/null +++ b/tests/lib/test_audio.py @@ -0,0 +1,83 @@ +from __future__ import annotations + +import sys +import inspect +import typing_extensions +from typing import get_args + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import evaluate_forwardref +from openai._utils import assert_signatures_in_sync +from openai._compat import is_literal_type +from openai._utils._typing import is_union_type +from openai.types.audio_response_format import AudioResponseFormat + + +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +def test_translation_create_overloads_in_sync(sync: bool, client: OpenAI, async_client: AsyncOpenAI) -> None: + checking_client: OpenAI | AsyncOpenAI = client if sync else async_client + + fn = checking_client.audio.translations.create + overload_response_formats: set[str] = set() + + for i, overload in enumerate(typing_extensions.get_overloads(fn)): + assert_signatures_in_sync( + fn, + overload, + exclude_params={"response_format"}, + description=f" for overload {i}", + ) + + sig = inspect.signature(overload) + typ = evaluate_forwardref( + sig.parameters["response_format"].annotation, + globalns=sys.modules[fn.__module__].__dict__, + ) + if is_union_type(typ): + for arg in get_args(typ): + if not is_literal_type(arg): + continue + + overload_response_formats.update(get_args(arg)) + elif is_literal_type(typ): + overload_response_formats.update(get_args(typ)) + + src_response_formats: set[str] = set(get_args(AudioResponseFormat)) + diff = src_response_formats.difference(overload_response_formats) + assert len(diff) == 0, f"some response format options don't have overloads" + + +@pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) +def test_transcription_create_overloads_in_sync(sync: bool, client: OpenAI, async_client: AsyncOpenAI) -> None: + checking_client: OpenAI | AsyncOpenAI = client if sync else async_client + + fn = checking_client.audio.transcriptions.create + overload_response_formats: set[str] = set() + + for i, overload in enumerate(typing_extensions.get_overloads(fn)): + assert_signatures_in_sync( + fn, + overload, + exclude_params={"response_format"}, + description=f" for overload {i}", + ) + + sig = inspect.signature(overload) + typ = evaluate_forwardref( + sig.parameters["response_format"].annotation, + globalns=sys.modules[fn.__module__].__dict__, + ) + if is_union_type(typ): + for arg in get_args(typ): + if not is_literal_type(arg): + continue + + overload_response_formats.update(get_args(arg)) + elif is_literal_type(typ): + overload_response_formats.update(get_args(typ)) + + src_response_formats: set[str] = set(get_args(AudioResponseFormat)) + diff = src_response_formats.difference(overload_response_formats) + assert len(diff) == 0, f"some response format options don't have overloads" diff --git a/tests/utils.py b/tests/utils.py index 8d5397f28e..16948a66f2 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -5,7 +5,7 @@ import inspect import traceback import contextlib -from typing import Any, TypeVar, Iterator, cast +from typing import Any, TypeVar, Iterator, ForwardRef, cast from datetime import date, datetime from typing_extensions import Literal, get_args, get_origin, assert_type @@ -26,6 +26,10 @@ BaseModelT = TypeVar("BaseModelT", bound=BaseModel) +def evaluate_forwardref(forwardref: ForwardRef, globalns: dict[str, Any]) -> type: + return eval(str(forwardref), globalns) # type: ignore[no-any-return] + + def assert_matches_model(model: type[BaseModelT], value: BaseModelT, *, path: list[str]) -> bool: for name, field in get_model_fields(model).items(): field_value = getattr(value, name) From aeaed488352274a9ca86c834eeb618d732989518 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 27 Sep 2024 23:04:57 +0000 Subject: [PATCH 526/816] release: 1.50.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 43515db369..b11d9e721d 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.50.1" + ".": "1.50.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index c51de0481b..37571051de 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.50.2 (2024-09-27) + +Full Changelog: [v1.50.1...v1.50.2](https://github.com/openai/openai-python/compare/v1.50.1...v1.50.2) + +### Bug Fixes + +* **audio:** correct types for transcriptions / translations ([#1755](https://github.com/openai/openai-python/issues/1755)) ([76c1f3f](https://github.com/openai/openai-python/commit/76c1f3f318b68003aae124c02efc4547a398a864)) + ## 1.50.1 (2024-09-27) Full Changelog: [v1.50.0...v1.50.1](https://github.com/openai/openai-python/compare/v1.50.0...v1.50.1) diff --git a/pyproject.toml b/pyproject.toml index 7ebf741165..90b8c8518c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.50.1" +version = "1.50.2" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 2b0fd31d26..641dd21648 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.50.1" # x-release-please-version +__version__ = "1.50.2" # x-release-please-version From 3b4821ff79433ba268ef66190747c14e1f1aeb71 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 30 Sep 2024 10:19:21 -0400 Subject: [PATCH 527/816] chore(internal): remove ds store --- .DS_Store | Bin 6148 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index c88a062b05be4fd1d362b3e4c6a7481e718b69d0..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeH~O$x$5422WzLU7Zi%h`AUZ!n0Spcima5J4*Vx1OW>k_m#k8KJGkN^pg011%5 z4-v3?8#bF)Wh4O-Ab}?V`#vPNX$~z_{nLTqBLK8P*$r!-C7{U)&>UK-q5{*H9yD6j z#}KP~J2b_)99pW@cF`C;crrWIXQgOGwy`I%~QMGk}L;X0y%TE9jyNVZZH|!@{KyzrRiVBQB0*--!1inh( E0rZ6u#{d8T From 4bd80b9f70773ae3a24874f2a82043db0ae7ef77 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 30 Sep 2024 14:51:54 +0000 Subject: [PATCH 528/816] chore(docs): fix maxium typo (#1762) --- .stats.yml | 2 +- src/openai/resources/beta/assistants.py | 8 ++++---- src/openai/resources/beta/threads/messages.py | 8 ++++---- .../resources/beta/threads/runs/runs.py | 16 +++++++-------- src/openai/resources/beta/threads/threads.py | 20 +++++++++---------- .../beta/vector_stores/vector_stores.py | 8 ++++---- src/openai/types/batch.py | 2 +- src/openai/types/beta/assistant.py | 2 +- .../types/beta/assistant_create_params.py | 4 ++-- .../types/beta/assistant_update_params.py | 2 +- src/openai/types/beta/thread.py | 2 +- .../beta/thread_create_and_run_params.py | 8 ++++---- src/openai/types/beta/thread_create_params.py | 6 +++--- src/openai/types/beta/thread_update_params.py | 2 +- src/openai/types/beta/threads/message.py | 2 +- .../beta/threads/message_create_params.py | 2 +- .../beta/threads/message_update_params.py | 2 +- src/openai/types/beta/threads/run.py | 2 +- .../types/beta/threads/run_create_params.py | 4 ++-- .../types/beta/threads/run_update_params.py | 2 +- .../types/beta/threads/runs/run_step.py | 2 +- src/openai/types/beta/vector_store.py | 2 +- .../types/beta/vector_store_create_params.py | 2 +- .../types/beta/vector_store_update_params.py | 2 +- 24 files changed, 56 insertions(+), 56 deletions(-) diff --git a/.stats.yml b/.stats.yml index 68789976bf..67778eef99 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-71e58a77027c67e003fdd1b1ac8ac11557d8bfabc7666d1a827c6b1ca8ab98b5.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-8ad878332083dd506a478a293db78dc9e7b1b2124f2682e1d991225bc5bbcc3b.yml diff --git a/src/openai/resources/beta/assistants.py b/src/openai/resources/beta/assistants.py index 5d8c6ec331..2ebef183b6 100644 --- a/src/openai/resources/beta/assistants.py +++ b/src/openai/resources/beta/assistants.py @@ -89,7 +89,7 @@ def create( metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. name: The name of the assistant. The maximum length is 256 characters. @@ -233,7 +233,7 @@ def update( metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. model: ID of the model to use. You can use the @@ -475,7 +475,7 @@ async def create( metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. name: The name of the assistant. The maximum length is 256 characters. @@ -619,7 +619,7 @@ async def update( metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. model: ID of the model to use. You can use the diff --git a/src/openai/resources/beta/threads/messages.py b/src/openai/resources/beta/threads/messages.py index 4901174329..de7ebcaf4d 100644 --- a/src/openai/resources/beta/threads/messages.py +++ b/src/openai/resources/beta/threads/messages.py @@ -82,7 +82,7 @@ def create( metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. extra_headers: Send extra headers @@ -169,7 +169,7 @@ def update( Args: metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. extra_headers: Send extra headers @@ -356,7 +356,7 @@ async def create( metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. extra_headers: Send extra headers @@ -443,7 +443,7 @@ async def update( Args: metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. extra_headers: Send extra headers diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index a4cbcc57e4..287c0ecf24 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -149,7 +149,7 @@ def create( metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to @@ -293,7 +293,7 @@ def create( metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to @@ -433,7 +433,7 @@ def create( metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to @@ -623,7 +623,7 @@ def update( Args: metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. extra_headers: Send extra headers @@ -1511,7 +1511,7 @@ async def create( metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to @@ -1655,7 +1655,7 @@ async def create( metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to @@ -1795,7 +1795,7 @@ async def create( metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to @@ -1986,7 +1986,7 @@ async def update( Args: metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. extra_headers: Send extra headers diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index acc0fe9bda..3b8851c03b 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -111,7 +111,7 @@ def create( metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. tool_resources: A set of resources that are made available to the assistant's tools in this @@ -197,7 +197,7 @@ def update( Args: metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. tool_resources: A set of resources that are made available to the assistant's tools in this @@ -317,7 +317,7 @@ def create_and_run( metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to @@ -451,7 +451,7 @@ def create_and_run( metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to @@ -581,7 +581,7 @@ def create_and_run( metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to @@ -945,7 +945,7 @@ async def create( metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. tool_resources: A set of resources that are made available to the assistant's tools in this @@ -1031,7 +1031,7 @@ async def update( Args: metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. tool_resources: A set of resources that are made available to the assistant's tools in this @@ -1151,7 +1151,7 @@ async def create_and_run( metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to @@ -1285,7 +1285,7 @@ async def create_and_run( metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to @@ -1415,7 +1415,7 @@ async def create_and_run( metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to diff --git a/src/openai/resources/beta/vector_stores/vector_stores.py b/src/openai/resources/beta/vector_stores/vector_stores.py index 06e26852b4..d69add7b26 100644 --- a/src/openai/resources/beta/vector_stores/vector_stores.py +++ b/src/openai/resources/beta/vector_stores/vector_stores.py @@ -105,7 +105,7 @@ def create( metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. name: The name of the vector store. @@ -193,7 +193,7 @@ def update( metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. name: The name of the vector store. @@ -383,7 +383,7 @@ async def create( metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. name: The name of the vector store. @@ -471,7 +471,7 @@ async def update( metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maxium of 512 + can be a maximum of 64 characters long and values can be a maximum of 512 characters long. name: The name of the vector store. diff --git a/src/openai/types/batch.py b/src/openai/types/batch.py index 90f6d79572..ac3d7ea119 100644 --- a/src/openai/types/batch.py +++ b/src/openai/types/batch.py @@ -75,7 +75,7 @@ class Batch(BaseModel): This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be - a maxium of 512 characters long. + a maximum of 512 characters long. """ output_file_id: Optional[str] = None diff --git a/src/openai/types/beta/assistant.py b/src/openai/types/beta/assistant.py index b4da08745d..ea97de440f 100644 --- a/src/openai/types/beta/assistant.py +++ b/src/openai/types/beta/assistant.py @@ -56,7 +56,7 @@ class Assistant(BaseModel): This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be - a maxium of 512 characters long. + a maximum of 512 characters long. """ model: str diff --git a/src/openai/types/beta/assistant_create_params.py b/src/openai/types/beta/assistant_create_params.py index eca4da0a2b..e11f842f05 100644 --- a/src/openai/types/beta/assistant_create_params.py +++ b/src/openai/types/beta/assistant_create_params.py @@ -44,7 +44,7 @@ class AssistantCreateParams(TypedDict, total=False): This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be - a maxium of 512 characters long. + a maximum of 512 characters long. """ name: Optional[str] @@ -135,7 +135,7 @@ class ToolResourcesFileSearchVectorStore(TypedDict, total=False): This can be useful for storing additional information about the vector store in a structured format. Keys can be a maximum of 64 characters long and values can - be a maxium of 512 characters long. + be a maximum of 512 characters long. """ diff --git a/src/openai/types/beta/assistant_update_params.py b/src/openai/types/beta/assistant_update_params.py index 5396233937..c4598df507 100644 --- a/src/openai/types/beta/assistant_update_params.py +++ b/src/openai/types/beta/assistant_update_params.py @@ -26,7 +26,7 @@ class AssistantUpdateParams(TypedDict, total=False): This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be - a maxium of 512 characters long. + a maximum of 512 characters long. """ model: str diff --git a/src/openai/types/beta/thread.py b/src/openai/types/beta/thread.py index 6f7a6c7d0c..37d50ccb93 100644 --- a/src/openai/types/beta/thread.py +++ b/src/openai/types/beta/thread.py @@ -45,7 +45,7 @@ class Thread(BaseModel): This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be - a maxium of 512 characters long. + a maximum of 512 characters long. """ object: Literal["thread"] diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index 20d525fa1a..64ee6a8710 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -72,7 +72,7 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be - a maxium of 512 characters long. + a maximum of 512 characters long. """ model: Union[str, ChatModel, None] @@ -202,7 +202,7 @@ class ThreadMessage(TypedDict, total=False): This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be - a maxium of 512 characters long. + a maximum of 512 characters long. """ @@ -235,7 +235,7 @@ class ThreadToolResourcesFileSearchVectorStore(TypedDict, total=False): This can be useful for storing additional information about the vector store in a structured format. Keys can be a maximum of 64 characters long and values can - be a maxium of 512 characters long. + be a maximum of 512 characters long. """ @@ -275,7 +275,7 @@ class Thread(TypedDict, total=False): This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be - a maxium of 512 characters long. + a maximum of 512 characters long. """ tool_resources: Optional[ThreadToolResources] diff --git a/src/openai/types/beta/thread_create_params.py b/src/openai/types/beta/thread_create_params.py index 729164b481..3ac6c7d69b 100644 --- a/src/openai/types/beta/thread_create_params.py +++ b/src/openai/types/beta/thread_create_params.py @@ -34,7 +34,7 @@ class ThreadCreateParams(TypedDict, total=False): This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be - a maxium of 512 characters long. + a maximum of 512 characters long. """ tool_resources: Optional[ToolResources] @@ -83,7 +83,7 @@ class Message(TypedDict, total=False): This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be - a maxium of 512 characters long. + a maximum of 512 characters long. """ @@ -116,7 +116,7 @@ class ToolResourcesFileSearchVectorStore(TypedDict, total=False): This can be useful for storing additional information about the vector store in a structured format. Keys can be a maximum of 64 characters long and values can - be a maxium of 512 characters long. + be a maximum of 512 characters long. """ diff --git a/src/openai/types/beta/thread_update_params.py b/src/openai/types/beta/thread_update_params.py index 7210ab77c9..78c5ec4f2e 100644 --- a/src/openai/types/beta/thread_update_params.py +++ b/src/openai/types/beta/thread_update_params.py @@ -14,7 +14,7 @@ class ThreadUpdateParams(TypedDict, total=False): This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be - a maxium of 512 characters long. + a maximum of 512 characters long. """ tool_resources: Optional[ToolResources] diff --git a/src/openai/types/beta/threads/message.py b/src/openai/types/beta/threads/message.py index 298a1d4273..63c5c4800a 100644 --- a/src/openai/types/beta/threads/message.py +++ b/src/openai/types/beta/threads/message.py @@ -71,7 +71,7 @@ class Message(BaseModel): This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be - a maxium of 512 characters long. + a maximum of 512 characters long. """ object: Literal["thread.message"] diff --git a/src/openai/types/beta/threads/message_create_params.py b/src/openai/types/beta/threads/message_create_params.py index 2b450deb5d..2c4edfdf71 100644 --- a/src/openai/types/beta/threads/message_create_params.py +++ b/src/openai/types/beta/threads/message_create_params.py @@ -32,7 +32,7 @@ class MessageCreateParams(TypedDict, total=False): This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be - a maxium of 512 characters long. + a maximum of 512 characters long. """ diff --git a/src/openai/types/beta/threads/message_update_params.py b/src/openai/types/beta/threads/message_update_params.py index 7000f33122..e8f8cc910c 100644 --- a/src/openai/types/beta/threads/message_update_params.py +++ b/src/openai/types/beta/threads/message_update_params.py @@ -16,5 +16,5 @@ class MessageUpdateParams(TypedDict, total=False): This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be - a maxium of 512 characters long. + a maximum of 512 characters long. """ diff --git a/src/openai/types/beta/threads/run.py b/src/openai/types/beta/threads/run.py index 5abc1de295..e8f2b74dee 100644 --- a/src/openai/types/beta/threads/run.py +++ b/src/openai/types/beta/threads/run.py @@ -138,7 +138,7 @@ class Run(BaseModel): This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be - a maxium of 512 characters long. + a maximum of 512 characters long. """ model: str diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index 824cb1a041..9767b142e1 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -85,7 +85,7 @@ class RunCreateParamsBase(TypedDict, total=False): This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be - a maxium of 512 characters long. + a maximum of 512 characters long. """ model: Union[str, ChatModel, None] @@ -204,7 +204,7 @@ class AdditionalMessage(TypedDict, total=False): This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be - a maxium of 512 characters long. + a maximum of 512 characters long. """ diff --git a/src/openai/types/beta/threads/run_update_params.py b/src/openai/types/beta/threads/run_update_params.py index e595eac882..cb4f053645 100644 --- a/src/openai/types/beta/threads/run_update_params.py +++ b/src/openai/types/beta/threads/run_update_params.py @@ -16,5 +16,5 @@ class RunUpdateParams(TypedDict, total=False): This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be - a maxium of 512 characters long. + a maximum of 512 characters long. """ diff --git a/src/openai/types/beta/threads/runs/run_step.py b/src/openai/types/beta/threads/runs/run_step.py index e3163c508b..0445ae360d 100644 --- a/src/openai/types/beta/threads/runs/run_step.py +++ b/src/openai/types/beta/threads/runs/run_step.py @@ -75,7 +75,7 @@ class RunStep(BaseModel): This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be - a maxium of 512 characters long. + a maximum of 512 characters long. """ object: Literal["thread.run.step"] diff --git a/src/openai/types/beta/vector_store.py b/src/openai/types/beta/vector_store.py index 488961b444..2d3ceea80c 100644 --- a/src/openai/types/beta/vector_store.py +++ b/src/openai/types/beta/vector_store.py @@ -53,7 +53,7 @@ class VectorStore(BaseModel): This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be - a maxium of 512 characters long. + a maximum of 512 characters long. """ name: str diff --git a/src/openai/types/beta/vector_store_create_params.py b/src/openai/types/beta/vector_store_create_params.py index a8f03a89b9..4fc7c38927 100644 --- a/src/openai/types/beta/vector_store_create_params.py +++ b/src/openai/types/beta/vector_store_create_params.py @@ -33,7 +33,7 @@ class VectorStoreCreateParams(TypedDict, total=False): This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be - a maxium of 512 characters long. + a maximum of 512 characters long. """ name: str diff --git a/src/openai/types/beta/vector_store_update_params.py b/src/openai/types/beta/vector_store_update_params.py index 0f9593e476..ff6c068efb 100644 --- a/src/openai/types/beta/vector_store_update_params.py +++ b/src/openai/types/beta/vector_store_update_params.py @@ -17,7 +17,7 @@ class VectorStoreUpdateParams(TypedDict, total=False): This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be - a maxium of 512 characters long. + a maximum of 512 characters long. """ name: Optional[str] From 94bfe19aaf5a96aed37e6405684743a39892092f Mon Sep 17 00:00:00 2001 From: Laziz Turakulov <4857092+LazaUK@users.noreply.github.com> Date: Mon, 30 Sep 2024 22:19:57 +0100 Subject: [PATCH 529/816] docs(helpers): fix method name typo (#1764) --- helpers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/helpers.md b/helpers.md index 65515df973..3f3fafa45c 100644 --- a/helpers.md +++ b/helpers.md @@ -508,7 +508,7 @@ The polling methods are: ```python client.beta.threads.create_and_run_poll(...) client.beta.threads.runs.create_and_poll(...) -client.beta.threads.runs.submit_tool_ouptputs_and_poll(...) +client.beta.threads.runs.submit_tool_outputs_and_poll(...) client.beta.vector_stores.files.upload_and_poll(...) client.beta.vector_stores.files.create_and_poll(...) client.beta.vector_stores.file_batches.create_and_poll(...) From 7c8c11158c4e0b63fef495c32447d6e31870073f Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Tue, 1 Oct 2024 12:10:34 -0400 Subject: [PATCH 530/816] feat(api): support storing chat completions, enabling evals and model distillation in the dashboard Learn more at http://openai.com/devday2024 --- .stats.yml | 2 +- src/openai/resources/beta/chat/completions.py | 16 +++ src/openai/resources/chat/completions.py | 104 ++++++++++++++++-- .../types/chat/completion_create_params.py | 18 ++- src/openai/types/chat_model.py | 1 + src/openai/types/completion_usage.py | 16 ++- tests/api_resources/chat/test_completions.py | 8 ++ tests/lib/chat/test_completions.py | 18 ++- tests/lib/chat/test_completions_streaming.py | 3 +- 9 files changed, 164 insertions(+), 22 deletions(-) diff --git a/.stats.yml b/.stats.yml index 67778eef99..ece287351b 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-8ad878332083dd506a478a293db78dc9e7b1b2124f2682e1d991225bc5bbcc3b.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-52b934aee6468039ec7f4ce046a282b5fbce114afc708e70f17121df654f71da.yml diff --git a/src/openai/resources/beta/chat/completions.py b/src/openai/resources/beta/chat/completions.py index da6f189929..c747464072 100644 --- a/src/openai/resources/beta/chat/completions.py +++ b/src/openai/resources/beta/chat/completions.py @@ -69,12 +69,14 @@ def parse( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, @@ -158,6 +160,7 @@ def parser(raw_completion: ChatCompletion) -> ParsedChatCompletion[ResponseForma "logprobs": logprobs, "max_completion_tokens": max_completion_tokens, "max_tokens": max_tokens, + "metadata": metadata, "n": n, "parallel_tool_calls": parallel_tool_calls, "presence_penalty": presence_penalty, @@ -165,6 +168,7 @@ def parser(raw_completion: ChatCompletion) -> ParsedChatCompletion[ResponseForma "seed": seed, "service_tier": service_tier, "stop": stop, + "store": store, "stream": False, "stream_options": stream_options, "temperature": temperature, @@ -202,12 +206,14 @@ def stream( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, @@ -262,11 +268,13 @@ def stream( logprobs=logprobs, max_completion_tokens=max_completion_tokens, max_tokens=max_tokens, + metadata=metadata, n=n, parallel_tool_calls=parallel_tool_calls, presence_penalty=presence_penalty, seed=seed, service_tier=service_tier, + store=store, stop=stop, stream_options=stream_options, temperature=temperature, @@ -320,12 +328,14 @@ async def parse( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, @@ -409,12 +419,14 @@ def parser(raw_completion: ChatCompletion) -> ParsedChatCompletion[ResponseForma "logprobs": logprobs, "max_completion_tokens": max_completion_tokens, "max_tokens": max_tokens, + "metadata": metadata, "n": n, "parallel_tool_calls": parallel_tool_calls, "presence_penalty": presence_penalty, "response_format": _type_to_response_format(response_format), "seed": seed, "service_tier": service_tier, + "store": store, "stop": stop, "stream": False, "stream_options": stream_options, @@ -453,12 +465,14 @@ def stream( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, @@ -514,12 +528,14 @@ def stream( logprobs=logprobs, max_completion_tokens=max_completion_tokens, max_tokens=max_tokens, + metadata=metadata, n=n, parallel_tool_calls=parallel_tool_calls, presence_penalty=presence_penalty, seed=seed, service_tier=service_tier, stop=stop, + store=store, stream_options=stream_options, temperature=temperature, tool_choice=tool_choice, diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index 05cfaacd83..c8080afaa1 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -66,6 +66,7 @@ def create( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -73,6 +74,7 @@ def create( seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -92,8 +94,12 @@ def create( Creates a model response for the given chat conversation. Args: - messages: A list of messages comprising the conversation so far. - [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models). + messages: A list of messages comprising the conversation so far. Depending on the + [model](https://platform.openai.com/docs/models) you use, different message + types (modalities) are supported, like + [text](https://platform.openai.com/docs/guides/text-generation), + [images](https://platform.openai.com/docs/guides/vision), and + [audio](https://platform.openai.com/docs/guides/audio). model: ID of the model to use. See the [model endpoint compatibility](https://platform.openai.com/docs/models/model-endpoint-compatibility) @@ -145,6 +151,9 @@ def create( compatible with [o1 series models](https://platform.openai.com/docs/guides/reasoning). + metadata: Developer-defined tags and values used for filtering completions in the + [dashboard](https://platform.openai.com/completions). + n: How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs. @@ -204,6 +213,9 @@ def create( stop: Up to 4 sequences where the API will stop generating further tokens. + store: Whether or not to store the output of this completion request for traffic + logging in the [dashboard](https://platform.openai.com/completions). + stream: If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) @@ -271,6 +283,7 @@ def create( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -278,6 +291,7 @@ def create( seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, @@ -296,8 +310,12 @@ def create( Creates a model response for the given chat conversation. Args: - messages: A list of messages comprising the conversation so far. - [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models). + messages: A list of messages comprising the conversation so far. Depending on the + [model](https://platform.openai.com/docs/models) you use, different message + types (modalities) are supported, like + [text](https://platform.openai.com/docs/guides/text-generation), + [images](https://platform.openai.com/docs/guides/vision), and + [audio](https://platform.openai.com/docs/guides/audio). model: ID of the model to use. See the [model endpoint compatibility](https://platform.openai.com/docs/models/model-endpoint-compatibility) @@ -356,6 +374,9 @@ def create( compatible with [o1 series models](https://platform.openai.com/docs/guides/reasoning). + metadata: Developer-defined tags and values used for filtering completions in the + [dashboard](https://platform.openai.com/completions). + n: How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs. @@ -415,6 +436,9 @@ def create( stop: Up to 4 sequences where the API will stop generating further tokens. + store: Whether or not to store the output of this completion request for traffic + logging in the [dashboard](https://platform.openai.com/completions). + stream_options: Options for streaming response. Only set this when you set `stream: true`. temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will @@ -475,6 +499,7 @@ def create( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -482,6 +507,7 @@ def create( seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, @@ -500,8 +526,12 @@ def create( Creates a model response for the given chat conversation. Args: - messages: A list of messages comprising the conversation so far. - [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models). + messages: A list of messages comprising the conversation so far. Depending on the + [model](https://platform.openai.com/docs/models) you use, different message + types (modalities) are supported, like + [text](https://platform.openai.com/docs/guides/text-generation), + [images](https://platform.openai.com/docs/guides/vision), and + [audio](https://platform.openai.com/docs/guides/audio). model: ID of the model to use. See the [model endpoint compatibility](https://platform.openai.com/docs/models/model-endpoint-compatibility) @@ -560,6 +590,9 @@ def create( compatible with [o1 series models](https://platform.openai.com/docs/guides/reasoning). + metadata: Developer-defined tags and values used for filtering completions in the + [dashboard](https://platform.openai.com/completions). + n: How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs. @@ -619,6 +652,9 @@ def create( stop: Up to 4 sequences where the API will stop generating further tokens. + store: Whether or not to store the output of this completion request for traffic + logging in the [dashboard](https://platform.openai.com/completions). + stream_options: Options for streaming response. Only set this when you set `stream: true`. temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will @@ -678,6 +714,7 @@ def create( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -685,6 +722,7 @@ def create( seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -714,6 +752,7 @@ def create( "logprobs": logprobs, "max_completion_tokens": max_completion_tokens, "max_tokens": max_tokens, + "metadata": metadata, "n": n, "parallel_tool_calls": parallel_tool_calls, "presence_penalty": presence_penalty, @@ -721,6 +760,7 @@ def create( "seed": seed, "service_tier": service_tier, "stop": stop, + "store": store, "stream": stream, "stream_options": stream_options, "temperature": temperature, @@ -774,6 +814,7 @@ async def create( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -781,6 +822,7 @@ async def create( seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -800,8 +842,12 @@ async def create( Creates a model response for the given chat conversation. Args: - messages: A list of messages comprising the conversation so far. - [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models). + messages: A list of messages comprising the conversation so far. Depending on the + [model](https://platform.openai.com/docs/models) you use, different message + types (modalities) are supported, like + [text](https://platform.openai.com/docs/guides/text-generation), + [images](https://platform.openai.com/docs/guides/vision), and + [audio](https://platform.openai.com/docs/guides/audio). model: ID of the model to use. See the [model endpoint compatibility](https://platform.openai.com/docs/models/model-endpoint-compatibility) @@ -853,6 +899,9 @@ async def create( compatible with [o1 series models](https://platform.openai.com/docs/guides/reasoning). + metadata: Developer-defined tags and values used for filtering completions in the + [dashboard](https://platform.openai.com/completions). + n: How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs. @@ -912,6 +961,9 @@ async def create( stop: Up to 4 sequences where the API will stop generating further tokens. + store: Whether or not to store the output of this completion request for traffic + logging in the [dashboard](https://platform.openai.com/completions). + stream: If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) @@ -979,6 +1031,7 @@ async def create( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -986,6 +1039,7 @@ async def create( seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, @@ -1004,8 +1058,12 @@ async def create( Creates a model response for the given chat conversation. Args: - messages: A list of messages comprising the conversation so far. - [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models). + messages: A list of messages comprising the conversation so far. Depending on the + [model](https://platform.openai.com/docs/models) you use, different message + types (modalities) are supported, like + [text](https://platform.openai.com/docs/guides/text-generation), + [images](https://platform.openai.com/docs/guides/vision), and + [audio](https://platform.openai.com/docs/guides/audio). model: ID of the model to use. See the [model endpoint compatibility](https://platform.openai.com/docs/models/model-endpoint-compatibility) @@ -1064,6 +1122,9 @@ async def create( compatible with [o1 series models](https://platform.openai.com/docs/guides/reasoning). + metadata: Developer-defined tags and values used for filtering completions in the + [dashboard](https://platform.openai.com/completions). + n: How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs. @@ -1123,6 +1184,9 @@ async def create( stop: Up to 4 sequences where the API will stop generating further tokens. + store: Whether or not to store the output of this completion request for traffic + logging in the [dashboard](https://platform.openai.com/completions). + stream_options: Options for streaming response. Only set this when you set `stream: true`. temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will @@ -1183,6 +1247,7 @@ async def create( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -1190,6 +1255,7 @@ async def create( seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: ChatCompletionToolChoiceOptionParam | NotGiven = NOT_GIVEN, @@ -1208,8 +1274,12 @@ async def create( Creates a model response for the given chat conversation. Args: - messages: A list of messages comprising the conversation so far. - [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models). + messages: A list of messages comprising the conversation so far. Depending on the + [model](https://platform.openai.com/docs/models) you use, different message + types (modalities) are supported, like + [text](https://platform.openai.com/docs/guides/text-generation), + [images](https://platform.openai.com/docs/guides/vision), and + [audio](https://platform.openai.com/docs/guides/audio). model: ID of the model to use. See the [model endpoint compatibility](https://platform.openai.com/docs/models/model-endpoint-compatibility) @@ -1268,6 +1338,9 @@ async def create( compatible with [o1 series models](https://platform.openai.com/docs/guides/reasoning). + metadata: Developer-defined tags and values used for filtering completions in the + [dashboard](https://platform.openai.com/completions). + n: How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs. @@ -1327,6 +1400,9 @@ async def create( stop: Up to 4 sequences where the API will stop generating further tokens. + store: Whether or not to store the output of this completion request for traffic + logging in the [dashboard](https://platform.openai.com/completions). + stream_options: Options for streaming response. Only set this when you set `stream: true`. temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will @@ -1386,6 +1462,7 @@ async def create( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -1393,6 +1470,7 @@ async def create( seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -1422,6 +1500,7 @@ async def create( "logprobs": logprobs, "max_completion_tokens": max_completion_tokens, "max_tokens": max_tokens, + "metadata": metadata, "n": n, "parallel_tool_calls": parallel_tool_calls, "presence_penalty": presence_penalty, @@ -1429,6 +1508,7 @@ async def create( "seed": seed, "service_tier": service_tier, "stop": stop, + "store": store, "stream": stream, "stream_options": stream_options, "temperature": temperature, diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 4ed89b00f5..3f55dfbe6e 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -30,7 +30,11 @@ class CompletionCreateParamsBase(TypedDict, total=False): messages: Required[Iterable[ChatCompletionMessageParam]] """A list of messages comprising the conversation so far. - [Example Python code](https://cookbook.openai.com/examples/how_to_format_inputs_to_chatgpt_models). + Depending on the [model](https://platform.openai.com/docs/models) you use, + different message types (modalities) are supported, like + [text](https://platform.openai.com/docs/guides/text-generation), + [images](https://platform.openai.com/docs/guides/vision), and + [audio](https://platform.openai.com/docs/guides/audio). """ model: Required[Union[str, ChatModel]] @@ -105,6 +109,12 @@ class CompletionCreateParamsBase(TypedDict, total=False): [o1 series models](https://platform.openai.com/docs/guides/reasoning). """ + metadata: Optional[Dict[str, str]] + """ + Developer-defined tags and values used for filtering completions in the + [dashboard](https://platform.openai.com/completions). + """ + n: Optional[int] """How many chat completion choices to generate for each input message. @@ -183,6 +193,12 @@ class CompletionCreateParamsBase(TypedDict, total=False): stop: Union[Optional[str], List[str]] """Up to 4 sequences where the API will stop generating further tokens.""" + store: Optional[bool] + """ + Whether or not to store the output of this completion request for traffic + logging in the [dashboard](https://platform.openai.com/completions). + """ + stream_options: Optional[ChatCompletionStreamOptionsParam] """Options for streaming response. Only set this when you set `stream: true`.""" diff --git a/src/openai/types/chat_model.py b/src/openai/types/chat_model.py index f8438c75c8..f2d5674786 100644 --- a/src/openai/types/chat_model.py +++ b/src/openai/types/chat_model.py @@ -12,6 +12,7 @@ "gpt-4o", "gpt-4o-2024-08-06", "gpt-4o-2024-05-13", + "gpt-4o-realtime-preview-2024-10-01", "chatgpt-4o-latest", "gpt-4o-mini", "gpt-4o-mini-2024-07-18", diff --git a/src/openai/types/completion_usage.py b/src/openai/types/completion_usage.py index a4b9116e35..fe112833e0 100644 --- a/src/openai/types/completion_usage.py +++ b/src/openai/types/completion_usage.py @@ -4,14 +4,25 @@ from .._models import BaseModel -__all__ = ["CompletionUsage", "CompletionTokensDetails"] +__all__ = ["CompletionUsage", "CompletionTokensDetails", "PromptTokensDetails"] class CompletionTokensDetails(BaseModel): + audio_tokens: Optional[int] = None + """Audio input tokens generated by the model.""" + reasoning_tokens: Optional[int] = None """Tokens generated by the model for reasoning.""" +class PromptTokensDetails(BaseModel): + audio_tokens: Optional[int] = None + """Audio input tokens present in the prompt.""" + + cached_tokens: Optional[int] = None + """Cached tokens present in the prompt.""" + + class CompletionUsage(BaseModel): completion_tokens: int """Number of tokens in the generated completion.""" @@ -24,3 +35,6 @@ class CompletionUsage(BaseModel): completion_tokens_details: Optional[CompletionTokensDetails] = None """Breakdown of tokens used in a completion.""" + + prompt_tokens_details: Optional[PromptTokensDetails] = None + """Breakdown of tokens used in the prompt.""" diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index c44703a434..8c1f263f54 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -57,6 +57,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: logprobs=True, max_completion_tokens=0, max_tokens=0, + metadata={"foo": "string"}, n=1, parallel_tool_calls=True, presence_penalty=-2, @@ -64,6 +65,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: seed=-9007199254740991, service_tier="auto", stop="string", + store=True, stream=False, stream_options={"include_usage": True}, temperature=1, @@ -178,6 +180,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: logprobs=True, max_completion_tokens=0, max_tokens=0, + metadata={"foo": "string"}, n=1, parallel_tool_calls=True, presence_penalty=-2, @@ -185,6 +188,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: seed=-9007199254740991, service_tier="auto", stop="string", + store=True, stream_options={"include_usage": True}, temperature=1, tool_choice="none", @@ -318,6 +322,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn logprobs=True, max_completion_tokens=0, max_tokens=0, + metadata={"foo": "string"}, n=1, parallel_tool_calls=True, presence_penalty=-2, @@ -325,6 +330,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn seed=-9007199254740991, service_tier="auto", stop="string", + store=True, stream=False, stream_options={"include_usage": True}, temperature=1, @@ -439,6 +445,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn logprobs=True, max_completion_tokens=0, max_tokens=0, + metadata={"foo": "string"}, n=1, parallel_tool_calls=True, presence_penalty=-2, @@ -446,6 +453,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn seed=-9007199254740991, service_tier="auto", stop="string", + store=True, stream_options={"include_usage": True}, temperature=1, tool_choice="none", diff --git a/tests/lib/chat/test_completions.py b/tests/lib/chat/test_completions.py index 7702a98d49..3cfea71f11 100644 --- a/tests/lib/chat/test_completions.py +++ b/tests/lib/chat/test_completions.py @@ -76,8 +76,9 @@ def test_parse_nothing(client: OpenAI, respx_mock: MockRouter, monkeypatch: pyte system_fingerprint='fp_b40fb1c6fb', usage=CompletionUsage( completion_tokens=37, - completion_tokens_details=CompletionTokensDetails(reasoning_tokens=0), + completion_tokens_details=CompletionTokensDetails(audio_tokens=None, reasoning_tokens=0), prompt_tokens=14, + prompt_tokens_details=None, total_tokens=51 ) ) @@ -136,8 +137,9 @@ class Location(BaseModel): system_fingerprint='fp_5050236cbd', usage=CompletionUsage( completion_tokens=14, - completion_tokens_details=CompletionTokensDetails(reasoning_tokens=0), + completion_tokens_details=CompletionTokensDetails(audio_tokens=None, reasoning_tokens=0), prompt_tokens=79, + prompt_tokens_details=None, total_tokens=93 ) ) @@ -198,8 +200,9 @@ class Location(BaseModel): system_fingerprint='fp_b40fb1c6fb', usage=CompletionUsage( completion_tokens=14, - completion_tokens_details=CompletionTokensDetails(reasoning_tokens=0), + completion_tokens_details=CompletionTokensDetails(audio_tokens=None, reasoning_tokens=0), prompt_tokens=88, + prompt_tokens_details=None, total_tokens=102 ) ) @@ -385,8 +388,9 @@ class CalendarEvent: system_fingerprint='fp_7568d46099', usage=CompletionUsage( completion_tokens=17, - completion_tokens_details=CompletionTokensDetails(reasoning_tokens=0), + completion_tokens_details=CompletionTokensDetails(audio_tokens=None, reasoning_tokens=0), prompt_tokens=92, + prompt_tokens_details=None, total_tokens=109 ) ) @@ -829,8 +833,9 @@ class Location(BaseModel): system_fingerprint='fp_5050236cbd', usage=CompletionUsage( completion_tokens=14, - completion_tokens_details=CompletionTokensDetails(reasoning_tokens=0), + completion_tokens_details=CompletionTokensDetails(audio_tokens=None, reasoning_tokens=0), prompt_tokens=79, + prompt_tokens_details=None, total_tokens=93 ) ) @@ -897,8 +902,9 @@ class Location(BaseModel): system_fingerprint='fp_5050236cbd', usage=CompletionUsage( completion_tokens=14, - completion_tokens_details=CompletionTokensDetails(reasoning_tokens=0), + completion_tokens_details=CompletionTokensDetails(audio_tokens=None, reasoning_tokens=0), prompt_tokens=79, + prompt_tokens_details=None, total_tokens=93 ) ) diff --git a/tests/lib/chat/test_completions_streaming.py b/tests/lib/chat/test_completions_streaming.py index ce402cd158..216fe9ddf5 100644 --- a/tests/lib/chat/test_completions_streaming.py +++ b/tests/lib/chat/test_completions_streaming.py @@ -155,8 +155,9 @@ def on_event(stream: ChatCompletionStream[Location], event: ChatCompletionStream system_fingerprint='fp_5050236cbd', usage=CompletionUsage( completion_tokens=14, - completion_tokens_details=CompletionTokensDetails(reasoning_tokens=0), + completion_tokens_details=CompletionTokensDetails(audio_tokens=None, reasoning_tokens=0), prompt_tokens=79, + prompt_tokens_details=None, total_tokens=93 ) ) From b7d9ce71669164a3864e170476b2846760f5e35f Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 1 Oct 2024 17:45:47 +0000 Subject: [PATCH 531/816] release: 1.51.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 19 +++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 22 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index b11d9e721d..3ff0a9eb32 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.50.2" + ".": "1.51.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 37571051de..8db39a51c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,24 @@ # Changelog +## 1.51.0 (2024-10-01) + +Full Changelog: [v1.50.2...v1.51.0](https://github.com/openai/openai-python/compare/v1.50.2...v1.51.0) + +### Features + +* **api:** support storing chat completions, enabling evals and model distillation in the dashboard ([2840c6d](https://github.com/openai/openai-python/commit/2840c6df94afb44cfd80efabe0405898331ee267)) + + +### Chores + +* **docs:** fix maxium typo ([#1762](https://github.com/openai/openai-python/issues/1762)) ([de94553](https://github.com/openai/openai-python/commit/de94553f93d71fc6c8187c8d3fbe924a71cc46dd)) +* **internal:** remove ds store ([47a3968](https://github.com/openai/openai-python/commit/47a3968f9b318eb02d5602f5b10e7d9e69c3ae84)) + + +### Documentation + +* **helpers:** fix method name typo ([#1764](https://github.com/openai/openai-python/issues/1764)) ([e1bcfe8](https://github.com/openai/openai-python/commit/e1bcfe86554017ac63055060153c4fd72e65c0cf)) + ## 1.50.2 (2024-09-27) Full Changelog: [v1.50.1...v1.50.2](https://github.com/openai/openai-python/compare/v1.50.1...v1.50.2) diff --git a/pyproject.toml b/pyproject.toml index 90b8c8518c..d1bffe39a9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.50.2" +version = "1.51.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 641dd21648..407f4cb969 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.50.2" # x-release-please-version +__version__ = "1.51.0" # x-release-please-version From a3001d8d91f9f991e2164671fd40cc16d495f006 Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Wed, 2 Oct 2024 19:16:58 +0000 Subject: [PATCH 532/816] docs: improve and reference contributing documentation (#1767) --- CONTRIBUTING.md | 44 ++++++++++++++++++++++++-------------------- README.md | 4 ++++ 2 files changed, 28 insertions(+), 20 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5a6639b8fc..37e060bdcf 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,9 +2,13 @@ ### With Rye -We use [Rye](https://rye-up.com/) to manage dependencies so we highly recommend [installing it](https://rye-up.com/guide/installation/) as it will automatically provision a Python environment with the expected Python version. +We use [Rye](https://rye.astral.sh/) to manage dependencies because it will automatically provision a Python environment with the expected Python version. To set it up, run: -After installing Rye, you'll just have to run this command: +```sh +$ ./scripts/bootstrap +``` + +Or [install Rye manually](https://rye.astral.sh/guide/installation/) and run: ```sh $ rye sync --all-features @@ -39,17 +43,17 @@ modify the contents of the `src/openai/lib/` and `examples/` directories. All files in the `examples/` directory are not modified by the generator and can be freely edited or added to. -```bash +```ts # add an example to examples/.py #!/usr/bin/env -S rye run python … ``` -``` -chmod +x examples/.py +```sh +$ chmod +x examples/.py # run the example against your api -./examples/.py +$ ./examples/.py ``` ## Using the repository from source @@ -58,8 +62,8 @@ If you’d like to use the repository from source, you can either install from g To install via git: -```bash -pip install git+ssh://git@github.com/openai/openai-python.git +```sh +$ pip install git+ssh://git@github.com/openai/openai-python.git ``` Alternatively, you can build from source and install the wheel file: @@ -68,29 +72,29 @@ Building this package will create two files in the `dist/` directory, a `.tar.gz To create a distributable version of the library, all you have to do is run this command: -```bash -rye build +```sh +$ rye build # or -python -m build +$ python -m build ``` Then to install: ```sh -pip install ./path-to-wheel-file.whl +$ pip install ./path-to-wheel-file.whl ``` ## Running tests Most tests require you to [set up a mock server](https://github.com/stoplightio/prism) against the OpenAPI spec to run the tests. -```bash +```sh # you will need npm installed -npx prism mock path/to/your/openapi.yml +$ npx prism mock path/to/your/openapi.yml ``` -```bash -rye run pytest +```sh +$ ./scripts/test ``` ## Linting and formatting @@ -100,14 +104,14 @@ This repository uses [ruff](https://github.com/astral-sh/ruff) and To lint: -```bash -rye run lint +```sh +$ ./scripts/lint ``` To format and fix all ruff issues automatically: -```bash -rye run format +```sh +$ ./scripts/format ``` ## Publishing and releases diff --git a/README.md b/README.md index c47bdd54c5..dada1abfbb 100644 --- a/README.md +++ b/README.md @@ -713,3 +713,7 @@ print(openai.__version__) ## Requirements Python 3.7 or higher. + +## Contributing + +See [the contributing documentation](./CONTRIBUTING.md). From 50de514b910aced32104833acd892bebfb2cf123 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 1 Oct 2024 20:04:38 +0000 Subject: [PATCH 533/816] docs: fix typo in fenced code block language (#1769) --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 37e060bdcf..52c2eb213a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -43,7 +43,7 @@ modify the contents of the `src/openai/lib/` and `examples/` directories. All files in the `examples/` directory are not modified by the generator and can be freely edited or added to. -```ts +```py # add an example to examples/.py #!/usr/bin/env -S rye run python From a7d9731bb1d79871ee4817faf0f3f558ce3d855c Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 4 Oct 2024 14:39:22 +0000 Subject: [PATCH 534/816] chore(internal): add support for parsing bool response content (#1774) --- src/openai/_legacy_response.py | 3 ++ src/openai/_response.py | 3 ++ tests/test_legacy_response.py | 25 +++++++++++++++++ tests/test_response.py | 50 ++++++++++++++++++++++++++++++++++ 4 files changed, 81 insertions(+) diff --git a/src/openai/_legacy_response.py b/src/openai/_legacy_response.py index c7dbd54e23..5260e90bc1 100644 --- a/src/openai/_legacy_response.py +++ b/src/openai/_legacy_response.py @@ -258,6 +258,9 @@ def _parse(self, *, to: type[_T] | None = None) -> R | _T: if cast_to == float: return cast(R, float(response.text)) + if cast_to == bool: + return cast(R, response.text.lower() == "true") + origin = get_origin(cast_to) or cast_to if inspect.isclass(origin) and issubclass(origin, HttpxBinaryResponseContent): diff --git a/src/openai/_response.py b/src/openai/_response.py index 20ce69ac8a..eac3fbae6c 100644 --- a/src/openai/_response.py +++ b/src/openai/_response.py @@ -192,6 +192,9 @@ def _parse(self, *, to: type[_T] | None = None) -> R | _T: if cast_to == float: return cast(R, float(response.text)) + if cast_to == bool: + return cast(R, response.text.lower() == "true") + origin = get_origin(cast_to) or cast_to # handle the legacy binary response case diff --git a/tests/test_legacy_response.py b/tests/test_legacy_response.py index f50a77c24d..9da1a80659 100644 --- a/tests/test_legacy_response.py +++ b/tests/test_legacy_response.py @@ -34,6 +34,31 @@ def test_response_parse_mismatched_basemodel(client: OpenAI) -> None: response.parse(to=PydanticModel) +@pytest.mark.parametrize( + "content, expected", + [ + ("false", False), + ("true", True), + ("False", False), + ("True", True), + ("TrUe", True), + ("FalSe", False), + ], +) +def test_response_parse_bool(client: OpenAI, content: str, expected: bool) -> None: + response = LegacyAPIResponse( + raw=httpx.Response(200, content=content), + client=client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + result = response.parse(to=bool) + assert result is expected + + def test_response_parse_custom_stream(client: OpenAI) -> None: response = LegacyAPIResponse( raw=httpx.Response(200, content=b"foo"), diff --git a/tests/test_response.py b/tests/test_response.py index e1fe332f2f..43f24c150d 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -237,6 +237,56 @@ async def test_async_response_parse_annotated_type(async_client: AsyncOpenAI) -> assert obj.bar == 2 +@pytest.mark.parametrize( + "content, expected", + [ + ("false", False), + ("true", True), + ("False", False), + ("True", True), + ("TrUe", True), + ("FalSe", False), + ], +) +def test_response_parse_bool(client: OpenAI, content: str, expected: bool) -> None: + response = APIResponse( + raw=httpx.Response(200, content=content), + client=client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + result = response.parse(to=bool) + assert result is expected + + +@pytest.mark.parametrize( + "content, expected", + [ + ("false", False), + ("true", True), + ("False", False), + ("True", True), + ("TrUe", True), + ("FalSe", False), + ], +) +async def test_async_response_parse_bool(client: AsyncOpenAI, content: str, expected: bool) -> None: + response = AsyncAPIResponse( + raw=httpx.Response(200, content=content), + client=client, + stream=False, + stream_cls=None, + cast_to=str, + options=FinalRequestOptions.construct(method="get", url="/foo"), + ) + + result = await response.parse(to=bool) + assert result is expected + + class OtherModel(BaseModel): a: str From 4d8fb73c8f1c0aa32364b0ab5000e1078f3a93c5 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 7 Oct 2024 13:52:45 +0000 Subject: [PATCH 535/816] fix(client): avoid OverflowError with very large retry counts (#1779) --- src/openai/_base_client.py | 3 ++- tests/test_client.py | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index c4c9803e74..931cbd8534 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -690,7 +690,8 @@ def _calculate_retry_timeout( if retry_after is not None and 0 < retry_after <= 60: return retry_after - nb_retries = max_retries - remaining_retries + # Also cap retry count to 1000 to avoid any potential overflows with `pow` + nb_retries = min(max_retries - remaining_retries, 1000) # Apply exponential backoff, but not more than the max. sleep_seconds = min(INITIAL_RETRY_DELAY * pow(2.0, nb_retries), MAX_RETRY_DELAY) diff --git a/tests/test_client.py b/tests/test_client.py index 463174465c..1da35ddd22 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -697,6 +697,7 @@ class Model(BaseModel): [3, "", 0.5], [2, "", 0.5 * 2.0], [1, "", 0.5 * 4.0], + [-1100, "", 7.8], # test large number potentially overflowing ], ) @mock.patch("time.time", mock.MagicMock(return_value=1696004797)) @@ -1553,6 +1554,7 @@ class Model(BaseModel): [3, "", 0.5], [2, "", 0.5 * 2.0], [1, "", 0.5 * 4.0], + [-1100, "", 7.8], # test large number potentially overflowing ], ) @mock.patch("time.time", mock.MagicMock(return_value=1696004797)) From 8467d41376c2b17eae1c78d56b39767e7807cb6f Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 7 Oct 2024 13:53:16 +0000 Subject: [PATCH 536/816] release: 1.51.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 19 +++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 22 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 3ff0a9eb32..3462272dee 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.51.0" + ".": "1.51.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 8db39a51c4..08b85350d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,24 @@ # Changelog +## 1.51.1 (2024-10-07) + +Full Changelog: [v1.51.0...v1.51.1](https://github.com/openai/openai-python/compare/v1.51.0...v1.51.1) + +### Bug Fixes + +* **client:** avoid OverflowError with very large retry counts ([#1779](https://github.com/openai/openai-python/issues/1779)) ([fb1dacf](https://github.com/openai/openai-python/commit/fb1dacfa4d9447d123c38ab3d3d433d900d32ec5)) + + +### Chores + +* **internal:** add support for parsing bool response content ([#1774](https://github.com/openai/openai-python/issues/1774)) ([aa2e25f](https://github.com/openai/openai-python/commit/aa2e25f9a4a632357051397ea34d269eafba026d)) + + +### Documentation + +* fix typo in fenced code block language ([#1769](https://github.com/openai/openai-python/issues/1769)) ([57bbc15](https://github.com/openai/openai-python/commit/57bbc155210cc439a36f4e5cbd082e94c3349d78)) +* improve and reference contributing documentation ([#1767](https://github.com/openai/openai-python/issues/1767)) ([a985a8b](https://github.com/openai/openai-python/commit/a985a8b8ab8d0b364bd3c26b6423a7c49ae7b1ce)) + ## 1.51.0 (2024-10-01) Full Changelog: [v1.50.2...v1.51.0](https://github.com/openai/openai-python/compare/v1.50.2...v1.51.0) diff --git a/pyproject.toml b/pyproject.toml index d1bffe39a9..41b3c18f01 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.51.0" +version = "1.51.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 407f4cb969..ce7c45ab73 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.51.0" # x-release-please-version +__version__ = "1.51.1" # x-release-please-version From cfd99e7b0cb0a52769a09422dfbcbf39f3b56652 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 7 Oct 2024 16:43:09 +0000 Subject: [PATCH 537/816] chore: add repr to PageInfo class (#1780) --- src/openai/_base_client.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 931cbd8534..b2929df072 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -144,6 +144,12 @@ def __init__( self.url = url self.params = params + @override + def __repr__(self) -> str: + if self.url: + return f"{self.__class__.__name__}(url={self.url})" + return f"{self.__class__.__name__}(params={self.params})" + class BasePage(GenericModel, Generic[_T]): """ From af8e0ad8b7988e72e1d02478022d80eff4f55b91 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 8 Oct 2024 05:04:18 +0000 Subject: [PATCH 538/816] release: 1.51.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 3462272dee..395be07b55 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.51.1" + ".": "1.51.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 08b85350d7..8f583fe89f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.51.2 (2024-10-08) + +Full Changelog: [v1.51.1...v1.51.2](https://github.com/openai/openai-python/compare/v1.51.1...v1.51.2) + +### Chores + +* add repr to PageInfo class ([#1780](https://github.com/openai/openai-python/issues/1780)) ([63118ee](https://github.com/openai/openai-python/commit/63118ee3c2481d217682e8a31337bdcc16893127)) + ## 1.51.1 (2024-10-07) Full Changelog: [v1.51.0...v1.51.1](https://github.com/openai/openai-python/compare/v1.51.0...v1.51.1) diff --git a/pyproject.toml b/pyproject.toml index 41b3c18f01..8da5e0e2ce 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.51.1" +version = "1.51.2" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index ce7c45ab73..cb98e08a8a 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.51.1" # x-release-please-version +__version__ = "1.51.2" # x-release-please-version From 550b855fe51dd3fad4e1c5c796d7c35b8e603d2f Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 17 Oct 2024 16:49:46 +0000 Subject: [PATCH 539/816] feat(api): add gpt-4o-audio-preview model for chat completions (#1796) This enables audio inputs and outputs. https://platform.openai.com/docs/guides/audio --- .stats.yml | 2 +- api.md | 4 + src/openai/resources/beta/chat/completions.py | 18 ++ src/openai/resources/chat/completions.py | 207 +++++++++++++++--- .../types/beta/assistant_stream_event.py | 5 +- src/openai/types/chat/__init__.py | 6 + ...chat_completion_assistant_message_param.py | 14 +- .../types/chat/chat_completion_audio.py | 27 +++ .../types/chat/chat_completion_audio_param.py | 21 ++ ...mpletion_content_part_input_audio_param.py | 22 ++ .../chat_completion_content_part_param.py | 3 +- .../types/chat/chat_completion_message.py | 8 + .../types/chat/chat_completion_modality.py | 7 + .../types/chat/completion_create_params.py | 30 ++- src/openai/types/chat_model.py | 3 + tests/api_resources/chat/test_completions.py | 20 ++ tests/lib/chat/test_completions.py | 15 ++ tests/lib/chat/test_completions_streaming.py | 14 ++ 18 files changed, 388 insertions(+), 38 deletions(-) create mode 100644 src/openai/types/chat/chat_completion_audio.py create mode 100644 src/openai/types/chat/chat_completion_audio_param.py create mode 100644 src/openai/types/chat/chat_completion_content_part_input_audio_param.py create mode 100644 src/openai/types/chat/chat_completion_modality.py diff --git a/.stats.yml b/.stats.yml index ece287351b..984e8a8d5f 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-52b934aee6468039ec7f4ce046a282b5fbce114afc708e70f17121df654f71da.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-8729aaa35436531ab453224af10e67f89677db8f350f0346bb3537489edea649.yml diff --git a/api.md b/api.md index 813c5cb615..f44169665d 100644 --- a/api.md +++ b/api.md @@ -39,9 +39,12 @@ Types: from openai.types.chat import ( ChatCompletion, ChatCompletionAssistantMessageParam, + ChatCompletionAudio, + ChatCompletionAudioParam, ChatCompletionChunk, ChatCompletionContentPart, ChatCompletionContentPartImage, + ChatCompletionContentPartInputAudio, ChatCompletionContentPartRefusal, ChatCompletionContentPartText, ChatCompletionFunctionCallOption, @@ -49,6 +52,7 @@ from openai.types.chat import ( ChatCompletionMessage, ChatCompletionMessageParam, ChatCompletionMessageToolCall, + ChatCompletionModality, ChatCompletionNamedToolChoice, ChatCompletionRole, ChatCompletionStreamOptions, diff --git a/src/openai/resources/beta/chat/completions.py b/src/openai/resources/beta/chat/completions.py index c747464072..47bcf42c16 100644 --- a/src/openai/resources/beta/chat/completions.py +++ b/src/openai/resources/beta/chat/completions.py @@ -28,7 +28,9 @@ from ....types.chat.chat_completion import ChatCompletion from ....types.chat.chat_completion_chunk import ChatCompletionChunk from ....types.chat.parsed_chat_completion import ParsedChatCompletion +from ....types.chat.chat_completion_modality import ChatCompletionModality from ....types.chat.chat_completion_tool_param import ChatCompletionToolParam +from ....types.chat.chat_completion_audio_param import ChatCompletionAudioParam from ....types.chat.chat_completion_message_param import ChatCompletionMessageParam from ....types.chat.chat_completion_stream_options_param import ChatCompletionStreamOptionsParam from ....types.chat.chat_completion_tool_choice_option_param import ChatCompletionToolChoiceOptionParam @@ -61,6 +63,7 @@ def parse( *, messages: Iterable[ChatCompletionMessageParam], model: Union[str, ChatModel], + audio: Optional[ChatCompletionAudioParam] | NotGiven = NOT_GIVEN, response_format: type[ResponseFormatT] | NotGiven = NOT_GIVEN, frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, @@ -70,6 +73,7 @@ def parse( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -153,6 +157,7 @@ def parser(raw_completion: ChatCompletion) -> ParsedChatCompletion[ResponseForma { "messages": messages, "model": model, + "audio": audio, "frequency_penalty": frequency_penalty, "function_call": function_call, "functions": functions, @@ -161,6 +166,7 @@ def parser(raw_completion: ChatCompletion) -> ParsedChatCompletion[ResponseForma "max_completion_tokens": max_completion_tokens, "max_tokens": max_tokens, "metadata": metadata, + "modalities": modalities, "n": n, "parallel_tool_calls": parallel_tool_calls, "presence_penalty": presence_penalty, @@ -198,6 +204,7 @@ def stream( *, messages: Iterable[ChatCompletionMessageParam], model: Union[str, ChatModel], + audio: Optional[ChatCompletionAudioParam] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | type[ResponseFormatT] | NotGiven = NOT_GIVEN, frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, @@ -207,6 +214,7 @@ def stream( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -259,6 +267,7 @@ def stream( self._client.chat.completions.create, messages=messages, model=model, + audio=audio, stream=True, response_format=_type_to_response_format(response_format), frequency_penalty=frequency_penalty, @@ -269,6 +278,7 @@ def stream( max_completion_tokens=max_completion_tokens, max_tokens=max_tokens, metadata=metadata, + modalities=modalities, n=n, parallel_tool_calls=parallel_tool_calls, presence_penalty=presence_penalty, @@ -320,6 +330,7 @@ async def parse( *, messages: Iterable[ChatCompletionMessageParam], model: Union[str, ChatModel], + audio: Optional[ChatCompletionAudioParam] | NotGiven = NOT_GIVEN, response_format: type[ResponseFormatT] | NotGiven = NOT_GIVEN, frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, @@ -329,6 +340,7 @@ async def parse( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -412,6 +424,7 @@ def parser(raw_completion: ChatCompletion) -> ParsedChatCompletion[ResponseForma { "messages": messages, "model": model, + "audio": audio, "frequency_penalty": frequency_penalty, "function_call": function_call, "functions": functions, @@ -420,6 +433,7 @@ def parser(raw_completion: ChatCompletion) -> ParsedChatCompletion[ResponseForma "max_completion_tokens": max_completion_tokens, "max_tokens": max_tokens, "metadata": metadata, + "modalities": modalities, "n": n, "parallel_tool_calls": parallel_tool_calls, "presence_penalty": presence_penalty, @@ -457,6 +471,7 @@ def stream( *, messages: Iterable[ChatCompletionMessageParam], model: Union[str, ChatModel], + audio: Optional[ChatCompletionAudioParam] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | type[ResponseFormatT] | NotGiven = NOT_GIVEN, frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, @@ -466,6 +481,7 @@ def stream( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -519,6 +535,7 @@ def stream( api_request = self._client.chat.completions.create( messages=messages, model=model, + audio=audio, stream=True, response_format=_type_to_response_format(response_format), frequency_penalty=frequency_penalty, @@ -529,6 +546,7 @@ def stream( max_completion_tokens=max_completion_tokens, max_tokens=max_tokens, metadata=metadata, + modalities=modalities, n=n, parallel_tool_calls=parallel_tool_calls, presence_penalty=presence_penalty, diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index c8080afaa1..ceaf3c2fec 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -20,12 +20,17 @@ from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ..._streaming import Stream, AsyncStream -from ...types.chat import completion_create_params +from ...types.chat import ( + ChatCompletionAudioParam, + completion_create_params, +) from ..._base_client import make_request_options from ...types.chat_model import ChatModel from ...types.chat.chat_completion import ChatCompletion from ...types.chat.chat_completion_chunk import ChatCompletionChunk +from ...types.chat.chat_completion_modality import ChatCompletionModality from ...types.chat.chat_completion_tool_param import ChatCompletionToolParam +from ...types.chat.chat_completion_audio_param import ChatCompletionAudioParam from ...types.chat.chat_completion_message_param import ChatCompletionMessageParam from ...types.chat.chat_completion_stream_options_param import ChatCompletionStreamOptionsParam from ...types.chat.chat_completion_tool_choice_option_param import ChatCompletionToolChoiceOptionParam @@ -59,6 +64,7 @@ def create( *, messages: Iterable[ChatCompletionMessageParam], model: Union[str, ChatModel], + audio: Optional[ChatCompletionAudioParam] | NotGiven = NOT_GIVEN, frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, @@ -67,6 +73,7 @@ def create( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -90,8 +97,12 @@ def create( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ChatCompletion: - """ - Creates a model response for the given chat conversation. + """Creates a model response for the given chat conversation. + + Learn more in the + [text generation](https://platform.openai.com/docs/guides/text-generation), + [vision](https://platform.openai.com/docs/guides/vision), and + [audio](https://platform.openai.com/docs/guides/audio) guides. Args: messages: A list of messages comprising the conversation so far. Depending on the @@ -105,6 +116,10 @@ def create( [model endpoint compatibility](https://platform.openai.com/docs/models/model-endpoint-compatibility) table for details on which models work with the Chat API. + audio: Parameters for audio output. Required when audio output is requested with + `modalities: ["audio"]`. + [Learn more](https://platform.openai.com/docs/guides/audio). + frequency_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. @@ -152,7 +167,18 @@ def create( [o1 series models](https://platform.openai.com/docs/guides/reasoning). metadata: Developer-defined tags and values used for filtering completions in the - [dashboard](https://platform.openai.com/completions). + [dashboard](https://platform.openai.com/chat-completions). + + modalities: Output types that you would like the model to generate for this request. Most + models are capable of generating text, which is the default: + + `["text"]` + + The `gpt-4o-audio-preview` model can also be used to + [generate audio](https://platform.openai.com/docs/guides/audio). To request that + this model generate both text and audio responses, you can use: + + `["text", "audio"]` n: How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the @@ -213,8 +239,9 @@ def create( stop: Up to 4 sequences where the API will stop generating further tokens. - store: Whether or not to store the output of this completion request for traffic - logging in the [dashboard](https://platform.openai.com/completions). + store: Whether or not to store the output of this chat completion request for use in + our [model distillation](https://platform.openai.com/docs/guides/distillation) + or [evals](https://platform.openai.com/docs/guides/evals) products. stream: If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only @@ -276,6 +303,7 @@ def create( messages: Iterable[ChatCompletionMessageParam], model: Union[str, ChatModel], stream: Literal[True], + audio: Optional[ChatCompletionAudioParam] | NotGiven = NOT_GIVEN, frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, @@ -284,6 +312,7 @@ def create( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -306,8 +335,12 @@ def create( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Stream[ChatCompletionChunk]: - """ - Creates a model response for the given chat conversation. + """Creates a model response for the given chat conversation. + + Learn more in the + [text generation](https://platform.openai.com/docs/guides/text-generation), + [vision](https://platform.openai.com/docs/guides/vision), and + [audio](https://platform.openai.com/docs/guides/audio) guides. Args: messages: A list of messages comprising the conversation so far. Depending on the @@ -328,6 +361,10 @@ def create( message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + audio: Parameters for audio output. Required when audio output is requested with + `modalities: ["audio"]`. + [Learn more](https://platform.openai.com/docs/guides/audio). + frequency_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. @@ -375,7 +412,18 @@ def create( [o1 series models](https://platform.openai.com/docs/guides/reasoning). metadata: Developer-defined tags and values used for filtering completions in the - [dashboard](https://platform.openai.com/completions). + [dashboard](https://platform.openai.com/chat-completions). + + modalities: Output types that you would like the model to generate for this request. Most + models are capable of generating text, which is the default: + + `["text"]` + + The `gpt-4o-audio-preview` model can also be used to + [generate audio](https://platform.openai.com/docs/guides/audio). To request that + this model generate both text and audio responses, you can use: + + `["text", "audio"]` n: How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the @@ -436,8 +484,9 @@ def create( stop: Up to 4 sequences where the API will stop generating further tokens. - store: Whether or not to store the output of this completion request for traffic - logging in the [dashboard](https://platform.openai.com/completions). + store: Whether or not to store the output of this chat completion request for use in + our [model distillation](https://platform.openai.com/docs/guides/distillation) + or [evals](https://platform.openai.com/docs/guides/evals) products. stream_options: Options for streaming response. Only set this when you set `stream: true`. @@ -492,6 +541,7 @@ def create( messages: Iterable[ChatCompletionMessageParam], model: Union[str, ChatModel], stream: bool, + audio: Optional[ChatCompletionAudioParam] | NotGiven = NOT_GIVEN, frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, @@ -500,6 +550,7 @@ def create( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -522,8 +573,12 @@ def create( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ChatCompletion | Stream[ChatCompletionChunk]: - """ - Creates a model response for the given chat conversation. + """Creates a model response for the given chat conversation. + + Learn more in the + [text generation](https://platform.openai.com/docs/guides/text-generation), + [vision](https://platform.openai.com/docs/guides/vision), and + [audio](https://platform.openai.com/docs/guides/audio) guides. Args: messages: A list of messages comprising the conversation so far. Depending on the @@ -544,6 +599,10 @@ def create( message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + audio: Parameters for audio output. Required when audio output is requested with + `modalities: ["audio"]`. + [Learn more](https://platform.openai.com/docs/guides/audio). + frequency_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. @@ -591,7 +650,18 @@ def create( [o1 series models](https://platform.openai.com/docs/guides/reasoning). metadata: Developer-defined tags and values used for filtering completions in the - [dashboard](https://platform.openai.com/completions). + [dashboard](https://platform.openai.com/chat-completions). + + modalities: Output types that you would like the model to generate for this request. Most + models are capable of generating text, which is the default: + + `["text"]` + + The `gpt-4o-audio-preview` model can also be used to + [generate audio](https://platform.openai.com/docs/guides/audio). To request that + this model generate both text and audio responses, you can use: + + `["text", "audio"]` n: How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the @@ -652,8 +722,9 @@ def create( stop: Up to 4 sequences where the API will stop generating further tokens. - store: Whether or not to store the output of this completion request for traffic - logging in the [dashboard](https://platform.openai.com/completions). + store: Whether or not to store the output of this chat completion request for use in + our [model distillation](https://platform.openai.com/docs/guides/distillation) + or [evals](https://platform.openai.com/docs/guides/evals) products. stream_options: Options for streaming response. Only set this when you set `stream: true`. @@ -707,6 +778,7 @@ def create( *, messages: Iterable[ChatCompletionMessageParam], model: Union[str, ChatModel], + audio: Optional[ChatCompletionAudioParam] | NotGiven = NOT_GIVEN, frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, @@ -715,6 +787,7 @@ def create( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -745,6 +818,7 @@ def create( { "messages": messages, "model": model, + "audio": audio, "frequency_penalty": frequency_penalty, "function_call": function_call, "functions": functions, @@ -753,6 +827,7 @@ def create( "max_completion_tokens": max_completion_tokens, "max_tokens": max_tokens, "metadata": metadata, + "modalities": modalities, "n": n, "parallel_tool_calls": parallel_tool_calls, "presence_penalty": presence_penalty, @@ -807,6 +882,7 @@ async def create( *, messages: Iterable[ChatCompletionMessageParam], model: Union[str, ChatModel], + audio: Optional[ChatCompletionAudioParam] | NotGiven = NOT_GIVEN, frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, @@ -815,6 +891,7 @@ async def create( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -838,8 +915,12 @@ async def create( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ChatCompletion: - """ - Creates a model response for the given chat conversation. + """Creates a model response for the given chat conversation. + + Learn more in the + [text generation](https://platform.openai.com/docs/guides/text-generation), + [vision](https://platform.openai.com/docs/guides/vision), and + [audio](https://platform.openai.com/docs/guides/audio) guides. Args: messages: A list of messages comprising the conversation so far. Depending on the @@ -853,6 +934,10 @@ async def create( [model endpoint compatibility](https://platform.openai.com/docs/models/model-endpoint-compatibility) table for details on which models work with the Chat API. + audio: Parameters for audio output. Required when audio output is requested with + `modalities: ["audio"]`. + [Learn more](https://platform.openai.com/docs/guides/audio). + frequency_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. @@ -900,7 +985,18 @@ async def create( [o1 series models](https://platform.openai.com/docs/guides/reasoning). metadata: Developer-defined tags and values used for filtering completions in the - [dashboard](https://platform.openai.com/completions). + [dashboard](https://platform.openai.com/chat-completions). + + modalities: Output types that you would like the model to generate for this request. Most + models are capable of generating text, which is the default: + + `["text"]` + + The `gpt-4o-audio-preview` model can also be used to + [generate audio](https://platform.openai.com/docs/guides/audio). To request that + this model generate both text and audio responses, you can use: + + `["text", "audio"]` n: How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the @@ -961,8 +1057,9 @@ async def create( stop: Up to 4 sequences where the API will stop generating further tokens. - store: Whether or not to store the output of this completion request for traffic - logging in the [dashboard](https://platform.openai.com/completions). + store: Whether or not to store the output of this chat completion request for use in + our [model distillation](https://platform.openai.com/docs/guides/distillation) + or [evals](https://platform.openai.com/docs/guides/evals) products. stream: If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only @@ -1024,6 +1121,7 @@ async def create( messages: Iterable[ChatCompletionMessageParam], model: Union[str, ChatModel], stream: Literal[True], + audio: Optional[ChatCompletionAudioParam] | NotGiven = NOT_GIVEN, frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, @@ -1032,6 +1130,7 @@ async def create( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -1054,8 +1153,12 @@ async def create( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AsyncStream[ChatCompletionChunk]: - """ - Creates a model response for the given chat conversation. + """Creates a model response for the given chat conversation. + + Learn more in the + [text generation](https://platform.openai.com/docs/guides/text-generation), + [vision](https://platform.openai.com/docs/guides/vision), and + [audio](https://platform.openai.com/docs/guides/audio) guides. Args: messages: A list of messages comprising the conversation so far. Depending on the @@ -1076,6 +1179,10 @@ async def create( message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + audio: Parameters for audio output. Required when audio output is requested with + `modalities: ["audio"]`. + [Learn more](https://platform.openai.com/docs/guides/audio). + frequency_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. @@ -1123,7 +1230,18 @@ async def create( [o1 series models](https://platform.openai.com/docs/guides/reasoning). metadata: Developer-defined tags and values used for filtering completions in the - [dashboard](https://platform.openai.com/completions). + [dashboard](https://platform.openai.com/chat-completions). + + modalities: Output types that you would like the model to generate for this request. Most + models are capable of generating text, which is the default: + + `["text"]` + + The `gpt-4o-audio-preview` model can also be used to + [generate audio](https://platform.openai.com/docs/guides/audio). To request that + this model generate both text and audio responses, you can use: + + `["text", "audio"]` n: How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the @@ -1184,8 +1302,9 @@ async def create( stop: Up to 4 sequences where the API will stop generating further tokens. - store: Whether or not to store the output of this completion request for traffic - logging in the [dashboard](https://platform.openai.com/completions). + store: Whether or not to store the output of this chat completion request for use in + our [model distillation](https://platform.openai.com/docs/guides/distillation) + or [evals](https://platform.openai.com/docs/guides/evals) products. stream_options: Options for streaming response. Only set this when you set `stream: true`. @@ -1240,6 +1359,7 @@ async def create( messages: Iterable[ChatCompletionMessageParam], model: Union[str, ChatModel], stream: bool, + audio: Optional[ChatCompletionAudioParam] | NotGiven = NOT_GIVEN, frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, @@ -1248,6 +1368,7 @@ async def create( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -1270,8 +1391,12 @@ async def create( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ChatCompletion | AsyncStream[ChatCompletionChunk]: - """ - Creates a model response for the given chat conversation. + """Creates a model response for the given chat conversation. + + Learn more in the + [text generation](https://platform.openai.com/docs/guides/text-generation), + [vision](https://platform.openai.com/docs/guides/vision), and + [audio](https://platform.openai.com/docs/guides/audio) guides. Args: messages: A list of messages comprising the conversation so far. Depending on the @@ -1292,6 +1417,10 @@ async def create( message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + audio: Parameters for audio output. Required when audio output is requested with + `modalities: ["audio"]`. + [Learn more](https://platform.openai.com/docs/guides/audio). + frequency_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. @@ -1339,7 +1468,18 @@ async def create( [o1 series models](https://platform.openai.com/docs/guides/reasoning). metadata: Developer-defined tags and values used for filtering completions in the - [dashboard](https://platform.openai.com/completions). + [dashboard](https://platform.openai.com/chat-completions). + + modalities: Output types that you would like the model to generate for this request. Most + models are capable of generating text, which is the default: + + `["text"]` + + The `gpt-4o-audio-preview` model can also be used to + [generate audio](https://platform.openai.com/docs/guides/audio). To request that + this model generate both text and audio responses, you can use: + + `["text", "audio"]` n: How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the @@ -1400,8 +1540,9 @@ async def create( stop: Up to 4 sequences where the API will stop generating further tokens. - store: Whether or not to store the output of this completion request for traffic - logging in the [dashboard](https://platform.openai.com/completions). + store: Whether or not to store the output of this chat completion request for use in + our [model distillation](https://platform.openai.com/docs/guides/distillation) + or [evals](https://platform.openai.com/docs/guides/evals) products. stream_options: Options for streaming response. Only set this when you set `stream: true`. @@ -1455,6 +1596,7 @@ async def create( *, messages: Iterable[ChatCompletionMessageParam], model: Union[str, ChatModel], + audio: Optional[ChatCompletionAudioParam] | NotGiven = NOT_GIVEN, frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN, function_call: completion_create_params.FunctionCall | NotGiven = NOT_GIVEN, functions: Iterable[completion_create_params.Function] | NotGiven = NOT_GIVEN, @@ -1463,6 +1605,7 @@ async def create( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, @@ -1493,6 +1636,7 @@ async def create( { "messages": messages, "model": model, + "audio": audio, "frequency_penalty": frequency_penalty, "function_call": function_call, "functions": functions, @@ -1501,6 +1645,7 @@ async def create( "max_completion_tokens": max_completion_tokens, "max_tokens": max_tokens, "metadata": metadata, + "modalities": modalities, "n": n, "parallel_tool_calls": parallel_tool_calls, "presence_penalty": presence_penalty, diff --git a/src/openai/types/beta/assistant_stream_event.py b/src/openai/types/beta/assistant_stream_event.py index f1d8898ff2..41d3a0c5ea 100644 --- a/src/openai/types/beta/assistant_stream_event.py +++ b/src/openai/types/beta/assistant_stream_event.py @@ -1,6 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing import Union +from typing import Union, Optional from typing_extensions import Literal, Annotated, TypeAlias from .thread import Thread @@ -51,6 +51,9 @@ class ThreadCreated(BaseModel): event: Literal["thread.created"] + enabled: Optional[bool] = None + """Whether to enable input audio transcription.""" + class ThreadRunCreated(BaseModel): data: Run diff --git a/src/openai/types/chat/__init__.py b/src/openai/types/chat/__init__.py index a5cf3734b8..eb818a132e 100644 --- a/src/openai/types/chat/__init__.py +++ b/src/openai/types/chat/__init__.py @@ -4,6 +4,7 @@ from .chat_completion import ChatCompletion as ChatCompletion from .chat_completion_role import ChatCompletionRole as ChatCompletionRole +from .chat_completion_audio import ChatCompletionAudio as ChatCompletionAudio from .chat_completion_chunk import ChatCompletionChunk as ChatCompletionChunk from .parsed_chat_completion import ( ParsedChoice as ParsedChoice, @@ -11,12 +12,14 @@ ParsedChatCompletionMessage as ParsedChatCompletionMessage, ) from .chat_completion_message import ChatCompletionMessage as ChatCompletionMessage +from .chat_completion_modality import ChatCompletionModality as ChatCompletionModality from .completion_create_params import CompletionCreateParams as CompletionCreateParams from .parsed_function_tool_call import ( ParsedFunction as ParsedFunction, ParsedFunctionToolCall as ParsedFunctionToolCall, ) from .chat_completion_tool_param import ChatCompletionToolParam as ChatCompletionToolParam +from .chat_completion_audio_param import ChatCompletionAudioParam as ChatCompletionAudioParam from .chat_completion_message_param import ChatCompletionMessageParam as ChatCompletionMessageParam from .chat_completion_token_logprob import ChatCompletionTokenLogprob as ChatCompletionTokenLogprob from .chat_completion_message_tool_call import ChatCompletionMessageToolCall as ChatCompletionMessageToolCall @@ -52,3 +55,6 @@ from .chat_completion_function_call_option_param import ( ChatCompletionFunctionCallOptionParam as ChatCompletionFunctionCallOptionParam, ) +from .chat_completion_content_part_input_audio_param import ( + ChatCompletionContentPartInputAudioParam as ChatCompletionContentPartInputAudioParam, +) diff --git a/src/openai/types/chat/chat_completion_assistant_message_param.py b/src/openai/types/chat/chat_completion_assistant_message_param.py index 2429d41d33..35e3a3d784 100644 --- a/src/openai/types/chat/chat_completion_assistant_message_param.py +++ b/src/openai/types/chat/chat_completion_assistant_message_param.py @@ -9,7 +9,13 @@ from .chat_completion_message_tool_call_param import ChatCompletionMessageToolCallParam from .chat_completion_content_part_refusal_param import ChatCompletionContentPartRefusalParam -__all__ = ["ChatCompletionAssistantMessageParam", "ContentArrayOfContentPart", "FunctionCall"] +__all__ = ["ChatCompletionAssistantMessageParam", "Audio", "ContentArrayOfContentPart", "FunctionCall"] + + +class Audio(TypedDict, total=False): + id: Required[str] + """Unique identifier for a previous audio response from the model.""" + ContentArrayOfContentPart: TypeAlias = Union[ChatCompletionContentPartTextParam, ChatCompletionContentPartRefusalParam] @@ -31,6 +37,12 @@ class ChatCompletionAssistantMessageParam(TypedDict, total=False): role: Required[Literal["assistant"]] """The role of the messages author, in this case `assistant`.""" + audio: Optional[Audio] + """Data about a previous audio response from the model. + + [Learn more](https://platform.openai.com/docs/guides/audio). + """ + content: Union[str, Iterable[ContentArrayOfContentPart], None] """The contents of the assistant message. diff --git a/src/openai/types/chat/chat_completion_audio.py b/src/openai/types/chat/chat_completion_audio.py new file mode 100644 index 0000000000..135ee8845c --- /dev/null +++ b/src/openai/types/chat/chat_completion_audio.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +from ..._models import BaseModel + +__all__ = ["ChatCompletionAudio"] + + +class ChatCompletionAudio(BaseModel): + id: str + """Unique identifier for this audio response.""" + + data: str + """ + Base64 encoded audio bytes generated by the model, in the format specified in + the request. + """ + + expires_at: int + """ + The Unix timestamp (in seconds) for when this audio response will no longer be + accessible on the server for use in multi-turn conversations. + """ + + transcript: str + """Transcript of the audio generated by the model.""" diff --git a/src/openai/types/chat/chat_completion_audio_param.py b/src/openai/types/chat/chat_completion_audio_param.py new file mode 100644 index 0000000000..6a4ce9ac1f --- /dev/null +++ b/src/openai/types/chat/chat_completion_audio_param.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ChatCompletionAudioParam"] + + +class ChatCompletionAudioParam(TypedDict, total=False): + format: Required[Literal["wav", "mp3", "flac", "opus", "pcm16"]] + """Specifies the output audio format. + + Must be one of `wav`, `mp3`, `flac`, `opus`, or `pcm16`. + """ + + voice: Required[Literal["alloy", "echo", "fable", "onyx", "nova", "shimmer"]] + """Specifies the voice type. + + Supported voices are `alloy`, `echo`, `fable`, `onyx`, `nova`, and `shimmer`. + """ diff --git a/src/openai/types/chat/chat_completion_content_part_input_audio_param.py b/src/openai/types/chat/chat_completion_content_part_input_audio_param.py new file mode 100644 index 0000000000..0b1b1a80b1 --- /dev/null +++ b/src/openai/types/chat/chat_completion_content_part_input_audio_param.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ChatCompletionContentPartInputAudioParam", "InputAudio"] + + +class InputAudio(TypedDict, total=False): + data: Required[str] + """Base64 encoded audio data.""" + + format: Required[Literal["wav", "mp3"]] + """The format of the encoded audio data. Currently supports "wav" and "mp3".""" + + +class ChatCompletionContentPartInputAudioParam(TypedDict, total=False): + input_audio: Required[InputAudio] + + type: Required[Literal["input_audio"]] + """The type of the content part. Always `input_audio`.""" diff --git a/src/openai/types/chat/chat_completion_content_part_param.py b/src/openai/types/chat/chat_completion_content_part_param.py index e0c6e480f2..682d11f4c7 100644 --- a/src/openai/types/chat/chat_completion_content_part_param.py +++ b/src/openai/types/chat/chat_completion_content_part_param.py @@ -7,9 +7,10 @@ from .chat_completion_content_part_text_param import ChatCompletionContentPartTextParam from .chat_completion_content_part_image_param import ChatCompletionContentPartImageParam +from .chat_completion_content_part_input_audio_param import ChatCompletionContentPartInputAudioParam __all__ = ["ChatCompletionContentPartParam"] ChatCompletionContentPartParam: TypeAlias = Union[ - ChatCompletionContentPartTextParam, ChatCompletionContentPartImageParam + ChatCompletionContentPartTextParam, ChatCompletionContentPartImageParam, ChatCompletionContentPartInputAudioParam ] diff --git a/src/openai/types/chat/chat_completion_message.py b/src/openai/types/chat/chat_completion_message.py index 492bb68c85..704fa5d5d1 100644 --- a/src/openai/types/chat/chat_completion_message.py +++ b/src/openai/types/chat/chat_completion_message.py @@ -4,6 +4,7 @@ from typing_extensions import Literal from ..._models import BaseModel +from .chat_completion_audio import ChatCompletionAudio from .chat_completion_message_tool_call import ChatCompletionMessageToolCall __all__ = ["ChatCompletionMessage", "FunctionCall"] @@ -32,6 +33,13 @@ class ChatCompletionMessage(BaseModel): role: Literal["assistant"] """The role of the author of this message.""" + audio: Optional[ChatCompletionAudio] = None + """ + If the audio output modality is requested, this object contains data about the + audio response from the model. + [Learn more](https://platform.openai.com/docs/guides/audio). + """ + function_call: Optional[FunctionCall] = None """Deprecated and replaced by `tool_calls`. diff --git a/src/openai/types/chat/chat_completion_modality.py b/src/openai/types/chat/chat_completion_modality.py new file mode 100644 index 0000000000..8e3c145979 --- /dev/null +++ b/src/openai/types/chat/chat_completion_modality.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["ChatCompletionModality"] + +ChatCompletionModality: TypeAlias = Literal["text", "audio"] diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 3f55dfbe6e..af6a47c219 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -6,7 +6,9 @@ from typing_extensions import Literal, Required, TypeAlias, TypedDict from ..chat_model import ChatModel +from .chat_completion_modality import ChatCompletionModality from .chat_completion_tool_param import ChatCompletionToolParam +from .chat_completion_audio_param import ChatCompletionAudioParam from .chat_completion_message_param import ChatCompletionMessageParam from ..shared_params.function_parameters import FunctionParameters from ..shared_params.response_format_text import ResponseFormatText @@ -45,6 +47,13 @@ class CompletionCreateParamsBase(TypedDict, total=False): table for details on which models work with the Chat API. """ + audio: Optional[ChatCompletionAudioParam] + """Parameters for audio output. + + Required when audio output is requested with `modalities: ["audio"]`. + [Learn more](https://platform.openai.com/docs/guides/audio). + """ + frequency_penalty: Optional[float] """Number between -2.0 and 2.0. @@ -112,7 +121,21 @@ class CompletionCreateParamsBase(TypedDict, total=False): metadata: Optional[Dict[str, str]] """ Developer-defined tags and values used for filtering completions in the - [dashboard](https://platform.openai.com/completions). + [dashboard](https://platform.openai.com/chat-completions). + """ + + modalities: Optional[List[ChatCompletionModality]] + """ + Output types that you would like the model to generate for this request. Most + models are capable of generating text, which is the default: + + `["text"]` + + The `gpt-4o-audio-preview` model can also be used to + [generate audio](https://platform.openai.com/docs/guides/audio). To request that + this model generate both text and audio responses, you can use: + + `["text", "audio"]` """ n: Optional[int] @@ -195,8 +218,9 @@ class CompletionCreateParamsBase(TypedDict, total=False): store: Optional[bool] """ - Whether or not to store the output of this completion request for traffic - logging in the [dashboard](https://platform.openai.com/completions). + Whether or not to store the output of this chat completion request for use in + our [model distillation](https://platform.openai.com/docs/guides/distillation) + or [evals](https://platform.openai.com/docs/guides/evals) products. """ stream_options: Optional[ChatCompletionStreamOptionsParam] diff --git a/src/openai/types/chat_model.py b/src/openai/types/chat_model.py index f2d5674786..b801aa0914 100644 --- a/src/openai/types/chat_model.py +++ b/src/openai/types/chat_model.py @@ -12,7 +12,10 @@ "gpt-4o", "gpt-4o-2024-08-06", "gpt-4o-2024-05-13", + "gpt-4o-realtime-preview", "gpt-4o-realtime-preview-2024-10-01", + "gpt-4o-audio-preview", + "gpt-4o-audio-preview-2024-10-01", "chatgpt-4o-latest", "gpt-4o-mini", "gpt-4o-mini-2024-07-18", diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index 8c1f263f54..d7162dc7db 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -44,6 +44,10 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: } ], model="gpt-4o", + audio={ + "format": "wav", + "voice": "alloy", + }, frequency_penalty=-2, function_call="none", functions=[ @@ -58,6 +62,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: max_completion_tokens=0, max_tokens=0, metadata={"foo": "string"}, + modalities=["text", "audio"], n=1, parallel_tool_calls=True, presence_penalty=-2, @@ -167,6 +172,10 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: ], model="gpt-4o", stream=True, + audio={ + "format": "wav", + "voice": "alloy", + }, frequency_penalty=-2, function_call="none", functions=[ @@ -181,6 +190,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: max_completion_tokens=0, max_tokens=0, metadata={"foo": "string"}, + modalities=["text", "audio"], n=1, parallel_tool_calls=True, presence_penalty=-2, @@ -309,6 +319,10 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn } ], model="gpt-4o", + audio={ + "format": "wav", + "voice": "alloy", + }, frequency_penalty=-2, function_call="none", functions=[ @@ -323,6 +337,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn max_completion_tokens=0, max_tokens=0, metadata={"foo": "string"}, + modalities=["text", "audio"], n=1, parallel_tool_calls=True, presence_penalty=-2, @@ -432,6 +447,10 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn ], model="gpt-4o", stream=True, + audio={ + "format": "wav", + "voice": "alloy", + }, frequency_penalty=-2, function_call="none", functions=[ @@ -446,6 +465,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn max_completion_tokens=0, max_tokens=0, metadata={"foo": "string"}, + modalities=["text", "audio"], n=1, parallel_tool_calls=True, presence_penalty=-2, diff --git a/tests/lib/chat/test_completions.py b/tests/lib/chat/test_completions.py index 3cfea71f11..5cd7b1ee53 100644 --- a/tests/lib/chat/test_completions.py +++ b/tests/lib/chat/test_completions.py @@ -58,6 +58,7 @@ def test_parse_nothing(client: OpenAI, respx_mock: MockRouter, monkeypatch: pyte index=0, logprobs=None, message=ParsedChatCompletionMessage[NoneType]( + audio=None, content="I'm unable to provide real-time weather updates. To get the current weather in San Francisco, I recommend checking a reliable weather website or app like the Weather Channel or a local news station.", function_call=None, @@ -120,6 +121,7 @@ class Location(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( + audio=None, content='{"city":"San Francisco","temperature":65,"units":"f"}', function_call=None, parsed=Location(city='San Francisco', temperature=65.0, units='f'), @@ -183,6 +185,7 @@ class Location(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( + audio=None, content='{"city":"San Francisco","temperature":65,"units":"f"}', function_call=None, parsed=Location(city='San Francisco', temperature=65.0, units='f'), @@ -248,6 +251,7 @@ class ColorDetection(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[ColorDetection]( + audio=None, content='{"color":"red","hex_color_code":"#FF0000"}', function_call=None, parsed=ColorDetection(color=, hex_color_code='#FF0000'), @@ -296,6 +300,7 @@ class Location(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( + audio=None, content='{"city":"San Francisco","temperature":64,"units":"f"}', function_call=None, parsed=Location(city='San Francisco', temperature=64.0, units='f'), @@ -309,6 +314,7 @@ class Location(BaseModel): index=1, logprobs=None, message=ParsedChatCompletionMessage[Location]( + audio=None, content='{"city":"San Francisco","temperature":65,"units":"f"}', function_call=None, parsed=Location(city='San Francisco', temperature=65.0, units='f'), @@ -322,6 +328,7 @@ class Location(BaseModel): index=2, logprobs=None, message=ParsedChatCompletionMessage[Location]( + audio=None, content='{"city":"San Francisco","temperature":63.0,"units":"f"}', function_call=None, parsed=Location(city='San Francisco', temperature=63.0, units='f'), @@ -371,6 +378,7 @@ class CalendarEvent: index=0, logprobs=None, message=ParsedChatCompletionMessage[CalendarEvent]( + audio=None, content='{"name":"Science Fair","date":"Friday","participants":["Alice","Bob"]}', function_call=None, parsed=CalendarEvent(name='Science Fair', date='Friday', participants=['Alice', 'Bob']), @@ -426,6 +434,7 @@ def test_pydantic_tool_model_all_types(client: OpenAI, respx_mock: MockRouter, m index=0, logprobs=None, message=ParsedChatCompletionMessage[Query]( + audio=None, content=None, function_call=None, parsed=None, @@ -536,6 +545,7 @@ class Location(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( + audio=None, content=None, function_call=None, parsed=None, @@ -584,6 +594,7 @@ class GetWeatherArgs(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[NoneType]( + audio=None, content=None, function_call=None, parsed=None, @@ -655,6 +666,7 @@ class GetStockPrice(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[NoneType]( + audio=None, content=None, function_call=None, parsed=None, @@ -735,6 +747,7 @@ def test_parse_strict_tools(client: OpenAI, respx_mock: MockRouter, monkeypatch: index=0, logprobs=None, message=ParsedChatCompletionMessage[NoneType]( + audio=None, content=None, function_call=None, parsed=None, @@ -816,6 +829,7 @@ class Location(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( + audio=None, content='{"city":"San Francisco","temperature":58,"units":"f"}', function_call=None, parsed=Location(city='San Francisco', temperature=58.0, units='f'), @@ -885,6 +899,7 @@ class Location(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( + audio=None, content='{"city":"San Francisco","temperature":65,"units":"f"}', function_call=None, parsed=Location(city='San Francisco', temperature=65.0, units='f'), diff --git a/tests/lib/chat/test_completions_streaming.py b/tests/lib/chat/test_completions_streaming.py index 216fe9ddf5..2846e6d2c3 100644 --- a/tests/lib/chat/test_completions_streaming.py +++ b/tests/lib/chat/test_completions_streaming.py @@ -61,6 +61,7 @@ def test_parse_nothing(client: OpenAI, respx_mock: MockRouter, monkeypatch: pyte index=0, logprobs=None, message=ParsedChatCompletionMessage[NoneType]( + audio=None, content="I'm unable to provide real-time weather updates. To get the current weather in San Francisco, I recommend checking a reliable weather website or a weather app.", function_call=None, @@ -138,6 +139,7 @@ def on_event(stream: ChatCompletionStream[Location], event: ChatCompletionStream index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( + audio=None, content='{"city":"San Francisco","temperature":61,"units":"f"}', function_call=None, parsed=Location(city='San Francisco', temperature=61.0, units='f'), @@ -309,6 +311,7 @@ class Location(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( + audio=None, content='{"city":"San Francisco","temperature":65,"units":"f"}', function_call=None, parsed=Location(city='San Francisco', temperature=65.0, units='f'), @@ -322,6 +325,7 @@ class Location(BaseModel): index=1, logprobs=None, message=ParsedChatCompletionMessage[Location]( + audio=None, content='{"city":"San Francisco","temperature":61,"units":"f"}', function_call=None, parsed=Location(city='San Francisco', temperature=61.0, units='f'), @@ -335,6 +339,7 @@ class Location(BaseModel): index=2, logprobs=None, message=ParsedChatCompletionMessage[Location]( + audio=None, content='{"city":"San Francisco","temperature":59,"units":"f"}', function_call=None, parsed=Location(city='San Francisco', temperature=59.0, units='f'), @@ -409,6 +414,7 @@ class Location(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( + audio=None, content=None, function_call=None, parsed=None, @@ -482,6 +488,7 @@ def test_content_logprobs_events(client: OpenAI, respx_mock: MockRouter, monkeyp refusal=None ), message=ParsedChatCompletionMessage[NoneType]( + audio=None, content='Foo!', function_call=None, parsed=None, @@ -592,6 +599,7 @@ class Location(BaseModel): ] ), message=ParsedChatCompletionMessage[Location]( + audio=None, content=None, function_call=None, parsed=None, @@ -637,6 +645,7 @@ class GetWeatherArgs(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[object]( + audio=None, content=None, function_call=None, parsed=None, @@ -668,6 +677,7 @@ class GetWeatherArgs(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[NoneType]( + audio=None, content=None, function_call=None, parsed=None, @@ -738,6 +748,7 @@ class GetStockPrice(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[object]( + audio=None, content=None, function_call=None, parsed=None, @@ -845,6 +856,7 @@ def test_parse_strict_tools(client: OpenAI, respx_mock: MockRouter, monkeypatch: index=0, logprobs=None, message=ParsedChatCompletionMessage[object]( + audio=None, content=None, function_call=None, parsed=None, @@ -895,6 +907,7 @@ def test_non_pydantic_response_format(client: OpenAI, respx_mock: MockRouter, mo index=0, logprobs=None, message=ParsedChatCompletionMessage[NoneType]( + audio=None, content='\\n {\\n "location": "San Francisco, CA",\\n "weather": {\\n "temperature": "18°C",\\n "condition": "Partly Cloudy",\\n "humidity": "72%",\\n "windSpeed": "15 km/h",\\n "windDirection": "NW"\\n },\\n "forecast": [\\n {\\n "day": "Monday",\\n "high": "20°C",\\n "low": "14°C",\\n @@ -954,6 +967,7 @@ def test_allows_non_strict_tools_but_no_parsing( index=0, logprobs=None, message=ParsedChatCompletionMessage[NoneType]( + audio=None, content=None, function_call=None, parsed=None, From fc4fce30aff7620c32e57301d3c40b4883810825 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 17 Oct 2024 16:51:33 +0000 Subject: [PATCH 540/816] release: 1.52.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 395be07b55..37d774d68f 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.51.2" + ".": "1.52.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f583fe89f..55691f3fd7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.52.0 (2024-10-17) + +Full Changelog: [v1.51.2...v1.52.0](https://github.com/openai/openai-python/compare/v1.51.2...v1.52.0) + +### Features + +* **api:** add gpt-4o-audio-preview model for chat completions ([#1796](https://github.com/openai/openai-python/issues/1796)) ([fbf1e0c](https://github.com/openai/openai-python/commit/fbf1e0c25c4d163f06b61a43d1a94ce001033a7b)) + ## 1.51.2 (2024-10-08) Full Changelog: [v1.51.1...v1.51.2](https://github.com/openai/openai-python/compare/v1.51.1...v1.51.2) diff --git a/pyproject.toml b/pyproject.toml index 8da5e0e2ce..490685d76d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.51.2" +version = "1.52.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index cb98e08a8a..cb5e5ffd0d 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.51.2" # x-release-please-version +__version__ = "1.52.0" # x-release-please-version From 8b5176139e93820d88f89e765685257f175bf77f Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 17 Oct 2024 17:40:28 +0000 Subject: [PATCH 541/816] chore(internal): update test syntax (#1798) --- tests/test_models.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_models.py b/tests/test_models.py index b703444248..117a90020e 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -245,7 +245,7 @@ class Model(BaseModel): assert m.foo is True m = Model.construct(foo="CARD_HOLDER") - assert m.foo is "CARD_HOLDER" + assert m.foo == "CARD_HOLDER" m = Model.construct(foo={"bar": False}) assert isinstance(m.foo, Submodel1) From 38d87a3d50b00d460401bb5c7ce023102f843d16 Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Fri, 18 Oct 2024 18:16:03 +0000 Subject: [PATCH 542/816] chore(internal): bump ruff dependency (#1801) --- pyproject.toml | 3 ++- requirements-dev.lock | 2 +- src/openai/types/chat/chat_completion_audio.py | 1 - 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 490685d76d..900fbdda8c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -74,11 +74,12 @@ format = { chain = [ "format:ruff", "format:docs", "fix:ruff", + # run formatting again to fix any inconsistencies when imports are stripped + "format:ruff", ]} "format:black" = "black ." "format:docs" = "python scripts/utils/ruffen-docs.py README.md api.md" "format:ruff" = "ruff format" -"format:isort" = "isort ." "lint" = { chain = [ "check:ruff", diff --git a/requirements-dev.lock b/requirements-dev.lock index a47de9656a..902a80c6ed 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -141,7 +141,7 @@ requests==2.31.0 respx==0.20.2 rich==13.7.1 # via inline-snapshot -ruff==0.6.5 +ruff==0.6.9 setuptools==68.2.2 # via nodeenv six==1.16.0 diff --git a/src/openai/types/chat/chat_completion_audio.py b/src/openai/types/chat/chat_completion_audio.py index 135ee8845c..dd15508ebb 100644 --- a/src/openai/types/chat/chat_completion_audio.py +++ b/src/openai/types/chat/chat_completion_audio.py @@ -1,7 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from ..._models import BaseModel __all__ = ["ChatCompletionAudio"] From a366120a4ef9b0865a039230161a6f7ee0885ff5 Mon Sep 17 00:00:00 2001 From: fzyzcjy <5236035+fzyzcjy@users.noreply.github.com> Date: Mon, 21 Oct 2024 14:43:12 +0800 Subject: [PATCH 543/816] fix(client/async): correctly retry in all cases (#1803) --- src/openai/_base_client.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index b2929df072..e1d4849ae2 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -1591,7 +1591,7 @@ async def _request( except Exception as err: log.debug("Encountered Exception", exc_info=True) - if retries_taken > 0: + if remaining_retries > 0: return await self._retry_request( input_options, cast_to, From 6634f5250c98a2487a29458e997c6f9e9ee66e02 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 21 Oct 2024 07:23:51 +0000 Subject: [PATCH 544/816] chore(tests): add more retry tests (#1806) --- tests/test_client.py | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/tests/test_client.py b/tests/test_client.py index 1da35ddd22..ff07ec393b 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -10,6 +10,7 @@ import tracemalloc from typing import Any, Union, cast from unittest import mock +from typing_extensions import Literal import httpx import pytest @@ -764,7 +765,14 @@ def test_retrying_status_errors_doesnt_leak(self, respx_mock: MockRouter) -> Non @pytest.mark.parametrize("failures_before_success", [0, 2, 4]) @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) @pytest.mark.respx(base_url=base_url) - def test_retries_taken(self, client: OpenAI, failures_before_success: int, respx_mock: MockRouter) -> None: + @pytest.mark.parametrize("failure_mode", ["status", "exception"]) + def test_retries_taken( + self, + client: OpenAI, + failures_before_success: int, + failure_mode: Literal["status", "exception"], + respx_mock: MockRouter, + ) -> None: client = client.with_options(max_retries=4) nb_retries = 0 @@ -773,6 +781,8 @@ def retry_handler(_request: httpx.Request) -> httpx.Response: nonlocal nb_retries if nb_retries < failures_before_success: nb_retries += 1 + if failure_mode == "exception": + raise RuntimeError("oops") return httpx.Response(500) return httpx.Response(200) @@ -1623,8 +1633,13 @@ async def test_retrying_status_errors_doesnt_leak(self, respx_mock: MockRouter) @mock.patch("openai._base_client.BaseClient._calculate_retry_timeout", _low_retry_timeout) @pytest.mark.respx(base_url=base_url) @pytest.mark.asyncio + @pytest.mark.parametrize("failure_mode", ["status", "exception"]) async def test_retries_taken( - self, async_client: AsyncOpenAI, failures_before_success: int, respx_mock: MockRouter + self, + async_client: AsyncOpenAI, + failures_before_success: int, + failure_mode: Literal["status", "exception"], + respx_mock: MockRouter, ) -> None: client = async_client.with_options(max_retries=4) @@ -1634,6 +1649,8 @@ def retry_handler(_request: httpx.Request) -> httpx.Response: nonlocal nb_retries if nb_retries < failures_before_success: nb_retries += 1 + if failure_mode == "exception": + raise RuntimeError("oops") return httpx.Response(500) return httpx.Response(200) From b186bc5786b75fb06260eadc32581438c0e61ea1 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 21 Oct 2024 11:54:15 +0000 Subject: [PATCH 545/816] chore(internal): remove unused black config (#1807) --- pyproject.toml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 900fbdda8c..4de8d3889b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -77,7 +77,6 @@ format = { chain = [ # run formatting again to fix any inconsistencies when imports are stripped "format:ruff", ]} -"format:black" = "black ." "format:docs" = "python scripts/utils/ruffen-docs.py README.md api.md" "format:ruff" = "ruff format" @@ -137,10 +136,6 @@ path = "README.md" pattern = '\[(.+?)\]\(((?!https?://)\S+?)\)' replacement = '[\1](https://github.com/openai/openai-python/tree/main/\g<2>)' -[tool.black] -line-length = 120 -target-version = ["py37"] - [tool.pytest.ini_options] testpaths = ["tests"] addopts = "--tb=short" From 73d20deb4792c13cbbf1861aef31c9a1123568d8 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 22 Oct 2024 18:24:19 +0000 Subject: [PATCH 546/816] chore(internal): update spec version (#1810) --- .stats.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index 984e8a8d5f..e1a430e50a 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-8729aaa35436531ab453224af10e67f89677db8f350f0346bb3537489edea649.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-f9320ebf347140052c7f8b0bc5c7db24f5e367c368c8cb34c3606af4e2b6591b.yml From 262f163cf19f22f45c493de0238a77c9e39f9e0a Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 22 Oct 2024 18:24:50 +0000 Subject: [PATCH 547/816] release: 1.52.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 17 +++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 20 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 37d774d68f..89493ef540 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.52.0" + ".": "1.52.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 55691f3fd7..c00cc6e66d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,22 @@ # Changelog +## 1.52.1 (2024-10-22) + +Full Changelog: [v1.52.0...v1.52.1](https://github.com/openai/openai-python/compare/v1.52.0...v1.52.1) + +### Bug Fixes + +* **client/async:** correctly retry in all cases ([#1803](https://github.com/openai/openai-python/issues/1803)) ([9fe3f3f](https://github.com/openai/openai-python/commit/9fe3f3f925e06769b7ef6abbf1314a5e82749b4a)) + + +### Chores + +* **internal:** bump ruff dependency ([#1801](https://github.com/openai/openai-python/issues/1801)) ([859c672](https://github.com/openai/openai-python/commit/859c6725865f1b3285698f68693f9491d511f7ea)) +* **internal:** remove unused black config ([#1807](https://github.com/openai/openai-python/issues/1807)) ([112dab0](https://github.com/openai/openai-python/commit/112dab0290342654265db612c37d327d652251bb)) +* **internal:** update spec version ([#1810](https://github.com/openai/openai-python/issues/1810)) ([aa25b7b](https://github.com/openai/openai-python/commit/aa25b7b88823836b418a63da59491f5f3842773c)) +* **internal:** update test syntax ([#1798](https://github.com/openai/openai-python/issues/1798)) ([d3098dd](https://github.com/openai/openai-python/commit/d3098dd0b9fbe627c21a8ad39c119d125b7cdb54)) +* **tests:** add more retry tests ([#1806](https://github.com/openai/openai-python/issues/1806)) ([5525a1b](https://github.com/openai/openai-python/commit/5525a1ba536058ecc13411e1f98e88f7ec4bf8b9)) + ## 1.52.0 (2024-10-17) Full Changelog: [v1.51.2...v1.52.0](https://github.com/openai/openai-python/compare/v1.51.2...v1.52.0) diff --git a/pyproject.toml b/pyproject.toml index 4de8d3889b..3ebb38343e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.52.0" +version = "1.52.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index cb5e5ffd0d..a027560c44 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.52.0" # x-release-please-version +__version__ = "1.52.1" # x-release-please-version From 865e390b537405ff16019ecac141eda9fd3a2a09 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 23 Oct 2024 21:57:02 +0000 Subject: [PATCH 548/816] chore(internal): update spec version (#1816) --- .stats.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index e1a430e50a..0b08725565 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-f9320ebf347140052c7f8b0bc5c7db24f5e367c368c8cb34c3606af4e2b6591b.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-b60d5559d5150ecd3b49136064e5e251d832899770ff385b711378389afba370.yml From e1b2f8216cc69e802475a0d438e40e0e74510de4 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 23 Oct 2024 21:57:32 +0000 Subject: [PATCH 549/816] release: 1.52.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 89493ef540..2f2a30a82e 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.52.1" + ".": "1.52.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index c00cc6e66d..21f6136744 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.52.2 (2024-10-23) + +Full Changelog: [v1.52.1...v1.52.2](https://github.com/openai/openai-python/compare/v1.52.1...v1.52.2) + +### Chores + +* **internal:** update spec version ([#1816](https://github.com/openai/openai-python/issues/1816)) ([c23282a](https://github.com/openai/openai-python/commit/c23282a328c48af90a88673ff5f6cc7a866f8758)) + ## 1.52.1 (2024-10-22) Full Changelog: [v1.52.0...v1.52.1](https://github.com/openai/openai-python/compare/v1.52.0...v1.52.1) diff --git a/pyproject.toml b/pyproject.toml index 3ebb38343e..3bd6246e43 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.52.1" +version = "1.52.2" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index a027560c44..641d4f5b30 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.52.1" # x-release-please-version +__version__ = "1.52.2" # x-release-please-version From 44ac1cef62316cc6c4548eb2007a93de9ddb6825 Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Mon, 28 Oct 2024 12:28:17 +0000 Subject: [PATCH 550/816] chore(internal): bump pytest to v8 & pydantic (#1829) --- requirements-dev.lock | 43 +++++++++---------- requirements.lock | 18 ++++---- src/openai/_compat.py | 2 +- src/openai/_models.py | 10 ++--- src/openai/_types.py | 6 ++- src/openai/lib/streaming/chat/_completions.py | 18 +++++--- tests/conftest.py | 14 +++--- tests/lib/test_old_api.py | 2 +- 8 files changed, 60 insertions(+), 53 deletions(-) diff --git a/requirements-dev.lock b/requirements-dev.lock index 902a80c6ed..2df8a39c76 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -18,14 +18,13 @@ argcomplete==3.1.2 # via nox asttokens==2.4.1 # via inline-snapshot -attrs==23.1.0 +attrs==24.2.0 # via outcome - # via pytest # via trio -azure-core==1.30.1 +azure-core==1.31.0 # via azure-identity -azure-identity==1.15.0 -black==24.4.2 +azure-identity==1.19.0 +black==24.10.0 # via inline-snapshot certifi==2023.7.22 # via httpcore @@ -49,10 +48,11 @@ distlib==0.3.7 # via virtualenv distro==1.8.0 # via openai -exceptiongroup==1.1.3 +exceptiongroup==1.2.2 # via anyio + # via pytest # via trio -executing==2.0.1 +executing==2.1.0 # via inline-snapshot filelock==3.12.4 # via virtualenv @@ -78,7 +78,7 @@ markdown-it-py==3.0.0 # via rich mdurl==0.1.2 # via markdown-it-py -msal==1.29.0 +msal==1.31.0 # via azure-identity # via msal-extensions msal-extensions==1.2.0 @@ -109,26 +109,24 @@ pathspec==0.12.1 platformdirs==3.11.0 # via black # via virtualenv -pluggy==1.3.0 +pluggy==1.5.0 # via pytest -portalocker==2.8.2 +portalocker==2.10.1 # via msal-extensions -py==1.11.0 - # via pytest pycparser==2.22 # via cffi -pydantic==2.7.1 +pydantic==2.9.2 # via openai -pydantic-core==2.18.2 +pydantic-core==2.23.4 # via pydantic pygments==2.18.0 # via rich pyjwt==2.8.0 # via msal pyright==1.1.380 -pytest==7.1.1 +pytest==8.3.3 # via pytest-asyncio -pytest-asyncio==0.21.1 +pytest-asyncio==0.24.0 python-dateutil==2.8.2 # via pandas # via time-machine @@ -158,21 +156,22 @@ sortedcontainers==2.4.0 time-machine==2.9.0 toml==0.10.2 # via inline-snapshot -tomli==2.0.1 +tomli==2.0.2 # via black # via mypy # via pytest -tqdm==4.66.1 +tqdm==4.66.5 # via openai -trio==0.22.2 -types-pyaudio==0.2.16.20240106 -types-pytz==2024.1.0.20240417 +trio==0.27.0 +types-pyaudio==0.2.16.20240516 +types-pytz==2024.2.0.20241003 # via pandas-stubs types-toml==0.10.8.20240310 # via inline-snapshot -types-tqdm==4.66.0.2 +types-tqdm==4.66.0.20240417 typing-extensions==4.12.2 # via azure-core + # via azure-identity # via black # via mypy # via openai diff --git a/requirements.lock b/requirements.lock index de632aefbd..019dfcb4c5 100644 --- a/requirements.lock +++ b/requirements.lock @@ -19,7 +19,7 @@ certifi==2023.7.22 # via httpx distro==1.8.0 # via openai -exceptiongroup==1.1.3 +exceptiongroup==1.2.2 # via anyio h11==0.14.0 # via httpcore @@ -30,19 +30,19 @@ httpx==0.25.2 idna==3.4 # via anyio # via httpx -jiter==0.5.0 +jiter==0.6.1 # via openai -numpy==1.26.4 +numpy==2.0.2 # via openai # via pandas # via pandas-stubs -pandas==2.2.2 +pandas==2.2.3 # via openai -pandas-stubs==2.2.1.240316 +pandas-stubs==2.2.2.240807 # via openai -pydantic==2.7.1 +pydantic==2.9.2 # via openai -pydantic-core==2.18.2 +pydantic-core==2.23.4 # via pydantic python-dateutil==2.9.0.post0 # via pandas @@ -54,9 +54,9 @@ sniffio==1.3.0 # via anyio # via httpx # via openai -tqdm==4.66.1 +tqdm==4.66.5 # via openai -types-pytz==2024.1.0.20240417 +types-pytz==2024.2.0.20241003 # via pandas-stubs typing-extensions==4.12.2 # via openai diff --git a/src/openai/_compat.py b/src/openai/_compat.py index 78851277eb..4dfa23845d 100644 --- a/src/openai/_compat.py +++ b/src/openai/_compat.py @@ -133,7 +133,7 @@ def model_json(model: pydantic.BaseModel, *, indent: int | None = None) -> str: def model_dump( model: pydantic.BaseModel, *, - exclude: IncEx = None, + exclude: IncEx | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, warnings: bool = True, diff --git a/src/openai/_models.py b/src/openai/_models.py index 710401defd..4100328c22 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -201,7 +201,7 @@ def __str__(self) -> str: # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836. @classmethod @override - def construct( + def construct( # pyright: ignore[reportIncompatibleMethodOverride] cls: Type[ModelT], _fields_set: set[str] | None = None, **values: object, @@ -273,8 +273,8 @@ def model_dump( self, *, mode: Literal["json", "python"] | str = "python", - include: IncEx = None, - exclude: IncEx = None, + include: IncEx | None = None, + exclude: IncEx | None = None, by_alias: bool = False, exclude_unset: bool = False, exclude_defaults: bool = False, @@ -328,8 +328,8 @@ def model_dump_json( self, *, indent: int | None = None, - include: IncEx = None, - exclude: IncEx = None, + include: IncEx | None = None, + exclude: IncEx | None = None, by_alias: bool = False, exclude_unset: bool = False, exclude_defaults: bool = False, diff --git a/src/openai/_types.py b/src/openai/_types.py index 5611b2d38f..c8f4d5a922 100644 --- a/src/openai/_types.py +++ b/src/openai/_types.py @@ -16,7 +16,7 @@ Optional, Sequence, ) -from typing_extensions import Literal, Protocol, TypeAlias, TypedDict, override, runtime_checkable +from typing_extensions import Set, Literal, Protocol, TypeAlias, TypedDict, override, runtime_checkable import httpx import pydantic @@ -195,7 +195,9 @@ def get(self, __key: str) -> str | None: ... # Note: copied from Pydantic # https://github.com/pydantic/pydantic/blob/32ea570bf96e84234d2992e1ddf40ab8a565925a/pydantic/main.py#L49 -IncEx: TypeAlias = "set[int] | set[str] | dict[int, Any] | dict[str, Any] | None" +IncEx: TypeAlias = Union[ + Set[int], Set[str], Mapping[int, Union["IncEx", Literal[True]]], Mapping[str, Union["IncEx", Literal[True]]] +] PostParser = Callable[[Any], Any] diff --git a/src/openai/lib/streaming/chat/_completions.py b/src/openai/lib/streaming/chat/_completions.py index a4b0f856f7..8518de967f 100644 --- a/src/openai/lib/streaming/chat/_completions.py +++ b/src/openai/lib/streaming/chat/_completions.py @@ -23,7 +23,7 @@ FunctionToolCallArgumentsDeltaEvent, ) from .._deltas import accumulate_delta -from ...._types import NOT_GIVEN, NotGiven +from ...._types import NOT_GIVEN, IncEx, NotGiven from ...._utils import is_given, consume_sync_iterator, consume_async_iterator from ...._compat import model_dump from ...._models import build, construct_type @@ -352,13 +352,17 @@ def _accumulate_chunk(self, chunk: ChatCompletionChunk) -> ParsedChatCompletionS # we don't want to serialise / deserialise our custom properties # as they won't appear in the delta and we don't want to have to # continuosly reparse the content - exclude={ - "parsed": True, - "tool_calls": { - idx: {"function": {"parsed_arguments": True}} - for idx, _ in enumerate(choice_snapshot.message.tool_calls or []) + exclude=cast( + # cast required as mypy isn't smart enough to infer `True` here to `Literal[True]` + IncEx, + { + "parsed": True, + "tool_calls": { + idx: {"function": {"parsed_arguments": True}} + for idx, _ in enumerate(choice_snapshot.message.tool_calls or []) + }, }, - }, + ), ), ), cast("dict[object, object]", choice.delta.to_dict()), diff --git a/tests/conftest.py b/tests/conftest.py index 15af57e770..fa82d39d86 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,11 +1,11 @@ from __future__ import annotations import os -import asyncio import logging from typing import TYPE_CHECKING, Iterator, AsyncIterator import pytest +from pytest_asyncio import is_async_test from openai import OpenAI, AsyncOpenAI @@ -17,11 +17,13 @@ logging.getLogger("openai").setLevel(logging.DEBUG) -@pytest.fixture(scope="session") -def event_loop() -> Iterator[asyncio.AbstractEventLoop]: - loop = asyncio.new_event_loop() - yield loop - loop.close() +# automatically add `pytest.mark.asyncio()` to all of our async tests +# so we don't have to add that boilerplate everywhere +def pytest_collection_modifyitems(items: list[pytest.Function]) -> None: + pytest_asyncio_tests = (item for item in items if is_async_test(item)) + session_scope_marker = pytest.mark.asyncio(loop_scope="session") + for async_test in pytest_asyncio_tests: + async_test.add_marker(session_scope_marker, append=False) base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") diff --git a/tests/lib/test_old_api.py b/tests/lib/test_old_api.py index 261b8acb94..bdb2a5398d 100644 --- a/tests/lib/test_old_api.py +++ b/tests/lib/test_old_api.py @@ -6,7 +6,7 @@ def test_basic_attribute_access_works() -> None: for attr in dir(openai): - dir(getattr(openai, attr)) + getattr(openai, attr) def test_helpful_error_is_raised() -> None: From c3ee00623709fcc67e9248af1c907cc7e863a5fd Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Wed, 30 Oct 2024 16:11:41 +0000 Subject: [PATCH 551/816] feat(api): add new, expressive voices for Realtime and Audio in Chat Completions https://platform.openai.com/docs/changelog --- .stats.yml | 2 +- src/openai/types/chat/chat_completion_audio_param.py | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/.stats.yml b/.stats.yml index 0b08725565..39413df445 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-b60d5559d5150ecd3b49136064e5e251d832899770ff385b711378389afba370.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-7b0a5d715d94f75ac7795bd4d2175a0e3243af9b935a86c273f371e45583140f.yml diff --git a/src/openai/types/chat/chat_completion_audio_param.py b/src/openai/types/chat/chat_completion_audio_param.py index 6a4ce9ac1f..b92326d294 100644 --- a/src/openai/types/chat/chat_completion_audio_param.py +++ b/src/openai/types/chat/chat_completion_audio_param.py @@ -14,8 +14,9 @@ class ChatCompletionAudioParam(TypedDict, total=False): Must be one of `wav`, `mp3`, `flac`, `opus`, or `pcm16`. """ - voice: Required[Literal["alloy", "echo", "fable", "onyx", "nova", "shimmer"]] - """Specifies the voice type. + voice: Required[Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"]] + """The voice the model uses to respond. - Supported voices are `alloy`, `echo`, `fable`, `onyx`, `nova`, and `shimmer`. + Supported voices are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, + `shimmer`, and `verse`. """ From 891e1c17b7fecbae34d1915ba90c15ddece807f9 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 30 Oct 2024 16:27:56 +0000 Subject: [PATCH 552/816] release: 1.53.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 2f2a30a82e..0b97f7533e 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.52.2" + ".": "1.53.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 21f6136744..4f5a63ae72 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.53.0 (2024-10-30) + +Full Changelog: [v1.52.2...v1.53.0](https://github.com/openai/openai-python/compare/v1.52.2...v1.53.0) + +### Features + +* **api:** add new, expressive voices for Realtime and Audio in Chat Completions ([7cf0a49](https://github.com/openai/openai-python/commit/7cf0a4958e4c985bef4d18bb919fa3948f389a82)) + + +### Chores + +* **internal:** bump pytest to v8 & pydantic ([#1829](https://github.com/openai/openai-python/issues/1829)) ([0e67a8a](https://github.com/openai/openai-python/commit/0e67a8af5daf9da029d2bd4bdf341cc8a494254a)) + ## 1.52.2 (2024-10-23) Full Changelog: [v1.52.1...v1.52.2](https://github.com/openai/openai-python/compare/v1.52.1...v1.52.2) diff --git a/pyproject.toml b/pyproject.toml index 3bd6246e43..46aced6fba 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.52.2" +version = "1.53.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 641d4f5b30..afda9b903f 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.52.2" # x-release-please-version +__version__ = "1.53.0" # x-release-please-version From c94ead1d0c865bb9a0c8b787149d1f34317ca935 Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Fri, 1 Nov 2024 12:34:07 +0000 Subject: [PATCH 553/816] chore(internal): bump mypy (#1839) --- requirements-dev.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.lock b/requirements-dev.lock index 2df8a39c76..5fe1ccad57 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -83,7 +83,7 @@ msal==1.31.0 # via msal-extensions msal-extensions==1.2.0 # via azure-identity -mypy==1.11.2 +mypy==1.13.0 mypy-extensions==1.0.0 # via black # via mypy From 643e500c52831f1966f16d7173651d06cb886a31 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Sat, 2 Nov 2024 02:46:36 +0000 Subject: [PATCH 554/816] fix: don't use dicts as iterables in transform (#1842) --- src/openai/_utils/_transform.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/openai/_utils/_transform.py b/src/openai/_utils/_transform.py index 47e262a515..7e9663d369 100644 --- a/src/openai/_utils/_transform.py +++ b/src/openai/_utils/_transform.py @@ -173,6 +173,11 @@ def _transform_recursive( # Iterable[T] or (is_iterable_type(stripped_type) and is_iterable(data) and not isinstance(data, str)) ): + # dicts are technically iterable, but it is an iterable on the keys of the dict and is not usually + # intended as an iterable, so we don't transform it. + if isinstance(data, dict): + return cast(object, data) + inner_type = extract_type_arg(stripped_type, 0) return [_transform_recursive(d, annotation=annotation, inner_type=inner_type) for d in data] From d21cd6c042e88629b81ae85c7d7023c973aa14f5 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 4 Nov 2024 14:59:58 +0000 Subject: [PATCH 555/816] fix: support json safe serialization for basemodel subclasses (#1844) --- src/openai/_compat.py | 6 ++++-- src/openai/_models.py | 9 ++++++--- src/openai/_utils/__init__.py | 1 + src/openai/_utils/_transform.py | 4 ++-- src/openai/_utils/_utils.py | 17 +++++++++++++++++ tests/test_models.py | 21 +++++++-------------- tests/test_transform.py | 15 +++++++++++++++ 7 files changed, 52 insertions(+), 21 deletions(-) diff --git a/src/openai/_compat.py b/src/openai/_compat.py index 4dfa23845d..7c3156a5eb 100644 --- a/src/openai/_compat.py +++ b/src/openai/_compat.py @@ -2,7 +2,7 @@ from typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, cast, overload from datetime import date, datetime -from typing_extensions import Self +from typing_extensions import Self, Literal import pydantic from pydantic.fields import FieldInfo @@ -137,9 +137,11 @@ def model_dump( exclude_unset: bool = False, exclude_defaults: bool = False, warnings: bool = True, + mode: Literal["json", "python"] = "python", ) -> dict[str, Any]: - if PYDANTIC_V2: + if PYDANTIC_V2 or hasattr(model, "model_dump"): return model.model_dump( + mode=mode, exclude=exclude, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, diff --git a/src/openai/_models.py b/src/openai/_models.py index 4100328c22..20cd4c29bc 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -38,6 +38,7 @@ PropertyInfo, is_list, is_given, + json_safe, lru_cache, is_mapping, parse_date, @@ -304,8 +305,8 @@ def model_dump( Returns: A dictionary representation of the model. """ - if mode != "python": - raise ValueError("mode is only supported in Pydantic v2") + if mode not in {"json", "python"}: + raise ValueError("mode must be either 'json' or 'python'") if round_trip != False: raise ValueError("round_trip is only supported in Pydantic v2") if warnings != True: @@ -314,7 +315,7 @@ def model_dump( raise ValueError("context is only supported in Pydantic v2") if serialize_as_any != False: raise ValueError("serialize_as_any is only supported in Pydantic v2") - return super().dict( # pyright: ignore[reportDeprecated] + dumped = super().dict( # pyright: ignore[reportDeprecated] include=include, exclude=exclude, by_alias=by_alias, @@ -323,6 +324,8 @@ def model_dump( exclude_none=exclude_none, ) + return cast(dict[str, Any], json_safe(dumped)) if mode == "json" else dumped + @override def model_dump_json( self, diff --git a/src/openai/_utils/__init__.py b/src/openai/_utils/__init__.py index 3efe66c8e8..a7cff3c091 100644 --- a/src/openai/_utils/__init__.py +++ b/src/openai/_utils/__init__.py @@ -6,6 +6,7 @@ is_list as is_list, is_given as is_given, is_tuple as is_tuple, + json_safe as json_safe, lru_cache as lru_cache, is_mapping as is_mapping, is_tuple_t as is_tuple_t, diff --git a/src/openai/_utils/_transform.py b/src/openai/_utils/_transform.py index 7e9663d369..d7c05345d1 100644 --- a/src/openai/_utils/_transform.py +++ b/src/openai/_utils/_transform.py @@ -191,7 +191,7 @@ def _transform_recursive( return data if isinstance(data, pydantic.BaseModel): - return model_dump(data, exclude_unset=True) + return model_dump(data, exclude_unset=True, mode="json") annotated_type = _get_annotated_type(annotation) if annotated_type is None: @@ -329,7 +329,7 @@ async def _async_transform_recursive( return data if isinstance(data, pydantic.BaseModel): - return model_dump(data, exclude_unset=True) + return model_dump(data, exclude_unset=True, mode="json") annotated_type = _get_annotated_type(annotation) if annotated_type is None: diff --git a/src/openai/_utils/_utils.py b/src/openai/_utils/_utils.py index 0bba17caad..e5811bba42 100644 --- a/src/openai/_utils/_utils.py +++ b/src/openai/_utils/_utils.py @@ -16,6 +16,7 @@ overload, ) from pathlib import Path +from datetime import date, datetime from typing_extensions import TypeGuard import sniffio @@ -395,3 +396,19 @@ def lru_cache(*, maxsize: int | None = 128) -> Callable[[CallableT], CallableT]: maxsize=maxsize, ) return cast(Any, wrapper) # type: ignore[no-any-return] + + +def json_safe(data: object) -> object: + """Translates a mapping / sequence recursively in the same fashion + as `pydantic` v2's `model_dump(mode="json")`. + """ + if is_mapping(data): + return {json_safe(key): json_safe(value) for key, value in data.items()} + + if is_iterable(data) and not isinstance(data, (str, bytes, bytearray)): + return [json_safe(item) for item in data] + + if isinstance(data, (datetime, date)): + return data.isoformat() + + return data diff --git a/tests/test_models.py b/tests/test_models.py index 117a90020e..84dbce6914 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -520,19 +520,15 @@ class Model(BaseModel): assert m3.to_dict(exclude_none=True) == {} assert m3.to_dict(exclude_defaults=True) == {} - if PYDANTIC_V2: - - class Model2(BaseModel): - created_at: datetime + class Model2(BaseModel): + created_at: datetime - time_str = "2024-03-21T11:39:01.275859" - m4 = Model2.construct(created_at=time_str) - assert m4.to_dict(mode="python") == {"created_at": datetime.fromisoformat(time_str)} - assert m4.to_dict(mode="json") == {"created_at": time_str} - else: - with pytest.raises(ValueError, match="mode is only supported in Pydantic v2"): - m.to_dict(mode="json") + time_str = "2024-03-21T11:39:01.275859" + m4 = Model2.construct(created_at=time_str) + assert m4.to_dict(mode="python") == {"created_at": datetime.fromisoformat(time_str)} + assert m4.to_dict(mode="json") == {"created_at": time_str} + if not PYDANTIC_V2: with pytest.raises(ValueError, match="warnings is only supported in Pydantic v2"): m.to_dict(warnings=False) @@ -558,9 +554,6 @@ class Model(BaseModel): assert m3.model_dump(exclude_none=True) == {} if not PYDANTIC_V2: - with pytest.raises(ValueError, match="mode is only supported in Pydantic v2"): - m.model_dump(mode="json") - with pytest.raises(ValueError, match="round_trip is only supported in Pydantic v2"): m.model_dump(round_trip=True) diff --git a/tests/test_transform.py b/tests/test_transform.py index 1eb6cde9d6..8c6aba6448 100644 --- a/tests/test_transform.py +++ b/tests/test_transform.py @@ -177,17 +177,32 @@ class DateDict(TypedDict, total=False): foo: Annotated[date, PropertyInfo(format="iso8601")] +class DatetimeModel(BaseModel): + foo: datetime + + +class DateModel(BaseModel): + foo: Optional[date] + + @parametrize @pytest.mark.asyncio async def test_iso8601_format(use_async: bool) -> None: dt = datetime.fromisoformat("2023-02-23T14:16:36.337692+00:00") + tz = "Z" if PYDANTIC_V2 else "+00:00" assert await transform({"foo": dt}, DatetimeDict, use_async) == {"foo": "2023-02-23T14:16:36.337692+00:00"} # type: ignore[comparison-overlap] + assert await transform(DatetimeModel(foo=dt), Any, use_async) == {"foo": "2023-02-23T14:16:36.337692" + tz} # type: ignore[comparison-overlap] dt = dt.replace(tzinfo=None) assert await transform({"foo": dt}, DatetimeDict, use_async) == {"foo": "2023-02-23T14:16:36.337692"} # type: ignore[comparison-overlap] + assert await transform(DatetimeModel(foo=dt), Any, use_async) == {"foo": "2023-02-23T14:16:36.337692"} # type: ignore[comparison-overlap] assert await transform({"foo": None}, DateDict, use_async) == {"foo": None} # type: ignore[comparison-overlap] + assert await transform(DateModel(foo=None), Any, use_async) == {"foo": None} # type: ignore assert await transform({"foo": date.fromisoformat("2023-02-23")}, DateDict, use_async) == {"foo": "2023-02-23"} # type: ignore[comparison-overlap] + assert await transform(DateModel(foo=date.fromisoformat("2023-02-23")), DateDict, use_async) == { + "foo": "2023-02-23" + } # type: ignore[comparison-overlap] @parametrize From 6e42e7879a8e22db9268d1ef2f3b80428534e752 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 4 Nov 2024 15:00:39 +0000 Subject: [PATCH 556/816] release: 1.53.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 14 ++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 17 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 0b97f7533e..5a86c0906c 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.53.0" + ".": "1.53.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f5a63ae72..c3a5a3cecb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,19 @@ # Changelog +## 1.53.1 (2024-11-04) + +Full Changelog: [v1.53.0...v1.53.1](https://github.com/openai/openai-python/compare/v1.53.0...v1.53.1) + +### Bug Fixes + +* don't use dicts as iterables in transform ([#1842](https://github.com/openai/openai-python/issues/1842)) ([258f265](https://github.com/openai/openai-python/commit/258f26535744ab3b2f0746991fd29eae72ebd667)) +* support json safe serialization for basemodel subclasses ([#1844](https://github.com/openai/openai-python/issues/1844)) ([2b80c90](https://github.com/openai/openai-python/commit/2b80c90c21d3b2468dfa3bf40c08c5b0e0eebffa)) + + +### Chores + +* **internal:** bump mypy ([#1839](https://github.com/openai/openai-python/issues/1839)) ([d92f959](https://github.com/openai/openai-python/commit/d92f959aa6f49be56574b4d1d1ac5ac48689dd46)) + ## 1.53.0 (2024-10-30) Full Changelog: [v1.52.2...v1.53.0](https://github.com/openai/openai-python/compare/v1.52.2...v1.53.0) diff --git a/pyproject.toml b/pyproject.toml index 46aced6fba..974e5fc740 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.53.0" +version = "1.53.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index afda9b903f..9d221eb538 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.53.0" # x-release-please-version +__version__ = "1.53.1" # x-release-please-version From cb88c2f01dd02b10ece80974f0b6403ae5921298 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 4 Nov 2024 18:00:25 +0000 Subject: [PATCH 557/816] feat(project): drop support for Python 3.7 (#1845) 3.7 has been EOL for over a year and accounts for a small number of downloads --- README.md | 4 ++-- pyproject.toml | 5 ++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index dada1abfbb..bc334e7e07 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [![PyPI version](https://img.shields.io/pypi/v/openai.svg)](https://pypi.org/project/openai/) -The OpenAI Python library provides convenient access to the OpenAI REST API from any Python 3.7+ +The OpenAI Python library provides convenient access to the OpenAI REST API from any Python 3.8+ application. The library includes type definitions for all request params and response fields, and offers both synchronous and asynchronous clients powered by [httpx](https://github.com/encode/httpx). @@ -712,7 +712,7 @@ print(openai.__version__) ## Requirements -Python 3.7 or higher. +Python 3.8 or higher. ## Contributing diff --git a/pyproject.toml b/pyproject.toml index 974e5fc740..20c0f3bb15 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -18,11 +18,10 @@ dependencies = [ "tqdm > 4", "jiter>=0.4.0, <1", ] -requires-python = ">= 3.7.1" +requires-python = ">= 3.8" classifiers = [ "Typing :: Typed", "Intended Audience :: Developers", - "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", @@ -150,7 +149,7 @@ filterwarnings = [ # there are a couple of flags that are still disabled by # default in strict mode as they are experimental and niche. typeCheckingMode = "strict" -pythonVersion = "3.7" +pythonVersion = "3.8" exclude = [ "_dev", From dfdcf571ced31f7859cd1871be39e2fb3af6bafa Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Mon, 4 Nov 2024 22:47:52 +0000 Subject: [PATCH 558/816] feat(api): add support for predicted outputs (#1847) --- .stats.yml | 2 +- api.md | 3 +- src/openai/resources/audio/speech.py | 8 +- src/openai/resources/audio/transcriptions.py | 4 +- src/openai/resources/audio/translations.py | 4 +- src/openai/resources/beta/assistants.py | 40 +++--- src/openai/resources/beta/threads/messages.py | 8 +- .../resources/beta/threads/runs/runs.py | 56 ++++---- .../resources/beta/threads/runs/steps.py | 16 +-- src/openai/resources/beta/threads/threads.py | 36 ++--- .../beta/vector_stores/file_batches.py | 8 +- .../resources/beta/vector_stores/files.py | 8 +- .../beta/vector_stores/vector_stores.py | 8 +- src/openai/resources/chat/completions.py | 125 +++++++++++------- src/openai/resources/completions.py | 60 ++++----- src/openai/resources/embeddings.py | 12 +- src/openai/resources/files.py | 74 ++++++++--- src/openai/resources/fine_tuning/jobs/jobs.py | 4 +- src/openai/resources/images.py | 12 +- src/openai/resources/moderations.py | 4 +- src/openai/resources/uploads/uploads.py | 4 +- .../types/audio/speech_create_params.py | 4 +- .../audio/transcription_create_params.py | 2 +- .../types/audio/translation_create_params.py | 2 +- src/openai/types/beta/assistant.py | 8 +- .../types/beta/assistant_create_params.py | 8 +- .../types/beta/assistant_list_params.py | 2 +- .../types/beta/assistant_update_params.py | 8 +- src/openai/types/beta/file_search_tool.py | 4 +- .../types/beta/file_search_tool_param.py | 4 +- .../beta/thread_create_and_run_params.py | 6 +- .../types/beta/threads/message_list_params.py | 2 +- src/openai/types/beta/threads/run.py | 6 +- .../types/beta/threads/run_create_params.py | 8 +- .../types/beta/threads/run_list_params.py | 2 +- .../beta/threads/runs/step_list_params.py | 4 +- .../beta/threads/runs/step_retrieve_params.py | 2 +- .../types/beta/vector_store_list_params.py | 2 +- .../file_batch_list_files_params.py | 2 +- .../beta/vector_stores/file_list_params.py | 2 +- src/openai/types/chat/__init__.py | 3 + ...hat_completion_content_part_image_param.py | 2 +- ...hat_completion_prediction_content_param.py | 25 ++++ .../types/chat/completion_create_params.py | 23 ++-- src/openai/types/completion_create_params.py | 10 +- src/openai/types/completion_usage.py | 14 ++ src/openai/types/embedding_create_params.py | 6 +- src/openai/types/file_list_params.py | 23 +++- .../types/fine_tuning/job_create_params.py | 2 +- .../types/image_create_variation_params.py | 2 +- src/openai/types/image_edit_params.py | 2 +- src/openai/types/image_generate_params.py | 2 +- src/openai/types/moderation_create_params.py | 2 +- tests/api_resources/chat/test_completions.py | 16 +++ tests/api_resources/test_files.py | 28 ++-- 55 files changed, 450 insertions(+), 284 deletions(-) create mode 100644 src/openai/types/chat/chat_completion_prediction_content_param.py diff --git a/.stats.yml b/.stats.yml index 39413df445..f368bc881d 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-7b0a5d715d94f75ac7795bd4d2175a0e3243af9b935a86c273f371e45583140f.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-2f8ca92b9b1879fd535b685e4767338413fcd533d42f3baac13a9c41da3fce35.yml diff --git a/api.md b/api.md index f44169665d..7def07bb79 100644 --- a/api.md +++ b/api.md @@ -54,6 +54,7 @@ from openai.types.chat import ( ChatCompletionMessageToolCall, ChatCompletionModality, ChatCompletionNamedToolChoice, + ChatCompletionPredictionContent, ChatCompletionRole, ChatCompletionStreamOptions, ChatCompletionSystemMessageParam, @@ -93,7 +94,7 @@ Methods: - client.files.create(\*\*params) -> FileObject - client.files.retrieve(file_id) -> FileObject -- client.files.list(\*\*params) -> SyncPage[FileObject] +- client.files.list(\*\*params) -> SyncCursorPage[FileObject] - client.files.delete(file_id) -> FileDeleted - client.files.content(file_id) -> HttpxBinaryResponseContent - client.files.retrieve_content(file_id) -> str diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index 6085ae8afe..09faaddda6 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -70,13 +70,13 @@ def create( input: The text to generate audio for. The maximum length is 4096 characters. model: - One of the available [TTS models](https://platform.openai.com/docs/models/tts): + One of the available [TTS models](https://platform.openai.com/docs/models#tts): `tts-1` or `tts-1-hd` voice: The voice to use when generating the audio. Supported voices are `alloy`, `echo`, `fable`, `onyx`, `nova`, and `shimmer`. Previews of the voices are available in the - [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech/voice-options). + [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech#voice-options). response_format: The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, `wav`, and `pcm`. @@ -154,13 +154,13 @@ async def create( input: The text to generate audio for. The maximum length is 4096 characters. model: - One of the available [TTS models](https://platform.openai.com/docs/models/tts): + One of the available [TTS models](https://platform.openai.com/docs/models#tts): `tts-1` or `tts-1-hd` voice: The voice to use when generating the audio. Supported voices are `alloy`, `echo`, `fable`, `onyx`, `nova`, and `shimmer`. Previews of the voices are available in the - [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech/voice-options). + [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech#voice-options). response_format: The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, `wav`, and `pcm`. diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index e6596a480e..8b5f4404fc 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -143,7 +143,7 @@ def create( prompt: An optional text to guide the model's style or continue a previous audio segment. The - [prompt](https://platform.openai.com/docs/guides/speech-to-text/prompting) + [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) should match the audio language. response_format: The format of the output, in one of these options: `json`, `text`, `srt`, @@ -307,7 +307,7 @@ async def create( prompt: An optional text to guide the model's style or continue a previous audio segment. The - [prompt](https://platform.openai.com/docs/guides/speech-to-text/prompting) + [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) should match the audio language. response_format: The format of the output, in one of these options: `json`, `text`, `srt`, diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index 53ab625873..a2d28afa03 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -130,7 +130,7 @@ def create( prompt: An optional text to guide the model's style or continue a previous audio segment. The - [prompt](https://platform.openai.com/docs/guides/speech-to-text/prompting) + [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) should be in English. response_format: The format of the output, in one of these options: `json`, `text`, `srt`, @@ -273,7 +273,7 @@ async def create( prompt: An optional text to guide the model's style or continue a previous audio segment. The - [prompt](https://platform.openai.com/docs/guides/speech-to-text/prompting) + [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) should be in English. response_format: The format of the output, in one of these options: `json`, `text`, `srt`, diff --git a/src/openai/resources/beta/assistants.py b/src/openai/resources/beta/assistants.py index 2ebef183b6..7df212f155 100644 --- a/src/openai/resources/beta/assistants.py +++ b/src/openai/resources/beta/assistants.py @@ -79,8 +79,8 @@ def create( model: ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our - [Model overview](https://platform.openai.com/docs/models/overview) for - descriptions of them. + [Model overview](https://platform.openai.com/docs/models) for descriptions of + them. description: The description of the assistant. The maximum length is 512 characters. @@ -95,8 +95,8 @@ def create( name: The name of the assistant. The maximum length is 256 characters. response_format: Specifies the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured @@ -239,14 +239,14 @@ def update( model: ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our - [Model overview](https://platform.openai.com/docs/models/overview) for - descriptions of them. + [Model overview](https://platform.openai.com/docs/models) for descriptions of + them. name: The name of the assistant. The maximum length is 256 characters. response_format: Specifies the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured @@ -344,8 +344,8 @@ def list( before: A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, - ending with obj_foo, your subsequent call can include before=obj_foo in order to - fetch the previous page of the list. + starting with obj_foo, your subsequent call can include before=obj_foo in order + to fetch the previous page of the list. limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. @@ -465,8 +465,8 @@ async def create( model: ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our - [Model overview](https://platform.openai.com/docs/models/overview) for - descriptions of them. + [Model overview](https://platform.openai.com/docs/models) for descriptions of + them. description: The description of the assistant. The maximum length is 512 characters. @@ -481,8 +481,8 @@ async def create( name: The name of the assistant. The maximum length is 256 characters. response_format: Specifies the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured @@ -625,14 +625,14 @@ async def update( model: ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our - [Model overview](https://platform.openai.com/docs/models/overview) for - descriptions of them. + [Model overview](https://platform.openai.com/docs/models) for descriptions of + them. name: The name of the assistant. The maximum length is 256 characters. response_format: Specifies the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured @@ -730,8 +730,8 @@ def list( before: A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, - ending with obj_foo, your subsequent call can include before=obj_foo in order to - fetch the previous page of the list. + starting with obj_foo, your subsequent call can include before=obj_foo in order + to fetch the previous page of the list. limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. diff --git a/src/openai/resources/beta/threads/messages.py b/src/openai/resources/beta/threads/messages.py index de7ebcaf4d..e848507387 100644 --- a/src/openai/resources/beta/threads/messages.py +++ b/src/openai/resources/beta/threads/messages.py @@ -221,8 +221,8 @@ def list( before: A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, - ending with obj_foo, your subsequent call can include before=obj_foo in order to - fetch the previous page of the list. + starting with obj_foo, your subsequent call can include before=obj_foo in order + to fetch the previous page of the list. limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. @@ -495,8 +495,8 @@ def list( before: A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, - ending with obj_foo, your subsequent call can include before=obj_foo in order to - fetch the previous page of the list. + starting with obj_foo, your subsequent call can include before=obj_foo in order + to fetch the previous page of the list. limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 287c0ecf24..620cc270e5 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -122,7 +122,7 @@ def create( to fetch the file search result content. See the - [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. additional_instructions: Appends additional instructions at the end of the instructions for the run. This @@ -158,12 +158,12 @@ def create( assistant will be used. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. response_format: Specifies the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured @@ -266,7 +266,7 @@ def create( to fetch the file search result content. See the - [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. additional_instructions: Appends additional instructions at the end of the instructions for the run. This @@ -302,12 +302,12 @@ def create( assistant will be used. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. response_format: Specifies the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured @@ -406,7 +406,7 @@ def create( to fetch the file search result content. See the - [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. additional_instructions: Appends additional instructions at the end of the instructions for the run. This @@ -442,12 +442,12 @@ def create( assistant will be used. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. response_format: Specifies the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured @@ -674,8 +674,8 @@ def list( before: A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, - ending with obj_foo, your subsequent call can include before=obj_foo in order to - fetch the previous page of the list. + starting with obj_foo, your subsequent call can include before=obj_foo in order + to fetch the previous page of the list. limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. @@ -1484,7 +1484,7 @@ async def create( to fetch the file search result content. See the - [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. additional_instructions: Appends additional instructions at the end of the instructions for the run. This @@ -1520,12 +1520,12 @@ async def create( assistant will be used. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. response_format: Specifies the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured @@ -1628,7 +1628,7 @@ async def create( to fetch the file search result content. See the - [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. additional_instructions: Appends additional instructions at the end of the instructions for the run. This @@ -1664,12 +1664,12 @@ async def create( assistant will be used. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. response_format: Specifies the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured @@ -1768,7 +1768,7 @@ async def create( to fetch the file search result content. See the - [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. additional_instructions: Appends additional instructions at the end of the instructions for the run. This @@ -1804,12 +1804,12 @@ async def create( assistant will be used. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. response_format: Specifies the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured @@ -2037,8 +2037,8 @@ def list( before: A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, - ending with obj_foo, your subsequent call can include before=obj_foo in order to - fetch the previous page of the list. + starting with obj_foo, your subsequent call can include before=obj_foo in order + to fetch the previous page of the list. limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. diff --git a/src/openai/resources/beta/threads/runs/steps.py b/src/openai/resources/beta/threads/runs/steps.py index 5d6d55f9d9..9bd91e39e0 100644 --- a/src/openai/resources/beta/threads/runs/steps.py +++ b/src/openai/resources/beta/threads/runs/steps.py @@ -68,7 +68,7 @@ def retrieve( to fetch the file search result content. See the - [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. extra_headers: Send extra headers @@ -126,15 +126,15 @@ def list( before: A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, - ending with obj_foo, your subsequent call can include before=obj_foo in order to - fetch the previous page of the list. + starting with obj_foo, your subsequent call can include before=obj_foo in order + to fetch the previous page of the list. include: A list of additional fields to include in the response. Currently the only supported value is `step_details.tool_calls[*].file_search.results[*].content` to fetch the file search result content. See the - [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. limit: A limit on the number of objects to be returned. Limit can range between 1 and @@ -222,7 +222,7 @@ async def retrieve( to fetch the file search result content. See the - [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. extra_headers: Send extra headers @@ -280,15 +280,15 @@ def list( before: A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, - ending with obj_foo, your subsequent call can include before=obj_foo in order to - fetch the previous page of the list. + starting with obj_foo, your subsequent call can include before=obj_foo in order + to fetch the previous page of the list. include: A list of additional fields to include in the response. Currently the only supported value is `step_details.tool_calls[*].file_search.results[*].content` to fetch the file search result content. See the - [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. limit: A limit on the number of objects to be returned. Limit can range between 1 and diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 3b8851c03b..058ba71a17 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -326,12 +326,12 @@ def create_and_run( assistant will be used. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. response_format: Specifies the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured @@ -460,12 +460,12 @@ def create_and_run( assistant will be used. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. response_format: Specifies the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured @@ -590,12 +590,12 @@ def create_and_run( assistant will be used. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. response_format: Specifies the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured @@ -1160,12 +1160,12 @@ async def create_and_run( assistant will be used. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. response_format: Specifies the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured @@ -1294,12 +1294,12 @@ async def create_and_run( assistant will be used. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. response_format: Specifies the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured @@ -1424,12 +1424,12 @@ async def create_and_run( assistant will be used. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. response_format: Specifies the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured diff --git a/src/openai/resources/beta/vector_stores/file_batches.py b/src/openai/resources/beta/vector_stores/file_batches.py index d1f9c872e4..9f9e643bd0 100644 --- a/src/openai/resources/beta/vector_stores/file_batches.py +++ b/src/openai/resources/beta/vector_stores/file_batches.py @@ -227,8 +227,8 @@ def list_files( before: A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, - ending with obj_foo, your subsequent call can include before=obj_foo in order to - fetch the previous page of the list. + starting with obj_foo, your subsequent call can include before=obj_foo in order + to fetch the previous page of the list. filter: Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`. @@ -556,8 +556,8 @@ def list_files( before: A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, - ending with obj_foo, your subsequent call can include before=obj_foo in order to - fetch the previous page of the list. + starting with obj_foo, your subsequent call can include before=obj_foo in order + to fetch the previous page of the list. filter: Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`. diff --git a/src/openai/resources/beta/vector_stores/files.py b/src/openai/resources/beta/vector_stores/files.py index fe43bb3488..7c155ac917 100644 --- a/src/openai/resources/beta/vector_stores/files.py +++ b/src/openai/resources/beta/vector_stores/files.py @@ -164,8 +164,8 @@ def list( before: A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, - ending with obj_foo, your subsequent call can include before=obj_foo in order to - fetch the previous page of the list. + starting with obj_foo, your subsequent call can include before=obj_foo in order + to fetch the previous page of the list. filter: Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`. @@ -476,8 +476,8 @@ def list( before: A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, - ending with obj_foo, your subsequent call can include before=obj_foo in order to - fetch the previous page of the list. + starting with obj_foo, your subsequent call can include before=obj_foo in order + to fetch the previous page of the list. filter: Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`. diff --git a/src/openai/resources/beta/vector_stores/vector_stores.py b/src/openai/resources/beta/vector_stores/vector_stores.py index d69add7b26..61a2eadc7b 100644 --- a/src/openai/resources/beta/vector_stores/vector_stores.py +++ b/src/openai/resources/beta/vector_stores/vector_stores.py @@ -251,8 +251,8 @@ def list( before: A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, - ending with obj_foo, your subsequent call can include before=obj_foo in order to - fetch the previous page of the list. + starting with obj_foo, your subsequent call can include before=obj_foo in order + to fetch the previous page of the list. limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. @@ -529,8 +529,8 @@ def list( before: A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, - ending with obj_foo, your subsequent call can include before=obj_foo in order to - fetch the previous page of the list. + starting with obj_foo, your subsequent call can include before=obj_foo in order + to fetch the previous page of the list. limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index ceaf3c2fec..60ab5138ba 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -33,6 +33,7 @@ from ...types.chat.chat_completion_audio_param import ChatCompletionAudioParam from ...types.chat.chat_completion_message_param import ChatCompletionMessageParam from ...types.chat.chat_completion_stream_options_param import ChatCompletionStreamOptionsParam +from ...types.chat.chat_completion_prediction_content_param import ChatCompletionPredictionContentParam from ...types.chat.chat_completion_tool_choice_option_param import ChatCompletionToolChoiceOptionParam __all__ = ["Completions", "AsyncCompletions"] @@ -76,6 +77,7 @@ def create( modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, @@ -113,7 +115,7 @@ def create( [audio](https://platform.openai.com/docs/guides/audio). model: ID of the model to use. See the - [model endpoint compatibility](https://platform.openai.com/docs/models/model-endpoint-compatibility) + [model endpoint compatibility](https://platform.openai.com/docs/models#model-endpoint-compatibility) table for details on which models work with the Chat API. audio: Parameters for audio output. Required when audio output is requested with @@ -124,7 +126,7 @@ def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) function_call: Deprecated in favor of `tool_choice`. @@ -185,19 +187,22 @@ def create( choices. Keep `n` as `1` to minimize costs. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. + prediction: Static predicted output content, such as the content of a text file that is + being regenerated. + presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) response_format: An object specifying the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4o mini](https://platform.openai.com/docs/models/gpt-4o-mini), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4o mini](https://platform.openai.com/docs/models#gpt-4o-mini), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured @@ -284,7 +289,7 @@ def create( user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). extra_headers: Send extra headers @@ -315,6 +320,7 @@ def create( modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, @@ -351,7 +357,7 @@ def create( [audio](https://platform.openai.com/docs/guides/audio). model: ID of the model to use. See the - [model endpoint compatibility](https://platform.openai.com/docs/models/model-endpoint-compatibility) + [model endpoint compatibility](https://platform.openai.com/docs/models#model-endpoint-compatibility) table for details on which models work with the Chat API. stream: If set, partial message deltas will be sent, like in ChatGPT. Tokens will be @@ -369,7 +375,7 @@ def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) function_call: Deprecated in favor of `tool_choice`. @@ -430,19 +436,22 @@ def create( choices. Keep `n` as `1` to minimize costs. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. + prediction: Static predicted output content, such as the content of a text file that is + being regenerated. + presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) response_format: An object specifying the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4o mini](https://platform.openai.com/docs/models/gpt-4o-mini), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4o mini](https://platform.openai.com/docs/models#gpt-4o-mini), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured @@ -522,7 +531,7 @@ def create( user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). extra_headers: Send extra headers @@ -553,6 +562,7 @@ def create( modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, @@ -589,7 +599,7 @@ def create( [audio](https://platform.openai.com/docs/guides/audio). model: ID of the model to use. See the - [model endpoint compatibility](https://platform.openai.com/docs/models/model-endpoint-compatibility) + [model endpoint compatibility](https://platform.openai.com/docs/models#model-endpoint-compatibility) table for details on which models work with the Chat API. stream: If set, partial message deltas will be sent, like in ChatGPT. Tokens will be @@ -607,7 +617,7 @@ def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) function_call: Deprecated in favor of `tool_choice`. @@ -668,19 +678,22 @@ def create( choices. Keep `n` as `1` to minimize costs. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. + prediction: Static predicted output content, such as the content of a text file that is + being regenerated. + presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) response_format: An object specifying the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4o mini](https://platform.openai.com/docs/models/gpt-4o-mini), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4o mini](https://platform.openai.com/docs/models#gpt-4o-mini), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured @@ -760,7 +773,7 @@ def create( user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). extra_headers: Send extra headers @@ -790,6 +803,7 @@ def create( modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, @@ -830,6 +844,7 @@ def create( "modalities": modalities, "n": n, "parallel_tool_calls": parallel_tool_calls, + "prediction": prediction, "presence_penalty": presence_penalty, "response_format": response_format, "seed": seed, @@ -894,6 +909,7 @@ async def create( modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, @@ -931,7 +947,7 @@ async def create( [audio](https://platform.openai.com/docs/guides/audio). model: ID of the model to use. See the - [model endpoint compatibility](https://platform.openai.com/docs/models/model-endpoint-compatibility) + [model endpoint compatibility](https://platform.openai.com/docs/models#model-endpoint-compatibility) table for details on which models work with the Chat API. audio: Parameters for audio output. Required when audio output is requested with @@ -942,7 +958,7 @@ async def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) function_call: Deprecated in favor of `tool_choice`. @@ -1003,19 +1019,22 @@ async def create( choices. Keep `n` as `1` to minimize costs. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. + prediction: Static predicted output content, such as the content of a text file that is + being regenerated. + presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) response_format: An object specifying the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4o mini](https://platform.openai.com/docs/models/gpt-4o-mini), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4o mini](https://platform.openai.com/docs/models#gpt-4o-mini), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured @@ -1102,7 +1121,7 @@ async def create( user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). extra_headers: Send extra headers @@ -1133,6 +1152,7 @@ async def create( modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, @@ -1169,7 +1189,7 @@ async def create( [audio](https://platform.openai.com/docs/guides/audio). model: ID of the model to use. See the - [model endpoint compatibility](https://platform.openai.com/docs/models/model-endpoint-compatibility) + [model endpoint compatibility](https://platform.openai.com/docs/models#model-endpoint-compatibility) table for details on which models work with the Chat API. stream: If set, partial message deltas will be sent, like in ChatGPT. Tokens will be @@ -1187,7 +1207,7 @@ async def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) function_call: Deprecated in favor of `tool_choice`. @@ -1248,19 +1268,22 @@ async def create( choices. Keep `n` as `1` to minimize costs. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. + prediction: Static predicted output content, such as the content of a text file that is + being regenerated. + presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) response_format: An object specifying the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4o mini](https://platform.openai.com/docs/models/gpt-4o-mini), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4o mini](https://platform.openai.com/docs/models#gpt-4o-mini), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured @@ -1340,7 +1363,7 @@ async def create( user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). extra_headers: Send extra headers @@ -1371,6 +1394,7 @@ async def create( modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, @@ -1407,7 +1431,7 @@ async def create( [audio](https://platform.openai.com/docs/guides/audio). model: ID of the model to use. See the - [model endpoint compatibility](https://platform.openai.com/docs/models/model-endpoint-compatibility) + [model endpoint compatibility](https://platform.openai.com/docs/models#model-endpoint-compatibility) table for details on which models work with the Chat API. stream: If set, partial message deltas will be sent, like in ChatGPT. Tokens will be @@ -1425,7 +1449,7 @@ async def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) function_call: Deprecated in favor of `tool_choice`. @@ -1486,19 +1510,22 @@ async def create( choices. Keep `n` as `1` to minimize costs. parallel_tool_calls: Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. + prediction: Static predicted output content, such as the content of a text file that is + being regenerated. + presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) response_format: An object specifying the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4o mini](https://platform.openai.com/docs/models/gpt-4o-mini), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4o mini](https://platform.openai.com/docs/models#gpt-4o-mini), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured @@ -1578,7 +1605,7 @@ async def create( user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). extra_headers: Send extra headers @@ -1608,6 +1635,7 @@ async def create( modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, @@ -1648,6 +1676,7 @@ async def create( "modalities": modalities, "n": n, "parallel_tool_calls": parallel_tool_calls, + "prediction": prediction, "presence_penalty": presence_penalty, "response_format": response_format, "seed": seed, diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index 49198d2687..1ac3575fd5 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -84,8 +84,8 @@ def create( model: ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our - [Model overview](https://platform.openai.com/docs/models/overview) for - descriptions of them. + [Model overview](https://platform.openai.com/docs/models) for descriptions of + them. prompt: The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays. @@ -110,7 +110,7 @@ def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) logit_bias: Modify the likelihood of specified tokens appearing in the completion. @@ -150,7 +150,7 @@ def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) seed: If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return @@ -189,7 +189,7 @@ def create( user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). extra_headers: Send extra headers @@ -237,8 +237,8 @@ def create( model: ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our - [Model overview](https://platform.openai.com/docs/models/overview) for - descriptions of them. + [Model overview](https://platform.openai.com/docs/models) for descriptions of + them. prompt: The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays. @@ -270,7 +270,7 @@ def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) logit_bias: Modify the likelihood of specified tokens appearing in the completion. @@ -310,7 +310,7 @@ def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) seed: If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return @@ -342,7 +342,7 @@ def create( user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). extra_headers: Send extra headers @@ -390,8 +390,8 @@ def create( model: ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our - [Model overview](https://platform.openai.com/docs/models/overview) for - descriptions of them. + [Model overview](https://platform.openai.com/docs/models) for descriptions of + them. prompt: The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays. @@ -423,7 +423,7 @@ def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) logit_bias: Modify the likelihood of specified tokens appearing in the completion. @@ -463,7 +463,7 @@ def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) seed: If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return @@ -495,7 +495,7 @@ def create( user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). extra_headers: Send extra headers @@ -626,8 +626,8 @@ async def create( model: ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our - [Model overview](https://platform.openai.com/docs/models/overview) for - descriptions of them. + [Model overview](https://platform.openai.com/docs/models) for descriptions of + them. prompt: The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays. @@ -652,7 +652,7 @@ async def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) logit_bias: Modify the likelihood of specified tokens appearing in the completion. @@ -692,7 +692,7 @@ async def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) seed: If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return @@ -731,7 +731,7 @@ async def create( user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). extra_headers: Send extra headers @@ -779,8 +779,8 @@ async def create( model: ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our - [Model overview](https://platform.openai.com/docs/models/overview) for - descriptions of them. + [Model overview](https://platform.openai.com/docs/models) for descriptions of + them. prompt: The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays. @@ -812,7 +812,7 @@ async def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) logit_bias: Modify the likelihood of specified tokens appearing in the completion. @@ -852,7 +852,7 @@ async def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) seed: If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return @@ -884,7 +884,7 @@ async def create( user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). extra_headers: Send extra headers @@ -932,8 +932,8 @@ async def create( model: ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our - [Model overview](https://platform.openai.com/docs/models/overview) for - descriptions of them. + [Model overview](https://platform.openai.com/docs/models) for descriptions of + them. prompt: The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays. @@ -965,7 +965,7 @@ async def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) logit_bias: Modify the likelihood of specified tokens appearing in the completion. @@ -1005,7 +1005,7 @@ async def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) seed: If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return @@ -1037,7 +1037,7 @@ async def create( user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). extra_headers: Send extra headers diff --git a/src/openai/resources/embeddings.py b/src/openai/resources/embeddings.py index c91e6cc13a..4ab2278e89 100644 --- a/src/openai/resources/embeddings.py +++ b/src/openai/resources/embeddings.py @@ -73,8 +73,8 @@ def create( model: ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our - [Model overview](https://platform.openai.com/docs/models/overview) for - descriptions of them. + [Model overview](https://platform.openai.com/docs/models) for descriptions of + them. dimensions: The number of dimensions the resulting output embeddings should have. Only supported in `text-embedding-3` and later models. @@ -84,7 +84,7 @@ def create( user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). extra_headers: Send extra headers @@ -185,8 +185,8 @@ async def create( model: ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our - [Model overview](https://platform.openai.com/docs/models/overview) for - descriptions of them. + [Model overview](https://platform.openai.com/docs/models) for descriptions of + them. dimensions: The number of dimensions the resulting output embeddings should have. Only supported in `text-embedding-3` and later models. @@ -196,7 +196,7 @@ async def create( user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). extra_headers: Send extra headers diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index e24eeec711..77706a7fd8 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -5,6 +5,7 @@ import time import typing_extensions from typing import Mapping, cast +from typing_extensions import Literal import httpx @@ -27,11 +28,8 @@ to_custom_streamed_response_wrapper, async_to_custom_streamed_response_wrapper, ) -from ..pagination import SyncPage, AsyncPage -from .._base_client import ( - AsyncPaginator, - make_request_options, -) +from ..pagination import SyncCursorPage, AsyncCursorPage +from .._base_client import AsyncPaginator, make_request_options from ..types.file_object import FileObject from ..types.file_deleted import FileDeleted from ..types.file_purpose import FilePurpose @@ -172,6 +170,9 @@ def retrieve( def list( self, *, + after: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, purpose: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -179,11 +180,23 @@ def list( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> SyncPage[FileObject]: - """ - Returns a list of files that belong to the user's organization. + ) -> SyncCursorPage[FileObject]: + """Returns a list of files. Args: + after: A cursor for use in pagination. + + `after` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include after=obj_foo in order to + fetch the next page of the list. + + limit: A limit on the number of objects to be returned. Limit can range between 1 and + 10,000, and the default is 10,000. + + order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending + order and `desc` for descending order. + purpose: Only return files with the given purpose. extra_headers: Send extra headers @@ -196,13 +209,21 @@ def list( """ return self._get_api_list( "/files", - page=SyncPage[FileObject], + page=SyncCursorPage[FileObject], options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout, - query=maybe_transform({"purpose": purpose}, file_list_params.FileListParams), + query=maybe_transform( + { + "after": after, + "limit": limit, + "order": order, + "purpose": purpose, + }, + file_list_params.FileListParams, + ), ), model=FileObject, ) @@ -465,6 +486,9 @@ async def retrieve( def list( self, *, + after: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, purpose: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -472,11 +496,23 @@ def list( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> AsyncPaginator[FileObject, AsyncPage[FileObject]]: - """ - Returns a list of files that belong to the user's organization. + ) -> AsyncPaginator[FileObject, AsyncCursorPage[FileObject]]: + """Returns a list of files. Args: + after: A cursor for use in pagination. + + `after` is an object ID that defines your place + in the list. For instance, if you make a list request and receive 100 objects, + ending with obj_foo, your subsequent call can include after=obj_foo in order to + fetch the next page of the list. + + limit: A limit on the number of objects to be returned. Limit can range between 1 and + 10,000, and the default is 10,000. + + order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending + order and `desc` for descending order. + purpose: Only return files with the given purpose. extra_headers: Send extra headers @@ -489,13 +525,21 @@ def list( """ return self._get_api_list( "/files", - page=AsyncPage[FileObject], + page=AsyncCursorPage[FileObject], options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout, - query=maybe_transform({"purpose": purpose}, file_list_params.FileListParams), + query=maybe_transform( + { + "after": after, + "limit": limit, + "order": order, + "purpose": purpose, + }, + file_list_params.FileListParams, + ), ), model=FileObject, ) diff --git a/src/openai/resources/fine_tuning/jobs/jobs.py b/src/openai/resources/fine_tuning/jobs/jobs.py index 44abf1cfe1..0ed5495b0e 100644 --- a/src/openai/resources/fine_tuning/jobs/jobs.py +++ b/src/openai/resources/fine_tuning/jobs/jobs.py @@ -88,7 +88,7 @@ def create( Args: model: The name of the model to fine-tune. You can select one of the - [supported models](https://platform.openai.com/docs/guides/fine-tuning/which-models-can-be-fine-tuned). + [supported models](https://platform.openai.com/docs/guides/fine-tuning#which-models-can-be-fine-tuned). training_file: The ID of an uploaded file that contains training data. @@ -379,7 +379,7 @@ async def create( Args: model: The name of the model to fine-tune. You can select one of the - [supported models](https://platform.openai.com/docs/guides/fine-tuning/which-models-can-be-fine-tuned). + [supported models](https://platform.openai.com/docs/guides/fine-tuning#which-models-can-be-fine-tuned). training_file: The ID of an uploaded file that contains training data. diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py index e9629d48fd..2fbc077dd9 100644 --- a/src/openai/resources/images.py +++ b/src/openai/resources/images.py @@ -84,7 +84,7 @@ def create_variation( user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). extra_headers: Send extra headers @@ -165,7 +165,7 @@ def edit( user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). extra_headers: Send extra headers @@ -251,7 +251,7 @@ def generate( user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). extra_headers: Send extra headers @@ -341,7 +341,7 @@ async def create_variation( user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). extra_headers: Send extra headers @@ -422,7 +422,7 @@ async def edit( user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). extra_headers: Send extra headers @@ -508,7 +508,7 @@ async def generate( user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). extra_headers: Send extra headers diff --git a/src/openai/resources/moderations.py b/src/openai/resources/moderations.py index 8b73da57b2..ce80bb7d55 100644 --- a/src/openai/resources/moderations.py +++ b/src/openai/resources/moderations.py @@ -68,7 +68,7 @@ def create( model: The content moderation model you would like to use. Learn more in [the moderation guide](https://platform.openai.com/docs/guides/moderation), and learn about available models - [here](https://platform.openai.com/docs/models/moderation). + [here](https://platform.openai.com/docs/models#moderation). extra_headers: Send extra headers @@ -138,7 +138,7 @@ async def create( model: The content moderation model you would like to use. Learn more in [the moderation guide](https://platform.openai.com/docs/guides/moderation), and learn about available models - [here](https://platform.openai.com/docs/models/moderation). + [here](https://platform.openai.com/docs/models#moderation). extra_headers: Send extra headers diff --git a/src/openai/resources/uploads/uploads.py b/src/openai/resources/uploads/uploads.py index 96a531a8e4..cfb500b62c 100644 --- a/src/openai/resources/uploads/uploads.py +++ b/src/openai/resources/uploads/uploads.py @@ -196,7 +196,7 @@ def create( For certain `purpose`s, the correct `mime_type` must be specified. Please refer to documentation for the supported MIME types for your use case: - - [Assistants](https://platform.openai.com/docs/assistants/tools/file-search/supported-files) + - [Assistants](https://platform.openai.com/docs/assistants/tools/file-search#supported-files) For guidance on the proper filename extensions for each purpose, please follow the documentation on @@ -500,7 +500,7 @@ async def create( For certain `purpose`s, the correct `mime_type` must be specified. Please refer to documentation for the supported MIME types for your use case: - - [Assistants](https://platform.openai.com/docs/assistants/tools/file-search/supported-files) + - [Assistants](https://platform.openai.com/docs/assistants/tools/file-search#supported-files) For guidance on the proper filename extensions for each purpose, please follow the documentation on diff --git a/src/openai/types/audio/speech_create_params.py b/src/openai/types/audio/speech_create_params.py index dff66e49c7..a60d000708 100644 --- a/src/openai/types/audio/speech_create_params.py +++ b/src/openai/types/audio/speech_create_params.py @@ -16,7 +16,7 @@ class SpeechCreateParams(TypedDict, total=False): model: Required[Union[str, SpeechModel]] """ - One of the available [TTS models](https://platform.openai.com/docs/models/tts): + One of the available [TTS models](https://platform.openai.com/docs/models#tts): `tts-1` or `tts-1-hd` """ @@ -25,7 +25,7 @@ class SpeechCreateParams(TypedDict, total=False): Supported voices are `alloy`, `echo`, `fable`, `onyx`, `nova`, and `shimmer`. Previews of the voices are available in the - [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech/voice-options). + [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech#voice-options). """ response_format: Literal["mp3", "opus", "aac", "flac", "wav", "pcm"] diff --git a/src/openai/types/audio/transcription_create_params.py b/src/openai/types/audio/transcription_create_params.py index 5ac2bb91e5..88805affbd 100644 --- a/src/openai/types/audio/transcription_create_params.py +++ b/src/openai/types/audio/transcription_create_params.py @@ -38,7 +38,7 @@ class TranscriptionCreateParams(TypedDict, total=False): """An optional text to guide the model's style or continue a previous audio segment. - The [prompt](https://platform.openai.com/docs/guides/speech-to-text/prompting) + The [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) should match the audio language. """ diff --git a/src/openai/types/audio/translation_create_params.py b/src/openai/types/audio/translation_create_params.py index 6859ed9d30..62f85b8757 100644 --- a/src/openai/types/audio/translation_create_params.py +++ b/src/openai/types/audio/translation_create_params.py @@ -30,7 +30,7 @@ class TranslationCreateParams(TypedDict, total=False): """An optional text to guide the model's style or continue a previous audio segment. - The [prompt](https://platform.openai.com/docs/guides/speech-to-text/prompting) + The [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) should be in English. """ diff --git a/src/openai/types/beta/assistant.py b/src/openai/types/beta/assistant.py index ea97de440f..3c8b8e403b 100644 --- a/src/openai/types/beta/assistant.py +++ b/src/openai/types/beta/assistant.py @@ -65,8 +65,8 @@ class Assistant(BaseModel): You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our - [Model overview](https://platform.openai.com/docs/models/overview) for - descriptions of them. + [Model overview](https://platform.openai.com/docs/models) for descriptions of + them. """ name: Optional[str] = None @@ -85,8 +85,8 @@ class Assistant(BaseModel): response_format: Optional[AssistantResponseFormatOption] = None """Specifies the format that the model must output. - Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured diff --git a/src/openai/types/beta/assistant_create_params.py b/src/openai/types/beta/assistant_create_params.py index e11f842f05..568b223ce7 100644 --- a/src/openai/types/beta/assistant_create_params.py +++ b/src/openai/types/beta/assistant_create_params.py @@ -26,8 +26,8 @@ class AssistantCreateParams(TypedDict, total=False): You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our - [Model overview](https://platform.openai.com/docs/models/overview) for - descriptions of them. + [Model overview](https://platform.openai.com/docs/models) for descriptions of + them. """ description: Optional[str] @@ -53,8 +53,8 @@ class AssistantCreateParams(TypedDict, total=False): response_format: Optional[AssistantResponseFormatOptionParam] """Specifies the format that the model must output. - Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured diff --git a/src/openai/types/beta/assistant_list_params.py b/src/openai/types/beta/assistant_list_params.py index f54f63120b..834ffbcaf8 100644 --- a/src/openai/types/beta/assistant_list_params.py +++ b/src/openai/types/beta/assistant_list_params.py @@ -21,7 +21,7 @@ class AssistantListParams(TypedDict, total=False): """A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if - you make a list request and receive 100 objects, ending with obj_foo, your + you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. """ diff --git a/src/openai/types/beta/assistant_update_params.py b/src/openai/types/beta/assistant_update_params.py index c4598df507..9a66e41ab3 100644 --- a/src/openai/types/beta/assistant_update_params.py +++ b/src/openai/types/beta/assistant_update_params.py @@ -35,8 +35,8 @@ class AssistantUpdateParams(TypedDict, total=False): You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our - [Model overview](https://platform.openai.com/docs/models/overview) for - descriptions of them. + [Model overview](https://platform.openai.com/docs/models) for descriptions of + them. """ name: Optional[str] @@ -45,8 +45,8 @@ class AssistantUpdateParams(TypedDict, total=False): response_format: Optional[AssistantResponseFormatOptionParam] """Specifies the format that the model must output. - Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured diff --git a/src/openai/types/beta/file_search_tool.py b/src/openai/types/beta/file_search_tool.py index aee6593e89..89fc16c04c 100644 --- a/src/openai/types/beta/file_search_tool.py +++ b/src/openai/types/beta/file_search_tool.py @@ -31,7 +31,7 @@ class FileSearch(BaseModel): Note that the file search tool may output fewer than `max_num_results` results. See the - [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. """ @@ -42,7 +42,7 @@ class FileSearch(BaseModel): score_threshold of 0. See the - [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. """ diff --git a/src/openai/types/beta/file_search_tool_param.py b/src/openai/types/beta/file_search_tool_param.py index 5ce91207ba..c73d0af79d 100644 --- a/src/openai/types/beta/file_search_tool_param.py +++ b/src/openai/types/beta/file_search_tool_param.py @@ -30,7 +30,7 @@ class FileSearch(TypedDict, total=False): Note that the file search tool may output fewer than `max_num_results` results. See the - [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. """ @@ -41,7 +41,7 @@ class FileSearch(TypedDict, total=False): score_threshold of 0. See the - [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. """ diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index 64ee6a8710..8310ba12f4 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -86,15 +86,15 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): parallel_tool_calls: bool """ Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. """ response_format: Optional[AssistantResponseFormatOptionParam] """Specifies the format that the model must output. - Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured diff --git a/src/openai/types/beta/threads/message_list_params.py b/src/openai/types/beta/threads/message_list_params.py index 18c2442fb5..a7c22a66fb 100644 --- a/src/openai/types/beta/threads/message_list_params.py +++ b/src/openai/types/beta/threads/message_list_params.py @@ -21,7 +21,7 @@ class MessageListParams(TypedDict, total=False): """A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if - you make a list request and receive 100 objects, ending with obj_foo, your + you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. """ diff --git a/src/openai/types/beta/threads/run.py b/src/openai/types/beta/threads/run.py index e8f2b74dee..ad32135b7d 100644 --- a/src/openai/types/beta/threads/run.py +++ b/src/openai/types/beta/threads/run.py @@ -154,7 +154,7 @@ class Run(BaseModel): parallel_tool_calls: bool """ Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. """ @@ -167,8 +167,8 @@ class Run(BaseModel): response_format: Optional[AssistantResponseFormatOption] = None """Specifies the format that the model must output. - Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index 9767b142e1..88dc39645e 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -41,7 +41,7 @@ class RunCreateParamsBase(TypedDict, total=False): search result content. See the - [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. """ @@ -99,15 +99,15 @@ class RunCreateParamsBase(TypedDict, total=False): parallel_tool_calls: bool """ Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. """ response_format: Optional[AssistantResponseFormatOptionParam] """Specifies the format that the model must output. - Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4), + Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured diff --git a/src/openai/types/beta/threads/run_list_params.py b/src/openai/types/beta/threads/run_list_params.py index 1e32bca4b4..fbea54f6f2 100644 --- a/src/openai/types/beta/threads/run_list_params.py +++ b/src/openai/types/beta/threads/run_list_params.py @@ -21,7 +21,7 @@ class RunListParams(TypedDict, total=False): """A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if - you make a list request and receive 100 objects, ending with obj_foo, your + you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. """ diff --git a/src/openai/types/beta/threads/runs/step_list_params.py b/src/openai/types/beta/threads/runs/step_list_params.py index 3931bd7e0c..a6be771d9f 100644 --- a/src/openai/types/beta/threads/runs/step_list_params.py +++ b/src/openai/types/beta/threads/runs/step_list_params.py @@ -26,7 +26,7 @@ class StepListParams(TypedDict, total=False): """A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if - you make a list request and receive 100 objects, ending with obj_foo, your + you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. """ @@ -39,7 +39,7 @@ class StepListParams(TypedDict, total=False): search result content. See the - [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. """ diff --git a/src/openai/types/beta/threads/runs/step_retrieve_params.py b/src/openai/types/beta/threads/runs/step_retrieve_params.py index 22c1c049f4..ecbb72edbd 100644 --- a/src/openai/types/beta/threads/runs/step_retrieve_params.py +++ b/src/openai/types/beta/threads/runs/step_retrieve_params.py @@ -23,6 +23,6 @@ class StepRetrieveParams(TypedDict, total=False): search result content. See the - [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search/customizing-file-search-settings) + [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. """ diff --git a/src/openai/types/beta/vector_store_list_params.py b/src/openai/types/beta/vector_store_list_params.py index f39f67266d..e26ff90a85 100644 --- a/src/openai/types/beta/vector_store_list_params.py +++ b/src/openai/types/beta/vector_store_list_params.py @@ -21,7 +21,7 @@ class VectorStoreListParams(TypedDict, total=False): """A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if - you make a list request and receive 100 objects, ending with obj_foo, your + you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. """ diff --git a/src/openai/types/beta/vector_stores/file_batch_list_files_params.py b/src/openai/types/beta/vector_stores/file_batch_list_files_params.py index 24dee7d5a5..2a0a6c6aa7 100644 --- a/src/openai/types/beta/vector_stores/file_batch_list_files_params.py +++ b/src/openai/types/beta/vector_stores/file_batch_list_files_params.py @@ -23,7 +23,7 @@ class FileBatchListFilesParams(TypedDict, total=False): """A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if - you make a list request and receive 100 objects, ending with obj_foo, your + you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. """ diff --git a/src/openai/types/beta/vector_stores/file_list_params.py b/src/openai/types/beta/vector_stores/file_list_params.py index 23dd7f0d94..867b5fb3bb 100644 --- a/src/openai/types/beta/vector_stores/file_list_params.py +++ b/src/openai/types/beta/vector_stores/file_list_params.py @@ -21,7 +21,7 @@ class FileListParams(TypedDict, total=False): """A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if - you make a list request and receive 100 objects, ending with obj_foo, your + you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. """ diff --git a/src/openai/types/chat/__init__.py b/src/openai/types/chat/__init__.py index eb818a132e..d0a5403e79 100644 --- a/src/openai/types/chat/__init__.py +++ b/src/openai/types/chat/__init__.py @@ -46,6 +46,9 @@ from .chat_completion_content_part_image_param import ( ChatCompletionContentPartImageParam as ChatCompletionContentPartImageParam, ) +from .chat_completion_prediction_content_param import ( + ChatCompletionPredictionContentParam as ChatCompletionPredictionContentParam, +) from .chat_completion_tool_choice_option_param import ( ChatCompletionToolChoiceOptionParam as ChatCompletionToolChoiceOptionParam, ) diff --git a/src/openai/types/chat/chat_completion_content_part_image_param.py b/src/openai/types/chat/chat_completion_content_part_image_param.py index b1a186aa6d..9d407324d0 100644 --- a/src/openai/types/chat/chat_completion_content_part_image_param.py +++ b/src/openai/types/chat/chat_completion_content_part_image_param.py @@ -15,7 +15,7 @@ class ImageURL(TypedDict, total=False): """Specifies the detail level of the image. Learn more in the - [Vision guide](https://platform.openai.com/docs/guides/vision/low-or-high-fidelity-image-understanding). + [Vision guide](https://platform.openai.com/docs/guides/vision#low-or-high-fidelity-image-understanding). """ diff --git a/src/openai/types/chat/chat_completion_prediction_content_param.py b/src/openai/types/chat/chat_completion_prediction_content_param.py new file mode 100644 index 0000000000..c44e6e3653 --- /dev/null +++ b/src/openai/types/chat/chat_completion_prediction_content_param.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import Literal, Required, TypedDict + +from .chat_completion_content_part_text_param import ChatCompletionContentPartTextParam + +__all__ = ["ChatCompletionPredictionContentParam"] + + +class ChatCompletionPredictionContentParam(TypedDict, total=False): + content: Required[Union[str, Iterable[ChatCompletionContentPartTextParam]]] + """ + The content that should be matched when generating a model response. If + generated tokens would match this content, the entire model response can be + returned much more quickly. + """ + + type: Required[Literal["content"]] + """The type of the predicted content you want to provide. + + This type is currently always `content`. + """ diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index af6a47c219..e838858314 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -13,6 +13,7 @@ from ..shared_params.function_parameters import FunctionParameters from ..shared_params.response_format_text import ResponseFormatText from .chat_completion_stream_options_param import ChatCompletionStreamOptionsParam +from .chat_completion_prediction_content_param import ChatCompletionPredictionContentParam from .chat_completion_tool_choice_option_param import ChatCompletionToolChoiceOptionParam from ..shared_params.response_format_json_object import ResponseFormatJSONObject from ..shared_params.response_format_json_schema import ResponseFormatJSONSchema @@ -43,7 +44,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): """ID of the model to use. See the - [model endpoint compatibility](https://platform.openai.com/docs/models/model-endpoint-compatibility) + [model endpoint compatibility](https://platform.openai.com/docs/models#model-endpoint-compatibility) table for details on which models work with the Chat API. """ @@ -60,7 +61,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) """ function_call: FunctionCall @@ -148,25 +149,31 @@ class CompletionCreateParamsBase(TypedDict, total=False): parallel_tool_calls: bool """ Whether to enable - [parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) + [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. """ + prediction: Optional[ChatCompletionPredictionContentParam] + """ + Static predicted output content, such as the content of a text file that is + being regenerated. + """ + presence_penalty: Optional[float] """Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) """ response_format: ResponseFormat """An object specifying the format that the model must output. - Compatible with [GPT-4o](https://platform.openai.com/docs/models/gpt-4o), - [GPT-4o mini](https://platform.openai.com/docs/models/gpt-4o-mini), - [GPT-4 Turbo](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo) and + Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), + [GPT-4o mini](https://platform.openai.com/docs/models#gpt-4o-mini), + [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4) and all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured @@ -276,7 +283,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): """ A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). """ diff --git a/src/openai/types/completion_create_params.py b/src/openai/types/completion_create_params.py index 6c112b3902..fdb1680d26 100644 --- a/src/openai/types/completion_create_params.py +++ b/src/openai/types/completion_create_params.py @@ -17,8 +17,8 @@ class CompletionCreateParamsBase(TypedDict, total=False): You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our - [Model overview](https://platform.openai.com/docs/models/overview) for - descriptions of them. + [Model overview](https://platform.openai.com/docs/models) for descriptions of + them. """ prompt: Required[Union[str, List[str], Iterable[int], Iterable[Iterable[int]], None]] @@ -53,7 +53,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) """ logit_bias: Optional[Dict[str, int]] @@ -106,7 +106,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation/parameter-details) + [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) """ seed: Optional[int] @@ -156,7 +156,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): """ A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). """ diff --git a/src/openai/types/completion_usage.py b/src/openai/types/completion_usage.py index fe112833e0..d8c4e84cf7 100644 --- a/src/openai/types/completion_usage.py +++ b/src/openai/types/completion_usage.py @@ -8,12 +8,26 @@ class CompletionTokensDetails(BaseModel): + accepted_prediction_tokens: Optional[int] = None + """ + When using Predicted Outputs, the number of tokens in the prediction that + appeared in the completion. + """ + audio_tokens: Optional[int] = None """Audio input tokens generated by the model.""" reasoning_tokens: Optional[int] = None """Tokens generated by the model for reasoning.""" + rejected_prediction_tokens: Optional[int] = None + """ + When using Predicted Outputs, the number of tokens in the prediction that did + not appear in the completion. However, like reasoning tokens, these tokens are + still counted in the total completion tokens for purposes of billing, output, + and context window limits. + """ + class PromptTokensDetails(BaseModel): audio_tokens: Optional[int] = None diff --git a/src/openai/types/embedding_create_params.py b/src/openai/types/embedding_create_params.py index 1548cdbd77..1385762885 100644 --- a/src/openai/types/embedding_create_params.py +++ b/src/openai/types/embedding_create_params.py @@ -28,8 +28,8 @@ class EmbeddingCreateParams(TypedDict, total=False): You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to see all of your available models, or see our - [Model overview](https://platform.openai.com/docs/models/overview) for - descriptions of them. + [Model overview](https://platform.openai.com/docs/models) for descriptions of + them. """ dimensions: int @@ -48,5 +48,5 @@ class EmbeddingCreateParams(TypedDict, total=False): """ A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). """ diff --git a/src/openai/types/file_list_params.py b/src/openai/types/file_list_params.py index 212eca13c0..058d874c29 100644 --- a/src/openai/types/file_list_params.py +++ b/src/openai/types/file_list_params.py @@ -2,11 +2,32 @@ from __future__ import annotations -from typing_extensions import TypedDict +from typing_extensions import Literal, TypedDict __all__ = ["FileListParams"] class FileListParams(TypedDict, total=False): + after: str + """A cursor for use in pagination. + + `after` is an object ID that defines your place in the list. For instance, if + you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include after=obj_foo in order to fetch the next page of the + list. + """ + + limit: int + """A limit on the number of objects to be returned. + + Limit can range between 1 and 10,000, and the default is 10,000. + """ + + order: Literal["asc", "desc"] + """Sort order by the `created_at` timestamp of the objects. + + `asc` for ascending order and `desc` for descending order. + """ + purpose: str """Only return files with the given purpose.""" diff --git a/src/openai/types/fine_tuning/job_create_params.py b/src/openai/types/fine_tuning/job_create_params.py index 8f5ea86274..8814229b2e 100644 --- a/src/openai/types/fine_tuning/job_create_params.py +++ b/src/openai/types/fine_tuning/job_create_params.py @@ -13,7 +13,7 @@ class JobCreateParams(TypedDict, total=False): """The name of the model to fine-tune. You can select one of the - [supported models](https://platform.openai.com/docs/guides/fine-tuning/which-models-can-be-fine-tuned). + [supported models](https://platform.openai.com/docs/guides/fine-tuning#which-models-can-be-fine-tuned). """ training_file: Required[str] diff --git a/src/openai/types/image_create_variation_params.py b/src/openai/types/image_create_variation_params.py index d6ecf0f1ae..d20f672912 100644 --- a/src/openai/types/image_create_variation_params.py +++ b/src/openai/types/image_create_variation_params.py @@ -47,5 +47,5 @@ class ImageCreateVariationParams(TypedDict, total=False): """ A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). """ diff --git a/src/openai/types/image_edit_params.py b/src/openai/types/image_edit_params.py index a596a8692b..1cb10611f3 100644 --- a/src/openai/types/image_edit_params.py +++ b/src/openai/types/image_edit_params.py @@ -58,5 +58,5 @@ class ImageEditParams(TypedDict, total=False): """ A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). """ diff --git a/src/openai/types/image_generate_params.py b/src/openai/types/image_generate_params.py index 307adeb3da..c88c45f518 100644 --- a/src/openai/types/image_generate_params.py +++ b/src/openai/types/image_generate_params.py @@ -61,5 +61,5 @@ class ImageGenerateParams(TypedDict, total=False): """ A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids). + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). """ diff --git a/src/openai/types/moderation_create_params.py b/src/openai/types/moderation_create_params.py index 3193fd9c2d..3ea2f3cd88 100644 --- a/src/openai/types/moderation_create_params.py +++ b/src/openai/types/moderation_create_params.py @@ -25,5 +25,5 @@ class ModerationCreateParams(TypedDict, total=False): Learn more in [the moderation guide](https://platform.openai.com/docs/guides/moderation), and learn about available models - [here](https://platform.openai.com/docs/models/moderation). + [here](https://platform.openai.com/docs/models#moderation). """ diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index d7162dc7db..dafedac9fb 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -65,6 +65,10 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: modalities=["text", "audio"], n=1, parallel_tool_calls=True, + prediction={ + "content": "string", + "type": "content", + }, presence_penalty=-2, response_format={"type": "text"}, seed=-9007199254740991, @@ -193,6 +197,10 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: modalities=["text", "audio"], n=1, parallel_tool_calls=True, + prediction={ + "content": "string", + "type": "content", + }, presence_penalty=-2, response_format={"type": "text"}, seed=-9007199254740991, @@ -340,6 +348,10 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn modalities=["text", "audio"], n=1, parallel_tool_calls=True, + prediction={ + "content": "string", + "type": "content", + }, presence_penalty=-2, response_format={"type": "text"}, seed=-9007199254740991, @@ -468,6 +480,10 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn modalities=["text", "audio"], n=1, parallel_tool_calls=True, + prediction={ + "content": "string", + "type": "content", + }, presence_penalty=-2, response_format={"type": "text"}, seed=-9007199254740991, diff --git a/tests/api_resources/test_files.py b/tests/api_resources/test_files.py index 882f0ddbe7..7402566d95 100644 --- a/tests/api_resources/test_files.py +++ b/tests/api_resources/test_files.py @@ -13,7 +13,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.types import FileObject, FileDeleted -from openai.pagination import SyncPage, AsyncPage +from openai.pagination import SyncCursorPage, AsyncCursorPage # pyright: reportDeprecated=false @@ -98,14 +98,17 @@ def test_path_params_retrieve(self, client: OpenAI) -> None: @parametrize def test_method_list(self, client: OpenAI) -> None: file = client.files.list() - assert_matches_type(SyncPage[FileObject], file, path=["response"]) + assert_matches_type(SyncCursorPage[FileObject], file, path=["response"]) @parametrize def test_method_list_with_all_params(self, client: OpenAI) -> None: file = client.files.list( - purpose="string", + after="after", + limit=0, + order="asc", + purpose="purpose", ) - assert_matches_type(SyncPage[FileObject], file, path=["response"]) + assert_matches_type(SyncCursorPage[FileObject], file, path=["response"]) @parametrize def test_raw_response_list(self, client: OpenAI) -> None: @@ -114,7 +117,7 @@ def test_raw_response_list(self, client: OpenAI) -> None: assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() - assert_matches_type(SyncPage[FileObject], file, path=["response"]) + assert_matches_type(SyncCursorPage[FileObject], file, path=["response"]) @parametrize def test_streaming_response_list(self, client: OpenAI) -> None: @@ -123,7 +126,7 @@ def test_streaming_response_list(self, client: OpenAI) -> None: assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() - assert_matches_type(SyncPage[FileObject], file, path=["response"]) + assert_matches_type(SyncCursorPage[FileObject], file, path=["response"]) assert cast(Any, response.is_closed) is True @@ -334,14 +337,17 @@ async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_method_list(self, async_client: AsyncOpenAI) -> None: file = await async_client.files.list() - assert_matches_type(AsyncPage[FileObject], file, path=["response"]) + assert_matches_type(AsyncCursorPage[FileObject], file, path=["response"]) @parametrize async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: file = await async_client.files.list( - purpose="string", + after="after", + limit=0, + order="asc", + purpose="purpose", ) - assert_matches_type(AsyncPage[FileObject], file, path=["response"]) + assert_matches_type(AsyncCursorPage[FileObject], file, path=["response"]) @parametrize async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: @@ -350,7 +356,7 @@ async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = response.parse() - assert_matches_type(AsyncPage[FileObject], file, path=["response"]) + assert_matches_type(AsyncCursorPage[FileObject], file, path=["response"]) @parametrize async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: @@ -359,7 +365,7 @@ async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: assert response.http_request.headers.get("X-Stainless-Lang") == "python" file = await response.parse() - assert_matches_type(AsyncPage[FileObject], file, path=["response"]) + assert_matches_type(AsyncCursorPage[FileObject], file, path=["response"]) assert cast(Any, response.is_closed) is True From b32507dd793b6b1dc218f76f7b485ae441db8841 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 4 Nov 2024 22:48:18 +0000 Subject: [PATCH 559/816] release: 1.54.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 9 +++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 5a86c0906c..7e66027ecd 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.53.1" + ".": "1.54.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index c3a5a3cecb..a60cd5cd31 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 1.54.0 (2024-11-04) + +Full Changelog: [v1.53.1...v1.54.0](https://github.com/openai/openai-python/compare/v1.53.1...v1.54.0) + +### Features + +* **api:** add support for predicted outputs ([#1847](https://github.com/openai/openai-python/issues/1847)) ([42a4103](https://github.com/openai/openai-python/commit/42a410379a1b5f72424cc2e96dc6ddff22fd00be)) +* **project:** drop support for Python 3.7 ([#1845](https://github.com/openai/openai-python/issues/1845)) ([0ed5b1a](https://github.com/openai/openai-python/commit/0ed5b1a9302ccf2f40c3c751cd777740a4749cda)) + ## 1.53.1 (2024-11-04) Full Changelog: [v1.53.0...v1.53.1](https://github.com/openai/openai-python/compare/v1.53.0...v1.53.1) diff --git a/pyproject.toml b/pyproject.toml index 20c0f3bb15..a88ce5608f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.53.1" +version = "1.54.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 9d221eb538..ef881a5f4c 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.53.1" # x-release-please-version +__version__ = "1.54.0" # x-release-please-version From 4ae58a7b80022504815c75929cf44be91ba18702 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Tue, 5 Nov 2024 09:31:27 +0000 Subject: [PATCH 560/816] fix: add new prediction param to all methods --- src/openai/resources/beta/chat/completions.py | 9 ++++ tests/lib/chat/test_completions.py | 42 ++++++++++++++++--- tests/lib/chat/test_completions_streaming.py | 7 +++- 3 files changed, 51 insertions(+), 7 deletions(-) diff --git a/src/openai/resources/beta/chat/completions.py b/src/openai/resources/beta/chat/completions.py index 47bcf42c16..38c09ce8dd 100644 --- a/src/openai/resources/beta/chat/completions.py +++ b/src/openai/resources/beta/chat/completions.py @@ -33,6 +33,7 @@ from ....types.chat.chat_completion_audio_param import ChatCompletionAudioParam from ....types.chat.chat_completion_message_param import ChatCompletionMessageParam from ....types.chat.chat_completion_stream_options_param import ChatCompletionStreamOptionsParam +from ....types.chat.chat_completion_prediction_content_param import ChatCompletionPredictionContentParam from ....types.chat.chat_completion_tool_choice_option_param import ChatCompletionToolChoiceOptionParam __all__ = ["Completions", "AsyncCompletions"] @@ -76,6 +77,7 @@ def parse( modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, @@ -169,6 +171,7 @@ def parser(raw_completion: ChatCompletion) -> ParsedChatCompletion[ResponseForma "modalities": modalities, "n": n, "parallel_tool_calls": parallel_tool_calls, + "prediction": prediction, "presence_penalty": presence_penalty, "response_format": _type_to_response_format(response_format), "seed": seed, @@ -217,6 +220,7 @@ def stream( modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, @@ -281,6 +285,7 @@ def stream( modalities=modalities, n=n, parallel_tool_calls=parallel_tool_calls, + prediction=prediction, presence_penalty=presence_penalty, seed=seed, service_tier=service_tier, @@ -343,6 +348,7 @@ async def parse( modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, @@ -436,6 +442,7 @@ def parser(raw_completion: ChatCompletion) -> ParsedChatCompletion[ResponseForma "modalities": modalities, "n": n, "parallel_tool_calls": parallel_tool_calls, + "prediction": prediction, "presence_penalty": presence_penalty, "response_format": _type_to_response_format(response_format), "seed": seed, @@ -484,6 +491,7 @@ def stream( modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, @@ -549,6 +557,7 @@ def stream( modalities=modalities, n=n, parallel_tool_calls=parallel_tool_calls, + prediction=prediction, presence_penalty=presence_penalty, seed=seed, service_tier=service_tier, diff --git a/tests/lib/chat/test_completions.py b/tests/lib/chat/test_completions.py index 5cd7b1ee53..48f41eb221 100644 --- a/tests/lib/chat/test_completions.py +++ b/tests/lib/chat/test_completions.py @@ -77,7 +77,12 @@ def test_parse_nothing(client: OpenAI, respx_mock: MockRouter, monkeypatch: pyte system_fingerprint='fp_b40fb1c6fb', usage=CompletionUsage( completion_tokens=37, - completion_tokens_details=CompletionTokensDetails(audio_tokens=None, reasoning_tokens=0), + completion_tokens_details=CompletionTokensDetails( + accepted_prediction_tokens=None, + audio_tokens=None, + reasoning_tokens=0, + rejected_prediction_tokens=None + ), prompt_tokens=14, prompt_tokens_details=None, total_tokens=51 @@ -139,7 +144,12 @@ class Location(BaseModel): system_fingerprint='fp_5050236cbd', usage=CompletionUsage( completion_tokens=14, - completion_tokens_details=CompletionTokensDetails(audio_tokens=None, reasoning_tokens=0), + completion_tokens_details=CompletionTokensDetails( + accepted_prediction_tokens=None, + audio_tokens=None, + reasoning_tokens=0, + rejected_prediction_tokens=None + ), prompt_tokens=79, prompt_tokens_details=None, total_tokens=93 @@ -203,7 +213,12 @@ class Location(BaseModel): system_fingerprint='fp_b40fb1c6fb', usage=CompletionUsage( completion_tokens=14, - completion_tokens_details=CompletionTokensDetails(audio_tokens=None, reasoning_tokens=0), + completion_tokens_details=CompletionTokensDetails( + accepted_prediction_tokens=None, + audio_tokens=None, + reasoning_tokens=0, + rejected_prediction_tokens=None + ), prompt_tokens=88, prompt_tokens_details=None, total_tokens=102 @@ -396,7 +411,12 @@ class CalendarEvent: system_fingerprint='fp_7568d46099', usage=CompletionUsage( completion_tokens=17, - completion_tokens_details=CompletionTokensDetails(audio_tokens=None, reasoning_tokens=0), + completion_tokens_details=CompletionTokensDetails( + accepted_prediction_tokens=None, + audio_tokens=None, + reasoning_tokens=0, + rejected_prediction_tokens=None + ), prompt_tokens=92, prompt_tokens_details=None, total_tokens=109 @@ -847,7 +867,12 @@ class Location(BaseModel): system_fingerprint='fp_5050236cbd', usage=CompletionUsage( completion_tokens=14, - completion_tokens_details=CompletionTokensDetails(audio_tokens=None, reasoning_tokens=0), + completion_tokens_details=CompletionTokensDetails( + accepted_prediction_tokens=None, + audio_tokens=None, + reasoning_tokens=0, + rejected_prediction_tokens=None + ), prompt_tokens=79, prompt_tokens_details=None, total_tokens=93 @@ -917,7 +942,12 @@ class Location(BaseModel): system_fingerprint='fp_5050236cbd', usage=CompletionUsage( completion_tokens=14, - completion_tokens_details=CompletionTokensDetails(audio_tokens=None, reasoning_tokens=0), + completion_tokens_details=CompletionTokensDetails( + accepted_prediction_tokens=None, + audio_tokens=None, + reasoning_tokens=0, + rejected_prediction_tokens=None + ), prompt_tokens=79, prompt_tokens_details=None, total_tokens=93 diff --git a/tests/lib/chat/test_completions_streaming.py b/tests/lib/chat/test_completions_streaming.py index 2846e6d2c3..ab12de44b3 100644 --- a/tests/lib/chat/test_completions_streaming.py +++ b/tests/lib/chat/test_completions_streaming.py @@ -157,7 +157,12 @@ def on_event(stream: ChatCompletionStream[Location], event: ChatCompletionStream system_fingerprint='fp_5050236cbd', usage=CompletionUsage( completion_tokens=14, - completion_tokens_details=CompletionTokensDetails(audio_tokens=None, reasoning_tokens=0), + completion_tokens_details=CompletionTokensDetails( + accepted_prediction_tokens=None, + audio_tokens=None, + reasoning_tokens=0, + rejected_prediction_tokens=None + ), prompt_tokens=79, prompt_tokens_details=None, total_tokens=93 From 22432e2d28a8503ea431b5c2599fd33e4a1cddb4 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 5 Nov 2024 09:32:01 +0000 Subject: [PATCH 561/816] release: 1.54.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 7e66027ecd..701df5bbab 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.54.0" + ".": "1.54.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index a60cd5cd31..511396ef95 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.54.1 (2024-11-05) + +Full Changelog: [v1.54.0...v1.54.1](https://github.com/openai/openai-python/compare/v1.54.0...v1.54.1) + +### Bug Fixes + +* add new prediction param to all methods ([6aa424d](https://github.com/openai/openai-python/commit/6aa424d076098312801febd938bd4b5e8baf4851)) + ## 1.54.0 (2024-11-04) Full Changelog: [v1.53.1...v1.54.0](https://github.com/openai/openai-python/compare/v1.53.1...v1.54.0) diff --git a/pyproject.toml b/pyproject.toml index a88ce5608f..a4ea633fb6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.54.0" +version = "1.54.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index ef881a5f4c..7d59fea6fe 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.54.0" # x-release-please-version +__version__ = "1.54.1" # x-release-please-version From 7f6a921c5951c4d464cd49a60db52a183cbf78f9 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 6 Nov 2024 15:54:29 +0000 Subject: [PATCH 562/816] chore(tests): adjust retry timeout values (#1851) --- tests/test_client.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_client.py b/tests/test_client.py index ff07ec393b..912ea1316c 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -698,7 +698,7 @@ class Model(BaseModel): [3, "", 0.5], [2, "", 0.5 * 2.0], [1, "", 0.5 * 4.0], - [-1100, "", 7.8], # test large number potentially overflowing + [-1100, "", 8], # test large number potentially overflowing ], ) @mock.patch("time.time", mock.MagicMock(return_value=1696004797)) @@ -1564,7 +1564,7 @@ class Model(BaseModel): [3, "", 0.5], [2, "", 0.5 * 2.0], [1, "", 0.5 * 4.0], - [-1100, "", 7.8], # test large number potentially overflowing + [-1100, "", 8], # test large number potentially overflowing ], ) @mock.patch("time.time", mock.MagicMock(return_value=1696004797)) From 74522adecf5d9919be8c797f3eb3da6e98b45229 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 6 Nov 2024 15:55:21 +0000 Subject: [PATCH 563/816] release: 1.54.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 701df5bbab..11adb14fb9 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.54.1" + ".": "1.54.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 511396ef95..61a18e3c8e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.54.2 (2024-11-06) + +Full Changelog: [v1.54.1...v1.54.2](https://github.com/openai/openai-python/compare/v1.54.1...v1.54.2) + +### Chores + +* **tests:** adjust retry timeout values ([#1851](https://github.com/openai/openai-python/issues/1851)) ([cc8009c](https://github.com/openai/openai-python/commit/cc8009c9de56fe80f2689f69e7b891ff4ed297a3)) + ## 1.54.1 (2024-11-05) Full Changelog: [v1.54.0...v1.54.1](https://github.com/openai/openai-python/compare/v1.54.0...v1.54.1) diff --git a/pyproject.toml b/pyproject.toml index a4ea633fb6..13087f543f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.54.1" +version = "1.54.2" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 7d59fea6fe..614d97d0f0 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.54.1" # x-release-please-version +__version__ = "1.54.2" # x-release-please-version From 1ca831cf60ead4151b061462f16d1894f02d025c Mon Sep 17 00:00:00 2001 From: Krista Pratico Date: Wed, 6 Nov 2024 13:18:00 -0800 Subject: [PATCH 564/816] fix(logs): redact sensitive headers (#1850) --- mypy.ini | 4 +- src/openai/_base_client.py | 3 +- src/openai/_utils/__init__.py | 1 + src/openai/_utils/_logs.py | 17 ++++++ tests/lib/test_azure.py | 101 +++++++++++++++++++++++++++++++ tests/test_utils/test_logging.py | 100 ++++++++++++++++++++++++++++++ 6 files changed, 223 insertions(+), 3 deletions(-) create mode 100644 tests/test_utils/test_logging.py diff --git a/mypy.ini b/mypy.ini index a4517a002d..97e5de4a60 100644 --- a/mypy.ini +++ b/mypy.ini @@ -2,10 +2,10 @@ pretty = True show_error_codes = True -# Exclude _files.py because mypy isn't smart enough to apply +# Exclude _files.py and _logs.py because mypy isn't smart enough to apply # the correct type narrowing and as this is an internal module # it's fine to just use Pyright. -exclude = ^(src/openai/_files\.py|_dev/.*\.py)$ +exclude = ^(src/openai/_files\.py|src/openai/_utils/_logs\.py|_dev/.*\.py)$ strict_equality = True implicit_reexport = True diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index e1d4849ae2..187518787a 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -62,7 +62,7 @@ HttpxRequestFiles, ModelBuilderProtocol, ) -from ._utils import is_dict, is_list, asyncify, is_given, lru_cache, is_mapping +from ._utils import SensitiveHeadersFilter, is_dict, is_list, asyncify, is_given, lru_cache, is_mapping from ._compat import model_copy, model_dump from ._models import GenericModel, FinalRequestOptions, validate_type, construct_type from ._response import ( @@ -90,6 +90,7 @@ from ._legacy_response import LegacyAPIResponse log: logging.Logger = logging.getLogger(__name__) +log.addFilter(SensitiveHeadersFilter()) # TODO: make base page type vars covariant SyncPageT = TypeVar("SyncPageT", bound="BaseSyncPage[Any]") diff --git a/src/openai/_utils/__init__.py b/src/openai/_utils/__init__.py index a7cff3c091..5abb34cde4 100644 --- a/src/openai/_utils/__init__.py +++ b/src/openai/_utils/__init__.py @@ -1,3 +1,4 @@ +from ._logs import SensitiveHeadersFilter as SensitiveHeadersFilter from ._sync import asyncify as asyncify from ._proxy import LazyProxy as LazyProxy from ._utils import ( diff --git a/src/openai/_utils/_logs.py b/src/openai/_utils/_logs.py index e5113fd8c0..376946933c 100644 --- a/src/openai/_utils/_logs.py +++ b/src/openai/_utils/_logs.py @@ -1,10 +1,16 @@ import os import logging +from typing_extensions import override + +from ._utils import is_dict logger: logging.Logger = logging.getLogger("openai") httpx_logger: logging.Logger = logging.getLogger("httpx") +SENSITIVE_HEADERS = {"api-key", "authorization"} + + def _basic_config() -> None: # e.g. [2023-10-05 14:12:26 - openai._base_client:818 - DEBUG] HTTP Request: POST http://127.0.0.1:4010/foo/bar "200 OK" logging.basicConfig( @@ -23,3 +29,14 @@ def setup_logging() -> None: _basic_config() logger.setLevel(logging.INFO) httpx_logger.setLevel(logging.INFO) + + +class SensitiveHeadersFilter(logging.Filter): + @override + def filter(self, record: logging.LogRecord) -> bool: + if is_dict(record.args) and "headers" in record.args and is_dict(record.args["headers"]): + headers = record.args["headers"] = {**record.args["headers"]} + for header in headers: + if str(header).lower() in SENSITIVE_HEADERS: + headers[header] = "" + return True diff --git a/tests/lib/test_azure.py b/tests/lib/test_azure.py index a9d3478350..626d7df311 100644 --- a/tests/lib/test_azure.py +++ b/tests/lib/test_azure.py @@ -1,3 +1,4 @@ +import logging from typing import Union, cast from typing_extensions import Literal, Protocol @@ -5,6 +6,7 @@ import pytest from respx import MockRouter +from openai._utils import SensitiveHeadersFilter, is_dict from openai._models import FinalRequestOptions from openai.lib.azure import AzureOpenAI, AsyncAzureOpenAI @@ -148,3 +150,102 @@ def token_provider() -> str: assert calls[0].request.headers.get("Authorization") == "Bearer first" assert calls[1].request.headers.get("Authorization") == "Bearer second" + + +class TestAzureLogging: + + @pytest.fixture(autouse=True) + def logger_with_filter(self) -> logging.Logger: + logger = logging.getLogger("openai") + logger.setLevel(logging.DEBUG) + logger.addFilter(SensitiveHeadersFilter()) + return logger + + @pytest.mark.respx() + def test_azure_api_key_redacted(self, respx_mock: MockRouter, caplog: pytest.LogCaptureFixture) -> None: + respx_mock.post( + "https://example-resource.azure.openai.com/openai/deployments/gpt-4/chat/completions?api-version=2024-06-01" + ).mock( + return_value=httpx.Response(200, json={"model": "gpt-4"}) + ) + + client = AzureOpenAI( + api_version="2024-06-01", + api_key="example_api_key", + azure_endpoint="https://example-resource.azure.openai.com/", + ) + + with caplog.at_level(logging.DEBUG): + client.chat.completions.create(messages=[], model="gpt-4") + + for record in caplog.records: + if is_dict(record.args) and record.args.get("headers") and is_dict(record.args["headers"]): + assert record.args["headers"]["api-key"] == "" + + + @pytest.mark.respx() + def test_azure_bearer_token_redacted(self, respx_mock: MockRouter, caplog: pytest.LogCaptureFixture) -> None: + respx_mock.post( + "https://example-resource.azure.openai.com/openai/deployments/gpt-4/chat/completions?api-version=2024-06-01" + ).mock( + return_value=httpx.Response(200, json={"model": "gpt-4"}) + ) + + client = AzureOpenAI( + api_version="2024-06-01", + azure_ad_token="example_token", + azure_endpoint="https://example-resource.azure.openai.com/", + ) + + with caplog.at_level(logging.DEBUG): + client.chat.completions.create(messages=[], model="gpt-4") + + for record in caplog.records: + if is_dict(record.args) and record.args.get("headers") and is_dict(record.args["headers"]): + assert record.args["headers"]["Authorization"] == "" + + + @pytest.mark.asyncio + @pytest.mark.respx() + async def test_azure_api_key_redacted_async(self, respx_mock: MockRouter, caplog: pytest.LogCaptureFixture) -> None: + respx_mock.post( + "https://example-resource.azure.openai.com/openai/deployments/gpt-4/chat/completions?api-version=2024-06-01" + ).mock( + return_value=httpx.Response(200, json={"model": "gpt-4"}) + ) + + client = AsyncAzureOpenAI( + api_version="2024-06-01", + api_key="example_api_key", + azure_endpoint="https://example-resource.azure.openai.com/", + ) + + with caplog.at_level(logging.DEBUG): + await client.chat.completions.create(messages=[], model="gpt-4") + + for record in caplog.records: + if is_dict(record.args) and record.args.get("headers") and is_dict(record.args["headers"]): + assert record.args["headers"]["api-key"] == "" + + + @pytest.mark.asyncio + @pytest.mark.respx() + async def test_azure_bearer_token_redacted_async(self, respx_mock: MockRouter, caplog: pytest.LogCaptureFixture) -> None: + respx_mock.post( + "https://example-resource.azure.openai.com/openai/deployments/gpt-4/chat/completions?api-version=2024-06-01" + ).mock( + return_value=httpx.Response(200, json={"model": "gpt-4"}) + ) + + client = AsyncAzureOpenAI( + api_version="2024-06-01", + azure_ad_token="example_token", + azure_endpoint="https://example-resource.azure.openai.com/", + ) + + with caplog.at_level(logging.DEBUG): + await client.chat.completions.create(messages=[], model="gpt-4") + + for record in caplog.records: + if is_dict(record.args) and record.args.get("headers") and is_dict(record.args["headers"]): + assert record.args["headers"]["Authorization"] == "" diff --git a/tests/test_utils/test_logging.py b/tests/test_utils/test_logging.py new file mode 100644 index 0000000000..cc018012e2 --- /dev/null +++ b/tests/test_utils/test_logging.py @@ -0,0 +1,100 @@ +import logging +from typing import Any, Dict, cast + +import pytest + +from openai._utils import SensitiveHeadersFilter + + +@pytest.fixture +def logger_with_filter() -> logging.Logger: + logger = logging.getLogger("test_logger") + logger.setLevel(logging.DEBUG) + logger.addFilter(SensitiveHeadersFilter()) + return logger + + +def test_keys_redacted(logger_with_filter: logging.Logger, caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level(logging.DEBUG): + logger_with_filter.debug( + "Request options: %s", + { + "method": "post", + "url": "chat/completions", + "headers": {"api-key": "12345", "Authorization": "Bearer token"}, + }, + ) + + log_record = cast(Dict[str, Any], caplog.records[0].args) + assert log_record["method"] == "post" + assert log_record["url"] == "chat/completions" + assert log_record["headers"]["api-key"] == "" + assert log_record["headers"]["Authorization"] == "" + assert ( + caplog.messages[0] + == "Request options: {'method': 'post', 'url': 'chat/completions', 'headers': {'api-key': '', 'Authorization': ''}}" + ) + + +def test_keys_redacted_case_insensitive(logger_with_filter: logging.Logger, caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level(logging.DEBUG): + logger_with_filter.debug( + "Request options: %s", + { + "method": "post", + "url": "chat/completions", + "headers": {"Api-key": "12345", "authorization": "Bearer token"}, + }, + ) + + log_record = cast(Dict[str, Any], caplog.records[0].args) + assert log_record["method"] == "post" + assert log_record["url"] == "chat/completions" + assert log_record["headers"]["Api-key"] == "" + assert log_record["headers"]["authorization"] == "" + assert ( + caplog.messages[0] + == "Request options: {'method': 'post', 'url': 'chat/completions', 'headers': {'Api-key': '', 'authorization': ''}}" + ) + + +def test_no_headers(logger_with_filter: logging.Logger, caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level(logging.DEBUG): + logger_with_filter.debug( + "Request options: %s", + {"method": "post", "url": "chat/completions"}, + ) + + log_record = cast(Dict[str, Any], caplog.records[0].args) + assert log_record["method"] == "post" + assert log_record["url"] == "chat/completions" + assert "api-key" not in log_record + assert "Authorization" not in log_record + assert caplog.messages[0] == "Request options: {'method': 'post', 'url': 'chat/completions'}" + + +def test_headers_without_sensitive_info(logger_with_filter: logging.Logger, caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level(logging.DEBUG): + logger_with_filter.debug( + "Request options: %s", + { + "method": "post", + "url": "chat/completions", + "headers": {"custom": "value"}, + }, + ) + + log_record = cast(Dict[str, Any], caplog.records[0].args) + assert log_record["method"] == "post" + assert log_record["url"] == "chat/completions" + assert log_record["headers"] == {"custom": "value"} + assert ( + caplog.messages[0] + == "Request options: {'method': 'post', 'url': 'chat/completions', 'headers': {'custom': 'value'}}" + ) + + +def test_standard_debug_msg(logger_with_filter: logging.Logger, caplog: pytest.LogCaptureFixture) -> None: + with caplog.at_level(logging.DEBUG): + logger_with_filter.debug("Sending HTTP Request: %s %s", "POST", "chat/completions") + assert caplog.messages[0] == "Sending HTTP Request: POST chat/completions" From 646a579cdb305a9d3fba6c5f9a96011c5e2c2882 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 6 Nov 2024 21:18:25 +0000 Subject: [PATCH 565/816] release: 1.54.3 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 11adb14fb9..2b6bc65c52 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.54.2" + ".": "1.54.3" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 61a18e3c8e..4addfb1025 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.54.3 (2024-11-06) + +Full Changelog: [v1.54.2...v1.54.3](https://github.com/openai/openai-python/compare/v1.54.2...v1.54.3) + +### Bug Fixes + +* **logs:** redact sensitive headers ([#1850](https://github.com/openai/openai-python/issues/1850)) ([466608f](https://github.com/openai/openai-python/commit/466608fa56b7a9939c08a4c78be2f6fe4a05111b)) + ## 1.54.2 (2024-11-06) Full Changelog: [v1.54.1...v1.54.2](https://github.com/openai/openai-python/compare/v1.54.1...v1.54.2) diff --git a/pyproject.toml b/pyproject.toml index 13087f543f..386f85e491 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.54.2" +version = "1.54.3" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 614d97d0f0..848cd40935 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.54.2" # x-release-please-version +__version__ = "1.54.3" # x-release-please-version From db0aa22c4299606e6b6b86d6dd3e473e902d274a Mon Sep 17 00:00:00 2001 From: Adel Basli Date: Mon, 11 Nov 2024 11:17:26 +0100 Subject: [PATCH 566/816] docs(readme): add missing asyncio import (#1858) * fix missing import * reorder imports --------- Co-authored-by: Robert Craigie --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index bc334e7e07..47504b9137 100644 --- a/README.md +++ b/README.md @@ -196,6 +196,7 @@ for chunk in stream: The async client uses the exact same interface. ```python +import asyncio from openai import AsyncOpenAI client = AsyncOpenAI() From 6c6dfb19e49a604fb35e97b7f5adf654a5397ed6 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 11 Nov 2024 22:39:39 +0000 Subject: [PATCH 567/816] docs: move comments in example snippets (#1860) --- README.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 47504b9137..1051f10bf2 100644 --- a/README.md +++ b/README.md @@ -31,8 +31,7 @@ import os from openai import OpenAI client = OpenAI( - # This is the default and can be omitted - api_key=os.environ.get("OPENAI_API_KEY"), + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted ) chat_completion = client.chat.completions.create( @@ -153,8 +152,7 @@ import asyncio from openai import AsyncOpenAI client = AsyncOpenAI( - # This is the default and can be omitted - api_key=os.environ.get("OPENAI_API_KEY"), + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted ) From 23444ed92cc81b3b1a8f17432f29b4020b50f023 Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Tue, 12 Nov 2024 07:43:40 +0000 Subject: [PATCH 568/816] docs: bump models in example snippets to gpt-4o (#1861) --- README.md | 29 +++++++++++++++++------------ tests/test_client.py | 8 ++++---- 2 files changed, 21 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 1051f10bf2..f1cd97b96e 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ chat_completion = client.chat.completions.create( "content": "Say this is a test", } ], - model="gpt-3.5-turbo", + model="gpt-4o", ) ``` @@ -164,7 +164,7 @@ async def main() -> None: "content": "Say this is a test", } ], - model="gpt-3.5-turbo", + model="gpt-4o", ) @@ -183,8 +183,13 @@ from openai import OpenAI client = OpenAI() stream = client.chat.completions.create( - model="gpt-4", - messages=[{"role": "user", "content": "Say this is a test"}], + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-4o", stream=True, ) for chunk in stream: @@ -231,7 +236,7 @@ openai.base_url = "https://.../" openai.default_headers = {"x-foo": "true"} completion = openai.chat.completions.create( - model="gpt-4", + model="gpt-4o", messages=[ { "role": "user", @@ -349,7 +354,7 @@ completion = client.chat.completions.create( "content": "Can you generate an example json object describing a fruit?", } ], - model="gpt-3.5-turbo-1106", + model="gpt-4o", response_format={"type": "json_object"}, ) ``` @@ -389,7 +394,7 @@ client = OpenAI() try: client.fine_tuning.jobs.create( - model="gpt-3.5-turbo", + model="gpt-4o", training_file="file-abc123", ) except openai.APIConnectionError as e: @@ -456,10 +461,10 @@ client.with_options(max_retries=5).chat.completions.create( messages=[ { "role": "user", - "content": "How can I get the name of the current day in Node.js?", + "content": "How can I get the name of the current day in JavaScript?", } ], - model="gpt-3.5-turbo", + model="gpt-4o", ) ``` @@ -490,7 +495,7 @@ client.with_options(timeout=5.0).chat.completions.create( "content": "How can I list all files in a directory using Python?", } ], - model="gpt-3.5-turbo", + model="gpt-4o", ) ``` @@ -535,7 +540,7 @@ response = client.chat.completions.with_raw_response.create( "role": "user", "content": "Say this is a test", }], - model="gpt-3.5-turbo", + model="gpt-4o", ) print(response.headers.get('X-My-Header')) @@ -568,7 +573,7 @@ with client.chat.completions.with_streaming_response.create( "content": "Say this is a test", } ], - model="gpt-3.5-turbo", + model="gpt-4o", ) as response: print(response.headers.get("X-My-Header")) diff --git a/tests/test_client.py b/tests/test_client.py index 912ea1316c..7ea2ab38d1 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -727,7 +727,7 @@ def test_retrying_timeout_errors_doesnt_leak(self, respx_mock: MockRouter) -> No "content": "Say this is a test", } ], - model="gpt-3.5-turbo", + model="gpt-4o", ), ), cast_to=httpx.Response, @@ -753,7 +753,7 @@ def test_retrying_status_errors_doesnt_leak(self, respx_mock: MockRouter) -> Non "content": "Say this is a test", } ], - model="gpt-3.5-turbo", + model="gpt-4o", ), ), cast_to=httpx.Response, @@ -1594,7 +1594,7 @@ async def test_retrying_timeout_errors_doesnt_leak(self, respx_mock: MockRouter) "content": "Say this is a test", } ], - model="gpt-3.5-turbo", + model="gpt-4o", ), ), cast_to=httpx.Response, @@ -1620,7 +1620,7 @@ async def test_retrying_status_errors_doesnt_leak(self, respx_mock: MockRouter) "content": "Say this is a test", } ], - model="gpt-3.5-turbo", + model="gpt-4o", ), ), cast_to=httpx.Response, From 9b28850fcd777a249e127ae4080d2720b4b76896 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 12 Nov 2024 12:11:55 +0000 Subject: [PATCH 569/816] fix: don't use dicts as iterables in transform (#1865) --- src/openai/_utils/_transform.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/openai/_utils/_transform.py b/src/openai/_utils/_transform.py index d7c05345d1..a6b62cad0c 100644 --- a/src/openai/_utils/_transform.py +++ b/src/openai/_utils/_transform.py @@ -316,6 +316,11 @@ async def _async_transform_recursive( # Iterable[T] or (is_iterable_type(stripped_type) and is_iterable(data) and not isinstance(data, str)) ): + # dicts are technically iterable, but it is an iterable on the keys of the dict and is not usually + # intended as an iterable, so we don't transform it. + if isinstance(data, dict): + return cast(object, data) + inner_type = extract_type_arg(stripped_type, 0) return [await _async_transform_recursive(d, annotation=annotation, inner_type=inner_type) for d in data] From 52357cff50bee57ef442e94d78a0de38b4173fc2 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 12 Nov 2024 12:12:24 +0000 Subject: [PATCH 570/816] release: 1.54.4 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 15 +++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 18 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 2b6bc65c52..7bfe725d47 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.54.3" + ".": "1.54.4" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 4addfb1025..d82ac42553 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## 1.54.4 (2024-11-12) + +Full Changelog: [v1.54.3...v1.54.4](https://github.com/openai/openai-python/compare/v1.54.3...v1.54.4) + +### Bug Fixes + +* don't use dicts as iterables in transform ([#1865](https://github.com/openai/openai-python/issues/1865)) ([76a51b1](https://github.com/openai/openai-python/commit/76a51b11efae50659a562197b1e18c6343964b56)) + + +### Documentation + +* bump models in example snippets to gpt-4o ([#1861](https://github.com/openai/openai-python/issues/1861)) ([adafe08](https://github.com/openai/openai-python/commit/adafe0859178d406fa93b38f3547f3d262651331)) +* move comments in example snippets ([#1860](https://github.com/openai/openai-python/issues/1860)) ([362cf74](https://github.com/openai/openai-python/commit/362cf74d6c34506f98f6c4fb2304357be21f7691)) +* **readme:** add missing asyncio import ([#1858](https://github.com/openai/openai-python/issues/1858)) ([dec9d0c](https://github.com/openai/openai-python/commit/dec9d0c97b702b6bcf9c71f5bdd6172bb5718354)) + ## 1.54.3 (2024-11-06) Full Changelog: [v1.54.2...v1.54.3](https://github.com/openai/openai-python/compare/v1.54.2...v1.54.3) diff --git a/pyproject.toml b/pyproject.toml index 386f85e491..e0a20e8387 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.54.3" +version = "1.54.4" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 848cd40935..5e531dd083 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.54.3" # x-release-please-version +__version__ = "1.54.4" # x-release-please-version From dd19d4f94a68ccecf38f23d10f5de2568345b79d Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Mon, 18 Nov 2024 10:35:41 +0000 Subject: [PATCH 571/816] chore(tests): limit array example length (#1870) --- .../audio/test_transcriptions.py | 4 +- tests/api_resources/beta/test_assistants.py | 20 +- tests/api_resources/beta/test_threads.py | 584 ++---------------- .../api_resources/beta/test_vector_stores.py | 4 +- .../beta/threads/test_messages.py | 28 +- tests/api_resources/beta/threads/test_runs.py | 460 ++------------ tests/api_resources/chat/test_completions.py | 88 +-- tests/api_resources/fine_tuning/test_jobs.py | 44 +- tests/api_resources/test_uploads.py | 20 +- 9 files changed, 146 insertions(+), 1106 deletions(-) diff --git a/tests/api_resources/audio/test_transcriptions.py b/tests/api_resources/audio/test_transcriptions.py index 0fa91eb152..bdb7e0dfb6 100644 --- a/tests/api_resources/audio/test_transcriptions.py +++ b/tests/api_resources/audio/test_transcriptions.py @@ -34,7 +34,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: prompt="string", response_format="json", temperature=0, - timestamp_granularities=["word", "segment"], + timestamp_granularities=["word"], ) assert_matches_type(TranscriptionCreateResponse, transcription, path=["response"]) @@ -85,7 +85,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> prompt="string", response_format="json", temperature=0, - timestamp_granularities=["word", "segment"], + timestamp_granularities=["word"], ) assert_matches_type(TranscriptionCreateResponse, transcription, path=["response"]) diff --git a/tests/api_resources/beta/test_assistants.py b/tests/api_resources/beta/test_assistants.py index 642935cdaf..d9944448b7 100644 --- a/tests/api_resources/beta/test_assistants.py +++ b/tests/api_resources/beta/test_assistants.py @@ -39,19 +39,19 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: response_format="auto", temperature=1, tool_resources={ - "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "code_interpreter": {"file_ids": ["string"]}, "file_search": { "vector_store_ids": ["string"], "vector_stores": [ { "chunking_strategy": {"type": "auto"}, - "file_ids": ["string", "string", "string"], + "file_ids": ["string"], "metadata": {}, } ], }, }, - tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + tools=[{"type": "code_interpreter"}], top_p=1, ) assert_matches_type(Assistant, assistant, path=["response"]) @@ -137,10 +137,10 @@ def test_method_update_with_all_params(self, client: OpenAI) -> None: response_format="auto", temperature=1, tool_resources={ - "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "code_interpreter": {"file_ids": ["string"]}, "file_search": {"vector_store_ids": ["string"]}, }, - tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + tools=[{"type": "code_interpreter"}], top_p=1, ) assert_matches_type(Assistant, assistant, path=["response"]) @@ -271,19 +271,19 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> response_format="auto", temperature=1, tool_resources={ - "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "code_interpreter": {"file_ids": ["string"]}, "file_search": { "vector_store_ids": ["string"], "vector_stores": [ { "chunking_strategy": {"type": "auto"}, - "file_ids": ["string", "string", "string"], + "file_ids": ["string"], "metadata": {}, } ], }, }, - tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + tools=[{"type": "code_interpreter"}], top_p=1, ) assert_matches_type(Assistant, assistant, path=["response"]) @@ -369,10 +369,10 @@ async def test_method_update_with_all_params(self, async_client: AsyncOpenAI) -> response_format="auto", temperature=1, tool_resources={ - "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "code_interpreter": {"file_ids": ["string"]}, "file_search": {"vector_store_ids": ["string"]}, }, - tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + tools=[{"type": "code_interpreter"}], top_p=1, ) assert_matches_type(Assistant, assistant, path=["response"]) diff --git a/tests/api_resources/beta/test_threads.py b/tests/api_resources/beta/test_threads.py index 95bebd84f5..789f870d6a 100644 --- a/tests/api_resources/beta/test_threads.py +++ b/tests/api_resources/beta/test_threads.py @@ -35,104 +35,22 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "role": "user", "attachments": [ { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - ], - "metadata": {}, - }, - { - "content": "string", - "role": "user", - "attachments": [ - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - ], - "metadata": {}, - }, - { - "content": "string", - "role": "user", - "attachments": [ - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, + "file_id": "file_id", + "tools": [{"type": "code_interpreter"}], + } ], "metadata": {}, - }, + } ], metadata={}, tool_resources={ - "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "code_interpreter": {"file_ids": ["string"]}, "file_search": { "vector_store_ids": ["string"], "vector_stores": [ { "chunking_strategy": {"type": "auto"}, - "file_ids": ["string", "string", "string"], + "file_ids": ["string"], "metadata": {}, } ], @@ -212,7 +130,7 @@ def test_method_update_with_all_params(self, client: OpenAI) -> None: "string", metadata={}, tool_resources={ - "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "code_interpreter": {"file_ids": ["string"]}, "file_search": {"vector_store_ids": ["string"]}, }, ) @@ -314,104 +232,22 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) "role": "user", "attachments": [ { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - ], - "metadata": {}, - }, - { - "content": "string", - "role": "user", - "attachments": [ - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - ], - "metadata": {}, - }, - { - "content": "string", - "role": "user", - "attachments": [ - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, + "file_id": "file_id", + "tools": [{"type": "code_interpreter"}], + } ], "metadata": {}, - }, + } ], "metadata": {}, "tool_resources": { - "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "code_interpreter": {"file_ids": ["string"]}, "file_search": { "vector_store_ids": ["string"], "vector_stores": [ { "chunking_strategy": {"type": "auto"}, - "file_ids": ["string", "string", "string"], + "file_ids": ["string"], "metadata": {}, } ], @@ -420,10 +256,10 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) }, tool_choice="none", tool_resources={ - "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "code_interpreter": {"file_ids": ["string"]}, "file_search": {"vector_store_ids": ["string"]}, }, - tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + tools=[{"type": "code_interpreter"}], top_p=1, truncation_strategy={ "type": "auto", @@ -484,104 +320,22 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) "role": "user", "attachments": [ { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - ], - "metadata": {}, - }, - { - "content": "string", - "role": "user", - "attachments": [ - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - ], - "metadata": {}, - }, - { - "content": "string", - "role": "user", - "attachments": [ - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, + "file_id": "file_id", + "tools": [{"type": "code_interpreter"}], + } ], "metadata": {}, - }, + } ], "metadata": {}, "tool_resources": { - "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "code_interpreter": {"file_ids": ["string"]}, "file_search": { "vector_store_ids": ["string"], "vector_stores": [ { "chunking_strategy": {"type": "auto"}, - "file_ids": ["string", "string", "string"], + "file_ids": ["string"], "metadata": {}, } ], @@ -590,10 +344,10 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) }, tool_choice="none", tool_resources={ - "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "code_interpreter": {"file_ids": ["string"]}, "file_search": {"vector_store_ids": ["string"]}, }, - tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + tools=[{"type": "code_interpreter"}], top_p=1, truncation_strategy={ "type": "auto", @@ -645,104 +399,22 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "role": "user", "attachments": [ { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - ], - "metadata": {}, - }, - { - "content": "string", - "role": "user", - "attachments": [ - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - ], - "metadata": {}, - }, - { - "content": "string", - "role": "user", - "attachments": [ - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, + "file_id": "file_id", + "tools": [{"type": "code_interpreter"}], + } ], "metadata": {}, - }, + } ], metadata={}, tool_resources={ - "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "code_interpreter": {"file_ids": ["string"]}, "file_search": { "vector_store_ids": ["string"], "vector_stores": [ { "chunking_strategy": {"type": "auto"}, - "file_ids": ["string", "string", "string"], + "file_ids": ["string"], "metadata": {}, } ], @@ -822,7 +494,7 @@ async def test_method_update_with_all_params(self, async_client: AsyncOpenAI) -> "string", metadata={}, tool_resources={ - "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "code_interpreter": {"file_ids": ["string"]}, "file_search": {"vector_store_ids": ["string"]}, }, ) @@ -924,104 +596,22 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie "role": "user", "attachments": [ { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - ], - "metadata": {}, - }, - { - "content": "string", - "role": "user", - "attachments": [ - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - ], - "metadata": {}, - }, - { - "content": "string", - "role": "user", - "attachments": [ - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, + "file_id": "file_id", + "tools": [{"type": "code_interpreter"}], + } ], "metadata": {}, - }, + } ], "metadata": {}, "tool_resources": { - "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "code_interpreter": {"file_ids": ["string"]}, "file_search": { "vector_store_ids": ["string"], "vector_stores": [ { "chunking_strategy": {"type": "auto"}, - "file_ids": ["string", "string", "string"], + "file_ids": ["string"], "metadata": {}, } ], @@ -1030,10 +620,10 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie }, tool_choice="none", tool_resources={ - "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "code_interpreter": {"file_ids": ["string"]}, "file_search": {"vector_store_ids": ["string"]}, }, - tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + tools=[{"type": "code_interpreter"}], top_p=1, truncation_strategy={ "type": "auto", @@ -1094,104 +684,22 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie "role": "user", "attachments": [ { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - ], - "metadata": {}, - }, - { - "content": "string", - "role": "user", - "attachments": [ - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - ], - "metadata": {}, - }, - { - "content": "string", - "role": "user", - "attachments": [ - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, + "file_id": "file_id", + "tools": [{"type": "code_interpreter"}], + } ], "metadata": {}, - }, + } ], "metadata": {}, "tool_resources": { - "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "code_interpreter": {"file_ids": ["string"]}, "file_search": { "vector_store_ids": ["string"], "vector_stores": [ { "chunking_strategy": {"type": "auto"}, - "file_ids": ["string", "string", "string"], + "file_ids": ["string"], "metadata": {}, } ], @@ -1200,10 +708,10 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie }, tool_choice="none", tool_resources={ - "code_interpreter": {"file_ids": ["string", "string", "string"]}, + "code_interpreter": {"file_ids": ["string"]}, "file_search": {"vector_store_ids": ["string"]}, }, - tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + tools=[{"type": "code_interpreter"}], top_p=1, truncation_strategy={ "type": "auto", diff --git a/tests/api_resources/beta/test_vector_stores.py b/tests/api_resources/beta/test_vector_stores.py index 39fdb9d1d4..99e1970c33 100644 --- a/tests/api_resources/beta/test_vector_stores.py +++ b/tests/api_resources/beta/test_vector_stores.py @@ -34,7 +34,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "anchor": "last_active_at", "days": 1, }, - file_ids=["string", "string", "string"], + file_ids=["string"], metadata={}, name="string", ) @@ -239,7 +239,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "anchor": "last_active_at", "days": 1, }, - file_ids=["string", "string", "string"], + file_ids=["string"], metadata={}, name="string", ) diff --git a/tests/api_resources/beta/threads/test_messages.py b/tests/api_resources/beta/threads/test_messages.py index b5be32a421..06c37e608a 100644 --- a/tests/api_resources/beta/threads/test_messages.py +++ b/tests/api_resources/beta/threads/test_messages.py @@ -38,17 +38,9 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: role="user", attachments=[ { - "file_id": "string", - "tools": [{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], - }, - { - "file_id": "string", - "tools": [{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], - }, - { - "file_id": "string", - "tools": [{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], - }, + "file_id": "file_id", + "tools": [{"type": "code_interpreter"}], + } ], metadata={}, ) @@ -315,17 +307,9 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> role="user", attachments=[ { - "file_id": "string", - "tools": [{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], - }, - { - "file_id": "string", - "tools": [{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], - }, - { - "file_id": "string", - "tools": [{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], - }, + "file_id": "file_id", + "tools": [{"type": "code_interpreter"}], + } ], metadata={}, ) diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index c8d70f5f89..c48cc6de43 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -43,94 +43,12 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: "role": "user", "attachments": [ { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, + "file_id": "file_id", + "tools": [{"type": "code_interpreter"}], + } ], "metadata": {}, - }, - { - "content": "string", - "role": "user", - "attachments": [ - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - ], - "metadata": {}, - }, - { - "content": "string", - "role": "user", - "attachments": [ - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - ], - "metadata": {}, - }, + } ], instructions="string", max_completion_tokens=256, @@ -142,7 +60,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: stream=False, temperature=1, tool_choice="none", - tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + tools=[{"type": "code_interpreter"}], top_p=1, truncation_strategy={ "type": "auto", @@ -208,94 +126,12 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: "role": "user", "attachments": [ { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, + "file_id": "file_id", + "tools": [{"type": "code_interpreter"}], + } ], "metadata": {}, - }, - { - "content": "string", - "role": "user", - "attachments": [ - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - ], - "metadata": {}, - }, - { - "content": "string", - "role": "user", - "attachments": [ - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - ], - "metadata": {}, - }, + } ], instructions="string", max_completion_tokens=256, @@ -306,7 +142,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: response_format="auto", temperature=1, tool_choice="none", - tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + tools=[{"type": "code_interpreter"}], top_p=1, truncation_strategy={ "type": "auto", @@ -556,9 +392,9 @@ def test_path_params_cancel(self, client: OpenAI) -> None: @parametrize def test_method_submit_tool_outputs_overload_1(self, client: OpenAI) -> None: run = client.beta.threads.runs.submit_tool_outputs( - "string", - thread_id="string", - tool_outputs=[{}, {}, {}], + run_id="run_id", + thread_id="thread_id", + tool_outputs=[{}], ) assert_matches_type(Run, run, path=["response"]) @@ -571,15 +407,7 @@ def test_method_submit_tool_outputs_with_all_params_overload_1(self, client: Ope { "output": "output", "tool_call_id": "tool_call_id", - }, - { - "output": "output", - "tool_call_id": "tool_call_id", - }, - { - "output": "output", - "tool_call_id": "tool_call_id", - }, + } ], stream=False, ) @@ -588,9 +416,9 @@ def test_method_submit_tool_outputs_with_all_params_overload_1(self, client: Ope @parametrize def test_raw_response_submit_tool_outputs_overload_1(self, client: OpenAI) -> None: response = client.beta.threads.runs.with_raw_response.submit_tool_outputs( - "string", - thread_id="string", - tool_outputs=[{}, {}, {}], + run_id="run_id", + thread_id="thread_id", + tool_outputs=[{}], ) assert response.is_closed is True @@ -601,9 +429,9 @@ def test_raw_response_submit_tool_outputs_overload_1(self, client: OpenAI) -> No @parametrize def test_streaming_response_submit_tool_outputs_overload_1(self, client: OpenAI) -> None: with client.beta.threads.runs.with_streaming_response.submit_tool_outputs( - "string", - thread_id="string", - tool_outputs=[{}, {}, {}], + run_id="run_id", + thread_id="thread_id", + tool_outputs=[{}], ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -619,14 +447,14 @@ def test_path_params_submit_tool_outputs_overload_1(self, client: OpenAI) -> Non client.beta.threads.runs.with_raw_response.submit_tool_outputs( "string", thread_id="", - tool_outputs=[{}, {}, {}], + tool_outputs=[{}], ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): client.beta.threads.runs.with_raw_response.submit_tool_outputs( - "", - thread_id="string", - tool_outputs=[{}, {}, {}], + run_id="", + thread_id="thread_id", + tool_outputs=[{}], ) @parametrize @@ -635,7 +463,7 @@ def test_method_submit_tool_outputs_overload_2(self, client: OpenAI) -> None: "string", thread_id="string", stream=True, - tool_outputs=[{}, {}, {}], + tool_outputs=[{}], ) run_stream.response.close() @@ -645,7 +473,7 @@ def test_raw_response_submit_tool_outputs_overload_2(self, client: OpenAI) -> No "string", thread_id="string", stream=True, - tool_outputs=[{}, {}, {}], + tool_outputs=[{}], ) assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -658,7 +486,7 @@ def test_streaming_response_submit_tool_outputs_overload_2(self, client: OpenAI) "string", thread_id="string", stream=True, - tool_outputs=[{}, {}, {}], + tool_outputs=[{}], ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -675,7 +503,7 @@ def test_path_params_submit_tool_outputs_overload_2(self, client: OpenAI) -> Non "string", thread_id="", stream=True, - tool_outputs=[{}, {}, {}], + tool_outputs=[{}], ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): @@ -683,7 +511,7 @@ def test_path_params_submit_tool_outputs_overload_2(self, client: OpenAI) -> Non "", thread_id="string", stream=True, - tool_outputs=[{}, {}, {}], + tool_outputs=[{}], ) @@ -711,94 +539,12 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn "role": "user", "attachments": [ { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, + "file_id": "file_id", + "tools": [{"type": "code_interpreter"}], + } ], "metadata": {}, - }, - { - "content": "string", - "role": "user", - "attachments": [ - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - ], - "metadata": {}, - }, - { - "content": "string", - "role": "user", - "attachments": [ - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - ], - "metadata": {}, - }, + } ], instructions="string", max_completion_tokens=256, @@ -810,7 +556,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn stream=False, temperature=1, tool_choice="none", - tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + tools=[{"type": "code_interpreter"}], top_p=1, truncation_strategy={ "type": "auto", @@ -876,94 +622,12 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn "role": "user", "attachments": [ { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, + "file_id": "file_id", + "tools": [{"type": "code_interpreter"}], + } ], "metadata": {}, - }, - { - "content": "string", - "role": "user", - "attachments": [ - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - ], - "metadata": {}, - }, - { - "content": "string", - "role": "user", - "attachments": [ - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - { - "file_id": "string", - "tools": [ - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - {"type": "code_interpreter"}, - ], - }, - ], - "metadata": {}, - }, + } ], instructions="string", max_completion_tokens=256, @@ -974,7 +638,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn response_format="auto", temperature=1, tool_choice="none", - tools=[{"type": "code_interpreter"}, {"type": "code_interpreter"}, {"type": "code_interpreter"}], + tools=[{"type": "code_interpreter"}], top_p=1, truncation_strategy={ "type": "auto", @@ -1224,9 +888,9 @@ async def test_path_params_cancel(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_method_submit_tool_outputs_overload_1(self, async_client: AsyncOpenAI) -> None: run = await async_client.beta.threads.runs.submit_tool_outputs( - "string", - thread_id="string", - tool_outputs=[{}, {}, {}], + run_id="run_id", + thread_id="thread_id", + tool_outputs=[{}], ) assert_matches_type(Run, run, path=["response"]) @@ -1239,15 +903,7 @@ async def test_method_submit_tool_outputs_with_all_params_overload_1(self, async { "output": "output", "tool_call_id": "tool_call_id", - }, - { - "output": "output", - "tool_call_id": "tool_call_id", - }, - { - "output": "output", - "tool_call_id": "tool_call_id", - }, + } ], stream=False, ) @@ -1256,9 +912,9 @@ async def test_method_submit_tool_outputs_with_all_params_overload_1(self, async @parametrize async def test_raw_response_submit_tool_outputs_overload_1(self, async_client: AsyncOpenAI) -> None: response = await async_client.beta.threads.runs.with_raw_response.submit_tool_outputs( - "string", - thread_id="string", - tool_outputs=[{}, {}, {}], + run_id="run_id", + thread_id="thread_id", + tool_outputs=[{}], ) assert response.is_closed is True @@ -1269,9 +925,9 @@ async def test_raw_response_submit_tool_outputs_overload_1(self, async_client: A @parametrize async def test_streaming_response_submit_tool_outputs_overload_1(self, async_client: AsyncOpenAI) -> None: async with async_client.beta.threads.runs.with_streaming_response.submit_tool_outputs( - "string", - thread_id="string", - tool_outputs=[{}, {}, {}], + run_id="run_id", + thread_id="thread_id", + tool_outputs=[{}], ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -1287,14 +943,14 @@ async def test_path_params_submit_tool_outputs_overload_1(self, async_client: As await async_client.beta.threads.runs.with_raw_response.submit_tool_outputs( "string", thread_id="", - tool_outputs=[{}, {}, {}], + tool_outputs=[{}], ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): await async_client.beta.threads.runs.with_raw_response.submit_tool_outputs( - "", - thread_id="string", - tool_outputs=[{}, {}, {}], + run_id="", + thread_id="thread_id", + tool_outputs=[{}], ) @parametrize @@ -1303,7 +959,7 @@ async def test_method_submit_tool_outputs_overload_2(self, async_client: AsyncOp "string", thread_id="string", stream=True, - tool_outputs=[{}, {}, {}], + tool_outputs=[{}], ) await run_stream.response.aclose() @@ -1313,7 +969,7 @@ async def test_raw_response_submit_tool_outputs_overload_2(self, async_client: A "string", thread_id="string", stream=True, - tool_outputs=[{}, {}, {}], + tool_outputs=[{}], ) assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -1326,7 +982,7 @@ async def test_streaming_response_submit_tool_outputs_overload_2(self, async_cli "string", thread_id="string", stream=True, - tool_outputs=[{}, {}, {}], + tool_outputs=[{}], ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -1343,7 +999,7 @@ async def test_path_params_submit_tool_outputs_overload_2(self, async_client: As "string", thread_id="", stream=True, - tool_outputs=[{}, {}, {}], + tool_outputs=[{}], ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): @@ -1351,5 +1007,5 @@ async def test_path_params_submit_tool_outputs_overload_2(self, async_client: As "", thread_id="string", stream=True, - tool_outputs=[{}, {}, {}], + tool_outputs=[{}], ) diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index dafedac9fb..1b52650b1d 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -62,7 +62,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: max_completion_tokens=0, max_tokens=0, metadata={"foo": "string"}, - modalities=["text", "audio"], + modalities=["text"], n=1, parallel_tool_calls=True, prediction={ @@ -88,25 +88,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: "strict": True, }, "type": "function", - }, - { - "function": { - "name": "name", - "description": "description", - "parameters": {"foo": "bar"}, - "strict": True, - }, - "type": "function", - }, - { - "function": { - "name": "name", - "description": "description", - "parameters": {"foo": "bar"}, - "strict": True, - }, - "type": "function", - }, + } ], top_logprobs=0, top_p=1, @@ -194,7 +176,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: max_completion_tokens=0, max_tokens=0, metadata={"foo": "string"}, - modalities=["text", "audio"], + modalities=["text"], n=1, parallel_tool_calls=True, prediction={ @@ -219,25 +201,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: "strict": True, }, "type": "function", - }, - { - "function": { - "name": "name", - "description": "description", - "parameters": {"foo": "bar"}, - "strict": True, - }, - "type": "function", - }, - { - "function": { - "name": "name", - "description": "description", - "parameters": {"foo": "bar"}, - "strict": True, - }, - "type": "function", - }, + } ], top_logprobs=0, top_p=1, @@ -345,7 +309,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn max_completion_tokens=0, max_tokens=0, metadata={"foo": "string"}, - modalities=["text", "audio"], + modalities=["text"], n=1, parallel_tool_calls=True, prediction={ @@ -371,25 +335,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn "strict": True, }, "type": "function", - }, - { - "function": { - "name": "name", - "description": "description", - "parameters": {"foo": "bar"}, - "strict": True, - }, - "type": "function", - }, - { - "function": { - "name": "name", - "description": "description", - "parameters": {"foo": "bar"}, - "strict": True, - }, - "type": "function", - }, + } ], top_logprobs=0, top_p=1, @@ -477,7 +423,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn max_completion_tokens=0, max_tokens=0, metadata={"foo": "string"}, - modalities=["text", "audio"], + modalities=["text"], n=1, parallel_tool_calls=True, prediction={ @@ -502,25 +448,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn "strict": True, }, "type": "function", - }, - { - "function": { - "name": "name", - "description": "description", - "parameters": {"foo": "bar"}, - "strict": True, - }, - "type": "function", - }, - { - "function": { - "name": "name", - "description": "description", - "parameters": {"foo": "bar"}, - "strict": True, - }, - "type": "function", - }, + } ], top_logprobs=0, top_p=1, diff --git a/tests/api_resources/fine_tuning/test_jobs.py b/tests/api_resources/fine_tuning/test_jobs.py index d1ad611219..aa2bf39528 100644 --- a/tests/api_resources/fine_tuning/test_jobs.py +++ b/tests/api_resources/fine_tuning/test_jobs.py @@ -46,27 +46,9 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "project": "my-wandb-project", "entity": "entity", "name": "name", - "tags": ["custom-tag", "custom-tag", "custom-tag"], + "tags": ["custom-tag"], }, - }, - { - "type": "wandb", - "wandb": { - "project": "my-wandb-project", - "entity": "entity", - "name": "name", - "tags": ["custom-tag", "custom-tag", "custom-tag"], - }, - }, - { - "type": "wandb", - "wandb": { - "project": "my-wandb-project", - "entity": "entity", - "name": "name", - "tags": ["custom-tag", "custom-tag", "custom-tag"], - }, - }, + } ], seed=42, suffix="x", @@ -285,27 +267,9 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "project": "my-wandb-project", "entity": "entity", "name": "name", - "tags": ["custom-tag", "custom-tag", "custom-tag"], - }, - }, - { - "type": "wandb", - "wandb": { - "project": "my-wandb-project", - "entity": "entity", - "name": "name", - "tags": ["custom-tag", "custom-tag", "custom-tag"], - }, - }, - { - "type": "wandb", - "wandb": { - "project": "my-wandb-project", - "entity": "entity", - "name": "name", - "tags": ["custom-tag", "custom-tag", "custom-tag"], + "tags": ["custom-tag"], }, - }, + } ], seed=42, suffix="x", diff --git a/tests/api_resources/test_uploads.py b/tests/api_resources/test_uploads.py index cb62df6b51..a14c4f8da2 100644 --- a/tests/api_resources/test_uploads.py +++ b/tests/api_resources/test_uploads.py @@ -99,7 +99,7 @@ def test_path_params_cancel(self, client: OpenAI) -> None: def test_method_complete(self, client: OpenAI) -> None: upload = client.uploads.complete( upload_id="upload_abc123", - part_ids=["string", "string", "string"], + part_ids=["string"], ) assert_matches_type(Upload, upload, path=["response"]) @@ -107,7 +107,7 @@ def test_method_complete(self, client: OpenAI) -> None: def test_method_complete_with_all_params(self, client: OpenAI) -> None: upload = client.uploads.complete( upload_id="upload_abc123", - part_ids=["string", "string", "string"], + part_ids=["string"], md5="md5", ) assert_matches_type(Upload, upload, path=["response"]) @@ -116,7 +116,7 @@ def test_method_complete_with_all_params(self, client: OpenAI) -> None: def test_raw_response_complete(self, client: OpenAI) -> None: response = client.uploads.with_raw_response.complete( upload_id="upload_abc123", - part_ids=["string", "string", "string"], + part_ids=["string"], ) assert response.is_closed is True @@ -128,7 +128,7 @@ def test_raw_response_complete(self, client: OpenAI) -> None: def test_streaming_response_complete(self, client: OpenAI) -> None: with client.uploads.with_streaming_response.complete( upload_id="upload_abc123", - part_ids=["string", "string", "string"], + part_ids=["string"], ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -143,7 +143,7 @@ def test_path_params_complete(self, client: OpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `upload_id` but received ''"): client.uploads.with_raw_response.complete( upload_id="", - part_ids=["string", "string", "string"], + part_ids=["string"], ) @@ -232,7 +232,7 @@ async def test_path_params_cancel(self, async_client: AsyncOpenAI) -> None: async def test_method_complete(self, async_client: AsyncOpenAI) -> None: upload = await async_client.uploads.complete( upload_id="upload_abc123", - part_ids=["string", "string", "string"], + part_ids=["string"], ) assert_matches_type(Upload, upload, path=["response"]) @@ -240,7 +240,7 @@ async def test_method_complete(self, async_client: AsyncOpenAI) -> None: async def test_method_complete_with_all_params(self, async_client: AsyncOpenAI) -> None: upload = await async_client.uploads.complete( upload_id="upload_abc123", - part_ids=["string", "string", "string"], + part_ids=["string"], md5="md5", ) assert_matches_type(Upload, upload, path=["response"]) @@ -249,7 +249,7 @@ async def test_method_complete_with_all_params(self, async_client: AsyncOpenAI) async def test_raw_response_complete(self, async_client: AsyncOpenAI) -> None: response = await async_client.uploads.with_raw_response.complete( upload_id="upload_abc123", - part_ids=["string", "string", "string"], + part_ids=["string"], ) assert response.is_closed is True @@ -261,7 +261,7 @@ async def test_raw_response_complete(self, async_client: AsyncOpenAI) -> None: async def test_streaming_response_complete(self, async_client: AsyncOpenAI) -> None: async with async_client.uploads.with_streaming_response.complete( upload_id="upload_abc123", - part_ids=["string", "string", "string"], + part_ids=["string"], ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -276,5 +276,5 @@ async def test_path_params_complete(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `upload_id` but received ''"): await async_client.uploads.with_raw_response.complete( upload_id="", - part_ids=["string", "string", "string"], + part_ids=["string"], ) From 0d6185edc2eb4155699a28415b8759653f91ef52 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 18 Nov 2024 10:42:24 +0000 Subject: [PATCH 572/816] chore(internal): spec update (#1873) --- .stats.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index f368bc881d..fdef8d2744 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-2f8ca92b9b1879fd535b685e4767338413fcd533d42f3baac13a9c41da3fce35.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-fb9db2d2c1f0d6b39d8ee042db5d5c59acba6ad1daf47c18792c1f5fb24b3401.yml From d8901d28587ad9db4f1435f1f00ad7b919c232f7 Mon Sep 17 00:00:00 2001 From: Seth Gilchrist Date: Mon, 18 Nov 2024 04:41:32 -0800 Subject: [PATCH 573/816] fix(asyncify): avoid hanging process under certain conditions (#1853) --- pyproject.toml | 4 +- requirements-dev.lock | 2 + requirements.lock | 1 + src/openai/_utils/_sync.py | 90 +++++++++++++++++--------------------- tests/test_client.py | 43 ++++++++++++++++++ 5 files changed, 88 insertions(+), 52 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index e0a20e8387..b22ef1927d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -65,7 +65,9 @@ dev-dependencies = [ "azure-identity >=1.14.1", "types-tqdm > 4", "types-pyaudio > 0", - "trio >=0.22.2" + "trio >=0.22.2", + "nest_asyncio==1.6.0" + ] [tool.rye.scripts] diff --git a/requirements-dev.lock b/requirements-dev.lock index 5fe1ccad57..4d0ab191a4 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -7,6 +7,7 @@ # all-features: true # with-sources: false # generate-hashes: false +# universal: false -e file:. annotated-types==0.6.0 @@ -87,6 +88,7 @@ mypy==1.13.0 mypy-extensions==1.0.0 # via black # via mypy +nest-asyncio==1.6.0 nodeenv==1.8.0 # via pyright nox==2023.4.22 diff --git a/requirements.lock b/requirements.lock index 019dfcb4c5..aef8bc0a9a 100644 --- a/requirements.lock +++ b/requirements.lock @@ -7,6 +7,7 @@ # all-features: true # with-sources: false # generate-hashes: false +# universal: false -e file:. annotated-types==0.6.0 diff --git a/src/openai/_utils/_sync.py b/src/openai/_utils/_sync.py index d0d810337e..c0a0ae714c 100644 --- a/src/openai/_utils/_sync.py +++ b/src/openai/_utils/_sync.py @@ -1,56 +1,60 @@ from __future__ import annotations +import sys +import asyncio import functools -from typing import TypeVar, Callable, Awaitable +import contextvars +from typing import Any, TypeVar, Callable, Awaitable from typing_extensions import ParamSpec -import anyio -import anyio.to_thread - -from ._reflection import function_has_argument - T_Retval = TypeVar("T_Retval") T_ParamSpec = ParamSpec("T_ParamSpec") -# copied from `asyncer`, https://github.com/tiangolo/asyncer -def asyncify( - function: Callable[T_ParamSpec, T_Retval], - *, - cancellable: bool = False, - limiter: anyio.CapacityLimiter | None = None, -) -> Callable[T_ParamSpec, Awaitable[T_Retval]]: - """ - Take a blocking function and create an async one that receives the same - positional and keyword arguments, and that when called, calls the original function - in a worker thread using `anyio.to_thread.run_sync()`. Internally, - `asyncer.asyncify()` uses the same `anyio.to_thread.run_sync()`, but it supports - keyword arguments additional to positional arguments and it adds better support for - autocompletion and inline errors for the arguments of the function called and the - return value. +if sys.version_info >= (3, 9): + to_thread = asyncio.to_thread +else: + async def _to_thread( + func: Callable[T_ParamSpec, T_Retval], /, *args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs + ) -> Any: + """Asynchronously run function *func* in a separate thread. - If the `cancellable` option is enabled and the task waiting for its completion is - cancelled, the thread will still run its course but its return value (or any raised - exception) will be ignored. + Any *args and **kwargs supplied for this function are directly passed + to *func*. Also, the current :class:`contextvars.Context` is propagated, + allowing context variables from the main thread to be accessed in the + separate thread. - Use it like this: + Returns a coroutine that can be awaited to get the eventual result of *func*. + """ + loop = asyncio.events.get_running_loop() + ctx = contextvars.copy_context() + func_call = functools.partial(ctx.run, func, *args, **kwargs) + return await loop.run_in_executor(None, func_call) + + to_thread = _to_thread + +# inspired by `asyncer`, https://github.com/tiangolo/asyncer +def asyncify(function: Callable[T_ParamSpec, T_Retval]) -> Callable[T_ParamSpec, Awaitable[T_Retval]]: + """ + Take a blocking function and create an async one that receives the same + positional and keyword arguments. For python version 3.9 and above, it uses + asyncio.to_thread to run the function in a separate thread. For python version + 3.8, it uses locally defined copy of the asyncio.to_thread function which was + introduced in python 3.9. - ```Python - def do_work(arg1, arg2, kwarg1="", kwarg2="") -> str: - # Do work - return "Some result" + Usage: + ```python + def blocking_func(arg1, arg2, kwarg1=None): + # blocking code + return result - result = await to_thread.asyncify(do_work)("spam", "ham", kwarg1="a", kwarg2="b") - print(result) + result = asyncify(blocking_function)(arg1, arg2, kwarg1=value1) ``` ## Arguments `function`: a blocking regular callable (e.g. a function) - `cancellable`: `True` to allow cancellation of the operation - `limiter`: capacity limiter to use to limit the total amount of threads running - (if omitted, the default limiter is used) ## Return @@ -60,22 +64,6 @@ def do_work(arg1, arg2, kwarg1="", kwarg2="") -> str: """ async def wrapper(*args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs) -> T_Retval: - partial_f = functools.partial(function, *args, **kwargs) - - # In `v4.1.0` anyio added the `abandon_on_cancel` argument and deprecated the old - # `cancellable` argument, so we need to use the new `abandon_on_cancel` to avoid - # surfacing deprecation warnings. - if function_has_argument(anyio.to_thread.run_sync, "abandon_on_cancel"): - return await anyio.to_thread.run_sync( - partial_f, - abandon_on_cancel=cancellable, - limiter=limiter, - ) - - return await anyio.to_thread.run_sync( - partial_f, - cancellable=cancellable, - limiter=limiter, - ) + return await to_thread(function, *args, **kwargs) return wrapper diff --git a/tests/test_client.py b/tests/test_client.py index 7ea2ab38d1..08aff23f53 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -4,11 +4,14 @@ import gc import os +import sys import json import asyncio import inspect +import subprocess import tracemalloc from typing import Any, Union, cast +from textwrap import dedent from unittest import mock from typing_extensions import Literal @@ -1766,3 +1769,43 @@ def retry_handler(_request: httpx.Request) -> httpx.Response: ) as response: assert response.retries_taken == failures_before_success assert int(response.http_request.headers.get("x-stainless-retry-count")) == failures_before_success + + def test_get_platform(self) -> None: + # Issue https://github.com/openai/openai-python/issues/1827 was caused + # asyncify leaving threads unterminated when used with nest_asyncio. + # Since nest_asyncio.apply() is global and cannot be un-applied, this + # test is run in a separate process to avoid affecting other tests. + test_code = dedent("""\ + import asyncio + import nest_asyncio + + import threading + + from openai._base_client import get_platform + from openai._utils import asyncify + + async def test_main() -> None: + result = await asyncify(get_platform)() + print(result) + for thread in threading.enumerate(): + print(thread.name) + + nest_asyncio.apply() + asyncio.run(test_main()) + """) + with subprocess.Popen( + [sys.executable, "-c", test_code], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) as process: + try: + process.wait(2) + if process.returncode: + print(process.stdout) + print(process.stderr) + raise AssertionError("calling get_platform using asyncify resulted in a non-zero exit code") + except subprocess.TimeoutExpired as e: + process.kill() + raise AssertionError("calling get_platform using asyncify resulted in a hung process") from e + From 53ab046716631e5539304052162e5b374a2d6f15 Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Mon, 18 Nov 2024 12:58:39 +0000 Subject: [PATCH 574/816] chore(internal): minor test changes (#1874) --- src/openai/_utils/_sync.py | 5 +++-- tests/test_client.py | 15 +++++---------- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/src/openai/_utils/_sync.py b/src/openai/_utils/_sync.py index c0a0ae714c..5d9e2c2ac9 100644 --- a/src/openai/_utils/_sync.py +++ b/src/openai/_utils/_sync.py @@ -14,7 +14,9 @@ if sys.version_info >= (3, 9): to_thread = asyncio.to_thread else: - async def _to_thread( + # backport of https://docs.python.org/3/library/asyncio-task.html#asyncio.to_thread + # for Python 3.8 support + async def to_thread( func: Callable[T_ParamSpec, T_Retval], /, *args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs ) -> Any: """Asynchronously run function *func* in a separate thread. @@ -31,7 +33,6 @@ async def _to_thread( func_call = functools.partial(ctx.run, func, *args, **kwargs) return await loop.run_in_executor(None, func_call) - to_thread = _to_thread # inspired by `asyncer`, https://github.com/tiangolo/asyncer def asyncify(function: Callable[T_ParamSpec, T_Retval]) -> Callable[T_ParamSpec, Awaitable[T_Retval]]: diff --git a/tests/test_client.py b/tests/test_client.py index 08aff23f53..7caa8cb319 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1771,18 +1771,18 @@ def retry_handler(_request: httpx.Request) -> httpx.Response: assert int(response.http_request.headers.get("x-stainless-retry-count")) == failures_before_success def test_get_platform(self) -> None: - # Issue https://github.com/openai/openai-python/issues/1827 was caused - # asyncify leaving threads unterminated when used with nest_asyncio. + # A previous implementation of asyncify could leave threads unterminated when + # used with nest_asyncio. + # # Since nest_asyncio.apply() is global and cannot be un-applied, this # test is run in a separate process to avoid affecting other tests. - test_code = dedent("""\ + test_code = dedent(""" import asyncio import nest_asyncio - import threading - from openai._base_client import get_platform from openai._utils import asyncify + from openai._base_client import get_platform async def test_main() -> None: result = await asyncify(get_platform)() @@ -1795,17 +1795,12 @@ async def test_main() -> None: """) with subprocess.Popen( [sys.executable, "-c", test_code], - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, text=True, ) as process: try: process.wait(2) if process.returncode: - print(process.stdout) - print(process.stderr) raise AssertionError("calling get_platform using asyncify resulted in a non-zero exit code") except subprocess.TimeoutExpired as e: process.kill() raise AssertionError("calling get_platform using asyncify resulted in a hung process") from e - From 7cdc6ddbdd3c09e567c5582490aec9d7f99c468e Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 19 Nov 2024 05:04:28 +0000 Subject: [PATCH 575/816] release: 1.54.5 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 15 +++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 18 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 7bfe725d47..68c5231faa 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.54.4" + ".": "1.54.5" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index d82ac42553..c646eca314 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## 1.54.5 (2024-11-19) + +Full Changelog: [v1.54.4...v1.54.5](https://github.com/openai/openai-python/compare/v1.54.4...v1.54.5) + +### Bug Fixes + +* **asyncify:** avoid hanging process under certain conditions ([#1853](https://github.com/openai/openai-python/issues/1853)) ([3d23437](https://github.com/openai/openai-python/commit/3d234377e7c9cd19db5186688612eb18e68cec8f)) + + +### Chores + +* **internal:** minor test changes ([#1874](https://github.com/openai/openai-python/issues/1874)) ([189339d](https://github.com/openai/openai-python/commit/189339d2a09d23ea1883286972f366e19b397f91)) +* **internal:** spec update ([#1873](https://github.com/openai/openai-python/issues/1873)) ([24c81f7](https://github.com/openai/openai-python/commit/24c81f729ae09ba3cec5542e5cc955c8b05b0f88)) +* **tests:** limit array example length ([#1870](https://github.com/openai/openai-python/issues/1870)) ([1e550df](https://github.com/openai/openai-python/commit/1e550df708fc3b5d903b7adfa2180058a216b676)) + ## 1.54.4 (2024-11-12) Full Changelog: [v1.54.3...v1.54.4](https://github.com/openai/openai-python/compare/v1.54.3...v1.54.4) diff --git a/pyproject.toml b/pyproject.toml index b22ef1927d..8138ffbaef 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.54.4" +version = "1.54.5" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 5e531dd083..75ee06518f 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.54.4" # x-release-please-version +__version__ = "1.54.5" # x-release-please-version From 8eba381dc2b062ca41e909adef95540a6234be50 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 20 Nov 2024 18:17:44 +0000 Subject: [PATCH 576/816] feat(api): add gpt-4o-2024-11-20 model (#1877) --- .stats.yml | 2 +- src/openai/resources/batches.py | 4 ++-- src/openai/resources/files.py | 4 ++-- src/openai/types/batch_create_params.py | 2 +- src/openai/types/chat/chat_completion_audio_param.py | 5 +++-- src/openai/types/chat_model.py | 1 + 6 files changed, 10 insertions(+), 8 deletions(-) diff --git a/.stats.yml b/.stats.yml index fdef8d2744..4827e5388f 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-fb9db2d2c1f0d6b39d8ee042db5d5c59acba6ad1daf47c18792c1f5fb24b3401.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-aa9b01fc0c17eb0cbc200533fc20d6a49c5e764ceaf8049e08b294532be6e9ff.yml diff --git a/src/openai/resources/batches.py b/src/openai/resources/batches.py index a8a0ba4bbc..7cab75785d 100644 --- a/src/openai/resources/batches.py +++ b/src/openai/resources/batches.py @@ -81,7 +81,7 @@ def create( Your input file must be formatted as a [JSONL file](https://platform.openai.com/docs/api-reference/batch/request-input), and must be uploaded with the purpose `batch`. The file can contain up to 50,000 - requests, and can be up to 100 MB in size. + requests, and can be up to 200 MB in size. metadata: Optional custom metadata for the batch. @@ -286,7 +286,7 @@ async def create( Your input file must be formatted as a [JSONL file](https://platform.openai.com/docs/api-reference/batch/request-input), and must be uploaded with the purpose `batch`. The file can contain up to 50,000 - requests, and can be up to 100 MB in size. + requests, and can be up to 200 MB in size. metadata: Optional custom metadata for the batch. diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index 77706a7fd8..6eaea1b568 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -86,7 +86,7 @@ def create( [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) models. - The Batch API only supports `.jsonl` files up to 100 MB in size. The input also + The Batch API only supports `.jsonl` files up to 200 MB in size. The input also has a specific required [format](https://platform.openai.com/docs/api-reference/batch/request-input). @@ -402,7 +402,7 @@ async def create( [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) models. - The Batch API only supports `.jsonl` files up to 100 MB in size. The input also + The Batch API only supports `.jsonl` files up to 200 MB in size. The input also has a specific required [format](https://platform.openai.com/docs/api-reference/batch/request-input). diff --git a/src/openai/types/batch_create_params.py b/src/openai/types/batch_create_params.py index 55517d285b..b30c4d4658 100644 --- a/src/openai/types/batch_create_params.py +++ b/src/openai/types/batch_create_params.py @@ -32,7 +32,7 @@ class BatchCreateParams(TypedDict, total=False): Your input file must be formatted as a [JSONL file](https://platform.openai.com/docs/api-reference/batch/request-input), and must be uploaded with the purpose `batch`. The file can contain up to 50,000 - requests, and can be up to 100 MB in size. + requests, and can be up to 200 MB in size. """ metadata: Optional[Dict[str, str]] diff --git a/src/openai/types/chat/chat_completion_audio_param.py b/src/openai/types/chat/chat_completion_audio_param.py index b92326d294..1e20a52b41 100644 --- a/src/openai/types/chat/chat_completion_audio_param.py +++ b/src/openai/types/chat/chat_completion_audio_param.py @@ -17,6 +17,7 @@ class ChatCompletionAudioParam(TypedDict, total=False): voice: Required[Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"]] """The voice the model uses to respond. - Supported voices are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, - `shimmer`, and `verse`. + Supported voices are `ash`, `ballad`, `coral`, `sage`, and `verse` (also + supported but not recommended are `alloy`, `echo`, and `shimmer`; these voices + are less expressive). """ diff --git a/src/openai/types/chat_model.py b/src/openai/types/chat_model.py index b801aa0914..3567a3ba65 100644 --- a/src/openai/types/chat_model.py +++ b/src/openai/types/chat_model.py @@ -10,6 +10,7 @@ "o1-mini", "o1-mini-2024-09-12", "gpt-4o", + "gpt-4o-2024-11-20", "gpt-4o-2024-08-06", "gpt-4o-2024-05-13", "gpt-4o-realtime-preview", From 83091e96cf43f344d22799c22eea301aeae36d51 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 20 Nov 2024 18:18:15 +0000 Subject: [PATCH 577/816] release: 1.55.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 68c5231faa..061f355bf3 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.54.5" + ".": "1.55.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index c646eca314..921f9b7bad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.55.0 (2024-11-20) + +Full Changelog: [v1.54.5...v1.55.0](https://github.com/openai/openai-python/compare/v1.54.5...v1.55.0) + +### Features + +* **api:** add gpt-4o-2024-11-20 model ([#1877](https://github.com/openai/openai-python/issues/1877)) ([ff64c2a](https://github.com/openai/openai-python/commit/ff64c2a0733854ed8cc1d7dd959a8287b2ec8120)) + ## 1.54.5 (2024-11-19) Full Changelog: [v1.54.4...v1.54.5](https://github.com/openai/openai-python/compare/v1.54.4...v1.54.5) diff --git a/pyproject.toml b/pyproject.toml index 8138ffbaef..02b3fbfb93 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.54.5" +version = "1.55.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 75ee06518f..093c3e3939 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.54.5" # x-release-please-version +__version__ = "1.55.0" # x-release-please-version From e9cbb256650a07c008e6529778e10cc66e9f7605 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 22 Nov 2024 11:22:30 +0000 Subject: [PATCH 578/816] fix(pydantic-v1): avoid runtime error for assistants streaming (#1885) --- src/openai/_compat.py | 3 ++- tests/test_models.py | 8 ++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/openai/_compat.py b/src/openai/_compat.py index 7c3156a5eb..d7196c9193 100644 --- a/src/openai/_compat.py +++ b/src/openai/_compat.py @@ -145,7 +145,8 @@ def model_dump( exclude=exclude, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, - warnings=warnings, + # warnings are not supported in Pydantic v1 + warnings=warnings if PYDANTIC_V2 else True, ) return cast( "dict[str, Any]", diff --git a/tests/test_models.py b/tests/test_models.py index 84dbce6914..d2884bcbfa 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -561,6 +561,14 @@ class Model(BaseModel): m.model_dump(warnings=False) +def test_compat_method_no_error_for_warnings() -> None: + class Model(BaseModel): + foo: Optional[str] + + m = Model(foo="hello") + assert isinstance(model_dump(m, warnings=False), dict) + + def test_to_json() -> None: class Model(BaseModel): foo: Optional[str] = Field(alias="FOO", default=None) From f6199d60a0384bfb71c0ca2eb24c5765d760715e Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 22 Nov 2024 16:06:42 +0000 Subject: [PATCH 579/816] docs: add info log level to readme (#1887) --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f1cd97b96e..5854e8d3ad 100644 --- a/README.md +++ b/README.md @@ -509,12 +509,14 @@ Note that requests that time out are [retried twice by default](#retries). We use the standard library [`logging`](https://docs.python.org/3/library/logging.html) module. -You can enable logging by setting the environment variable `OPENAI_LOG` to `debug`. +You can enable logging by setting the environment variable `OPENAI_LOG` to `info`. ```shell -$ export OPENAI_LOG=debug +$ export OPENAI_LOG=info ``` +Or to `debug` for more verbose logging. + ### How to tell whether `None` means `null` or missing In an API response, a field may be explicitly `null`, or missing entirely; in either case, its value is `None` in this library. You can differentiate the two cases with `.model_fields_set`: From 5dfb00886eb56db340a689380c6a481a7b7ea34f Mon Sep 17 00:00:00 2001 From: Harutaka Kawamura Date: Mon, 25 Nov 2024 21:17:54 +0900 Subject: [PATCH 580/816] chore: remove now unused `cached-property` dep (#1867) --- pyproject.toml | 1 - src/openai/_compat.py | 5 +---- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 02b3fbfb93..4c41631edd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,7 +14,6 @@ dependencies = [ "anyio>=3.5.0, <5", "distro>=1.7.0, <2", "sniffio", - "cached-property; python_version < '3.8'", "tqdm > 4", "jiter>=0.4.0, <1", ] diff --git a/src/openai/_compat.py b/src/openai/_compat.py index d7196c9193..87fc370765 100644 --- a/src/openai/_compat.py +++ b/src/openai/_compat.py @@ -226,9 +226,6 @@ def __set_name__(self, owner: type[Any], name: str) -> None: ... # __set__ is not defined at runtime, but @cached_property is designed to be settable def __set__(self, instance: object, value: _T) -> None: ... else: - try: - from functools import cached_property as cached_property - except ImportError: - from cached_property import cached_property as cached_property + from functools import cached_property as cached_property typed_cached_property = cached_property From 83f4774156dc3e29c7fe6be9ffd681df68534509 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 25 Nov 2024 12:25:56 +0000 Subject: [PATCH 581/816] release: 1.55.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 19 +++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 22 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 061f355bf3..af721f5395 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.55.0" + ".": "1.55.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 921f9b7bad..409d3c2df0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,24 @@ # Changelog +## 1.55.1 (2024-11-25) + +Full Changelog: [v1.55.0...v1.55.1](https://github.com/openai/openai-python/compare/v1.55.0...v1.55.1) + +### Bug Fixes + +* **pydantic-v1:** avoid runtime error for assistants streaming ([#1885](https://github.com/openai/openai-python/issues/1885)) ([197c94b](https://github.com/openai/openai-python/commit/197c94b9e2620da8902aeed6959d2f871bb70461)) + + +### Chores + +* remove now unused `cached-property` dep ([#1867](https://github.com/openai/openai-python/issues/1867)) ([df5fac1](https://github.com/openai/openai-python/commit/df5fac1e557f79ed8d0935c48ca7f3f0bf77fa98)) +* remove now unused `cached-property` dep ([#1891](https://github.com/openai/openai-python/issues/1891)) ([feebaae](https://github.com/openai/openai-python/commit/feebaae85d76960cb8f1c58dd9b5180136c47962)) + + +### Documentation + +* add info log level to readme ([#1887](https://github.com/openai/openai-python/issues/1887)) ([358255d](https://github.com/openai/openai-python/commit/358255d15ed220f8c80a3c0861b98e61e909a7ae)) + ## 1.55.0 (2024-11-20) Full Changelog: [v1.54.5...v1.55.0](https://github.com/openai/openai-python/compare/v1.54.5...v1.55.0) diff --git a/pyproject.toml b/pyproject.toml index 4c41631edd..fb48acf1f2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.55.0" +version = "1.55.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 093c3e3939..f3c5f8db8b 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.55.0" # x-release-please-version +__version__ = "1.55.1" # x-release-please-version From 3ad59995e7475fa30007255d2a26bad09392b515 Mon Sep 17 00:00:00 2001 From: Vincent Josse Date: Wed, 27 Nov 2024 11:35:24 +0100 Subject: [PATCH 582/816] docs(assistants): correct on_text_delta example (#1896) --- src/openai/lib/streaming/_assistants.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/openai/lib/streaming/_assistants.py b/src/openai/lib/streaming/_assistants.py index 103e4c40aa..6efb3ca3f1 100644 --- a/src/openai/lib/streaming/_assistants.py +++ b/src/openai/lib/streaming/_assistants.py @@ -243,7 +243,7 @@ def on_text_delta(self, delta: TextDelta, snapshot: Text) -> None: on_text_delta(TextDelta(value=" solution"), Text(value="The solution")), on_text_delta(TextDelta(value=" to"), Text(value="The solution to")), on_text_delta(TextDelta(value=" the"), Text(value="The solution to the")), - on_text_delta(TextDelta(value=" equation"), Text(value="The solution to the equivalent")), + on_text_delta(TextDelta(value=" equation"), Text(value="The solution to the equation")), """ def on_text_done(self, text: Text) -> None: From f2607f54b9f51a6f3fcb168834bd6351c1512ab9 Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Wed, 27 Nov 2024 14:04:44 +0000 Subject: [PATCH 583/816] chore(internal): exclude mypy from running on tests (#1899) --- mypy.ini | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/mypy.ini b/mypy.ini index 97e5de4a60..50e5add04b 100644 --- a/mypy.ini +++ b/mypy.ini @@ -5,7 +5,10 @@ show_error_codes = True # Exclude _files.py and _logs.py because mypy isn't smart enough to apply # the correct type narrowing and as this is an internal module # it's fine to just use Pyright. -exclude = ^(src/openai/_files\.py|src/openai/_utils/_logs\.py|_dev/.*\.py)$ +# +# We also exclude our `tests` as mypy doesn't always infer +# types correctly and Pyright will still catch any type errors. +exclude = ^(src/openai/_files\.py|src/openai/_utils/_logs\.py|_dev/.*\.py|tests/.*)$ strict_equality = True implicit_reexport = True From 95bd2582a1e37bb35eac429925ffa0aea10078a5 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 27 Nov 2024 14:05:13 +0000 Subject: [PATCH 584/816] release: 1.55.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index af721f5395..488f1adb5e 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.55.1" + ".": "1.55.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 409d3c2df0..8009aac671 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.55.2 (2024-11-27) + +Full Changelog: [v1.55.1...v1.55.2](https://github.com/openai/openai-python/compare/v1.55.1...v1.55.2) + +### Chores + +* **internal:** exclude mypy from running on tests ([#1899](https://github.com/openai/openai-python/issues/1899)) ([e2496f1](https://github.com/openai/openai-python/commit/e2496f1d274126bdaa46a8256b3dd384b4ae244b)) + + +### Documentation + +* **assistants:** correct on_text_delta example ([#1896](https://github.com/openai/openai-python/issues/1896)) ([460b663](https://github.com/openai/openai-python/commit/460b663567ed1031467a8d69eb13fd3b3da38827)) + ## 1.55.1 (2024-11-25) Full Changelog: [v1.55.0...v1.55.1](https://github.com/openai/openai-python/compare/v1.55.0...v1.55.1) diff --git a/pyproject.toml b/pyproject.toml index fb48acf1f2..4842cceea4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.55.1" +version = "1.55.2" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index f3c5f8db8b..5b04f5cc00 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.55.1" # x-release-please-version +__version__ = "1.55.2" # x-release-please-version From bb9cf7a6acfd1729fa76247da041a4787a6bfc1a Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 28 Nov 2024 16:16:48 +0000 Subject: [PATCH 585/816] fix(client): compat with new httpx 0.28.0 release (#1904) --- src/openai/_base_client.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 187518787a..cceec903d9 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -794,6 +794,7 @@ def __init__( custom_query: Mapping[str, object] | None = None, _strict_response_validation: bool, ) -> None: + kwargs: dict[str, Any] = {} if limits is not None: warnings.warn( "The `connection_pool_limits` argument is deprecated. The `http_client` argument should be passed instead", @@ -806,6 +807,7 @@ def __init__( limits = DEFAULT_CONNECTION_LIMITS if transport is not None: + kwargs["transport"] = transport warnings.warn( "The `transport` argument is deprecated. The `http_client` argument should be passed instead", category=DeprecationWarning, @@ -815,6 +817,7 @@ def __init__( raise ValueError("The `http_client` argument is mutually exclusive with `transport`") if proxies is not None: + kwargs["proxies"] = proxies warnings.warn( "The `proxies` argument is deprecated. The `http_client` argument should be passed instead", category=DeprecationWarning, @@ -858,10 +861,9 @@ def __init__( base_url=base_url, # cast to a valid type because mypy doesn't understand our type narrowing timeout=cast(Timeout, timeout), - proxies=proxies, - transport=transport, limits=limits, follow_redirects=True, + **kwargs, # type: ignore ) def is_closed(self) -> bool: @@ -1375,6 +1377,7 @@ def __init__( custom_headers: Mapping[str, str] | None = None, custom_query: Mapping[str, object] | None = None, ) -> None: + kwargs: dict[str, Any] = {} if limits is not None: warnings.warn( "The `connection_pool_limits` argument is deprecated. The `http_client` argument should be passed instead", @@ -1387,6 +1390,7 @@ def __init__( limits = DEFAULT_CONNECTION_LIMITS if transport is not None: + kwargs["transport"] = transport warnings.warn( "The `transport` argument is deprecated. The `http_client` argument should be passed instead", category=DeprecationWarning, @@ -1396,6 +1400,7 @@ def __init__( raise ValueError("The `http_client` argument is mutually exclusive with `transport`") if proxies is not None: + kwargs["proxies"] = proxies warnings.warn( "The `proxies` argument is deprecated. The `http_client` argument should be passed instead", category=DeprecationWarning, @@ -1439,10 +1444,9 @@ def __init__( base_url=base_url, # cast to a valid type because mypy doesn't understand our type narrowing timeout=cast(Timeout, timeout), - proxies=proxies, - transport=transport, limits=limits, follow_redirects=True, + **kwargs, # type: ignore ) def is_closed(self) -> bool: From 6974a981aec1814b5abba429a8ea21be9ac58538 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 28 Nov 2024 16:17:16 +0000 Subject: [PATCH 586/816] release: 1.55.3 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 488f1adb5e..d23d0104a4 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.55.2" + ".": "1.55.3" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 8009aac671..866d34cb4f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.55.3 (2024-11-28) + +Full Changelog: [v1.55.2...v1.55.3](https://github.com/openai/openai-python/compare/v1.55.2...v1.55.3) + +### Bug Fixes + +* **client:** compat with new httpx 0.28.0 release ([#1904](https://github.com/openai/openai-python/issues/1904)) ([72b6c63](https://github.com/openai/openai-python/commit/72b6c636c526885ef873580a07eff1c18e76bc10)) + ## 1.55.2 (2024-11-27) Full Changelog: [v1.55.1...v1.55.2](https://github.com/openai/openai-python/compare/v1.55.1...v1.55.2) diff --git a/pyproject.toml b/pyproject.toml index 4842cceea4..06c0e7fd73 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.55.2" +version = "1.55.3" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 5b04f5cc00..c6d4c88a6d 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.55.2" # x-release-please-version +__version__ = "1.55.3" # x-release-please-version From 778e28e5658b4fcf2b11b51b5d7506bd1884e2d2 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Fri, 29 Nov 2024 16:05:14 -0500 Subject: [PATCH 587/816] feat(client): make ChatCompletionStreamState public (#1898) --- src/openai/lib/streaming/chat/__init__.py | 1 + src/openai/lib/streaming/chat/_completions.py | 33 ++++++- tests/lib/chat/test_completions_streaming.py | 94 ++++++++++++++++++- 3 files changed, 123 insertions(+), 5 deletions(-) diff --git a/src/openai/lib/streaming/chat/__init__.py b/src/openai/lib/streaming/chat/__init__.py index 5881c39b9a..dfa3f3f2e3 100644 --- a/src/openai/lib/streaming/chat/__init__.py +++ b/src/openai/lib/streaming/chat/__init__.py @@ -21,6 +21,7 @@ from ._completions import ( ChatCompletionStream as ChatCompletionStream, AsyncChatCompletionStream as AsyncChatCompletionStream, + ChatCompletionStreamState as ChatCompletionStreamState, ChatCompletionStreamManager as ChatCompletionStreamManager, AsyncChatCompletionStreamManager as AsyncChatCompletionStreamManager, ) diff --git a/src/openai/lib/streaming/chat/_completions.py b/src/openai/lib/streaming/chat/_completions.py index 8518de967f..2146091354 100644 --- a/src/openai/lib/streaming/chat/_completions.py +++ b/src/openai/lib/streaming/chat/_completions.py @@ -287,11 +287,31 @@ async def __aexit__( class ChatCompletionStreamState(Generic[ResponseFormatT]): + """Helper class for manually accumulating `ChatCompletionChunk`s into a final `ChatCompletion` object. + + This is useful in cases where you can't always use the `.stream()` method, e.g. + + ```py + from openai.lib.streaming.chat import ChatCompletionStreamState + + state = ChatCompletionStreamState() + + stream = client.chat.completions.create(..., stream=True) + for chunk in response: + state.handle_chunk(chunk) + + # can also access the accumulated `ChatCompletion` mid-stream + state.current_completion_snapshot + + print(state.get_final_completion()) + ``` + """ + def __init__( self, *, - input_tools: Iterable[ChatCompletionToolParam] | NotGiven, - response_format: type[ResponseFormatT] | ResponseFormatParam | NotGiven, + input_tools: Iterable[ChatCompletionToolParam] | NotGiven = NOT_GIVEN, + response_format: type[ResponseFormatT] | ResponseFormatParam | NotGiven = NOT_GIVEN, ) -> None: self.__current_completion_snapshot: ParsedChatCompletionSnapshot | None = None self.__choice_event_states: list[ChoiceEventState] = [] @@ -301,6 +321,11 @@ def __init__( self._rich_response_format: type | NotGiven = response_format if inspect.isclass(response_format) else NOT_GIVEN def get_final_completion(self) -> ParsedChatCompletion[ResponseFormatT]: + """Parse the final completion object. + + Note this does not provide any guarantees that the stream has actually finished, you must + only call this method when the stream is finished. + """ return parse_chat_completion( chat_completion=self.current_completion_snapshot, response_format=self._rich_response_format, @@ -312,8 +337,8 @@ def current_completion_snapshot(self) -> ParsedChatCompletionSnapshot: assert self.__current_completion_snapshot is not None return self.__current_completion_snapshot - def handle_chunk(self, chunk: ChatCompletionChunk) -> list[ChatCompletionStreamEvent[ResponseFormatT]]: - """Accumulate a new chunk into the snapshot and returns a list of events to yield.""" + def handle_chunk(self, chunk: ChatCompletionChunk) -> Iterable[ChatCompletionStreamEvent[ResponseFormatT]]: + """Accumulate a new chunk into the snapshot and returns an iterable of events to yield.""" self.__current_completion_snapshot = self._accumulate_chunk(chunk) return self._build_events( diff --git a/tests/lib/chat/test_completions_streaming.py b/tests/lib/chat/test_completions_streaming.py index ab12de44b3..1eed031af7 100644 --- a/tests/lib/chat/test_completions_streaming.py +++ b/tests/lib/chat/test_completions_streaming.py @@ -13,12 +13,14 @@ import openai from openai import OpenAI, AsyncOpenAI -from openai._utils import assert_signatures_in_sync +from openai._utils import consume_sync_iterator, assert_signatures_in_sync from openai._compat import model_copy +from openai.types.chat import ChatCompletionChunk from openai.lib.streaming.chat import ( ContentDoneEvent, ChatCompletionStream, ChatCompletionStreamEvent, + ChatCompletionStreamState, ChatCompletionStreamManager, ParsedChatCompletionSnapshot, ) @@ -997,6 +999,55 @@ def test_allows_non_strict_tools_but_no_parsing( ) +@pytest.mark.respx(base_url=base_url) +def test_chat_completion_state_helper(client: OpenAI, respx_mock: MockRouter, monkeypatch: pytest.MonkeyPatch) -> None: + state = ChatCompletionStreamState() + + def streamer(client: OpenAI) -> Iterator[ChatCompletionChunk]: + stream = client.chat.completions.create( + model="gpt-4o-2024-08-06", + messages=[ + { + "role": "user", + "content": "What's the weather like in SF?", + }, + ], + stream=True, + ) + for chunk in stream: + state.handle_chunk(chunk) + yield chunk + + _make_raw_stream_snapshot_request( + streamer, + content_snapshot=snapshot(external("e2aad469b71d*.bin")), + mock_client=client, + respx_mock=respx_mock, + ) + + assert print_obj(state.get_final_completion().choices, monkeypatch) == snapshot( + """\ +[ + ParsedChoice[NoneType]( + finish_reason='stop', + index=0, + logprobs=None, + message=ParsedChatCompletionMessage[NoneType]( + audio=None, + content="I'm unable to provide real-time weather updates. To get the current weather in San Francisco, I +recommend checking a reliable weather website or a weather app.", + function_call=None, + parsed=None, + refusal=None, + role='assistant', + tool_calls=[] + ) + ) +] +""" + ) + + @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"]) def test_stream_method_in_sync(sync: bool, client: OpenAI, async_client: AsyncOpenAI) -> None: checking_client: OpenAI | AsyncOpenAI = client if sync else async_client @@ -1075,3 +1126,44 @@ def _on_response(response: httpx.Response) -> None: client.close() return listener + + +def _make_raw_stream_snapshot_request( + func: Callable[[OpenAI], Iterator[ChatCompletionChunk]], + *, + content_snapshot: Any, + respx_mock: MockRouter, + mock_client: OpenAI, +) -> None: + live = os.environ.get("OPENAI_LIVE") == "1" + if live: + + def _on_response(response: httpx.Response) -> None: + # update the content snapshot + assert outsource(response.read()) == content_snapshot + + respx_mock.stop() + + client = OpenAI( + http_client=httpx.Client( + event_hooks={ + "response": [_on_response], + } + ) + ) + else: + respx_mock.post("/chat/completions").mock( + return_value=httpx.Response( + 200, + content=content_snapshot._old_value._load_value(), + headers={"content-type": "text/event-stream"}, + ) + ) + + client = mock_client + + stream = func(client) + consume_sync_iterator(stream) + + if live: + client.close() From 534d6c58f6c07d219ca74dd336eaca59d48d0ada Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 2 Dec 2024 05:04:35 +0000 Subject: [PATCH 588/816] release: 1.56.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index d23d0104a4..24b1176fb1 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.55.3" + ".": "1.56.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 866d34cb4f..614dbb5795 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.56.0 (2024-12-02) + +Full Changelog: [v1.55.3...v1.56.0](https://github.com/openai/openai-python/compare/v1.55.3...v1.56.0) + +### Features + +* **client:** make ChatCompletionStreamState public ([#1898](https://github.com/openai/openai-python/issues/1898)) ([dc7f6cb](https://github.com/openai/openai-python/commit/dc7f6cb2618686ff04bfdca228913cda3d320884)) + ## 1.55.3 (2024-11-28) Full Changelog: [v1.55.2...v1.55.3](https://github.com/openai/openai-python/compare/v1.55.2...v1.55.3) diff --git a/pyproject.toml b/pyproject.toml index 06c0e7fd73..b5cf535fe5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.55.3" +version = "1.56.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index c6d4c88a6d..8561c9379b 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.55.3" # x-release-please-version +__version__ = "1.56.0" # x-release-please-version From 439ab56fe0933077a41290f588a6528f89e05c87 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 2 Dec 2024 15:21:20 -0500 Subject: [PATCH 589/816] fix(cli): remove usage of httpx proxies --- src/openai/cli/_cli.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/openai/cli/_cli.py b/src/openai/cli/_cli.py index 72e5c923bd..fd165f48ab 100644 --- a/src/openai/cli/_cli.py +++ b/src/openai/cli/_cli.py @@ -15,7 +15,6 @@ from .. import _ApiType, __version__ from ._api import register_commands from ._utils import can_use_http2 -from .._types import ProxiesDict from ._errors import CLIError, display_error from .._compat import PYDANTIC_V2, ConfigDict, model_parse from .._models import BaseModel @@ -167,17 +166,17 @@ def _main() -> None: if args.verbosity != 0: sys.stderr.write("Warning: --verbosity isn't supported yet\n") - proxies: ProxiesDict = {} + proxies: dict[str, httpx.BaseTransport] = {} if args.proxy is not None: for proxy in args.proxy: key = "https://" if proxy.startswith("https") else "http://" if key in proxies: raise CLIError(f"Multiple {key} proxies given - only the last one would be used") - proxies[key] = proxy + proxies[key] = httpx.HTTPTransport(proxy=httpx.Proxy(httpx.URL(proxy))) http_client = httpx.Client( - proxies=proxies or None, + mounts=proxies or None, http2=can_use_http2(), ) openai.http_client = http_client From 6a692ffb5e00e0e1ff9ae39633a62774c6fb5c31 Mon Sep 17 00:00:00 2001 From: Stainless Bot Date: Mon, 2 Dec 2024 20:47:19 +0000 Subject: [PATCH 590/816] chore(internal): bump pyright (#1917) --- requirements-dev.lock | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/requirements-dev.lock b/requirements-dev.lock index 4d0ab191a4..c8e74372aa 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -125,7 +125,7 @@ pygments==2.18.0 # via rich pyjwt==2.8.0 # via msal -pyright==1.1.380 +pyright==1.1.389 pytest==8.3.3 # via pytest-asyncio pytest-asyncio==0.24.0 @@ -179,6 +179,7 @@ typing-extensions==4.12.2 # via openai # via pydantic # via pydantic-core + # via pyright tzdata==2024.1 # via pandas urllib3==2.2.1 From 5e3e4d1b0f16ccc4469a90a5bff09cafe0de7a2e Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 3 Dec 2024 05:04:28 +0000 Subject: [PATCH 591/816] release: 1.56.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 24b1176fb1..7e4064260b 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.56.0" + ".": "1.56.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 614dbb5795..ad4ea007e8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.56.1 (2024-12-03) + +Full Changelog: [v1.56.0...v1.56.1](https://github.com/openai/openai-python/compare/v1.56.0...v1.56.1) + +### Bug Fixes + +* **cli:** remove usage of httpx proxies ([0e9fc3d](https://github.com/openai/openai-python/commit/0e9fc3dfbc7dec5b8c8f84dea9d87aad9f3d9cf6)) + + +### Chores + +* **internal:** bump pyright ([#1917](https://github.com/openai/openai-python/issues/1917)) ([0e87346](https://github.com/openai/openai-python/commit/0e8734637666ab22bc27fe4ec2cf7c39fddb5d08)) + ## 1.56.0 (2024-12-02) Full Changelog: [v1.55.3...v1.56.0](https://github.com/openai/openai-python/compare/v1.55.3...v1.56.0) diff --git a/pyproject.toml b/pyproject.toml index b5cf535fe5..93ababf9b7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.56.0" +version = "1.56.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 8561c9379b..c879d22094 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.56.0" # x-release-please-version +__version__ = "1.56.1" # x-release-please-version From f3f2ae529a86b110f97a38977b20794284be1726 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 4 Dec 2024 02:15:40 +0000 Subject: [PATCH 592/816] chore: make the `Omit` type public (#1919) --- src/openai/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/openai/__init__.py b/src/openai/__init__.py index 3c1ebb573d..21c60f7e87 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -6,7 +6,7 @@ from typing_extensions import override from . import types -from ._types import NOT_GIVEN, NoneType, NotGiven, Transport, ProxiesTypes +from ._types import NOT_GIVEN, Omit, NoneType, NotGiven, Transport, ProxiesTypes from ._utils import file_from_path from ._client import Client, OpenAI, Stream, Timeout, Transport, AsyncClient, AsyncOpenAI, AsyncStream, RequestOptions from ._models import BaseModel @@ -43,6 +43,7 @@ "ProxiesTypes", "NotGiven", "NOT_GIVEN", + "Omit", "OpenAIError", "APIError", "APIStatusError", From bb9c2de913279acc89e79f6154173a422f31de45 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 4 Dec 2024 05:04:28 +0000 Subject: [PATCH 593/816] release: 1.56.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 7e4064260b..028ed90273 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.56.1" + ".": "1.56.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index ad4ea007e8..f91f69338b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.56.2 (2024-12-04) + +Full Changelog: [v1.56.1...v1.56.2](https://github.com/openai/openai-python/compare/v1.56.1...v1.56.2) + +### Chores + +* make the `Omit` type public ([#1919](https://github.com/openai/openai-python/issues/1919)) ([4fb8a1c](https://github.com/openai/openai-python/commit/4fb8a1cf1f8df37ce8c027bbaaac85a648bae02a)) + ## 1.56.1 (2024-12-03) Full Changelog: [v1.56.0...v1.56.1](https://github.com/openai/openai-python/compare/v1.56.0...v1.56.1) diff --git a/pyproject.toml b/pyproject.toml index 93ababf9b7..7ca731eb7d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.56.1" +version = "1.56.2" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index c879d22094..190d3a5fe1 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.56.1" # x-release-please-version +__version__ = "1.56.2" # x-release-please-version From 52f3525276149fb2375d4af5e5903ffa77330cc3 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 4 Dec 2024 20:20:39 +0000 Subject: [PATCH 594/816] chore: bump openapi url (#1922) --- .stats.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index 4827e5388f..19920c8be8 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-aa9b01fc0c17eb0cbc200533fc20d6a49c5e764ceaf8049e08b294532be6e9ff.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-d702cba829ceda336f44d0eb89ce61dba353849a40f0193e7007439345daf1bb.yml From afa2b1e089f9b43ff8db35ecb554c688aba5cf01 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 4 Dec 2024 20:53:44 +0000 Subject: [PATCH 595/816] feat(api): updates (#1924) --- .stats.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index 19920c8be8..3cc042fe0a 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-d702cba829ceda336f44d0eb89ce61dba353849a40f0193e7007439345daf1bb.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-2e0e0678be19d1118fd796af291822075e40538dba326611e177e9f3dc245a53.yml From ea049cd0c42e115b90f1b9c7db80b2659a0bb92a Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 5 Dec 2024 05:04:40 +0000 Subject: [PATCH 596/816] release: 1.57.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 028ed90273..3794816acd 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.56.2" + ".": "1.57.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index f91f69338b..c5baf5ab80 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.57.0 (2024-12-05) + +Full Changelog: [v1.56.2...v1.57.0](https://github.com/openai/openai-python/compare/v1.56.2...v1.57.0) + +### Features + +* **api:** updates ([#1924](https://github.com/openai/openai-python/issues/1924)) ([82ba614](https://github.com/openai/openai-python/commit/82ba6144682b0a6b3a22d4f764231c0c6afdcf6e)) + + +### Chores + +* bump openapi url ([#1922](https://github.com/openai/openai-python/issues/1922)) ([a472a8f](https://github.com/openai/openai-python/commit/a472a8fd0ba36b6897dcd02b6005fcf23f98f056)) + ## 1.56.2 (2024-12-04) Full Changelog: [v1.56.1...v1.56.2](https://github.com/openai/openai-python/compare/v1.56.1...v1.56.2) diff --git a/pyproject.toml b/pyproject.toml index 7ca731eb7d..c488c40622 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.56.2" +version = "1.57.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 190d3a5fe1..58e2de3bd5 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.56.2" # x-release-please-version +__version__ = "1.57.0" # x-release-please-version From 64e3ec0f571cf9b43bbe5d26e6629a8f9d6049fb Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 9 Dec 2024 14:40:47 +0000 Subject: [PATCH 597/816] chore(internal): bump pydantic dependency (#1929) --- requirements-dev.lock | 5 ++--- requirements.lock | 5 ++--- src/openai/_types.py | 6 ++---- 3 files changed, 6 insertions(+), 10 deletions(-) diff --git a/requirements-dev.lock b/requirements-dev.lock index c8e74372aa..d7ecc4fcda 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -7,7 +7,6 @@ # all-features: true # with-sources: false # generate-hashes: false -# universal: false -e file:. annotated-types==0.6.0 @@ -117,9 +116,9 @@ portalocker==2.10.1 # via msal-extensions pycparser==2.22 # via cffi -pydantic==2.9.2 +pydantic==2.10.3 # via openai -pydantic-core==2.23.4 +pydantic-core==2.27.1 # via pydantic pygments==2.18.0 # via rich diff --git a/requirements.lock b/requirements.lock index aef8bc0a9a..826f0bc927 100644 --- a/requirements.lock +++ b/requirements.lock @@ -7,7 +7,6 @@ # all-features: true # with-sources: false # generate-hashes: false -# universal: false -e file:. annotated-types==0.6.0 @@ -41,9 +40,9 @@ pandas==2.2.3 # via openai pandas-stubs==2.2.2.240807 # via openai -pydantic==2.9.2 +pydantic==2.10.3 # via openai -pydantic-core==2.23.4 +pydantic-core==2.27.1 # via pydantic python-dateutil==2.9.0.post0 # via pandas diff --git a/src/openai/_types.py b/src/openai/_types.py index c8f4d5a922..a5cf207aa3 100644 --- a/src/openai/_types.py +++ b/src/openai/_types.py @@ -194,10 +194,8 @@ def get(self, __key: str) -> str | None: ... StrBytesIntFloat = Union[str, bytes, int, float] # Note: copied from Pydantic -# https://github.com/pydantic/pydantic/blob/32ea570bf96e84234d2992e1ddf40ab8a565925a/pydantic/main.py#L49 -IncEx: TypeAlias = Union[ - Set[int], Set[str], Mapping[int, Union["IncEx", Literal[True]]], Mapping[str, Union["IncEx", Literal[True]]] -] +# https://github.com/pydantic/pydantic/blob/6f31f8f68ef011f84357330186f603ff295312fd/pydantic/main.py#L79 +IncEx: TypeAlias = Union[Set[int], Set[str], Mapping[int, Union["IncEx", bool]], Mapping[str, Union["IncEx", bool]]] PostParser = Callable[[Any], Any] From 995cce048f9427bba4f7ac1e5fc60abbf1f8f0b7 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 9 Dec 2024 14:41:16 +0000 Subject: [PATCH 598/816] release: 1.57.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 3794816acd..4a5d7b25e2 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.57.0" + ".": "1.57.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index c5baf5ab80..b436c25abf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.57.1 (2024-12-09) + +Full Changelog: [v1.57.0...v1.57.1](https://github.com/openai/openai-python/compare/v1.57.0...v1.57.1) + +### Chores + +* **internal:** bump pydantic dependency ([#1929](https://github.com/openai/openai-python/issues/1929)) ([5227c95](https://github.com/openai/openai-python/commit/5227c95eff9c7b1395e6d8f14b94652a91ed2ee2)) + ## 1.57.0 (2024-12-05) Full Changelog: [v1.56.2...v1.57.0](https://github.com/openai/openai-python/compare/v1.56.2...v1.57.0) diff --git a/pyproject.toml b/pyproject.toml index c488c40622..9a92574c73 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.57.0" +version = "1.57.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 58e2de3bd5..a59207d618 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.57.0" # x-release-please-version +__version__ = "1.57.1" # x-release-please-version From 6a1ab55104822b9e987e1227988c084cd415d294 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 9 Dec 2024 18:18:18 +0000 Subject: [PATCH 599/816] docs(readme): fix http client proxies example (#1932) --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5854e8d3ad..780ee261fe 100644 --- a/README.md +++ b/README.md @@ -624,18 +624,19 @@ can also get all the extra fields on the Pydantic model as a dict with You can directly override the [httpx client](https://www.python-httpx.org/api/#client) to customize it for your use case, including: -- Support for proxies -- Custom transports +- Support for [proxies](https://www.python-httpx.org/advanced/proxies/) +- Custom [transports](https://www.python-httpx.org/advanced/transports/) - Additional [advanced](https://www.python-httpx.org/advanced/clients/) functionality ```python +import httpx from openai import OpenAI, DefaultHttpxClient client = OpenAI( # Or use the `OPENAI_BASE_URL` env var base_url="http://my.test.server.example.com:8083/v1", http_client=DefaultHttpxClient( - proxies="http://my.test.proxy.example.com/", + proxy="http://my.test.proxy.example.com/", transport=httpx.HTTPTransport(local_address="0.0.0.0"), ), ) From 3cf3dd7b412414a6ca48a588ee4c7f0ef91c9e92 Mon Sep 17 00:00:00 2001 From: Kenji Hikmatullah <43457338+kenjihikmatullah@users.noreply.github.com> Date: Tue, 10 Dec 2024 18:52:45 +0700 Subject: [PATCH 600/816] fix(azure): handle trailing slash in `azure_endpoint` (#1935) --- src/openai/lib/azure.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/openai/lib/azure.py b/src/openai/lib/azure.py index 5d21f10b70..54122dbecb 100644 --- a/src/openai/lib/azure.py +++ b/src/openai/lib/azure.py @@ -193,9 +193,9 @@ def __init__( ) if azure_deployment is not None: - base_url = f"{azure_endpoint}/openai/deployments/{azure_deployment}" + base_url = f"{azure_endpoint.rstrip('/')}/openai/deployments/{azure_deployment}" else: - base_url = f"{azure_endpoint}/openai" + base_url = f"{azure_endpoint.rstrip('/')}/openai" else: if azure_endpoint is not None: raise ValueError("base_url and azure_endpoint are mutually exclusive") @@ -433,9 +433,9 @@ def __init__( ) if azure_deployment is not None: - base_url = f"{azure_endpoint}/openai/deployments/{azure_deployment}" + base_url = f"{azure_endpoint.rstrip('/')}/openai/deployments/{azure_deployment}" else: - base_url = f"{azure_endpoint}/openai" + base_url = f"{azure_endpoint.rstrip('/')}/openai" else: if azure_endpoint is not None: raise ValueError("base_url and azure_endpoint are mutually exclusive") From 6e1161bc3ed20eef070063ddd5ac52fd9a531e88 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 10 Dec 2024 11:53:14 +0000 Subject: [PATCH 601/816] release: 1.57.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 4a5d7b25e2..18d9ec48a9 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.57.1" + ".": "1.57.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index b436c25abf..7319ebd651 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.57.2 (2024-12-10) + +Full Changelog: [v1.57.1...v1.57.2](https://github.com/openai/openai-python/compare/v1.57.1...v1.57.2) + +### Bug Fixes + +* **azure:** handle trailing slash in `azure_endpoint` ([#1935](https://github.com/openai/openai-python/issues/1935)) ([69b73c5](https://github.com/openai/openai-python/commit/69b73c553b1982277c2f1b9d110ed951ddca689e)) + + +### Documentation + +* **readme:** fix http client proxies example ([#1932](https://github.com/openai/openai-python/issues/1932)) ([7a83e0f](https://github.com/openai/openai-python/commit/7a83e0fe4cc29e484ae417448b002c997745e4a3)) + ## 1.57.1 (2024-12-09) Full Changelog: [v1.57.0...v1.57.1](https://github.com/openai/openai-python/compare/v1.57.0...v1.57.1) diff --git a/pyproject.toml b/pyproject.toml index 9a92574c73..6df6f43789 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.57.1" +version = "1.57.2" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index a59207d618..0757da4c78 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.57.1" # x-release-please-version +__version__ = "1.57.2" # x-release-please-version From f32d466b2d69b0ca8fa8a59f2b74ed84448f9459 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 12 Dec 2024 12:18:04 +0000 Subject: [PATCH 602/816] chore(internal): bump pyright (#1939) --- requirements-dev.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements-dev.lock b/requirements-dev.lock index d7ecc4fcda..2cf6ab5ea9 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -124,7 +124,7 @@ pygments==2.18.0 # via rich pyjwt==2.8.0 # via msal -pyright==1.1.389 +pyright==1.1.390 pytest==8.3.3 # via pytest-asyncio pytest-asyncio==0.24.0 From bed71312acd1658d6128f9142f2882162bb127ec Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 12 Dec 2024 12:44:38 +0000 Subject: [PATCH 603/816] chore(internal): add support for TypeAliasType (#1942) --- src/openai/_legacy_response.py | 20 ++++++++++---------- src/openai/_models.py | 3 +++ src/openai/_response.py | 20 ++++++++++---------- src/openai/_utils/__init__.py | 1 + src/openai/_utils/_typing.py | 31 ++++++++++++++++++++++++++++++- tests/test_models.py | 18 +++++++++++++++++- tests/utils.py | 4 ++++ 7 files changed, 75 insertions(+), 22 deletions(-) diff --git a/src/openai/_legacy_response.py b/src/openai/_legacy_response.py index 5260e90bc1..7a14f27adb 100644 --- a/src/openai/_legacy_response.py +++ b/src/openai/_legacy_response.py @@ -24,7 +24,7 @@ import pydantic from ._types import NoneType -from ._utils import is_given, extract_type_arg, is_annotated_type +from ._utils import is_given, extract_type_arg, is_annotated_type, is_type_alias_type from ._models import BaseModel, is_basemodel, add_request_id from ._constants import RAW_RESPONSE_HEADER from ._streaming import Stream, AsyncStream, is_stream_class_type, extract_stream_chunk_type @@ -195,9 +195,15 @@ def elapsed(self) -> datetime.timedelta: return self.http_response.elapsed def _parse(self, *, to: type[_T] | None = None) -> R | _T: + cast_to = to if to is not None else self._cast_to + + # unwrap `TypeAlias('Name', T)` -> `T` + if is_type_alias_type(cast_to): + cast_to = cast_to.__value__ # type: ignore[unreachable] + # unwrap `Annotated[T, ...]` -> `T` - if to and is_annotated_type(to): - to = extract_type_arg(to, 0) + if cast_to and is_annotated_type(cast_to): + cast_to = extract_type_arg(cast_to, 0) if self._stream: if to: @@ -233,18 +239,12 @@ def _parse(self, *, to: type[_T] | None = None) -> R | _T: return cast( R, stream_cls( - cast_to=self._cast_to, + cast_to=cast_to, response=self.http_response, client=cast(Any, self._client), ), ) - cast_to = to if to is not None else self._cast_to - - # unwrap `Annotated[T, ...]` -> `T` - if is_annotated_type(cast_to): - cast_to = extract_type_arg(cast_to, 0) - if cast_to is NoneType: return cast(R, None) diff --git a/src/openai/_models.py b/src/openai/_models.py index 20cd4c29bc..2f67e5eb4d 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -47,6 +47,7 @@ strip_not_given, extract_type_arg, is_annotated_type, + is_type_alias_type, strip_annotated_type, ) from ._compat import ( @@ -453,6 +454,8 @@ def construct_type(*, value: object, type_: object) -> object: # we allow `object` as the input type because otherwise, passing things like # `Literal['value']` will be reported as a type error by type checkers type_ = cast("type[object]", type_) + if is_type_alias_type(type_): + type_ = type_.__value__ # type: ignore[unreachable] # unwrap `Annotated[T, ...]` -> `T` if is_annotated_type(type_): diff --git a/src/openai/_response.py b/src/openai/_response.py index eac3fbae6c..1527446585 100644 --- a/src/openai/_response.py +++ b/src/openai/_response.py @@ -25,7 +25,7 @@ import pydantic from ._types import NoneType -from ._utils import is_given, extract_type_arg, is_annotated_type, extract_type_var_from_base +from ._utils import is_given, extract_type_arg, is_annotated_type, is_type_alias_type, extract_type_var_from_base from ._models import BaseModel, is_basemodel, add_request_id from ._constants import RAW_RESPONSE_HEADER, OVERRIDE_CAST_TO_HEADER from ._streaming import Stream, AsyncStream, is_stream_class_type, extract_stream_chunk_type @@ -126,9 +126,15 @@ def __repr__(self) -> str: ) def _parse(self, *, to: type[_T] | None = None) -> R | _T: + cast_to = to if to is not None else self._cast_to + + # unwrap `TypeAlias('Name', T)` -> `T` + if is_type_alias_type(cast_to): + cast_to = cast_to.__value__ # type: ignore[unreachable] + # unwrap `Annotated[T, ...]` -> `T` - if to and is_annotated_type(to): - to = extract_type_arg(to, 0) + if cast_to and is_annotated_type(cast_to): + cast_to = extract_type_arg(cast_to, 0) if self._is_sse_stream: if to: @@ -164,18 +170,12 @@ def _parse(self, *, to: type[_T] | None = None) -> R | _T: return cast( R, stream_cls( - cast_to=self._cast_to, + cast_to=cast_to, response=self.http_response, client=cast(Any, self._client), ), ) - cast_to = to if to is not None else self._cast_to - - # unwrap `Annotated[T, ...]` -> `T` - if is_annotated_type(cast_to): - cast_to = extract_type_arg(cast_to, 0) - if cast_to is NoneType: return cast(R, None) diff --git a/src/openai/_utils/__init__.py b/src/openai/_utils/__init__.py index 5abb34cde4..af2c9bb77e 100644 --- a/src/openai/_utils/__init__.py +++ b/src/openai/_utils/__init__.py @@ -40,6 +40,7 @@ is_iterable_type as is_iterable_type, is_required_type as is_required_type, is_annotated_type as is_annotated_type, + is_type_alias_type as is_type_alias_type, strip_annotated_type as strip_annotated_type, extract_type_var_from_base as extract_type_var_from_base, ) diff --git a/src/openai/_utils/_typing.py b/src/openai/_utils/_typing.py index c036991f04..278749b147 100644 --- a/src/openai/_utils/_typing.py +++ b/src/openai/_utils/_typing.py @@ -1,8 +1,17 @@ from __future__ import annotations +import sys +import typing +import typing_extensions from typing import Any, TypeVar, Iterable, cast from collections import abc as _c_abc -from typing_extensions import Required, Annotated, get_args, get_origin +from typing_extensions import ( + TypeIs, + Required, + Annotated, + get_args, + get_origin, +) from .._types import InheritsGeneric from .._compat import is_union as _is_union @@ -36,6 +45,26 @@ def is_typevar(typ: type) -> bool: return type(typ) == TypeVar # type: ignore +_TYPE_ALIAS_TYPES: tuple[type[typing_extensions.TypeAliasType], ...] = (typing_extensions.TypeAliasType,) +if sys.version_info >= (3, 12): + _TYPE_ALIAS_TYPES = (*_TYPE_ALIAS_TYPES, typing.TypeAliasType) + + +def is_type_alias_type(tp: Any, /) -> TypeIs[typing_extensions.TypeAliasType]: + """Return whether the provided argument is an instance of `TypeAliasType`. + + ```python + type Int = int + is_type_alias_type(Int) + # > True + Str = TypeAliasType("Str", str) + is_type_alias_type(Str) + # > True + ``` + """ + return isinstance(tp, _TYPE_ALIAS_TYPES) + + # Extracts T from Annotated[T, ...] or from Required[Annotated[T, ...]] def strip_annotated_type(typ: type) -> type: if is_required_type(typ) or is_annotated_type(typ): diff --git a/tests/test_models.py b/tests/test_models.py index d2884bcbfa..19a71f13ba 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -1,7 +1,7 @@ import json from typing import Any, Dict, List, Union, Optional, cast from datetime import datetime, timezone -from typing_extensions import Literal, Annotated +from typing_extensions import Literal, Annotated, TypeAliasType import pytest import pydantic @@ -828,3 +828,19 @@ class B(BaseModel): # if the discriminator details object stays the same between invocations then # we hit the cache assert UnionType.__discriminator__ is discriminator + + +@pytest.mark.skipif(not PYDANTIC_V2, reason="TypeAliasType is not supported in Pydantic v1") +def test_type_alias_type() -> None: + Alias = TypeAliasType("Alias", str) + + class Model(BaseModel): + alias: Alias + union: Union[int, Alias] + + m = construct_type(value={"alias": "foo", "union": "bar"}, type_=Model) + assert isinstance(m, Model) + assert isinstance(m.alias, str) + assert m.alias == "foo" + assert isinstance(m.union, str) + assert m.union == "bar" diff --git a/tests/utils.py b/tests/utils.py index 16948a66f2..4cf5ce171b 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -19,6 +19,7 @@ is_union_type, extract_type_arg, is_annotated_type, + is_type_alias_type, ) from openai._compat import PYDANTIC_V2, field_outer_type, get_model_fields from openai._models import BaseModel @@ -58,6 +59,9 @@ def assert_matches_type( path: list[str], allow_none: bool = False, ) -> None: + if is_type_alias_type(type_): + type_ = type_.__value__ + # unwrap `Annotated[T, ...]` -> `T` if is_annotated_type(type_): type_ = extract_type_arg(type_, 0) From 0ae6f6b0ce55b6a9dd7e5caa684dfae2780c0088 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 12 Dec 2024 12:45:06 +0000 Subject: [PATCH 604/816] release: 1.57.3 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 9 +++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 18d9ec48a9..58e64c502c 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.57.2" + ".": "1.57.3" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 7319ebd651..80ed457618 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 1.57.3 (2024-12-12) + +Full Changelog: [v1.57.2...v1.57.3](https://github.com/openai/openai-python/compare/v1.57.2...v1.57.3) + +### Chores + +* **internal:** add support for TypeAliasType ([#1942](https://github.com/openai/openai-python/issues/1942)) ([d3442ff](https://github.com/openai/openai-python/commit/d3442ff28f2394200e14122f683d1f94686e8231)) +* **internal:** bump pyright ([#1939](https://github.com/openai/openai-python/issues/1939)) ([190d1a8](https://github.com/openai/openai-python/commit/190d1a805dee7c37fb8f9dcb93b1715caa06cf95)) + ## 1.57.2 (2024-12-10) Full Changelog: [v1.57.1...v1.57.2](https://github.com/openai/openai-python/compare/v1.57.1...v1.57.2) diff --git a/pyproject.toml b/pyproject.toml index 6df6f43789..a6a0868405 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.57.2" +version = "1.57.3" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 0757da4c78..94ba432279 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.57.2" # x-release-please-version +__version__ = "1.57.3" # x-release-please-version From e93e3bd45fcef320c4fa70eed3987d852e9c96e5 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 13 Dec 2024 11:17:39 +0000 Subject: [PATCH 605/816] chore(internal): remove some duplicated imports (#1946) --- src/openai/resources/beta/beta.py | 20 +++++++++---------- src/openai/resources/beta/threads/threads.py | 17 ++++++++-------- .../resources/fine_tuning/fine_tuning.py | 5 ++--- 3 files changed, 19 insertions(+), 23 deletions(-) diff --git a/src/openai/resources/beta/beta.py b/src/openai/resources/beta/beta.py index a7d3e707c8..5079c989a5 100644 --- a/src/openai/resources/beta/beta.py +++ b/src/openai/resources/beta/beta.py @@ -2,14 +2,6 @@ from __future__ import annotations -from .threads import ( - Threads, - AsyncThreads, - ThreadsWithRawResponse, - AsyncThreadsWithRawResponse, - ThreadsWithStreamingResponse, - AsyncThreadsWithStreamingResponse, -) from ..._compat import cached_property from .chat.chat import Chat, AsyncChat from .assistants import ( @@ -21,7 +13,15 @@ AsyncAssistantsWithStreamingResponse, ) from ..._resource import SyncAPIResource, AsyncAPIResource -from .vector_stores import ( +from .threads.threads import ( + Threads, + AsyncThreads, + ThreadsWithRawResponse, + AsyncThreadsWithRawResponse, + ThreadsWithStreamingResponse, + AsyncThreadsWithStreamingResponse, +) +from .vector_stores.vector_stores import ( VectorStores, AsyncVectorStores, VectorStoresWithRawResponse, @@ -29,8 +29,6 @@ VectorStoresWithStreamingResponse, AsyncVectorStoresWithStreamingResponse, ) -from .threads.threads import Threads, AsyncThreads -from .vector_stores.vector_stores import VectorStores, AsyncVectorStores __all__ = ["Beta", "AsyncBeta"] diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 058ba71a17..e45090abb0 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -9,14 +9,6 @@ import httpx from .... import _legacy_response -from .runs import ( - Runs, - AsyncRuns, - RunsWithRawResponse, - AsyncRunsWithRawResponse, - RunsWithStreamingResponse, - AsyncRunsWithStreamingResponse, -) from .messages import ( Messages, AsyncMessages, @@ -31,7 +23,14 @@ maybe_transform, async_maybe_transform, ) -from .runs.runs import Runs, AsyncRuns +from .runs.runs import ( + Runs, + AsyncRuns, + RunsWithRawResponse, + AsyncRunsWithRawResponse, + RunsWithStreamingResponse, + AsyncRunsWithStreamingResponse, +) from ...._compat import cached_property from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper diff --git a/src/openai/resources/fine_tuning/fine_tuning.py b/src/openai/resources/fine_tuning/fine_tuning.py index c386de3c2a..d2bce87c48 100644 --- a/src/openai/resources/fine_tuning/fine_tuning.py +++ b/src/openai/resources/fine_tuning/fine_tuning.py @@ -2,7 +2,8 @@ from __future__ import annotations -from .jobs import ( +from ..._compat import cached_property +from .jobs.jobs import ( Jobs, AsyncJobs, JobsWithRawResponse, @@ -10,8 +11,6 @@ JobsWithStreamingResponse, AsyncJobsWithStreamingResponse, ) -from ..._compat import cached_property -from .jobs.jobs import Jobs, AsyncJobs from ..._resource import SyncAPIResource, AsyncAPIResource __all__ = ["FineTuning", "AsyncFineTuning"] From 2e2531d944a0c4ff748f9fb0b1c9a015f029dd2f Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 13 Dec 2024 14:01:59 +0000 Subject: [PATCH 606/816] chore(internal): updated imports (#1948) --- src/openai/_client.py | 212 +++++++++++++++++++++--------------------- 1 file changed, 104 insertions(+), 108 deletions(-) diff --git a/src/openai/_client.py b/src/openai/_client.py index d3ee6cf0f1..5419e88f06 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -8,7 +8,7 @@ import httpx -from . import resources, _exceptions +from . import _exceptions from ._qs import Querystring from ._types import ( NOT_GIVEN, @@ -25,6 +25,7 @@ get_async_library, ) from ._version import __version__ +from .resources import files, images, models, batches, embeddings, completions, moderations from ._streaming import Stream as Stream, AsyncStream as AsyncStream from ._exceptions import OpenAIError, APIStatusError from ._base_client import ( @@ -32,33 +33,28 @@ SyncAPIClient, AsyncAPIClient, ) +from .resources.beta import beta +from .resources.chat import chat +from .resources.audio import audio +from .resources.uploads import uploads +from .resources.fine_tuning import fine_tuning -__all__ = [ - "Timeout", - "Transport", - "ProxiesTypes", - "RequestOptions", - "resources", - "OpenAI", - "AsyncOpenAI", - "Client", - "AsyncClient", -] +__all__ = ["Timeout", "Transport", "ProxiesTypes", "RequestOptions", "OpenAI", "AsyncOpenAI", "Client", "AsyncClient"] class OpenAI(SyncAPIClient): - completions: resources.Completions - chat: resources.Chat - embeddings: resources.Embeddings - files: resources.Files - images: resources.Images - audio: resources.Audio - moderations: resources.Moderations - models: resources.Models - fine_tuning: resources.FineTuning - beta: resources.Beta - batches: resources.Batches - uploads: resources.Uploads + completions: completions.Completions + chat: chat.Chat + embeddings: embeddings.Embeddings + files: files.Files + images: images.Images + audio: audio.Audio + moderations: moderations.Moderations + models: models.Models + fine_tuning: fine_tuning.FineTuning + beta: beta.Beta + batches: batches.Batches + uploads: uploads.Uploads with_raw_response: OpenAIWithRawResponse with_streaming_response: OpenAIWithStreamedResponse @@ -133,18 +129,18 @@ def __init__( self._default_stream_cls = Stream - self.completions = resources.Completions(self) - self.chat = resources.Chat(self) - self.embeddings = resources.Embeddings(self) - self.files = resources.Files(self) - self.images = resources.Images(self) - self.audio = resources.Audio(self) - self.moderations = resources.Moderations(self) - self.models = resources.Models(self) - self.fine_tuning = resources.FineTuning(self) - self.beta = resources.Beta(self) - self.batches = resources.Batches(self) - self.uploads = resources.Uploads(self) + self.completions = completions.Completions(self) + self.chat = chat.Chat(self) + self.embeddings = embeddings.Embeddings(self) + self.files = files.Files(self) + self.images = images.Images(self) + self.audio = audio.Audio(self) + self.moderations = moderations.Moderations(self) + self.models = models.Models(self) + self.fine_tuning = fine_tuning.FineTuning(self) + self.beta = beta.Beta(self) + self.batches = batches.Batches(self) + self.uploads = uploads.Uploads(self) self.with_raw_response = OpenAIWithRawResponse(self) self.with_streaming_response = OpenAIWithStreamedResponse(self) @@ -261,18 +257,18 @@ def _make_status_error( class AsyncOpenAI(AsyncAPIClient): - completions: resources.AsyncCompletions - chat: resources.AsyncChat - embeddings: resources.AsyncEmbeddings - files: resources.AsyncFiles - images: resources.AsyncImages - audio: resources.AsyncAudio - moderations: resources.AsyncModerations - models: resources.AsyncModels - fine_tuning: resources.AsyncFineTuning - beta: resources.AsyncBeta - batches: resources.AsyncBatches - uploads: resources.AsyncUploads + completions: completions.AsyncCompletions + chat: chat.AsyncChat + embeddings: embeddings.AsyncEmbeddings + files: files.AsyncFiles + images: images.AsyncImages + audio: audio.AsyncAudio + moderations: moderations.AsyncModerations + models: models.AsyncModels + fine_tuning: fine_tuning.AsyncFineTuning + beta: beta.AsyncBeta + batches: batches.AsyncBatches + uploads: uploads.AsyncUploads with_raw_response: AsyncOpenAIWithRawResponse with_streaming_response: AsyncOpenAIWithStreamedResponse @@ -347,18 +343,18 @@ def __init__( self._default_stream_cls = AsyncStream - self.completions = resources.AsyncCompletions(self) - self.chat = resources.AsyncChat(self) - self.embeddings = resources.AsyncEmbeddings(self) - self.files = resources.AsyncFiles(self) - self.images = resources.AsyncImages(self) - self.audio = resources.AsyncAudio(self) - self.moderations = resources.AsyncModerations(self) - self.models = resources.AsyncModels(self) - self.fine_tuning = resources.AsyncFineTuning(self) - self.beta = resources.AsyncBeta(self) - self.batches = resources.AsyncBatches(self) - self.uploads = resources.AsyncUploads(self) + self.completions = completions.AsyncCompletions(self) + self.chat = chat.AsyncChat(self) + self.embeddings = embeddings.AsyncEmbeddings(self) + self.files = files.AsyncFiles(self) + self.images = images.AsyncImages(self) + self.audio = audio.AsyncAudio(self) + self.moderations = moderations.AsyncModerations(self) + self.models = models.AsyncModels(self) + self.fine_tuning = fine_tuning.AsyncFineTuning(self) + self.beta = beta.AsyncBeta(self) + self.batches = batches.AsyncBatches(self) + self.uploads = uploads.AsyncUploads(self) self.with_raw_response = AsyncOpenAIWithRawResponse(self) self.with_streaming_response = AsyncOpenAIWithStreamedResponse(self) @@ -476,66 +472,66 @@ def _make_status_error( class OpenAIWithRawResponse: def __init__(self, client: OpenAI) -> None: - self.completions = resources.CompletionsWithRawResponse(client.completions) - self.chat = resources.ChatWithRawResponse(client.chat) - self.embeddings = resources.EmbeddingsWithRawResponse(client.embeddings) - self.files = resources.FilesWithRawResponse(client.files) - self.images = resources.ImagesWithRawResponse(client.images) - self.audio = resources.AudioWithRawResponse(client.audio) - self.moderations = resources.ModerationsWithRawResponse(client.moderations) - self.models = resources.ModelsWithRawResponse(client.models) - self.fine_tuning = resources.FineTuningWithRawResponse(client.fine_tuning) - self.beta = resources.BetaWithRawResponse(client.beta) - self.batches = resources.BatchesWithRawResponse(client.batches) - self.uploads = resources.UploadsWithRawResponse(client.uploads) + self.completions = completions.CompletionsWithRawResponse(client.completions) + self.chat = chat.ChatWithRawResponse(client.chat) + self.embeddings = embeddings.EmbeddingsWithRawResponse(client.embeddings) + self.files = files.FilesWithRawResponse(client.files) + self.images = images.ImagesWithRawResponse(client.images) + self.audio = audio.AudioWithRawResponse(client.audio) + self.moderations = moderations.ModerationsWithRawResponse(client.moderations) + self.models = models.ModelsWithRawResponse(client.models) + self.fine_tuning = fine_tuning.FineTuningWithRawResponse(client.fine_tuning) + self.beta = beta.BetaWithRawResponse(client.beta) + self.batches = batches.BatchesWithRawResponse(client.batches) + self.uploads = uploads.UploadsWithRawResponse(client.uploads) class AsyncOpenAIWithRawResponse: def __init__(self, client: AsyncOpenAI) -> None: - self.completions = resources.AsyncCompletionsWithRawResponse(client.completions) - self.chat = resources.AsyncChatWithRawResponse(client.chat) - self.embeddings = resources.AsyncEmbeddingsWithRawResponse(client.embeddings) - self.files = resources.AsyncFilesWithRawResponse(client.files) - self.images = resources.AsyncImagesWithRawResponse(client.images) - self.audio = resources.AsyncAudioWithRawResponse(client.audio) - self.moderations = resources.AsyncModerationsWithRawResponse(client.moderations) - self.models = resources.AsyncModelsWithRawResponse(client.models) - self.fine_tuning = resources.AsyncFineTuningWithRawResponse(client.fine_tuning) - self.beta = resources.AsyncBetaWithRawResponse(client.beta) - self.batches = resources.AsyncBatchesWithRawResponse(client.batches) - self.uploads = resources.AsyncUploadsWithRawResponse(client.uploads) + self.completions = completions.AsyncCompletionsWithRawResponse(client.completions) + self.chat = chat.AsyncChatWithRawResponse(client.chat) + self.embeddings = embeddings.AsyncEmbeddingsWithRawResponse(client.embeddings) + self.files = files.AsyncFilesWithRawResponse(client.files) + self.images = images.AsyncImagesWithRawResponse(client.images) + self.audio = audio.AsyncAudioWithRawResponse(client.audio) + self.moderations = moderations.AsyncModerationsWithRawResponse(client.moderations) + self.models = models.AsyncModelsWithRawResponse(client.models) + self.fine_tuning = fine_tuning.AsyncFineTuningWithRawResponse(client.fine_tuning) + self.beta = beta.AsyncBetaWithRawResponse(client.beta) + self.batches = batches.AsyncBatchesWithRawResponse(client.batches) + self.uploads = uploads.AsyncUploadsWithRawResponse(client.uploads) class OpenAIWithStreamedResponse: def __init__(self, client: OpenAI) -> None: - self.completions = resources.CompletionsWithStreamingResponse(client.completions) - self.chat = resources.ChatWithStreamingResponse(client.chat) - self.embeddings = resources.EmbeddingsWithStreamingResponse(client.embeddings) - self.files = resources.FilesWithStreamingResponse(client.files) - self.images = resources.ImagesWithStreamingResponse(client.images) - self.audio = resources.AudioWithStreamingResponse(client.audio) - self.moderations = resources.ModerationsWithStreamingResponse(client.moderations) - self.models = resources.ModelsWithStreamingResponse(client.models) - self.fine_tuning = resources.FineTuningWithStreamingResponse(client.fine_tuning) - self.beta = resources.BetaWithStreamingResponse(client.beta) - self.batches = resources.BatchesWithStreamingResponse(client.batches) - self.uploads = resources.UploadsWithStreamingResponse(client.uploads) + self.completions = completions.CompletionsWithStreamingResponse(client.completions) + self.chat = chat.ChatWithStreamingResponse(client.chat) + self.embeddings = embeddings.EmbeddingsWithStreamingResponse(client.embeddings) + self.files = files.FilesWithStreamingResponse(client.files) + self.images = images.ImagesWithStreamingResponse(client.images) + self.audio = audio.AudioWithStreamingResponse(client.audio) + self.moderations = moderations.ModerationsWithStreamingResponse(client.moderations) + self.models = models.ModelsWithStreamingResponse(client.models) + self.fine_tuning = fine_tuning.FineTuningWithStreamingResponse(client.fine_tuning) + self.beta = beta.BetaWithStreamingResponse(client.beta) + self.batches = batches.BatchesWithStreamingResponse(client.batches) + self.uploads = uploads.UploadsWithStreamingResponse(client.uploads) class AsyncOpenAIWithStreamedResponse: def __init__(self, client: AsyncOpenAI) -> None: - self.completions = resources.AsyncCompletionsWithStreamingResponse(client.completions) - self.chat = resources.AsyncChatWithStreamingResponse(client.chat) - self.embeddings = resources.AsyncEmbeddingsWithStreamingResponse(client.embeddings) - self.files = resources.AsyncFilesWithStreamingResponse(client.files) - self.images = resources.AsyncImagesWithStreamingResponse(client.images) - self.audio = resources.AsyncAudioWithStreamingResponse(client.audio) - self.moderations = resources.AsyncModerationsWithStreamingResponse(client.moderations) - self.models = resources.AsyncModelsWithStreamingResponse(client.models) - self.fine_tuning = resources.AsyncFineTuningWithStreamingResponse(client.fine_tuning) - self.beta = resources.AsyncBetaWithStreamingResponse(client.beta) - self.batches = resources.AsyncBatchesWithStreamingResponse(client.batches) - self.uploads = resources.AsyncUploadsWithStreamingResponse(client.uploads) + self.completions = completions.AsyncCompletionsWithStreamingResponse(client.completions) + self.chat = chat.AsyncChatWithStreamingResponse(client.chat) + self.embeddings = embeddings.AsyncEmbeddingsWithStreamingResponse(client.embeddings) + self.files = files.AsyncFilesWithStreamingResponse(client.files) + self.images = images.AsyncImagesWithStreamingResponse(client.images) + self.audio = audio.AsyncAudioWithStreamingResponse(client.audio) + self.moderations = moderations.AsyncModerationsWithStreamingResponse(client.moderations) + self.models = models.AsyncModelsWithStreamingResponse(client.models) + self.fine_tuning = fine_tuning.AsyncFineTuningWithStreamingResponse(client.fine_tuning) + self.beta = beta.AsyncBetaWithStreamingResponse(client.beta) + self.batches = batches.AsyncBatchesWithStreamingResponse(client.batches) + self.uploads = uploads.AsyncUploadsWithStreamingResponse(client.uploads) Client = OpenAI From e94d98e9bf97a5d2d02d79d58f2abdbab26ff2bd Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 13 Dec 2024 14:02:30 +0000 Subject: [PATCH 607/816] release: 1.57.4 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 9 +++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 58e64c502c..f9ae229e1a 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.57.3" + ".": "1.57.4" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 80ed457618..02b7d0271d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 1.57.4 (2024-12-13) + +Full Changelog: [v1.57.3...v1.57.4](https://github.com/openai/openai-python/compare/v1.57.3...v1.57.4) + +### Chores + +* **internal:** remove some duplicated imports ([#1946](https://github.com/openai/openai-python/issues/1946)) ([f94fddd](https://github.com/openai/openai-python/commit/f94fddd377015764b3c82919fdf956f619447b77)) +* **internal:** updated imports ([#1948](https://github.com/openai/openai-python/issues/1948)) ([13971fc](https://github.com/openai/openai-python/commit/13971fc450106746c0ae02ab931e68b770ee105e)) + ## 1.57.3 (2024-12-12) Full Changelog: [v1.57.2...v1.57.3](https://github.com/openai/openai-python/compare/v1.57.2...v1.57.3) diff --git a/pyproject.toml b/pyproject.toml index a6a0868405..e03d4e798f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.57.3" +version = "1.57.4" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 94ba432279..5b82015017 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.57.3" # x-release-please-version +__version__ = "1.57.4" # x-release-please-version From af791d5188cc142c6ec82fc0f0be90fa3036a85f Mon Sep 17 00:00:00 2001 From: Vincent Date: Mon, 16 Dec 2024 13:12:53 +0100 Subject: [PATCH 608/816] fix(cli/migrate): change grit binaries prefix (#1951) --- src/openai/cli/_tools/migrate.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/openai/cli/_tools/migrate.py b/src/openai/cli/_tools/migrate.py index 7a0b0f90f6..841b777528 100644 --- a/src/openai/cli/_tools/migrate.py +++ b/src/openai/cli/_tools/migrate.py @@ -92,8 +92,8 @@ def install() -> Path: install_dir = dir_name / ".install" target_dir = install_dir / "bin" - target_path = target_dir / "marzano" - temp_file = target_dir / "marzano.tmp" + target_path = target_dir / "grit" + temp_file = target_dir / "grit.tmp" if target_path.exists(): _debug(f"{target_path} already exists") @@ -110,7 +110,7 @@ def install() -> Path: arch = _get_arch() _debug(f"Using architecture {arch}") - file_name = f"marzano-{arch}-{platform}" + file_name = f"grit-{arch}-{platform}" download_url = f"https://github.com/getgrit/gritql/releases/latest/download/%7Bfile_name%7D.tar.gz" sys.stdout.write(f"Downloading Grit CLI from {download_url}\n") From 0bfd8c4d2c7377cd14d7be84ee4f4c1d1ed8a40c Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 16 Dec 2024 12:22:00 +0000 Subject: [PATCH 609/816] fix(assistants): correctly send `include` query param --- src/openai/resources/beta/threads/runs/runs.py | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 620cc270e5..0418d570ba 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -1106,7 +1106,6 @@ def stream( body=maybe_transform( { "assistant_id": assistant_id, - "include": include, "additional_instructions": additional_instructions, "additional_messages": additional_messages, "instructions": instructions, @@ -1126,7 +1125,11 @@ def stream( run_create_params.RunCreateParams, ), options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform({"include": include}, run_create_params.RunCreateParams), ), cast_to=Run, stream=True, @@ -1899,7 +1902,6 @@ async def create( body=await async_maybe_transform( { "assistant_id": assistant_id, - "include": include, "additional_instructions": additional_instructions, "additional_messages": additional_messages, "instructions": instructions, @@ -2472,7 +2474,6 @@ def stream( body=maybe_transform( { "assistant_id": assistant_id, - "include": include, "additional_instructions": additional_instructions, "additional_messages": additional_messages, "instructions": instructions, @@ -2492,7 +2493,11 @@ def stream( run_create_params.RunCreateParams, ), options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform({"include": include}, run_create_params.RunCreateParams), ), cast_to=Run, stream=True, From 588935e273fc934efddad15c702b3d11987bb44e Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 16 Dec 2024 16:04:05 +0000 Subject: [PATCH 610/816] docs(readme): example snippet for client context manager (#1953) --- README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/README.md b/README.md index 780ee261fe..cbcfdb4447 100644 --- a/README.md +++ b/README.md @@ -652,6 +652,16 @@ client.with_options(http_client=DefaultHttpxClient(...)) By default the library closes underlying HTTP connections whenever the client is [garbage collected](https://docs.python.org/3/reference/datamodel.html#object.__del__). You can manually close the client using the `.close()` method if desired, or with a context manager that closes when exiting. +```py +from openai import OpenAI + +with OpenAI() as client: + # make requests here + ... + +# HTTP client is now closed +``` + ## Microsoft Azure OpenAI To use this library with [Azure OpenAI](https://learn.microsoft.com/azure/ai-services/openai/overview), use the `AzureOpenAI` From eba67815fd3ae4ab068d244464dcbb389efa9f0b Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 17 Dec 2024 17:26:44 +0000 Subject: [PATCH 611/816] chore(internal): fix some typos (#1955) --- tests/test_client.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/test_client.py b/tests/test_client.py index 7caa8cb319..7751e7d463 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -349,11 +349,11 @@ def test_default_query_option(self) -> None: FinalRequestOptions( method="get", url="/foo", - params={"foo": "baz", "query_param": "overriden"}, + params={"foo": "baz", "query_param": "overridden"}, ) ) url = httpx.URL(request.url) - assert dict(url.params) == {"foo": "baz", "query_param": "overriden"} + assert dict(url.params) == {"foo": "baz", "query_param": "overridden"} def test_request_extra_json(self) -> None: request = self.client._build_request( @@ -1201,11 +1201,11 @@ def test_default_query_option(self) -> None: FinalRequestOptions( method="get", url="/foo", - params={"foo": "baz", "query_param": "overriden"}, + params={"foo": "baz", "query_param": "overridden"}, ) ) url = httpx.URL(request.url) - assert dict(url.params) == {"foo": "baz", "query_param": "overriden"} + assert dict(url.params) == {"foo": "baz", "query_param": "overridden"} def test_request_extra_json(self) -> None: request = self.client._build_request( From 575ff6078fcf84fba1c4478073969cbfd00ae4b4 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 17 Dec 2024 17:59:13 +0000 Subject: [PATCH 612/816] feat(api): new o1 and GPT-4o models + preference fine-tuning (#1956) learn more here: https://platform.openai.com/docs/changelog --- .stats.yml | 4 +- api.md | 16 + src/openai/resources/beta/beta.py | 32 ++ .../resources/beta/realtime/__init__.py | 33 ++ .../resources/beta/realtime/realtime.py | 102 ++++++ .../resources/beta/realtime/sessions.py | 337 ++++++++++++++++++ src/openai/resources/chat/completions.py | 240 ++++++++----- src/openai/resources/fine_tuning/jobs/jobs.py | 22 +- src/openai/types/beta/realtime/__init__.py | 6 + .../beta/realtime/session_create_params.py | 149 ++++++++ .../beta/realtime/session_create_response.py | 150 ++++++++ src/openai/types/chat/__init__.py | 4 + ...chat_completion_developer_message_param.py | 25 ++ .../chat/chat_completion_message_param.py | 2 + .../chat/chat_completion_reasoning_effort.py | 7 + .../types/chat/completion_create_params.py | 34 +- src/openai/types/chat_model.py | 7 +- .../types/fine_tuning/fine_tuning_job.py | 106 +++++- .../fine_tuning/fine_tuning_job_event.py | 13 + .../types/fine_tuning/job_create_params.py | 94 ++++- tests/api_resources/beta/realtime/__init__.py | 1 + .../beta/realtime/test_sessions.py | 146 ++++++++ tests/api_resources/chat/test_completions.py | 44 +-- tests/api_resources/fine_tuning/test_jobs.py | 36 ++ tests/test_client.py | 16 +- 25 files changed, 1475 insertions(+), 151 deletions(-) create mode 100644 src/openai/resources/beta/realtime/__init__.py create mode 100644 src/openai/resources/beta/realtime/realtime.py create mode 100644 src/openai/resources/beta/realtime/sessions.py create mode 100644 src/openai/types/beta/realtime/__init__.py create mode 100644 src/openai/types/beta/realtime/session_create_params.py create mode 100644 src/openai/types/beta/realtime/session_create_response.py create mode 100644 src/openai/types/chat/chat_completion_developer_message_param.py create mode 100644 src/openai/types/chat/chat_completion_reasoning_effort.py create mode 100644 tests/api_resources/beta/realtime/__init__.py create mode 100644 tests/api_resources/beta/realtime/test_sessions.py diff --git a/.stats.yml b/.stats.yml index 3cc042fe0a..e3a0040a5a 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ -configured_endpoints: 68 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-2e0e0678be19d1118fd796af291822075e40538dba326611e177e9f3dc245a53.yml +configured_endpoints: 69 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-779ea2754025daf5e18eb8ceb203ec321692636bc3a999338556a479178efa6c.yml diff --git a/api.md b/api.md index 7def07bb79..91b2a9c2fd 100644 --- a/api.md +++ b/api.md @@ -47,6 +47,7 @@ from openai.types.chat import ( ChatCompletionContentPartInputAudio, ChatCompletionContentPartRefusal, ChatCompletionContentPartText, + ChatCompletionDeveloperMessageParam, ChatCompletionFunctionCallOption, ChatCompletionFunctionMessageParam, ChatCompletionMessage, @@ -55,6 +56,7 @@ from openai.types.chat import ( ChatCompletionModality, ChatCompletionNamedToolChoice, ChatCompletionPredictionContent, + ChatCompletionReasoningEffort, ChatCompletionRole, ChatCompletionStreamOptions, ChatCompletionSystemMessageParam, @@ -235,6 +237,20 @@ Methods: # Beta +## Realtime + +### Sessions + +Types: + +```python +from openai.types.beta.realtime import Session, SessionCreateResponse +``` + +Methods: + +- client.beta.realtime.sessions.create(\*\*params) -> SessionCreateResponse + ## VectorStores Types: diff --git a/src/openai/resources/beta/beta.py b/src/openai/resources/beta/beta.py index 5079c989a5..1ffa6c8e79 100644 --- a/src/openai/resources/beta/beta.py +++ b/src/openai/resources/beta/beta.py @@ -21,6 +21,14 @@ ThreadsWithStreamingResponse, AsyncThreadsWithStreamingResponse, ) +from .realtime.realtime import ( + Realtime, + AsyncRealtime, + RealtimeWithRawResponse, + AsyncRealtimeWithRawResponse, + RealtimeWithStreamingResponse, + AsyncRealtimeWithStreamingResponse, +) from .vector_stores.vector_stores import ( VectorStores, AsyncVectorStores, @@ -38,6 +46,10 @@ class Beta(SyncAPIResource): def chat(self) -> Chat: return Chat(self._client) + @cached_property + def realtime(self) -> Realtime: + return Realtime(self._client) + @cached_property def vector_stores(self) -> VectorStores: return VectorStores(self._client) @@ -75,6 +87,10 @@ class AsyncBeta(AsyncAPIResource): def chat(self) -> AsyncChat: return AsyncChat(self._client) + @cached_property + def realtime(self) -> AsyncRealtime: + return AsyncRealtime(self._client) + @cached_property def vector_stores(self) -> AsyncVectorStores: return AsyncVectorStores(self._client) @@ -111,6 +127,10 @@ class BetaWithRawResponse: def __init__(self, beta: Beta) -> None: self._beta = beta + @cached_property + def realtime(self) -> RealtimeWithRawResponse: + return RealtimeWithRawResponse(self._beta.realtime) + @cached_property def vector_stores(self) -> VectorStoresWithRawResponse: return VectorStoresWithRawResponse(self._beta.vector_stores) @@ -128,6 +148,10 @@ class AsyncBetaWithRawResponse: def __init__(self, beta: AsyncBeta) -> None: self._beta = beta + @cached_property + def realtime(self) -> AsyncRealtimeWithRawResponse: + return AsyncRealtimeWithRawResponse(self._beta.realtime) + @cached_property def vector_stores(self) -> AsyncVectorStoresWithRawResponse: return AsyncVectorStoresWithRawResponse(self._beta.vector_stores) @@ -145,6 +169,10 @@ class BetaWithStreamingResponse: def __init__(self, beta: Beta) -> None: self._beta = beta + @cached_property + def realtime(self) -> RealtimeWithStreamingResponse: + return RealtimeWithStreamingResponse(self._beta.realtime) + @cached_property def vector_stores(self) -> VectorStoresWithStreamingResponse: return VectorStoresWithStreamingResponse(self._beta.vector_stores) @@ -162,6 +190,10 @@ class AsyncBetaWithStreamingResponse: def __init__(self, beta: AsyncBeta) -> None: self._beta = beta + @cached_property + def realtime(self) -> AsyncRealtimeWithStreamingResponse: + return AsyncRealtimeWithStreamingResponse(self._beta.realtime) + @cached_property def vector_stores(self) -> AsyncVectorStoresWithStreamingResponse: return AsyncVectorStoresWithStreamingResponse(self._beta.vector_stores) diff --git a/src/openai/resources/beta/realtime/__init__.py b/src/openai/resources/beta/realtime/__init__.py new file mode 100644 index 0000000000..474434e6e1 --- /dev/null +++ b/src/openai/resources/beta/realtime/__init__.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .realtime import ( + Realtime, + AsyncRealtime, + RealtimeWithRawResponse, + AsyncRealtimeWithRawResponse, + RealtimeWithStreamingResponse, + AsyncRealtimeWithStreamingResponse, +) +from .sessions import ( + Sessions, + AsyncSessions, + SessionsWithRawResponse, + AsyncSessionsWithRawResponse, + SessionsWithStreamingResponse, + AsyncSessionsWithStreamingResponse, +) + +__all__ = [ + "Sessions", + "AsyncSessions", + "SessionsWithRawResponse", + "AsyncSessionsWithRawResponse", + "SessionsWithStreamingResponse", + "AsyncSessionsWithStreamingResponse", + "Realtime", + "AsyncRealtime", + "RealtimeWithRawResponse", + "AsyncRealtimeWithRawResponse", + "RealtimeWithStreamingResponse", + "AsyncRealtimeWithStreamingResponse", +] diff --git a/src/openai/resources/beta/realtime/realtime.py b/src/openai/resources/beta/realtime/realtime.py new file mode 100644 index 0000000000..e57e0be503 --- /dev/null +++ b/src/openai/resources/beta/realtime/realtime.py @@ -0,0 +1,102 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .sessions import ( + Sessions, + AsyncSessions, + SessionsWithRawResponse, + AsyncSessionsWithRawResponse, + SessionsWithStreamingResponse, + AsyncSessionsWithStreamingResponse, +) +from ...._compat import cached_property +from ...._resource import SyncAPIResource, AsyncAPIResource + +__all__ = ["Realtime", "AsyncRealtime"] + + +class Realtime(SyncAPIResource): + @cached_property + def sessions(self) -> Sessions: + return Sessions(self._client) + + @cached_property + def with_raw_response(self) -> RealtimeWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return RealtimeWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> RealtimeWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return RealtimeWithStreamingResponse(self) + + +class AsyncRealtime(AsyncAPIResource): + @cached_property + def sessions(self) -> AsyncSessions: + return AsyncSessions(self._client) + + @cached_property + def with_raw_response(self) -> AsyncRealtimeWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return AsyncRealtimeWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncRealtimeWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return AsyncRealtimeWithStreamingResponse(self) + + +class RealtimeWithRawResponse: + def __init__(self, realtime: Realtime) -> None: + self._realtime = realtime + + @cached_property + def sessions(self) -> SessionsWithRawResponse: + return SessionsWithRawResponse(self._realtime.sessions) + + +class AsyncRealtimeWithRawResponse: + def __init__(self, realtime: AsyncRealtime) -> None: + self._realtime = realtime + + @cached_property + def sessions(self) -> AsyncSessionsWithRawResponse: + return AsyncSessionsWithRawResponse(self._realtime.sessions) + + +class RealtimeWithStreamingResponse: + def __init__(self, realtime: Realtime) -> None: + self._realtime = realtime + + @cached_property + def sessions(self) -> SessionsWithStreamingResponse: + return SessionsWithStreamingResponse(self._realtime.sessions) + + +class AsyncRealtimeWithStreamingResponse: + def __init__(self, realtime: AsyncRealtime) -> None: + self._realtime = realtime + + @cached_property + def sessions(self) -> AsyncSessionsWithStreamingResponse: + return AsyncSessionsWithStreamingResponse(self._realtime.sessions) diff --git a/src/openai/resources/beta/realtime/sessions.py b/src/openai/resources/beta/realtime/sessions.py new file mode 100644 index 0000000000..1d1ee701e5 --- /dev/null +++ b/src/openai/resources/beta/realtime/sessions.py @@ -0,0 +1,337 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Union, Iterable +from typing_extensions import Literal + +import httpx + +from .... import _legacy_response +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ...._utils import ( + maybe_transform, + async_maybe_transform, +) +from ...._compat import cached_property +from ...._resource import SyncAPIResource, AsyncAPIResource +from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ...._base_client import make_request_options +from ....types.beta.realtime import session_create_params +from ....types.beta.realtime.session_create_response import SessionCreateResponse + +__all__ = ["Sessions", "AsyncSessions"] + + +class Sessions(SyncAPIResource): + @cached_property + def with_raw_response(self) -> SessionsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return SessionsWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> SessionsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return SessionsWithStreamingResponse(self) + + def create( + self, + *, + model: Literal[ + "gpt-4o-realtime-preview", + "gpt-4o-realtime-preview-2024-10-01", + "gpt-4o-realtime-preview-2024-12-17", + "gpt-4o-mini-realtime-preview", + "gpt-4o-mini-realtime-preview-2024-12-17", + ], + input_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"] | NotGiven = NOT_GIVEN, + input_audio_transcription: session_create_params.InputAudioTranscription | NotGiven = NOT_GIVEN, + instructions: str | NotGiven = NOT_GIVEN, + max_response_output_tokens: Union[int, Literal["inf"]] | NotGiven = NOT_GIVEN, + modalities: List[Literal["text", "audio"]] | NotGiven = NOT_GIVEN, + output_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"] | NotGiven = NOT_GIVEN, + temperature: float | NotGiven = NOT_GIVEN, + tool_choice: str | NotGiven = NOT_GIVEN, + tools: Iterable[session_create_params.Tool] | NotGiven = NOT_GIVEN, + turn_detection: session_create_params.TurnDetection | NotGiven = NOT_GIVEN, + voice: Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> SessionCreateResponse: + """ + Create an ephemeral API token for use in client-side applications with the + Realtime API. Can be configured with the same session parameters as the + `session.update` client event. + + It responds with a session object, plus a `client_secret` key which contains a + usable ephemeral API token that can be used to authenticate browser clients for + the Realtime API. + + Args: + model: The Realtime model used for this session. + + input_audio_format: The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. + + input_audio_transcription: Configuration for input audio transcription, defaults to off and can be set to + `null` to turn off once on. Input audio transcription is not native to the + model, since the model consumes audio directly. Transcription runs + asynchronously through Whisper and should be treated as rough guidance rather + than the representation understood by the model. + + instructions: The default system instructions (i.e. system message) prepended to model calls. + This field allows the client to guide the model on desired responses. The model + can be instructed on response content and format, (e.g. "be extremely succinct", + "act friendly", "here are examples of good responses") and on audio behavior + (e.g. "talk quickly", "inject emotion into your voice", "laugh frequently"). The + instructions are not guaranteed to be followed by the model, but they provide + guidance to the model on the desired behavior. + + Note that the server sets default instructions which will be used if this field + is not set and are visible in the `session.created` event at the start of the + session. + + max_response_output_tokens: Maximum number of output tokens for a single assistant response, inclusive of + tool calls. Provide an integer between 1 and 4096 to limit output tokens, or + `inf` for the maximum available tokens for a given model. Defaults to `inf`. + + modalities: The set of modalities the model can respond with. To disable audio, set this to + ["text"]. + + output_audio_format: The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. + + temperature: Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8. + + tool_choice: How the model chooses tools. Options are `auto`, `none`, `required`, or specify + a function. + + tools: Tools (functions) available to the model. + + turn_detection: Configuration for turn detection. Can be set to `null` to turn off. Server VAD + means that the model will detect the start and end of speech based on audio + volume and respond at the end of user speech. + + voice: The voice the model uses to respond. Voice cannot be changed during the session + once the model has responded with audio at least once. Current voice options are + `alloy`, `ash`, `ballad`, `coral`, `echo` `sage`, `shimmer` and `verse`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return self._post( + "/realtime/sessions", + body=maybe_transform( + { + "model": model, + "input_audio_format": input_audio_format, + "input_audio_transcription": input_audio_transcription, + "instructions": instructions, + "max_response_output_tokens": max_response_output_tokens, + "modalities": modalities, + "output_audio_format": output_audio_format, + "temperature": temperature, + "tool_choice": tool_choice, + "tools": tools, + "turn_detection": turn_detection, + "voice": voice, + }, + session_create_params.SessionCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=SessionCreateResponse, + ) + + +class AsyncSessions(AsyncAPIResource): + @cached_property + def with_raw_response(self) -> AsyncSessionsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return the + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return AsyncSessionsWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncSessionsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return AsyncSessionsWithStreamingResponse(self) + + async def create( + self, + *, + model: Literal[ + "gpt-4o-realtime-preview", + "gpt-4o-realtime-preview-2024-10-01", + "gpt-4o-realtime-preview-2024-12-17", + "gpt-4o-mini-realtime-preview", + "gpt-4o-mini-realtime-preview-2024-12-17", + ], + input_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"] | NotGiven = NOT_GIVEN, + input_audio_transcription: session_create_params.InputAudioTranscription | NotGiven = NOT_GIVEN, + instructions: str | NotGiven = NOT_GIVEN, + max_response_output_tokens: Union[int, Literal["inf"]] | NotGiven = NOT_GIVEN, + modalities: List[Literal["text", "audio"]] | NotGiven = NOT_GIVEN, + output_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"] | NotGiven = NOT_GIVEN, + temperature: float | NotGiven = NOT_GIVEN, + tool_choice: str | NotGiven = NOT_GIVEN, + tools: Iterable[session_create_params.Tool] | NotGiven = NOT_GIVEN, + turn_detection: session_create_params.TurnDetection | NotGiven = NOT_GIVEN, + voice: Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> SessionCreateResponse: + """ + Create an ephemeral API token for use in client-side applications with the + Realtime API. Can be configured with the same session parameters as the + `session.update` client event. + + It responds with a session object, plus a `client_secret` key which contains a + usable ephemeral API token that can be used to authenticate browser clients for + the Realtime API. + + Args: + model: The Realtime model used for this session. + + input_audio_format: The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. + + input_audio_transcription: Configuration for input audio transcription, defaults to off and can be set to + `null` to turn off once on. Input audio transcription is not native to the + model, since the model consumes audio directly. Transcription runs + asynchronously through Whisper and should be treated as rough guidance rather + than the representation understood by the model. + + instructions: The default system instructions (i.e. system message) prepended to model calls. + This field allows the client to guide the model on desired responses. The model + can be instructed on response content and format, (e.g. "be extremely succinct", + "act friendly", "here are examples of good responses") and on audio behavior + (e.g. "talk quickly", "inject emotion into your voice", "laugh frequently"). The + instructions are not guaranteed to be followed by the model, but they provide + guidance to the model on the desired behavior. + + Note that the server sets default instructions which will be used if this field + is not set and are visible in the `session.created` event at the start of the + session. + + max_response_output_tokens: Maximum number of output tokens for a single assistant response, inclusive of + tool calls. Provide an integer between 1 and 4096 to limit output tokens, or + `inf` for the maximum available tokens for a given model. Defaults to `inf`. + + modalities: The set of modalities the model can respond with. To disable audio, set this to + ["text"]. + + output_audio_format: The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. + + temperature: Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8. + + tool_choice: How the model chooses tools. Options are `auto`, `none`, `required`, or specify + a function. + + tools: Tools (functions) available to the model. + + turn_detection: Configuration for turn detection. Can be set to `null` to turn off. Server VAD + means that the model will detect the start and end of speech based on audio + volume and respond at the end of user speech. + + voice: The voice the model uses to respond. Voice cannot be changed during the session + once the model has responded with audio at least once. Current voice options are + `alloy`, `ash`, `ballad`, `coral`, `echo` `sage`, `shimmer` and `verse`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return await self._post( + "/realtime/sessions", + body=await async_maybe_transform( + { + "model": model, + "input_audio_format": input_audio_format, + "input_audio_transcription": input_audio_transcription, + "instructions": instructions, + "max_response_output_tokens": max_response_output_tokens, + "modalities": modalities, + "output_audio_format": output_audio_format, + "temperature": temperature, + "tool_choice": tool_choice, + "tools": tools, + "turn_detection": turn_detection, + "voice": voice, + }, + session_create_params.SessionCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=SessionCreateResponse, + ) + + +class SessionsWithRawResponse: + def __init__(self, sessions: Sessions) -> None: + self._sessions = sessions + + self.create = _legacy_response.to_raw_response_wrapper( + sessions.create, + ) + + +class AsyncSessionsWithRawResponse: + def __init__(self, sessions: AsyncSessions) -> None: + self._sessions = sessions + + self.create = _legacy_response.async_to_raw_response_wrapper( + sessions.create, + ) + + +class SessionsWithStreamingResponse: + def __init__(self, sessions: Sessions) -> None: + self._sessions = sessions + + self.create = to_streamed_response_wrapper( + sessions.create, + ) + + +class AsyncSessionsWithStreamingResponse: + def __init__(self, sessions: AsyncSessions) -> None: + self._sessions = sessions + + self.create = async_to_streamed_response_wrapper( + sessions.create, + ) diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index 60ab5138ba..728c744327 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -22,6 +22,7 @@ from ..._streaming import Stream, AsyncStream from ...types.chat import ( ChatCompletionAudioParam, + ChatCompletionReasoningEffort, completion_create_params, ) from ..._base_client import make_request_options @@ -32,6 +33,7 @@ from ...types.chat.chat_completion_tool_param import ChatCompletionToolParam from ...types.chat.chat_completion_audio_param import ChatCompletionAudioParam from ...types.chat.chat_completion_message_param import ChatCompletionMessageParam +from ...types.chat.chat_completion_reasoning_effort import ChatCompletionReasoningEffort from ...types.chat.chat_completion_stream_options_param import ChatCompletionStreamOptionsParam from ...types.chat.chat_completion_prediction_content_param import ChatCompletionPredictionContentParam from ...types.chat.chat_completion_tool_choice_option_param import ChatCompletionToolChoiceOptionParam @@ -79,6 +81,7 @@ def create( parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + reasoning_effort: ChatCompletionReasoningEffort | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, @@ -106,6 +109,12 @@ def create( [vision](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio) guides. + Parameter support can differ depending on the model used to generate the + response, particularly for newer reasoning models. Parameters that are only + supported for reasoning models are noted below. For the current state of + unsupported parameters in reasoning models, + [refer to the reasoning guide](https://platform.openai.com/docs/guides/reasoning). + Args: messages: A list of messages comprising the conversation so far. Depending on the [model](https://platform.openai.com/docs/models) you use, different message @@ -126,16 +135,18 @@ def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) - function_call: Deprecated in favor of `tool_choice`. - Controls which (if any) function is called by the model. `none` means the model - will not call a function and instead generates a message. `auto` means the model - can pick between generating a message or calling a function. Specifying a - particular function via `{"name": "my_function"}` forces the model to call that + Controls which (if any) function is called by the model. + + `none` means the model will not call a function and instead generates a message. + + `auto` means the model can pick between generating a message or calling a function. + Specifying a particular function via `{"name": "my_function"}` forces the model + to call that function. + `none` is the default when no functions are present. `auto` is the default if functions are present. @@ -197,13 +208,14 @@ def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) + reasoning_effort: **o1 models only** + + Constrains effort on reasoning for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + supported values are `low`, `medium`, and `high`. Reducing reasoning effort can + result in faster responses and fewer tokens used on reasoning in a response. - response_format: An object specifying the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), - [GPT-4o mini](https://platform.openai.com/docs/models#gpt-4o-mini), - [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + response_format: An object specifying the format that the model must output. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which ensures the model will match your supplied JSON schema. Learn more @@ -259,9 +271,8 @@ def create( temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more - focused and deterministic. - - We generally recommend altering this or `top_p` but not both. + focused and deterministic. We generally recommend altering this or `top_p` but + not both. tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tool and instead generates a message. `auto` means the model can @@ -322,6 +333,7 @@ def create( parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + reasoning_effort: ChatCompletionReasoningEffort | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, @@ -348,6 +360,12 @@ def create( [vision](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio) guides. + Parameter support can differ depending on the model used to generate the + response, particularly for newer reasoning models. Parameters that are only + supported for reasoning models are noted below. For the current state of + unsupported parameters in reasoning models, + [refer to the reasoning guide](https://platform.openai.com/docs/guides/reasoning). + Args: messages: A list of messages comprising the conversation so far. Depending on the [model](https://platform.openai.com/docs/models) you use, different message @@ -375,16 +393,18 @@ def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) - function_call: Deprecated in favor of `tool_choice`. - Controls which (if any) function is called by the model. `none` means the model - will not call a function and instead generates a message. `auto` means the model - can pick between generating a message or calling a function. Specifying a - particular function via `{"name": "my_function"}` forces the model to call that + Controls which (if any) function is called by the model. + + `none` means the model will not call a function and instead generates a message. + + `auto` means the model can pick between generating a message or calling a function. + Specifying a particular function via `{"name": "my_function"}` forces the model + to call that function. + `none` is the default when no functions are present. `auto` is the default if functions are present. @@ -446,13 +466,14 @@ def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) + reasoning_effort: **o1 models only** + + Constrains effort on reasoning for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + supported values are `low`, `medium`, and `high`. Reducing reasoning effort can + result in faster responses and fewer tokens used on reasoning in a response. - response_format: An object specifying the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), - [GPT-4o mini](https://platform.openai.com/docs/models#gpt-4o-mini), - [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + response_format: An object specifying the format that the model must output. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which ensures the model will match your supplied JSON schema. Learn more @@ -501,9 +522,8 @@ def create( temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more - focused and deterministic. - - We generally recommend altering this or `top_p` but not both. + focused and deterministic. We generally recommend altering this or `top_p` but + not both. tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tool and instead generates a message. `auto` means the model can @@ -564,6 +584,7 @@ def create( parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + reasoning_effort: ChatCompletionReasoningEffort | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, @@ -590,6 +611,12 @@ def create( [vision](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio) guides. + Parameter support can differ depending on the model used to generate the + response, particularly for newer reasoning models. Parameters that are only + supported for reasoning models are noted below. For the current state of + unsupported parameters in reasoning models, + [refer to the reasoning guide](https://platform.openai.com/docs/guides/reasoning). + Args: messages: A list of messages comprising the conversation so far. Depending on the [model](https://platform.openai.com/docs/models) you use, different message @@ -617,16 +644,18 @@ def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) - function_call: Deprecated in favor of `tool_choice`. - Controls which (if any) function is called by the model. `none` means the model - will not call a function and instead generates a message. `auto` means the model - can pick between generating a message or calling a function. Specifying a - particular function via `{"name": "my_function"}` forces the model to call that + Controls which (if any) function is called by the model. + + `none` means the model will not call a function and instead generates a message. + + `auto` means the model can pick between generating a message or calling a function. + Specifying a particular function via `{"name": "my_function"}` forces the model + to call that function. + `none` is the default when no functions are present. `auto` is the default if functions are present. @@ -688,13 +717,14 @@ def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) + reasoning_effort: **o1 models only** - response_format: An object specifying the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), - [GPT-4o mini](https://platform.openai.com/docs/models#gpt-4o-mini), - [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + Constrains effort on reasoning for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + supported values are `low`, `medium`, and `high`. Reducing reasoning effort can + result in faster responses and fewer tokens used on reasoning in a response. + + response_format: An object specifying the format that the model must output. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which ensures the model will match your supplied JSON schema. Learn more @@ -743,9 +773,8 @@ def create( temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more - focused and deterministic. - - We generally recommend altering this or `top_p` but not both. + focused and deterministic. We generally recommend altering this or `top_p` but + not both. tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tool and instead generates a message. `auto` means the model can @@ -805,6 +834,7 @@ def create( parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + reasoning_effort: ChatCompletionReasoningEffort | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, @@ -846,6 +876,7 @@ def create( "parallel_tool_calls": parallel_tool_calls, "prediction": prediction, "presence_penalty": presence_penalty, + "reasoning_effort": reasoning_effort, "response_format": response_format, "seed": seed, "service_tier": service_tier, @@ -911,6 +942,7 @@ async def create( parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + reasoning_effort: ChatCompletionReasoningEffort | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, @@ -938,6 +970,12 @@ async def create( [vision](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio) guides. + Parameter support can differ depending on the model used to generate the + response, particularly for newer reasoning models. Parameters that are only + supported for reasoning models are noted below. For the current state of + unsupported parameters in reasoning models, + [refer to the reasoning guide](https://platform.openai.com/docs/guides/reasoning). + Args: messages: A list of messages comprising the conversation so far. Depending on the [model](https://platform.openai.com/docs/models) you use, different message @@ -958,16 +996,18 @@ async def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) - function_call: Deprecated in favor of `tool_choice`. - Controls which (if any) function is called by the model. `none` means the model - will not call a function and instead generates a message. `auto` means the model - can pick between generating a message or calling a function. Specifying a - particular function via `{"name": "my_function"}` forces the model to call that + Controls which (if any) function is called by the model. + + `none` means the model will not call a function and instead generates a message. + + `auto` means the model can pick between generating a message or calling a function. + Specifying a particular function via `{"name": "my_function"}` forces the model + to call that function. + `none` is the default when no functions are present. `auto` is the default if functions are present. @@ -1029,13 +1069,14 @@ async def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) + reasoning_effort: **o1 models only** + + Constrains effort on reasoning for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + supported values are `low`, `medium`, and `high`. Reducing reasoning effort can + result in faster responses and fewer tokens used on reasoning in a response. - response_format: An object specifying the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), - [GPT-4o mini](https://platform.openai.com/docs/models#gpt-4o-mini), - [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + response_format: An object specifying the format that the model must output. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which ensures the model will match your supplied JSON schema. Learn more @@ -1091,9 +1132,8 @@ async def create( temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more - focused and deterministic. - - We generally recommend altering this or `top_p` but not both. + focused and deterministic. We generally recommend altering this or `top_p` but + not both. tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tool and instead generates a message. `auto` means the model can @@ -1154,6 +1194,7 @@ async def create( parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + reasoning_effort: ChatCompletionReasoningEffort | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, @@ -1180,6 +1221,12 @@ async def create( [vision](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio) guides. + Parameter support can differ depending on the model used to generate the + response, particularly for newer reasoning models. Parameters that are only + supported for reasoning models are noted below. For the current state of + unsupported parameters in reasoning models, + [refer to the reasoning guide](https://platform.openai.com/docs/guides/reasoning). + Args: messages: A list of messages comprising the conversation so far. Depending on the [model](https://platform.openai.com/docs/models) you use, different message @@ -1207,16 +1254,18 @@ async def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) - function_call: Deprecated in favor of `tool_choice`. - Controls which (if any) function is called by the model. `none` means the model - will not call a function and instead generates a message. `auto` means the model - can pick between generating a message or calling a function. Specifying a - particular function via `{"name": "my_function"}` forces the model to call that + Controls which (if any) function is called by the model. + + `none` means the model will not call a function and instead generates a message. + + `auto` means the model can pick between generating a message or calling a function. + Specifying a particular function via `{"name": "my_function"}` forces the model + to call that function. + `none` is the default when no functions are present. `auto` is the default if functions are present. @@ -1278,13 +1327,14 @@ async def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) + reasoning_effort: **o1 models only** + + Constrains effort on reasoning for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + supported values are `low`, `medium`, and `high`. Reducing reasoning effort can + result in faster responses and fewer tokens used on reasoning in a response. - response_format: An object specifying the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), - [GPT-4o mini](https://platform.openai.com/docs/models#gpt-4o-mini), - [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + response_format: An object specifying the format that the model must output. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which ensures the model will match your supplied JSON schema. Learn more @@ -1333,9 +1383,8 @@ async def create( temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more - focused and deterministic. - - We generally recommend altering this or `top_p` but not both. + focused and deterministic. We generally recommend altering this or `top_p` but + not both. tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tool and instead generates a message. `auto` means the model can @@ -1396,6 +1445,7 @@ async def create( parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + reasoning_effort: ChatCompletionReasoningEffort | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, @@ -1422,6 +1472,12 @@ async def create( [vision](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio) guides. + Parameter support can differ depending on the model used to generate the + response, particularly for newer reasoning models. Parameters that are only + supported for reasoning models are noted below. For the current state of + unsupported parameters in reasoning models, + [refer to the reasoning guide](https://platform.openai.com/docs/guides/reasoning). + Args: messages: A list of messages comprising the conversation so far. Depending on the [model](https://platform.openai.com/docs/models) you use, different message @@ -1449,16 +1505,18 @@ async def create( existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) - function_call: Deprecated in favor of `tool_choice`. - Controls which (if any) function is called by the model. `none` means the model - will not call a function and instead generates a message. `auto` means the model - can pick between generating a message or calling a function. Specifying a - particular function via `{"name": "my_function"}` forces the model to call that + Controls which (if any) function is called by the model. + + `none` means the model will not call a function and instead generates a message. + + `auto` means the model can pick between generating a message or calling a function. + Specifying a particular function via `{"name": "my_function"}` forces the model + to call that function. + `none` is the default when no functions are present. `auto` is the default if functions are present. @@ -1520,13 +1578,14 @@ async def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) + reasoning_effort: **o1 models only** - response_format: An object specifying the format that the model must output. Compatible with - [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), - [GPT-4o mini](https://platform.openai.com/docs/models#gpt-4o-mini), - [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. + Constrains effort on reasoning for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + supported values are `low`, `medium`, and `high`. Reducing reasoning effort can + result in faster responses and fewer tokens used on reasoning in a response. + + response_format: An object specifying the format that the model must output. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which ensures the model will match your supplied JSON schema. Learn more @@ -1575,9 +1634,8 @@ async def create( temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more - focused and deterministic. - - We generally recommend altering this or `top_p` but not both. + focused and deterministic. We generally recommend altering this or `top_p` but + not both. tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tool and instead generates a message. `auto` means the model can @@ -1637,6 +1695,7 @@ async def create( parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + reasoning_effort: ChatCompletionReasoningEffort | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, @@ -1678,6 +1737,7 @@ async def create( "parallel_tool_calls": parallel_tool_calls, "prediction": prediction, "presence_penalty": presence_penalty, + "reasoning_effort": reasoning_effort, "response_format": response_format, "seed": seed, "service_tier": service_tier, diff --git a/src/openai/resources/fine_tuning/jobs/jobs.py b/src/openai/resources/fine_tuning/jobs/jobs.py index 0ed5495b0e..78eefc253c 100644 --- a/src/openai/resources/fine_tuning/jobs/jobs.py +++ b/src/openai/resources/fine_tuning/jobs/jobs.py @@ -67,6 +67,7 @@ def create( training_file: str, hyperparameters: job_create_params.Hyperparameters | NotGiven = NOT_GIVEN, integrations: Optional[Iterable[job_create_params.Integration]] | NotGiven = NOT_GIVEN, + method: job_create_params.Method | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, suffix: Optional[str] | NotGiven = NOT_GIVEN, validation_file: Optional[str] | NotGiven = NOT_GIVEN, @@ -99,17 +100,22 @@ def create( your file with the purpose `fine-tune`. The contents of the file should differ depending on if the model uses the - [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or + [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input), [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) + format, or if the fine-tuning method uses the + [preference](https://platform.openai.com/docs/api-reference/fine-tuning/preference-input) format. See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) for more details. - hyperparameters: The hyperparameters used for the fine-tuning job. + hyperparameters: The hyperparameters used for the fine-tuning job. This value is now deprecated + in favor of `method`, and should be passed in under the `method` parameter. integrations: A list of integrations to enable for your fine-tuning job. + method: The method used for fine-tuning. + seed: The seed controls the reproducibility of the job. Passing in the same seed and job parameters should produce the same results, but may differ in rare cases. If a seed is not specified, one will be generated for you. @@ -149,6 +155,7 @@ def create( "training_file": training_file, "hyperparameters": hyperparameters, "integrations": integrations, + "method": method, "seed": seed, "suffix": suffix, "validation_file": validation_file, @@ -358,6 +365,7 @@ async def create( training_file: str, hyperparameters: job_create_params.Hyperparameters | NotGiven = NOT_GIVEN, integrations: Optional[Iterable[job_create_params.Integration]] | NotGiven = NOT_GIVEN, + method: job_create_params.Method | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, suffix: Optional[str] | NotGiven = NOT_GIVEN, validation_file: Optional[str] | NotGiven = NOT_GIVEN, @@ -390,17 +398,22 @@ async def create( your file with the purpose `fine-tune`. The contents of the file should differ depending on if the model uses the - [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or + [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input), [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) + format, or if the fine-tuning method uses the + [preference](https://platform.openai.com/docs/api-reference/fine-tuning/preference-input) format. See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) for more details. - hyperparameters: The hyperparameters used for the fine-tuning job. + hyperparameters: The hyperparameters used for the fine-tuning job. This value is now deprecated + in favor of `method`, and should be passed in under the `method` parameter. integrations: A list of integrations to enable for your fine-tuning job. + method: The method used for fine-tuning. + seed: The seed controls the reproducibility of the job. Passing in the same seed and job parameters should produce the same results, but may differ in rare cases. If a seed is not specified, one will be generated for you. @@ -440,6 +453,7 @@ async def create( "training_file": training_file, "hyperparameters": hyperparameters, "integrations": integrations, + "method": method, "seed": seed, "suffix": suffix, "validation_file": validation_file, diff --git a/src/openai/types/beta/realtime/__init__.py b/src/openai/types/beta/realtime/__init__.py new file mode 100644 index 0000000000..1c5246db7a --- /dev/null +++ b/src/openai/types/beta/realtime/__init__.py @@ -0,0 +1,6 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .session_create_params import SessionCreateParams as SessionCreateParams +from .session_create_response import SessionCreateResponse as SessionCreateResponse diff --git a/src/openai/types/beta/realtime/session_create_params.py b/src/openai/types/beta/realtime/session_create_params.py new file mode 100644 index 0000000000..f56f2c5c22 --- /dev/null +++ b/src/openai/types/beta/realtime/session_create_params.py @@ -0,0 +1,149 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Union, Iterable +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["SessionCreateParams", "InputAudioTranscription", "Tool", "TurnDetection"] + + +class SessionCreateParams(TypedDict, total=False): + model: Required[ + Literal[ + "gpt-4o-realtime-preview", + "gpt-4o-realtime-preview-2024-10-01", + "gpt-4o-realtime-preview-2024-12-17", + "gpt-4o-mini-realtime-preview", + "gpt-4o-mini-realtime-preview-2024-12-17", + ] + ] + """The Realtime model used for this session.""" + + input_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"] + """The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.""" + + input_audio_transcription: InputAudioTranscription + """ + Configuration for input audio transcription, defaults to off and can be set to + `null` to turn off once on. Input audio transcription is not native to the + model, since the model consumes audio directly. Transcription runs + asynchronously through Whisper and should be treated as rough guidance rather + than the representation understood by the model. + """ + + instructions: str + """The default system instructions (i.e. + + system message) prepended to model calls. This field allows the client to guide + the model on desired responses. The model can be instructed on response content + and format, (e.g. "be extremely succinct", "act friendly", "here are examples of + good responses") and on audio behavior (e.g. "talk quickly", "inject emotion + into your voice", "laugh frequently"). The instructions are not guaranteed to be + followed by the model, but they provide guidance to the model on the desired + behavior. + + Note that the server sets default instructions which will be used if this field + is not set and are visible in the `session.created` event at the start of the + session. + """ + + max_response_output_tokens: Union[int, Literal["inf"]] + """ + Maximum number of output tokens for a single assistant response, inclusive of + tool calls. Provide an integer between 1 and 4096 to limit output tokens, or + `inf` for the maximum available tokens for a given model. Defaults to `inf`. + """ + + modalities: List[Literal["text", "audio"]] + """The set of modalities the model can respond with. + + To disable audio, set this to ["text"]. + """ + + output_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"] + """The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.""" + + temperature: float + """Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.""" + + tool_choice: str + """How the model chooses tools. + + Options are `auto`, `none`, `required`, or specify a function. + """ + + tools: Iterable[Tool] + """Tools (functions) available to the model.""" + + turn_detection: TurnDetection + """Configuration for turn detection. + + Can be set to `null` to turn off. Server VAD means that the model will detect + the start and end of speech based on audio volume and respond at the end of user + speech. + """ + + voice: Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"] + """The voice the model uses to respond. + + Voice cannot be changed during the session once the model has responded with + audio at least once. Current voice options are `alloy`, `ash`, `ballad`, + `coral`, `echo` `sage`, `shimmer` and `verse`. + """ + + +class InputAudioTranscription(TypedDict, total=False): + model: str + """ + The model to use for transcription, `whisper-1` is the only currently supported + model. + """ + + +class Tool(TypedDict, total=False): + description: str + """ + The description of the function, including guidance on when and how to call it, + and guidance about what to tell the user when calling (if anything). + """ + + name: str + """The name of the function.""" + + parameters: object + """Parameters of the function in JSON Schema.""" + + type: Literal["function"] + """The type of the tool, i.e. `function`.""" + + +class TurnDetection(TypedDict, total=False): + create_response: bool + """Whether or not to automatically generate a response when VAD is enabled. + + `true` by default. + """ + + prefix_padding_ms: int + """Amount of audio to include before the VAD detected speech (in milliseconds). + + Defaults to 300ms. + """ + + silence_duration_ms: int + """Duration of silence to detect speech stop (in milliseconds). + + Defaults to 500ms. With shorter values the model will respond more quickly, but + may jump in on short pauses from the user. + """ + + threshold: float + """Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. + + A higher threshold will require louder audio to activate the model, and thus + might perform better in noisy environments. + """ + + type: str + """Type of turn detection, only `server_vad` is currently supported.""" diff --git a/src/openai/types/beta/realtime/session_create_response.py b/src/openai/types/beta/realtime/session_create_response.py new file mode 100644 index 0000000000..31f591b261 --- /dev/null +++ b/src/openai/types/beta/realtime/session_create_response.py @@ -0,0 +1,150 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["SessionCreateResponse", "ClientSecret", "InputAudioTranscription", "Tool", "TurnDetection"] + + +class ClientSecret(BaseModel): + expires_at: Optional[int] = None + """Timestamp for when the token expires. + + Currently, all tokens expire after one minute. + """ + + value: Optional[str] = None + """ + Ephemeral key usable in client environments to authenticate connections to the + Realtime API. Use this in client-side environments rather than a standard API + token, which should only be used server-side. + """ + + +class InputAudioTranscription(BaseModel): + model: Optional[str] = None + """ + The model to use for transcription, `whisper-1` is the only currently supported + model. + """ + + +class Tool(BaseModel): + description: Optional[str] = None + """ + The description of the function, including guidance on when and how to call it, + and guidance about what to tell the user when calling (if anything). + """ + + name: Optional[str] = None + """The name of the function.""" + + parameters: Optional[object] = None + """Parameters of the function in JSON Schema.""" + + type: Optional[Literal["function"]] = None + """The type of the tool, i.e. `function`.""" + + +class TurnDetection(BaseModel): + prefix_padding_ms: Optional[int] = None + """Amount of audio to include before the VAD detected speech (in milliseconds). + + Defaults to 300ms. + """ + + silence_duration_ms: Optional[int] = None + """Duration of silence to detect speech stop (in milliseconds). + + Defaults to 500ms. With shorter values the model will respond more quickly, but + may jump in on short pauses from the user. + """ + + threshold: Optional[float] = None + """Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. + + A higher threshold will require louder audio to activate the model, and thus + might perform better in noisy environments. + """ + + type: Optional[str] = None + """Type of turn detection, only `server_vad` is currently supported.""" + + +class SessionCreateResponse(BaseModel): + client_secret: Optional[ClientSecret] = None + """Ephemeral key returned by the API.""" + + input_audio_format: Optional[str] = None + """The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.""" + + input_audio_transcription: Optional[InputAudioTranscription] = None + """ + Configuration for input audio transcription, defaults to off and can be set to + `null` to turn off once on. Input audio transcription is not native to the + model, since the model consumes audio directly. Transcription runs + asynchronously through Whisper and should be treated as rough guidance rather + than the representation understood by the model. + """ + + instructions: Optional[str] = None + """The default system instructions (i.e. + + system message) prepended to model calls. This field allows the client to guide + the model on desired responses. The model can be instructed on response content + and format, (e.g. "be extremely succinct", "act friendly", "here are examples of + good responses") and on audio behavior (e.g. "talk quickly", "inject emotion + into your voice", "laugh frequently"). The instructions are not guaranteed to be + followed by the model, but they provide guidance to the model on the desired + behavior. + + Note that the server sets default instructions which will be used if this field + is not set and are visible in the `session.created` event at the start of the + session. + """ + + max_response_output_tokens: Union[int, Literal["inf"], None] = None + """ + Maximum number of output tokens for a single assistant response, inclusive of + tool calls. Provide an integer between 1 and 4096 to limit output tokens, or + `inf` for the maximum available tokens for a given model. Defaults to `inf`. + """ + + modalities: Optional[List[Literal["text", "audio"]]] = None + """The set of modalities the model can respond with. + + To disable audio, set this to ["text"]. + """ + + output_audio_format: Optional[str] = None + """The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.""" + + temperature: Optional[float] = None + """Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.""" + + tool_choice: Optional[str] = None + """How the model chooses tools. + + Options are `auto`, `none`, `required`, or specify a function. + """ + + tools: Optional[List[Tool]] = None + """Tools (functions) available to the model.""" + + turn_detection: Optional[TurnDetection] = None + """Configuration for turn detection. + + Can be set to `null` to turn off. Server VAD means that the model will detect + the start and end of speech based on audio volume and respond at the end of user + speech. + """ + + voice: Optional[Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"]] = None + """The voice the model uses to respond. + + Voice cannot be changed during the session once the model has responded with + audio at least once. Current voice options are `alloy`, `ash`, `ballad`, + `coral`, `echo` `sage`, `shimmer` and `verse`. + """ diff --git a/src/openai/types/chat/__init__.py b/src/openai/types/chat/__init__.py index d0a5403e79..c623a982af 100644 --- a/src/openai/types/chat/__init__.py +++ b/src/openai/types/chat/__init__.py @@ -22,6 +22,7 @@ from .chat_completion_audio_param import ChatCompletionAudioParam as ChatCompletionAudioParam from .chat_completion_message_param import ChatCompletionMessageParam as ChatCompletionMessageParam from .chat_completion_token_logprob import ChatCompletionTokenLogprob as ChatCompletionTokenLogprob +from .chat_completion_reasoning_effort import ChatCompletionReasoningEffort as ChatCompletionReasoningEffort from .chat_completion_message_tool_call import ChatCompletionMessageToolCall as ChatCompletionMessageToolCall from .chat_completion_content_part_param import ChatCompletionContentPartParam as ChatCompletionContentPartParam from .chat_completion_tool_message_param import ChatCompletionToolMessageParam as ChatCompletionToolMessageParam @@ -37,6 +38,9 @@ from .chat_completion_content_part_text_param import ( ChatCompletionContentPartTextParam as ChatCompletionContentPartTextParam, ) +from .chat_completion_developer_message_param import ( + ChatCompletionDeveloperMessageParam as ChatCompletionDeveloperMessageParam, +) from .chat_completion_message_tool_call_param import ( ChatCompletionMessageToolCallParam as ChatCompletionMessageToolCallParam, ) diff --git a/src/openai/types/chat/chat_completion_developer_message_param.py b/src/openai/types/chat/chat_completion_developer_message_param.py new file mode 100644 index 0000000000..01e4fdb654 --- /dev/null +++ b/src/openai/types/chat/chat_completion_developer_message_param.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import Literal, Required, TypedDict + +from .chat_completion_content_part_text_param import ChatCompletionContentPartTextParam + +__all__ = ["ChatCompletionDeveloperMessageParam"] + + +class ChatCompletionDeveloperMessageParam(TypedDict, total=False): + content: Required[Union[str, Iterable[ChatCompletionContentPartTextParam]]] + """The contents of the developer message.""" + + role: Required[Literal["developer"]] + """The role of the messages author, in this case `developer`.""" + + name: str + """An optional name for the participant. + + Provides the model information to differentiate between participants of the same + role. + """ diff --git a/src/openai/types/chat/chat_completion_message_param.py b/src/openai/types/chat/chat_completion_message_param.py index ec65d94cae..942da24304 100644 --- a/src/openai/types/chat/chat_completion_message_param.py +++ b/src/openai/types/chat/chat_completion_message_param.py @@ -10,10 +10,12 @@ from .chat_completion_system_message_param import ChatCompletionSystemMessageParam from .chat_completion_function_message_param import ChatCompletionFunctionMessageParam from .chat_completion_assistant_message_param import ChatCompletionAssistantMessageParam +from .chat_completion_developer_message_param import ChatCompletionDeveloperMessageParam __all__ = ["ChatCompletionMessageParam"] ChatCompletionMessageParam: TypeAlias = Union[ + ChatCompletionDeveloperMessageParam, ChatCompletionSystemMessageParam, ChatCompletionUserMessageParam, ChatCompletionAssistantMessageParam, diff --git a/src/openai/types/chat/chat_completion_reasoning_effort.py b/src/openai/types/chat/chat_completion_reasoning_effort.py new file mode 100644 index 0000000000..9e7946974a --- /dev/null +++ b/src/openai/types/chat/chat_completion_reasoning_effort.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["ChatCompletionReasoningEffort"] + +ChatCompletionReasoningEffort: TypeAlias = Literal["low", "medium", "high"] diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index e838858314..f168ddea6e 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -10,6 +10,7 @@ from .chat_completion_tool_param import ChatCompletionToolParam from .chat_completion_audio_param import ChatCompletionAudioParam from .chat_completion_message_param import ChatCompletionMessageParam +from .chat_completion_reasoning_effort import ChatCompletionReasoningEffort from ..shared_params.function_parameters import FunctionParameters from ..shared_params.response_format_text import ResponseFormatText from .chat_completion_stream_options_param import ChatCompletionStreamOptionsParam @@ -60,19 +61,21 @@ class CompletionCreateParamsBase(TypedDict, total=False): Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. - - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) """ function_call: FunctionCall """Deprecated in favor of `tool_choice`. - Controls which (if any) function is called by the model. `none` means the model - will not call a function and instead generates a message. `auto` means the model - can pick between generating a message or calling a function. Specifying a - particular function via `{"name": "my_function"}` forces the model to call that + Controls which (if any) function is called by the model. + + `none` means the model will not call a function and instead generates a message. + + `auto` means the model can pick between generating a message or calling a function. + Specifying a particular function via `{"name": "my_function"}` forces the model + to call that function. + `none` is the default when no functions are present. `auto` is the default if functions are present. """ @@ -164,18 +167,20 @@ class CompletionCreateParamsBase(TypedDict, total=False): Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. + """ + + reasoning_effort: ChatCompletionReasoningEffort + """**o1 models only** - [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation) + Constrains effort on reasoning for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + supported values are `low`, `medium`, and `high`. Reducing reasoning effort can + result in faster responses and fewer tokens used on reasoning in a response. """ response_format: ResponseFormat """An object specifying the format that the model must output. - Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), - [GPT-4o mini](https://platform.openai.com/docs/models#gpt-4o-mini), - [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4) and - all GPT-3.5 Turbo models newer than `gpt-3.5-turbo-1106`. - Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which ensures the model will match your supplied JSON schema. Learn more in the @@ -237,9 +242,8 @@ class CompletionCreateParamsBase(TypedDict, total=False): """What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like - 0.2 will make it more focused and deterministic. - - We generally recommend altering this or `top_p` but not both. + 0.2 will make it more focused and deterministic. We generally recommend altering + this or `top_p` but not both. """ tool_choice: ChatCompletionToolChoiceOptionParam diff --git a/src/openai/types/chat_model.py b/src/openai/types/chat_model.py index 3567a3ba65..e1ac464320 100644 --- a/src/openai/types/chat_model.py +++ b/src/openai/types/chat_model.py @@ -5,6 +5,8 @@ __all__ = ["ChatModel"] ChatModel: TypeAlias = Literal[ + "o1", + "o1-2024-12-17", "o1-preview", "o1-preview-2024-09-12", "o1-mini", @@ -13,10 +15,11 @@ "gpt-4o-2024-11-20", "gpt-4o-2024-08-06", "gpt-4o-2024-05-13", - "gpt-4o-realtime-preview", - "gpt-4o-realtime-preview-2024-10-01", "gpt-4o-audio-preview", "gpt-4o-audio-preview-2024-10-01", + "gpt-4o-audio-preview-2024-12-17", + "gpt-4o-mini-audio-preview", + "gpt-4o-mini-audio-preview-2024-12-17", "chatgpt-4o-latest", "gpt-4o-mini", "gpt-4o-mini-2024-07-18", diff --git a/src/openai/types/fine_tuning/fine_tuning_job.py b/src/openai/types/fine_tuning/fine_tuning_job.py index 7ac8792787..f5a11c2107 100644 --- a/src/openai/types/fine_tuning/fine_tuning_job.py +++ b/src/openai/types/fine_tuning/fine_tuning_job.py @@ -6,7 +6,16 @@ from ..._models import BaseModel from .fine_tuning_job_wandb_integration_object import FineTuningJobWandbIntegrationObject -__all__ = ["FineTuningJob", "Error", "Hyperparameters"] +__all__ = [ + "FineTuningJob", + "Error", + "Hyperparameters", + "Method", + "MethodDpo", + "MethodDpoHyperparameters", + "MethodSupervised", + "MethodSupervisedHyperparameters", +] class Error(BaseModel): @@ -24,15 +33,96 @@ class Error(BaseModel): class Hyperparameters(BaseModel): - n_epochs: Union[Literal["auto"], int] + batch_size: Union[Literal["auto"], int, None] = None + """Number of examples in each batch. + + A larger batch size means that model parameters are updated less frequently, but + with lower variance. + """ + + learning_rate_multiplier: Union[Literal["auto"], float, None] = None + """Scaling factor for the learning rate. + + A smaller learning rate may be useful to avoid overfitting. + """ + + n_epochs: Union[Literal["auto"], int, None] = None + """The number of epochs to train the model for. + + An epoch refers to one full cycle through the training dataset. + """ + + +class MethodDpoHyperparameters(BaseModel): + batch_size: Union[Literal["auto"], int, None] = None + """Number of examples in each batch. + + A larger batch size means that model parameters are updated less frequently, but + with lower variance. + """ + + beta: Union[Literal["auto"], float, None] = None + """The beta value for the DPO method. + + A higher beta value will increase the weight of the penalty between the policy + and reference model. + """ + + learning_rate_multiplier: Union[Literal["auto"], float, None] = None + """Scaling factor for the learning rate. + + A smaller learning rate may be useful to avoid overfitting. + """ + + n_epochs: Union[Literal["auto"], int, None] = None """The number of epochs to train the model for. - An epoch refers to one full cycle through the training dataset. "auto" decides - the optimal number of epochs based on the size of the dataset. If setting the - number manually, we support any number between 1 and 50 epochs. + An epoch refers to one full cycle through the training dataset. """ +class MethodDpo(BaseModel): + hyperparameters: Optional[MethodDpoHyperparameters] = None + """The hyperparameters used for the fine-tuning job.""" + + +class MethodSupervisedHyperparameters(BaseModel): + batch_size: Union[Literal["auto"], int, None] = None + """Number of examples in each batch. + + A larger batch size means that model parameters are updated less frequently, but + with lower variance. + """ + + learning_rate_multiplier: Union[Literal["auto"], float, None] = None + """Scaling factor for the learning rate. + + A smaller learning rate may be useful to avoid overfitting. + """ + + n_epochs: Union[Literal["auto"], int, None] = None + """The number of epochs to train the model for. + + An epoch refers to one full cycle through the training dataset. + """ + + +class MethodSupervised(BaseModel): + hyperparameters: Optional[MethodSupervisedHyperparameters] = None + """The hyperparameters used for the fine-tuning job.""" + + +class Method(BaseModel): + dpo: Optional[MethodDpo] = None + """Configuration for the DPO fine-tuning method.""" + + supervised: Optional[MethodSupervised] = None + """Configuration for the supervised fine-tuning method.""" + + type: Optional[Literal["supervised", "dpo"]] = None + """The type of method. Is either `supervised` or `dpo`.""" + + class FineTuningJob(BaseModel): id: str """The object identifier, which can be referenced in the API endpoints.""" @@ -61,8 +151,7 @@ class FineTuningJob(BaseModel): hyperparameters: Hyperparameters """The hyperparameters used for the fine-tuning job. - See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) - for more details. + This value will only be returned when running `supervised` jobs. """ model: str @@ -118,3 +207,6 @@ class FineTuningJob(BaseModel): integrations: Optional[List[FineTuningJobWandbIntegrationObject]] = None """A list of integrations to enable for this fine-tuning job.""" + + method: Optional[Method] = None + """The method used for fine-tuning.""" diff --git a/src/openai/types/fine_tuning/fine_tuning_job_event.py b/src/openai/types/fine_tuning/fine_tuning_job_event.py index 2d204bb980..1d728bd765 100644 --- a/src/openai/types/fine_tuning/fine_tuning_job_event.py +++ b/src/openai/types/fine_tuning/fine_tuning_job_event.py @@ -1,5 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +import builtins +from typing import Optional from typing_extensions import Literal from ..._models import BaseModel @@ -9,11 +11,22 @@ class FineTuningJobEvent(BaseModel): id: str + """The object identifier.""" created_at: int + """The Unix timestamp (in seconds) for when the fine-tuning job was created.""" level: Literal["info", "warn", "error"] + """The log level of the event.""" message: str + """The message of the event.""" object: Literal["fine_tuning.job.event"] + """The object type, which is always "fine_tuning.job.event".""" + + data: Optional[builtins.object] = None + """The data associated with the event.""" + + type: Optional[Literal["message", "metrics"]] = None + """The type of event.""" diff --git a/src/openai/types/fine_tuning/job_create_params.py b/src/openai/types/fine_tuning/job_create_params.py index 8814229b2e..09c3f8571c 100644 --- a/src/openai/types/fine_tuning/job_create_params.py +++ b/src/openai/types/fine_tuning/job_create_params.py @@ -5,7 +5,17 @@ from typing import List, Union, Iterable, Optional from typing_extensions import Literal, Required, TypedDict -__all__ = ["JobCreateParams", "Hyperparameters", "Integration", "IntegrationWandb"] +__all__ = [ + "JobCreateParams", + "Hyperparameters", + "Integration", + "IntegrationWandb", + "Method", + "MethodDpo", + "MethodDpoHyperparameters", + "MethodSupervised", + "MethodSupervisedHyperparameters", +] class JobCreateParams(TypedDict, total=False): @@ -26,8 +36,10 @@ class JobCreateParams(TypedDict, total=False): your file with the purpose `fine-tune`. The contents of the file should differ depending on if the model uses the - [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or + [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input), [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) + format, or if the fine-tuning method uses the + [preference](https://platform.openai.com/docs/api-reference/fine-tuning/preference-input) format. See the [fine-tuning guide](https://platform.openai.com/docs/guides/fine-tuning) @@ -35,11 +47,17 @@ class JobCreateParams(TypedDict, total=False): """ hyperparameters: Hyperparameters - """The hyperparameters used for the fine-tuning job.""" + """ + The hyperparameters used for the fine-tuning job. This value is now deprecated + in favor of `method`, and should be passed in under the `method` parameter. + """ integrations: Optional[Iterable[Integration]] """A list of integrations to enable for your fine-tuning job.""" + method: Method + """The method used for fine-tuning.""" + seed: Optional[int] """The seed controls the reproducibility of the job. @@ -134,3 +152,73 @@ class Integration(TypedDict, total=False): can set an explicit display name for your run, add tags to your run, and set a default entity (team, username, etc) to be associated with your run. """ + + +class MethodDpoHyperparameters(TypedDict, total=False): + batch_size: Union[Literal["auto"], int] + """Number of examples in each batch. + + A larger batch size means that model parameters are updated less frequently, but + with lower variance. + """ + + beta: Union[Literal["auto"], float] + """The beta value for the DPO method. + + A higher beta value will increase the weight of the penalty between the policy + and reference model. + """ + + learning_rate_multiplier: Union[Literal["auto"], float] + """Scaling factor for the learning rate. + + A smaller learning rate may be useful to avoid overfitting. + """ + + n_epochs: Union[Literal["auto"], int] + """The number of epochs to train the model for. + + An epoch refers to one full cycle through the training dataset. + """ + + +class MethodDpo(TypedDict, total=False): + hyperparameters: MethodDpoHyperparameters + """The hyperparameters used for the fine-tuning job.""" + + +class MethodSupervisedHyperparameters(TypedDict, total=False): + batch_size: Union[Literal["auto"], int] + """Number of examples in each batch. + + A larger batch size means that model parameters are updated less frequently, but + with lower variance. + """ + + learning_rate_multiplier: Union[Literal["auto"], float] + """Scaling factor for the learning rate. + + A smaller learning rate may be useful to avoid overfitting. + """ + + n_epochs: Union[Literal["auto"], int] + """The number of epochs to train the model for. + + An epoch refers to one full cycle through the training dataset. + """ + + +class MethodSupervised(TypedDict, total=False): + hyperparameters: MethodSupervisedHyperparameters + """The hyperparameters used for the fine-tuning job.""" + + +class Method(TypedDict, total=False): + dpo: MethodDpo + """Configuration for the DPO fine-tuning method.""" + + supervised: MethodSupervised + """Configuration for the supervised fine-tuning method.""" + + type: Literal["supervised", "dpo"] + """The type of method. Is either `supervised` or `dpo`.""" diff --git a/tests/api_resources/beta/realtime/__init__.py b/tests/api_resources/beta/realtime/__init__.py new file mode 100644 index 0000000000..fd8019a9a1 --- /dev/null +++ b/tests/api_resources/beta/realtime/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/beta/realtime/test_sessions.py b/tests/api_resources/beta/realtime/test_sessions.py new file mode 100644 index 0000000000..65bfa27572 --- /dev/null +++ b/tests/api_resources/beta/realtime/test_sessions.py @@ -0,0 +1,146 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai.types.beta.realtime import SessionCreateResponse + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") + + +class TestSessions: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + def test_method_create(self, client: OpenAI) -> None: + session = client.beta.realtime.sessions.create( + model="gpt-4o-realtime-preview", + ) + assert_matches_type(SessionCreateResponse, session, path=["response"]) + + @parametrize + def test_method_create_with_all_params(self, client: OpenAI) -> None: + session = client.beta.realtime.sessions.create( + model="gpt-4o-realtime-preview", + input_audio_format="pcm16", + input_audio_transcription={"model": "model"}, + instructions="instructions", + max_response_output_tokens=0, + modalities=["text"], + output_audio_format="pcm16", + temperature=0, + tool_choice="tool_choice", + tools=[ + { + "description": "description", + "name": "name", + "parameters": {}, + "type": "function", + } + ], + turn_detection={ + "create_response": True, + "prefix_padding_ms": 0, + "silence_duration_ms": 0, + "threshold": 0, + "type": "type", + }, + voice="alloy", + ) + assert_matches_type(SessionCreateResponse, session, path=["response"]) + + @parametrize + def test_raw_response_create(self, client: OpenAI) -> None: + response = client.beta.realtime.sessions.with_raw_response.create( + model="gpt-4o-realtime-preview", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + session = response.parse() + assert_matches_type(SessionCreateResponse, session, path=["response"]) + + @parametrize + def test_streaming_response_create(self, client: OpenAI) -> None: + with client.beta.realtime.sessions.with_streaming_response.create( + model="gpt-4o-realtime-preview", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + session = response.parse() + assert_matches_type(SessionCreateResponse, session, path=["response"]) + + assert cast(Any, response.is_closed) is True + + +class TestAsyncSessions: + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + async def test_method_create(self, async_client: AsyncOpenAI) -> None: + session = await async_client.beta.realtime.sessions.create( + model="gpt-4o-realtime-preview", + ) + assert_matches_type(SessionCreateResponse, session, path=["response"]) + + @parametrize + async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: + session = await async_client.beta.realtime.sessions.create( + model="gpt-4o-realtime-preview", + input_audio_format="pcm16", + input_audio_transcription={"model": "model"}, + instructions="instructions", + max_response_output_tokens=0, + modalities=["text"], + output_audio_format="pcm16", + temperature=0, + tool_choice="tool_choice", + tools=[ + { + "description": "description", + "name": "name", + "parameters": {}, + "type": "function", + } + ], + turn_detection={ + "create_response": True, + "prefix_padding_ms": 0, + "silence_duration_ms": 0, + "threshold": 0, + "type": "type", + }, + voice="alloy", + ) + assert_matches_type(SessionCreateResponse, session, path=["response"]) + + @parametrize + async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.realtime.sessions.with_raw_response.create( + model="gpt-4o-realtime-preview", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + session = response.parse() + assert_matches_type(SessionCreateResponse, session, path=["response"]) + + @parametrize + async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.realtime.sessions.with_streaming_response.create( + model="gpt-4o-realtime-preview", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + session = await response.parse() + assert_matches_type(SessionCreateResponse, session, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index 1b52650b1d..393a790549 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -26,7 +26,7 @@ def test_method_create_overload_1(self, client: OpenAI) -> None: messages=[ { "content": "string", - "role": "system", + "role": "developer", } ], model="gpt-4o", @@ -39,8 +39,8 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: messages=[ { "content": "string", - "role": "system", - "name": "string", + "role": "developer", + "name": "name", } ], model="gpt-4o", @@ -70,6 +70,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: "type": "content", }, presence_penalty=-2, + reasoning_effort="low", response_format={"type": "text"}, seed=-9007199254740991, service_tier="auto", @@ -102,7 +103,7 @@ def test_raw_response_create_overload_1(self, client: OpenAI) -> None: messages=[ { "content": "string", - "role": "system", + "role": "developer", } ], model="gpt-4o", @@ -119,7 +120,7 @@ def test_streaming_response_create_overload_1(self, client: OpenAI) -> None: messages=[ { "content": "string", - "role": "system", + "role": "developer", } ], model="gpt-4o", @@ -138,7 +139,7 @@ def test_method_create_overload_2(self, client: OpenAI) -> None: messages=[ { "content": "string", - "role": "system", + "role": "developer", } ], model="gpt-4o", @@ -152,8 +153,8 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: messages=[ { "content": "string", - "role": "system", - "name": "string", + "role": "developer", + "name": "name", } ], model="gpt-4o", @@ -184,6 +185,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: "type": "content", }, presence_penalty=-2, + reasoning_effort="low", response_format={"type": "text"}, seed=-9007199254740991, service_tier="auto", @@ -215,7 +217,7 @@ def test_raw_response_create_overload_2(self, client: OpenAI) -> None: messages=[ { "content": "string", - "role": "system", + "role": "developer", } ], model="gpt-4o", @@ -232,7 +234,7 @@ def test_streaming_response_create_overload_2(self, client: OpenAI) -> None: messages=[ { "content": "string", - "role": "system", + "role": "developer", } ], model="gpt-4o", @@ -273,7 +275,7 @@ async def test_method_create_overload_1(self, async_client: AsyncOpenAI) -> None messages=[ { "content": "string", - "role": "system", + "role": "developer", } ], model="gpt-4o", @@ -286,8 +288,8 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn messages=[ { "content": "string", - "role": "system", - "name": "string", + "role": "developer", + "name": "name", } ], model="gpt-4o", @@ -317,6 +319,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn "type": "content", }, presence_penalty=-2, + reasoning_effort="low", response_format={"type": "text"}, seed=-9007199254740991, service_tier="auto", @@ -349,7 +352,7 @@ async def test_raw_response_create_overload_1(self, async_client: AsyncOpenAI) - messages=[ { "content": "string", - "role": "system", + "role": "developer", } ], model="gpt-4o", @@ -366,7 +369,7 @@ async def test_streaming_response_create_overload_1(self, async_client: AsyncOpe messages=[ { "content": "string", - "role": "system", + "role": "developer", } ], model="gpt-4o", @@ -385,7 +388,7 @@ async def test_method_create_overload_2(self, async_client: AsyncOpenAI) -> None messages=[ { "content": "string", - "role": "system", + "role": "developer", } ], model="gpt-4o", @@ -399,8 +402,8 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn messages=[ { "content": "string", - "role": "system", - "name": "string", + "role": "developer", + "name": "name", } ], model="gpt-4o", @@ -431,6 +434,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn "type": "content", }, presence_penalty=-2, + reasoning_effort="low", response_format={"type": "text"}, seed=-9007199254740991, service_tier="auto", @@ -462,7 +466,7 @@ async def test_raw_response_create_overload_2(self, async_client: AsyncOpenAI) - messages=[ { "content": "string", - "role": "system", + "role": "developer", } ], model="gpt-4o", @@ -479,7 +483,7 @@ async def test_streaming_response_create_overload_2(self, async_client: AsyncOpe messages=[ { "content": "string", - "role": "system", + "role": "developer", } ], model="gpt-4o", diff --git a/tests/api_resources/fine_tuning/test_jobs.py b/tests/api_resources/fine_tuning/test_jobs.py index aa2bf39528..1e421c30c0 100644 --- a/tests/api_resources/fine_tuning/test_jobs.py +++ b/tests/api_resources/fine_tuning/test_jobs.py @@ -50,6 +50,24 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: }, } ], + method={ + "dpo": { + "hyperparameters": { + "batch_size": "auto", + "beta": "auto", + "learning_rate_multiplier": "auto", + "n_epochs": "auto", + } + }, + "supervised": { + "hyperparameters": { + "batch_size": "auto", + "learning_rate_multiplier": "auto", + "n_epochs": "auto", + } + }, + "type": "supervised", + }, seed=42, suffix="x", validation_file="file-abc123", @@ -271,6 +289,24 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> }, } ], + method={ + "dpo": { + "hyperparameters": { + "batch_size": "auto", + "beta": "auto", + "learning_rate_multiplier": "auto", + "n_epochs": "auto", + } + }, + "supervised": { + "hyperparameters": { + "batch_size": "auto", + "learning_rate_multiplier": "auto", + "n_epochs": "auto", + } + }, + "type": "supervised", + }, seed=42, suffix="x", validation_file="file-abc123", diff --git a/tests/test_client.py b/tests/test_client.py index 7751e7d463..e0d23403b1 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -795,7 +795,7 @@ def retry_handler(_request: httpx.Request) -> httpx.Response: messages=[ { "content": "string", - "role": "system", + "role": "developer", } ], model="gpt-4o", @@ -827,7 +827,7 @@ def retry_handler(_request: httpx.Request) -> httpx.Response: messages=[ { "content": "string", - "role": "system", + "role": "developer", } ], model="gpt-4o", @@ -859,7 +859,7 @@ def retry_handler(_request: httpx.Request) -> httpx.Response: messages=[ { "content": "string", - "role": "system", + "role": "developer", } ], model="gpt-4o", @@ -891,7 +891,7 @@ def retry_handler(_request: httpx.Request) -> httpx.Response: messages=[ { "content": "string", - "role": "system", + "role": "developer", } ], model="gpt-4o", @@ -1663,7 +1663,7 @@ def retry_handler(_request: httpx.Request) -> httpx.Response: messages=[ { "content": "string", - "role": "system", + "role": "developer", } ], model="gpt-4o", @@ -1696,7 +1696,7 @@ def retry_handler(_request: httpx.Request) -> httpx.Response: messages=[ { "content": "string", - "role": "system", + "role": "developer", } ], model="gpt-4o", @@ -1729,7 +1729,7 @@ def retry_handler(_request: httpx.Request) -> httpx.Response: messages=[ { "content": "string", - "role": "system", + "role": "developer", } ], model="gpt-4o", @@ -1762,7 +1762,7 @@ def retry_handler(_request: httpx.Request) -> httpx.Response: messages=[ { "content": "string", - "role": "system", + "role": "developer", } ], model="gpt-4o", From 5fdba4864b5a9dc00f50a939fcf40b992a550db9 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 17 Dec 2024 18:09:06 +0000 Subject: [PATCH 613/816] feat: add Realtime API support (#1958) More information on the Realtime API can be found here: https://platform.openai.com/docs/guides/realtime --- .stats.yml | 2 +- api.md | 51 ++ pyproject.toml | 7 +- requirements-dev.lock | 2 + requirements.lock | 2 + src/openai/_client.py | 26 + src/openai/lib/azure.py | 14 + .../resources/beta/realtime/realtime.py | 852 ++++++++++++++++++ src/openai/types/__init__.py | 1 + src/openai/types/beta/realtime/__init__.py | 74 ++ .../realtime/conversation_created_event.py | 27 + .../types/beta/realtime/conversation_item.py | 61 ++ .../realtime/conversation_item_content.py | 28 + .../conversation_item_content_param.py | 27 + .../conversation_item_create_event.py | 28 + .../conversation_item_create_event_param.py | 28 + .../conversation_item_created_event.py | 25 + .../conversation_item_delete_event.py | 19 + .../conversation_item_delete_event_param.py | 18 + .../conversation_item_deleted_event.py | 18 + ...put_audio_transcription_completed_event.py | 26 + ..._input_audio_transcription_failed_event.py | 39 + .../beta/realtime/conversation_item_param.py | 62 ++ .../conversation_item_truncate_event.py | 32 + .../conversation_item_truncate_event_param.py | 31 + .../conversation_item_truncated_event.py | 24 + src/openai/types/beta/realtime/error_event.py | 36 + .../input_audio_buffer_append_event.py | 23 + .../input_audio_buffer_append_event_param.py | 22 + .../input_audio_buffer_clear_event.py | 16 + .../input_audio_buffer_clear_event_param.py | 15 + .../input_audio_buffer_cleared_event.py | 15 + .../input_audio_buffer_commit_event.py | 16 + .../input_audio_buffer_commit_event_param.py | 15 + .../input_audio_buffer_committed_event.py | 21 + ...input_audio_buffer_speech_started_event.py | 26 + ...input_audio_buffer_speech_stopped_event.py | 25 + .../realtime/rate_limits_updated_event.py | 33 + .../beta/realtime/realtime_client_event.py | 32 + .../realtime/realtime_client_event_param.py | 30 + .../beta/realtime/realtime_connect_params.py | 11 + .../types/beta/realtime/realtime_response.py | 42 + .../beta/realtime/realtime_response_status.py | 39 + .../beta/realtime/realtime_response_usage.py | 52 ++ .../beta/realtime/realtime_server_event.py | 72 ++ .../realtime/response_audio_delta_event.py | 30 + .../realtime/response_audio_done_event.py | 27 + .../response_audio_transcript_delta_event.py | 30 + .../response_audio_transcript_done_event.py | 30 + .../beta/realtime/response_cancel_event.py | 22 + .../realtime/response_cancel_event_param.py | 21 + .../response_content_part_added_event.py | 45 + .../response_content_part_done_event.py | 45 + .../beta/realtime/response_create_event.py | 115 +++ .../realtime/response_create_event_param.py | 116 +++ .../beta/realtime/response_created_event.py | 19 + .../beta/realtime/response_done_event.py | 19 + ...nse_function_call_arguments_delta_event.py | 30 + ...onse_function_call_arguments_done_event.py | 30 + .../response_output_item_added_event.py | 25 + .../response_output_item_done_event.py | 25 + .../realtime/response_text_delta_event.py | 30 + .../beta/realtime/response_text_done_event.py | 30 + src/openai/types/beta/realtime/session.py | 148 +++ .../beta/realtime/session_created_event.py | 19 + .../beta/realtime/session_update_event.py | 158 ++++ .../realtime/session_update_event_param.py | 166 ++++ .../beta/realtime/session_updated_event.py | 19 + .../types/websocket_connection_options.py | 36 + tests/api_resources/beta/test_realtime.py | 17 + 70 files changed, 3313 insertions(+), 4 deletions(-) create mode 100644 src/openai/types/beta/realtime/conversation_created_event.py create mode 100644 src/openai/types/beta/realtime/conversation_item.py create mode 100644 src/openai/types/beta/realtime/conversation_item_content.py create mode 100644 src/openai/types/beta/realtime/conversation_item_content_param.py create mode 100644 src/openai/types/beta/realtime/conversation_item_create_event.py create mode 100644 src/openai/types/beta/realtime/conversation_item_create_event_param.py create mode 100644 src/openai/types/beta/realtime/conversation_item_created_event.py create mode 100644 src/openai/types/beta/realtime/conversation_item_delete_event.py create mode 100644 src/openai/types/beta/realtime/conversation_item_delete_event_param.py create mode 100644 src/openai/types/beta/realtime/conversation_item_deleted_event.py create mode 100644 src/openai/types/beta/realtime/conversation_item_input_audio_transcription_completed_event.py create mode 100644 src/openai/types/beta/realtime/conversation_item_input_audio_transcription_failed_event.py create mode 100644 src/openai/types/beta/realtime/conversation_item_param.py create mode 100644 src/openai/types/beta/realtime/conversation_item_truncate_event.py create mode 100644 src/openai/types/beta/realtime/conversation_item_truncate_event_param.py create mode 100644 src/openai/types/beta/realtime/conversation_item_truncated_event.py create mode 100644 src/openai/types/beta/realtime/error_event.py create mode 100644 src/openai/types/beta/realtime/input_audio_buffer_append_event.py create mode 100644 src/openai/types/beta/realtime/input_audio_buffer_append_event_param.py create mode 100644 src/openai/types/beta/realtime/input_audio_buffer_clear_event.py create mode 100644 src/openai/types/beta/realtime/input_audio_buffer_clear_event_param.py create mode 100644 src/openai/types/beta/realtime/input_audio_buffer_cleared_event.py create mode 100644 src/openai/types/beta/realtime/input_audio_buffer_commit_event.py create mode 100644 src/openai/types/beta/realtime/input_audio_buffer_commit_event_param.py create mode 100644 src/openai/types/beta/realtime/input_audio_buffer_committed_event.py create mode 100644 src/openai/types/beta/realtime/input_audio_buffer_speech_started_event.py create mode 100644 src/openai/types/beta/realtime/input_audio_buffer_speech_stopped_event.py create mode 100644 src/openai/types/beta/realtime/rate_limits_updated_event.py create mode 100644 src/openai/types/beta/realtime/realtime_client_event.py create mode 100644 src/openai/types/beta/realtime/realtime_client_event_param.py create mode 100644 src/openai/types/beta/realtime/realtime_connect_params.py create mode 100644 src/openai/types/beta/realtime/realtime_response.py create mode 100644 src/openai/types/beta/realtime/realtime_response_status.py create mode 100644 src/openai/types/beta/realtime/realtime_response_usage.py create mode 100644 src/openai/types/beta/realtime/realtime_server_event.py create mode 100644 src/openai/types/beta/realtime/response_audio_delta_event.py create mode 100644 src/openai/types/beta/realtime/response_audio_done_event.py create mode 100644 src/openai/types/beta/realtime/response_audio_transcript_delta_event.py create mode 100644 src/openai/types/beta/realtime/response_audio_transcript_done_event.py create mode 100644 src/openai/types/beta/realtime/response_cancel_event.py create mode 100644 src/openai/types/beta/realtime/response_cancel_event_param.py create mode 100644 src/openai/types/beta/realtime/response_content_part_added_event.py create mode 100644 src/openai/types/beta/realtime/response_content_part_done_event.py create mode 100644 src/openai/types/beta/realtime/response_create_event.py create mode 100644 src/openai/types/beta/realtime/response_create_event_param.py create mode 100644 src/openai/types/beta/realtime/response_created_event.py create mode 100644 src/openai/types/beta/realtime/response_done_event.py create mode 100644 src/openai/types/beta/realtime/response_function_call_arguments_delta_event.py create mode 100644 src/openai/types/beta/realtime/response_function_call_arguments_done_event.py create mode 100644 src/openai/types/beta/realtime/response_output_item_added_event.py create mode 100644 src/openai/types/beta/realtime/response_output_item_done_event.py create mode 100644 src/openai/types/beta/realtime/response_text_delta_event.py create mode 100644 src/openai/types/beta/realtime/response_text_done_event.py create mode 100644 src/openai/types/beta/realtime/session.py create mode 100644 src/openai/types/beta/realtime/session_created_event.py create mode 100644 src/openai/types/beta/realtime/session_update_event.py create mode 100644 src/openai/types/beta/realtime/session_update_event_param.py create mode 100644 src/openai/types/beta/realtime/session_updated_event.py create mode 100644 src/openai/types/websocket_connection_options.py create mode 100644 tests/api_resources/beta/test_realtime.py diff --git a/.stats.yml b/.stats.yml index e3a0040a5a..12219ccaa1 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 69 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-779ea2754025daf5e18eb8ceb203ec321692636bc3a999338556a479178efa6c.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-0d64ca9e45f51b4279f87b205eeb3a3576df98407698ce053f2e2302c1c08df1.yml diff --git a/api.md b/api.md index 91b2a9c2fd..ace93e0559 100644 --- a/api.md +++ b/api.md @@ -239,6 +239,57 @@ Methods: ## Realtime +Types: + +```python +from openai.types.beta.realtime import ( + ConversationCreatedEvent, + ConversationItem, + ConversationItemContent, + ConversationItemCreateEvent, + ConversationItemCreatedEvent, + ConversationItemDeleteEvent, + ConversationItemDeletedEvent, + ConversationItemInputAudioTranscriptionCompletedEvent, + ConversationItemInputAudioTranscriptionFailedEvent, + ConversationItemTruncateEvent, + ConversationItemTruncatedEvent, + ErrorEvent, + InputAudioBufferAppendEvent, + InputAudioBufferClearEvent, + InputAudioBufferClearedEvent, + InputAudioBufferCommitEvent, + InputAudioBufferCommittedEvent, + InputAudioBufferSpeechStartedEvent, + InputAudioBufferSpeechStoppedEvent, + RateLimitsUpdatedEvent, + RealtimeClientEvent, + RealtimeResponse, + RealtimeResponseStatus, + RealtimeResponseUsage, + RealtimeServerEvent, + ResponseAudioDeltaEvent, + ResponseAudioDoneEvent, + ResponseAudioTranscriptDeltaEvent, + ResponseAudioTranscriptDoneEvent, + ResponseCancelEvent, + ResponseContentPartAddedEvent, + ResponseContentPartDoneEvent, + ResponseCreateEvent, + ResponseCreatedEvent, + ResponseDoneEvent, + ResponseFunctionCallArgumentsDeltaEvent, + ResponseFunctionCallArgumentsDoneEvent, + ResponseOutputItemAddedEvent, + ResponseOutputItemDoneEvent, + ResponseTextDeltaEvent, + ResponseTextDoneEvent, + SessionCreatedEvent, + SessionUpdateEvent, + SessionUpdatedEvent, +) +``` + ### Sessions Types: diff --git a/pyproject.toml b/pyproject.toml index e03d4e798f..f83aff6fee 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -35,9 +35,6 @@ classifiers = [ "License :: OSI Approved :: Apache Software License" ] -[project.optional-dependencies] -datalib = ["numpy >= 1", "pandas >= 1.2.3", "pandas-stubs >= 1.1.0.11"] - [project.urls] Homepage = "https://github.com/openai/openai-python" Repository = "https://github.com/openai/openai-python" @@ -45,6 +42,10 @@ Repository = "https://github.com/openai/openai-python" [project.scripts] openai = "openai.cli:main" +[project.optional-dependencies] +realtime = ["websockets >= 13, < 15"] +datalib = ["numpy >= 1", "pandas >= 1.2.3", "pandas-stubs >= 1.1.0.11"] + [tool.rye] managed = true # version pins are in requirements-dev.lock diff --git a/requirements-dev.lock b/requirements-dev.lock index 2cf6ab5ea9..94cf6aca07 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -185,5 +185,7 @@ urllib3==2.2.1 # via requests virtualenv==20.24.5 # via nox +websockets==14.1 + # via openai zipp==3.17.0 # via importlib-metadata diff --git a/requirements.lock b/requirements.lock index 826f0bc927..c10449ac20 100644 --- a/requirements.lock +++ b/requirements.lock @@ -64,3 +64,5 @@ typing-extensions==4.12.2 # via pydantic-core tzdata==2024.1 # via pandas +websockets==14.1 + # via openai diff --git a/src/openai/_client.py b/src/openai/_client.py index 5419e88f06..c784694f20 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -63,6 +63,14 @@ class OpenAI(SyncAPIClient): organization: str | None project: str | None + websocket_base_url: str | httpx.URL | None + """Base URL for WebSocket connections. + + If not specified, the default base URL will be used, with 'wss://' replacing the + 'http://' or 'https://' scheme. For example: 'http://example.com/' becomes + 'wss://example.com' + """ + def __init__( self, *, @@ -70,6 +78,7 @@ def __init__( organization: str | None = None, project: str | None = None, base_url: str | httpx.URL | None = None, + websocket_base_url: str | httpx.URL | None = None, timeout: Union[float, Timeout, None, NotGiven] = NOT_GIVEN, max_retries: int = DEFAULT_MAX_RETRIES, default_headers: Mapping[str, str] | None = None, @@ -111,6 +120,8 @@ def __init__( project = os.environ.get("OPENAI_PROJECT_ID") self.project = project + self.websocket_base_url = websocket_base_url + if base_url is None: base_url = os.environ.get("OPENAI_BASE_URL") if base_url is None: @@ -172,6 +183,7 @@ def copy( api_key: str | None = None, organization: str | None = None, project: str | None = None, + websocket_base_url: str | httpx.URL | None = None, base_url: str | httpx.URL | None = None, timeout: float | Timeout | None | NotGiven = NOT_GIVEN, http_client: httpx.Client | None = None, @@ -208,6 +220,7 @@ def copy( api_key=api_key or self.api_key, organization=organization or self.organization, project=project or self.project, + websocket_base_url=websocket_base_url or self.websocket_base_url, base_url=base_url or self.base_url, timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, http_client=http_client, @@ -277,6 +290,14 @@ class AsyncOpenAI(AsyncAPIClient): organization: str | None project: str | None + websocket_base_url: str | httpx.URL | None + """Base URL for WebSocket connections. + + If not specified, the default base URL will be used, with 'wss://' replacing the + 'http://' or 'https://' scheme. For example: 'http://example.com/' becomes + 'wss://example.com' + """ + def __init__( self, *, @@ -284,6 +305,7 @@ def __init__( organization: str | None = None, project: str | None = None, base_url: str | httpx.URL | None = None, + websocket_base_url: str | httpx.URL | None = None, timeout: Union[float, Timeout, None, NotGiven] = NOT_GIVEN, max_retries: int = DEFAULT_MAX_RETRIES, default_headers: Mapping[str, str] | None = None, @@ -325,6 +347,8 @@ def __init__( project = os.environ.get("OPENAI_PROJECT_ID") self.project = project + self.websocket_base_url = websocket_base_url + if base_url is None: base_url = os.environ.get("OPENAI_BASE_URL") if base_url is None: @@ -386,6 +410,7 @@ def copy( api_key: str | None = None, organization: str | None = None, project: str | None = None, + websocket_base_url: str | httpx.URL | None = None, base_url: str | httpx.URL | None = None, timeout: float | Timeout | None | NotGiven = NOT_GIVEN, http_client: httpx.AsyncClient | None = None, @@ -422,6 +447,7 @@ def copy( api_key=api_key or self.api_key, organization=organization or self.organization, project=project or self.project, + websocket_base_url=websocket_base_url or self.websocket_base_url, base_url=base_url or self.base_url, timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, http_client=http_client, diff --git a/src/openai/lib/azure.py b/src/openai/lib/azure.py index 54122dbecb..13d9f31838 100644 --- a/src/openai/lib/azure.py +++ b/src/openai/lib/azure.py @@ -76,6 +76,7 @@ def __init__( azure_ad_token: str | None = None, azure_ad_token_provider: AzureADTokenProvider | None = None, organization: str | None = None, + websocket_base_url: str | httpx.URL | None = None, timeout: float | Timeout | None | NotGiven = NOT_GIVEN, max_retries: int = DEFAULT_MAX_RETRIES, default_headers: Mapping[str, str] | None = None, @@ -94,6 +95,7 @@ def __init__( azure_ad_token: str | None = None, azure_ad_token_provider: AzureADTokenProvider | None = None, organization: str | None = None, + websocket_base_url: str | httpx.URL | None = None, timeout: float | Timeout | None | NotGiven = NOT_GIVEN, max_retries: int = DEFAULT_MAX_RETRIES, default_headers: Mapping[str, str] | None = None, @@ -112,6 +114,7 @@ def __init__( azure_ad_token: str | None = None, azure_ad_token_provider: AzureADTokenProvider | None = None, organization: str | None = None, + websocket_base_url: str | httpx.URL | None = None, timeout: float | Timeout | None | NotGiven = NOT_GIVEN, max_retries: int = DEFAULT_MAX_RETRIES, default_headers: Mapping[str, str] | None = None, @@ -131,6 +134,7 @@ def __init__( azure_ad_token_provider: AzureADTokenProvider | None = None, organization: str | None = None, project: str | None = None, + websocket_base_url: str | httpx.URL | None = None, base_url: str | None = None, timeout: float | Timeout | None | NotGiven = NOT_GIVEN, max_retries: int = DEFAULT_MAX_RETRIES, @@ -214,6 +218,7 @@ def __init__( default_headers=default_headers, default_query=default_query, http_client=http_client, + websocket_base_url=websocket_base_url, _strict_response_validation=_strict_response_validation, ) self._api_version = api_version @@ -227,6 +232,7 @@ def copy( api_key: str | None = None, organization: str | None = None, project: str | None = None, + websocket_base_url: str | httpx.URL | None = None, api_version: str | None = None, azure_ad_token: str | None = None, azure_ad_token_provider: AzureADTokenProvider | None = None, @@ -247,6 +253,7 @@ def copy( api_key=api_key, organization=organization, project=project, + websocket_base_url=websocket_base_url, base_url=base_url, timeout=timeout, http_client=http_client, @@ -314,6 +321,7 @@ def __init__( azure_ad_token_provider: AsyncAzureADTokenProvider | None = None, organization: str | None = None, project: str | None = None, + websocket_base_url: str | httpx.URL | None = None, timeout: float | Timeout | None | NotGiven = NOT_GIVEN, max_retries: int = DEFAULT_MAX_RETRIES, default_headers: Mapping[str, str] | None = None, @@ -333,6 +341,7 @@ def __init__( azure_ad_token_provider: AsyncAzureADTokenProvider | None = None, organization: str | None = None, project: str | None = None, + websocket_base_url: str | httpx.URL | None = None, timeout: float | Timeout | None | NotGiven = NOT_GIVEN, max_retries: int = DEFAULT_MAX_RETRIES, default_headers: Mapping[str, str] | None = None, @@ -352,6 +361,7 @@ def __init__( azure_ad_token_provider: AsyncAzureADTokenProvider | None = None, organization: str | None = None, project: str | None = None, + websocket_base_url: str | httpx.URL | None = None, timeout: float | Timeout | None | NotGiven = NOT_GIVEN, max_retries: int = DEFAULT_MAX_RETRIES, default_headers: Mapping[str, str] | None = None, @@ -372,6 +382,7 @@ def __init__( organization: str | None = None, project: str | None = None, base_url: str | None = None, + websocket_base_url: str | httpx.URL | None = None, timeout: float | Timeout | None | NotGiven = NOT_GIVEN, max_retries: int = DEFAULT_MAX_RETRIES, default_headers: Mapping[str, str] | None = None, @@ -454,6 +465,7 @@ def __init__( default_headers=default_headers, default_query=default_query, http_client=http_client, + websocket_base_url=websocket_base_url, _strict_response_validation=_strict_response_validation, ) self._api_version = api_version @@ -467,6 +479,7 @@ def copy( api_key: str | None = None, organization: str | None = None, project: str | None = None, + websocket_base_url: str | httpx.URL | None = None, api_version: str | None = None, azure_ad_token: str | None = None, azure_ad_token_provider: AsyncAzureADTokenProvider | None = None, @@ -487,6 +500,7 @@ def copy( api_key=api_key, organization=organization, project=project, + websocket_base_url=websocket_base_url, base_url=base_url, timeout=timeout, http_client=http_client, diff --git a/src/openai/resources/beta/realtime/realtime.py b/src/openai/resources/beta/realtime/realtime.py index e57e0be503..c79fd46217 100644 --- a/src/openai/resources/beta/realtime/realtime.py +++ b/src/openai/resources/beta/realtime/realtime.py @@ -2,6 +2,15 @@ from __future__ import annotations +import json +import logging +from types import TracebackType +from typing import TYPE_CHECKING, Any, Iterator, cast +from typing_extensions import AsyncIterator + +import httpx +from pydantic import BaseModel + from .sessions import ( Sessions, AsyncSessions, @@ -10,11 +19,34 @@ SessionsWithStreamingResponse, AsyncSessionsWithStreamingResponse, ) +from ...._types import NOT_GIVEN, Query, Headers, NotGiven +from ...._utils import ( + maybe_transform, + strip_not_given, + async_maybe_transform, +) from ...._compat import cached_property +from ...._models import construct_type_unchecked from ...._resource import SyncAPIResource, AsyncAPIResource +from ...._exceptions import OpenAIError +from ...._base_client import _merge_mappings +from ....types.beta.realtime import session_update_event_param, response_create_event_param +from ....types.websocket_connection_options import WebsocketConnectionOptions +from ....types.beta.realtime.realtime_client_event import RealtimeClientEvent +from ....types.beta.realtime.realtime_server_event import RealtimeServerEvent +from ....types.beta.realtime.conversation_item_param import ConversationItemParam +from ....types.beta.realtime.realtime_client_event_param import RealtimeClientEventParam + +if TYPE_CHECKING: + from websockets.sync.client import ClientConnection as WebsocketConnection + from websockets.asyncio.client import ClientConnection as AsyncWebsocketConnection + + from ...._client import OpenAI, AsyncOpenAI __all__ = ["Realtime", "AsyncRealtime"] +log: logging.Logger = logging.getLogger(__name__) + class Realtime(SyncAPIResource): @cached_property @@ -40,6 +72,33 @@ def with_streaming_response(self) -> RealtimeWithStreamingResponse: """ return RealtimeWithStreamingResponse(self) + def connect( + self, + *, + model: str, + extra_query: Query = {}, + extra_headers: Headers = {}, + websocket_connection_options: WebsocketConnectionOptions = {}, + ) -> RealtimeConnectionManager: + """ + The Realtime API enables you to build low-latency, multi-modal conversational experiences. It currently supports text and audio as both input and output, as well as function calling. + + Some notable benefits of the API include: + + - Native speech-to-speech: Skipping an intermediate text format means low latency and nuanced output. + - Natural, steerable voices: The models have natural inflection and can laugh, whisper, and adhere to tone direction. + - Simultaneous multimodal output: Text is useful for moderation; faster-than-realtime audio ensures stable playback. + + The Realtime API is a stateful, event-based API that communicates over a WebSocket. + """ + return RealtimeConnectionManager( + client=self._client, + extra_query=extra_query, + extra_headers=extra_headers, + websocket_connection_options=websocket_connection_options, + model=model, + ) + class AsyncRealtime(AsyncAPIResource): @cached_property @@ -65,6 +124,33 @@ def with_streaming_response(self) -> AsyncRealtimeWithStreamingResponse: """ return AsyncRealtimeWithStreamingResponse(self) + def connect( + self, + *, + model: str, + extra_query: Query = {}, + extra_headers: Headers = {}, + websocket_connection_options: WebsocketConnectionOptions = {}, + ) -> AsyncRealtimeConnectionManager: + """ + The Realtime API enables you to build low-latency, multi-modal conversational experiences. It currently supports text and audio as both input and output, as well as function calling. + + Some notable benefits of the API include: + + - Native speech-to-speech: Skipping an intermediate text format means low latency and nuanced output. + - Natural, steerable voices: The models have natural inflection and can laugh, whisper, and adhere to tone direction. + - Simultaneous multimodal output: Text is useful for moderation; faster-than-realtime audio ensures stable playback. + + The Realtime API is a stateful, event-based API that communicates over a WebSocket. + """ + return AsyncRealtimeConnectionManager( + client=self._client, + extra_query=extra_query, + extra_headers=extra_headers, + websocket_connection_options=websocket_connection_options, + model=model, + ) + class RealtimeWithRawResponse: def __init__(self, realtime: Realtime) -> None: @@ -100,3 +186,769 @@ def __init__(self, realtime: AsyncRealtime) -> None: @cached_property def sessions(self) -> AsyncSessionsWithStreamingResponse: return AsyncSessionsWithStreamingResponse(self._realtime.sessions) + + +class AsyncRealtimeConnection: + """Represents a live websocket connection to the Realtime API""" + + session: AsyncRealtimeSessionResource + response: AsyncRealtimeResponseResource + conversation: AsyncRealtimeConversationResource + input_audio_buffer: AsyncRealtimeInputAudioBufferResource + + _connection: AsyncWebsocketConnection + + def __init__(self, connection: AsyncWebsocketConnection) -> None: + self._connection = connection + + self.session = AsyncRealtimeSessionResource(self) + self.response = AsyncRealtimeResponseResource(self) + self.conversation = AsyncRealtimeConversationResource(self) + self.input_audio_buffer = AsyncRealtimeInputAudioBufferResource(self) + + async def __aiter__(self) -> AsyncIterator[RealtimeServerEvent]: + """ + An infinite-iterator that will continue to yield events until + the connection is closed. + """ + from websockets.exceptions import ConnectionClosedOK + + try: + while True: + yield await self.recv() + except ConnectionClosedOK: + return + + async def recv(self) -> RealtimeServerEvent: + """ + Receive the next message from the connection and parses it into a `RealtimeServerEvent` object. + + Canceling this method is safe. There's no risk of losing data. + """ + return self.parse_event(await self.recv_bytes()) + + async def recv_bytes(self) -> bytes: + """Receive the next message from the connection as raw bytes. + + Canceling this method is safe. There's no risk of losing data. + + If you want to parse the message into a `RealtimeServerEvent` object like `.recv()` does, + then you can call `.parse_event(data)`. + """ + message = await self._connection.recv(decode=False) + log.debug(f"Received websocket message: %s", message) + if not isinstance(message, bytes): + # passing `decode=False` should always result in us getting `bytes` back + raise TypeError(f"Expected `.recv(decode=False)` to return `bytes` but got {type(message)}") + + return message + + async def send(self, event: RealtimeClientEvent | RealtimeClientEventParam) -> None: + data = ( + event.to_json(use_api_names=True, exclude_defaults=True, exclude_unset=True) + if isinstance(event, BaseModel) + else json.dumps(await async_maybe_transform(event, RealtimeClientEventParam)) + ) + await self._connection.send(data) + + async def close(self, *, code: int = 1000, reason: str = "") -> None: + await self._connection.close(code=code, reason=reason) + + def parse_event(self, data: str | bytes) -> RealtimeServerEvent: + """ + Converts a raw `str` or `bytes` message into a `RealtimeServerEvent` object. + + This is helpful if you're using `.recv_bytes()`. + """ + return cast( + RealtimeServerEvent, construct_type_unchecked(value=json.loads(data), type_=cast(Any, RealtimeServerEvent)) + ) + + +class AsyncRealtimeConnectionManager: + """ + Context manager over a `AsyncRealtimeConnection` that is returned by `beta.realtime.connect()` + + This context manager ensures that the connection will be closed when it exits. + + --- + + Note that if your application doesn't work well with the context manager approach then you + can call the `.enter()` method directly to initiate a connection. + + **Warning**: You must remember to close the connection with `.close()`. + + ```py + connection = await client.beta.realtime.connect(...).enter() + # ... + await connection.close() + ``` + """ + + def __init__( + self, + *, + client: AsyncOpenAI, + model: str, + extra_query: Query, + extra_headers: Headers, + websocket_connection_options: WebsocketConnectionOptions, + ) -> None: + self.__client = client + self.__model = model + self.__connection: AsyncRealtimeConnection | None = None + self.__extra_query = extra_query + self.__extra_headers = extra_headers + self.__websocket_connection_options = websocket_connection_options + + async def __aenter__(self) -> AsyncRealtimeConnection: + """ + 👋 If your application doesn't work well with the context manager approach then you + can call this method directly to initiate a connection. + + **Warning**: You must remember to close the connection with `.close()`. + + ```py + connection = await client.beta.realtime.connect(...).enter() + # ... + await connection.close() + ``` + """ + try: + from websockets.asyncio.client import connect + except ImportError as exc: + raise OpenAIError("You need to install `openai[realtime]` to use this method") from exc + + url = self._prepare_url().copy_with( + params={ + **self.__client.base_url.params, + "model": self.__model, + **self.__extra_query, + }, + ) + log.debug("Connecting to %s", url) + if self.__websocket_connection_options: + log.debug("Connection options: %s", self.__websocket_connection_options) + + self.__connection = AsyncRealtimeConnection( + await connect( + str(url), + user_agent_header=self.__client.user_agent, + additional_headers=_merge_mappings( + { + **self.__client.auth_headers, + "OpenAI-Beta": "realtime=v1", + }, + self.__extra_headers, + ), + **self.__websocket_connection_options, + ) + ) + + return self.__connection + + enter = __aenter__ + + def _prepare_url(http://github.com/self) -> httpx.URL: + if self.__client.websocket_base_url is not None: + base_url = httpx.URL(self.__client.websocket_base_url) + else: + base_url = self.__client._base_url.copy_with(scheme="wss") + + merge_raw_path = base_url.raw_path.rstrip(b"/") + b"/realtime" + return base_url.copy_with(raw_path=merge_raw_path) + + async def __aexit__( + self, exc_type: type[BaseException] | None, exc: BaseException | None, exc_tb: TracebackType | None + ) -> None: + if self.__connection is not None: + await self.__connection.close() + + +class RealtimeConnection: + """Represents a live websocket connection to the Realtime API""" + + session: RealtimeSessionResource + response: RealtimeResponseResource + conversation: RealtimeConversationResource + input_audio_buffer: RealtimeInputAudioBufferResource + + _connection: WebsocketConnection + + def __init__(self, connection: WebsocketConnection) -> None: + self._connection = connection + + self.session = RealtimeSessionResource(self) + self.response = RealtimeResponseResource(self) + self.conversation = RealtimeConversationResource(self) + self.input_audio_buffer = RealtimeInputAudioBufferResource(self) + + def __iter__(self) -> Iterator[RealtimeServerEvent]: + """ + An infinite-iterator that will continue to yield events until + the connection is closed. + """ + from websockets.exceptions import ConnectionClosedOK + + try: + while True: + yield self.recv() + except ConnectionClosedOK: + return + + def recv(self) -> RealtimeServerEvent: + """ + Receive the next message from the connection and parses it into a `RealtimeServerEvent` object. + + Canceling this method is safe. There's no risk of losing data. + """ + return self.parse_event(self.recv_bytes()) + + def recv_bytes(self) -> bytes: + """Receive the next message from the connection as raw bytes. + + Canceling this method is safe. There's no risk of losing data. + + If you want to parse the message into a `RealtimeServerEvent` object like `.recv()` does, + then you can call `.parse_event(data)`. + """ + message = self._connection.recv(decode=False) + log.debug(f"Received websocket message: %s", message) + if not isinstance(message, bytes): + # passing `decode=False` should always result in us getting `bytes` back + raise TypeError(f"Expected `.recv(decode=False)` to return `bytes` but got {type(message)}") + + return message + + def send(self, event: RealtimeClientEvent | RealtimeClientEventParam) -> None: + data = ( + event.to_json(use_api_names=True, exclude_defaults=True, exclude_unset=True) + if isinstance(event, BaseModel) + else json.dumps(maybe_transform(event, RealtimeClientEventParam)) + ) + self._connection.send(data) + + def close(self, *, code: int = 1000, reason: str = "") -> None: + self._connection.close(code=code, reason=reason) + + def parse_event(self, data: str | bytes) -> RealtimeServerEvent: + """ + Converts a raw `str` or `bytes` message into a `RealtimeServerEvent` object. + + This is helpful if you're using `.recv_bytes()`. + """ + return cast( + RealtimeServerEvent, construct_type_unchecked(value=json.loads(data), type_=cast(Any, RealtimeServerEvent)) + ) + + +class RealtimeConnectionManager: + """ + Context manager over a `RealtimeConnection` that is returned by `beta.realtime.connect()` + + This context manager ensures that the connection will be closed when it exits. + + --- + + Note that if your application doesn't work well with the context manager approach then you + can call the `.enter()` method directly to initiate a connection. + + **Warning**: You must remember to close the connection with `.close()`. + + ```py + connection = client.beta.realtime.connect(...).enter() + # ... + connection.close() + ``` + """ + + def __init__( + self, + *, + client: OpenAI, + model: str, + extra_query: Query, + extra_headers: Headers, + websocket_connection_options: WebsocketConnectionOptions, + ) -> None: + self.__client = client + self.__model = model + self.__connection: RealtimeConnection | None = None + self.__extra_query = extra_query + self.__extra_headers = extra_headers + self.__websocket_connection_options = websocket_connection_options + + def __enter__(self) -> RealtimeConnection: + """ + 👋 If your application doesn't work well with the context manager approach then you + can call this method directly to initiate a connection. + + **Warning**: You must remember to close the connection with `.close()`. + + ```py + connection = client.beta.realtime.connect(...).enter() + # ... + connection.close() + ``` + """ + try: + from websockets.sync.client import connect + except ImportError as exc: + raise OpenAIError("You need to install `openai[realtime]` to use this method") from exc + + url = self._prepare_url().copy_with( + params={ + **self.__client.base_url.params, + "model": self.__model, + **self.__extra_query, + }, + ) + log.debug("Connecting to %s", url) + if self.__websocket_connection_options: + log.debug("Connection options: %s", self.__websocket_connection_options) + + self.__connection = RealtimeConnection( + connect( + str(url), + user_agent_header=self.__client.user_agent, + additional_headers=_merge_mappings( + { + **self.__client.auth_headers, + "OpenAI-Beta": "realtime=v1", + }, + self.__extra_headers, + ), + **self.__websocket_connection_options, + ) + ) + + return self.__connection + + enter = __enter__ + + def _prepare_url(http://github.com/self) -> httpx.URL: + if self.__client.websocket_base_url is not None: + base_url = httpx.URL(self.__client.websocket_base_url) + else: + base_url = self.__client._base_url.copy_with(scheme="wss") + + merge_raw_path = base_url.raw_path.rstrip(b"/") + b"/realtime" + return base_url.copy_with(raw_path=merge_raw_path) + + def __exit__( + self, exc_type: type[BaseException] | None, exc: BaseException | None, exc_tb: TracebackType | None + ) -> None: + if self.__connection is not None: + self.__connection.close() + + +class BaseRealtimeConnectionResource: + def __init__(self, connection: RealtimeConnection) -> None: + self._connection = connection + + +class RealtimeSessionResource(BaseRealtimeConnectionResource): + def update(self, *, session: session_update_event_param.Session, event_id: str | NotGiven = NOT_GIVEN) -> None: + """Send this event to update the session’s default configuration. + + The client may + send this event at any time to update the session configuration, and any + field may be updated at any time, except for "voice". The server will respond + with a `session.updated` event that shows the full effective configuration. + Only fields that are present are updated, thus the correct way to clear a + field like "instructions" is to pass an empty string. + """ + self._connection.send( + cast( + RealtimeClientEventParam, + strip_not_given({"type": "session.update", "session": session, "event_id": event_id}), + ) + ) + + +class RealtimeResponseResource(BaseRealtimeConnectionResource): + def cancel(self, *, event_id: str | NotGiven = NOT_GIVEN, response_id: str | NotGiven = NOT_GIVEN) -> None: + """Send this event to cancel an in-progress response. + + The server will respond + with a `response.cancelled` event or an error if there is no response to + cancel. + """ + self._connection.send( + cast( + RealtimeClientEventParam, + strip_not_given({"type": "response.cancel", "event_id": event_id, "response_id": response_id}), + ) + ) + + def create( + self, + *, + event_id: str | NotGiven = NOT_GIVEN, + response: response_create_event_param.Response | NotGiven = NOT_GIVEN, + ) -> None: + """ + This event instructs the server to create a Response, which means triggering + model inference. When in Server VAD mode, the server will create Responses + automatically. + + A Response will include at least one Item, and may have two, in which case + the second will be a function call. These Items will be appended to the + conversation history. + + The server will respond with a `response.created` event, events for Items + and content created, and finally a `response.done` event to indicate the + Response is complete. + + The `response.create` event includes inference configuration like + `instructions`, and `temperature`. These fields will override the Session's + configuration for this Response only. + """ + self._connection.send( + cast( + RealtimeClientEventParam, + strip_not_given({"type": "response.create", "event_id": event_id, "response": response}), + ) + ) + + +class RealtimeConversationResource(BaseRealtimeConnectionResource): + @cached_property + def item(self) -> RealtimeConversationItemResource: + return RealtimeConversationItemResource(self._connection) + + +class RealtimeConversationItemResource(BaseRealtimeConnectionResource): + def delete(self, *, item_id: str, event_id: str | NotGiven = NOT_GIVEN) -> None: + """Send this event when you want to remove any item from the conversation + history. + + The server will respond with a `conversation.item.deleted` event, + unless the item does not exist in the conversation history, in which case the + server will respond with an error. + """ + self._connection.send( + cast( + RealtimeClientEventParam, + strip_not_given({"type": "conversation.item.delete", "item_id": item_id, "event_id": event_id}), + ) + ) + + def create( + self, + *, + item: ConversationItemParam, + event_id: str | NotGiven = NOT_GIVEN, + previous_item_id: str | NotGiven = NOT_GIVEN, + ) -> None: + """ + Add a new Item to the Conversation's context, including messages, function + calls, and function call responses. This event can be used both to populate a + "history" of the conversation and to add new items mid-stream, but has the + current limitation that it cannot populate assistant audio messages. + + If successful, the server will respond with a `conversation.item.created` + event, otherwise an `error` event will be sent. + """ + self._connection.send( + cast( + RealtimeClientEventParam, + strip_not_given( + { + "type": "conversation.item.create", + "item": item, + "event_id": event_id, + "previous_item_id": previous_item_id, + } + ), + ) + ) + + def truncate( + self, *, audio_end_ms: int, content_index: int, item_id: str, event_id: str | NotGiven = NOT_GIVEN + ) -> None: + """Send this event to truncate a previous assistant message’s audio. + + The server + will produce audio faster than realtime, so this event is useful when the user + interrupts to truncate audio that has already been sent to the client but not + yet played. This will synchronize the server's understanding of the audio with + the client's playback. + + Truncating audio will delete the server-side text transcript to ensure there + is not text in the context that hasn't been heard by the user. + + If successful, the server will respond with a `conversation.item.truncated` + event. + """ + self._connection.send( + cast( + RealtimeClientEventParam, + strip_not_given( + { + "type": "conversation.item.truncate", + "audio_end_ms": audio_end_ms, + "content_index": content_index, + "item_id": item_id, + "event_id": event_id, + } + ), + ) + ) + + +class RealtimeInputAudioBufferResource(BaseRealtimeConnectionResource): + def clear(self, *, event_id: str | NotGiven = NOT_GIVEN) -> None: + """Send this event to clear the audio bytes in the buffer. + + The server will + respond with an `input_audio_buffer.cleared` event. + """ + self._connection.send( + cast(RealtimeClientEventParam, strip_not_given({"type": "input_audio_buffer.clear", "event_id": event_id})) + ) + + def commit(self, *, event_id: str | NotGiven = NOT_GIVEN) -> None: + """ + Send this event to commit the user input audio buffer, which will create a + new user message item in the conversation. This event will produce an error + if the input audio buffer is empty. When in Server VAD mode, the client does + not need to send this event, the server will commit the audio buffer + automatically. + + Committing the input audio buffer will trigger input audio transcription + (if enabled in session configuration), but it will not create a response + from the model. The server will respond with an `input_audio_buffer.committed` + event. + """ + self._connection.send( + cast(RealtimeClientEventParam, strip_not_given({"type": "input_audio_buffer.commit", "event_id": event_id})) + ) + + def append(self, *, audio: str, event_id: str | NotGiven = NOT_GIVEN) -> None: + """Send this event to append audio bytes to the input audio buffer. + + The audio + buffer is temporary storage you can write to and later commit. In Server VAD + mode, the audio buffer is used to detect speech and the server will decide + when to commit. When Server VAD is disabled, you must commit the audio buffer + manually. + + The client may choose how much audio to place in each event up to a maximum + of 15 MiB, for example streaming smaller chunks from the client may allow the + VAD to be more responsive. Unlike made other client events, the server will + not send a confirmation response to this event. + """ + self._connection.send( + cast( + RealtimeClientEventParam, + strip_not_given({"type": "input_audio_buffer.append", "audio": audio, "event_id": event_id}), + ) + ) + + +class BaseAsyncRealtimeConnectionResource: + def __init__(self, connection: AsyncRealtimeConnection) -> None: + self._connection = connection + + +class AsyncRealtimeSessionResource(BaseAsyncRealtimeConnectionResource): + async def update( + self, *, session: session_update_event_param.Session, event_id: str | NotGiven = NOT_GIVEN + ) -> None: + """Send this event to update the session’s default configuration. + + The client may + send this event at any time to update the session configuration, and any + field may be updated at any time, except for "voice". The server will respond + with a `session.updated` event that shows the full effective configuration. + Only fields that are present are updated, thus the correct way to clear a + field like "instructions" is to pass an empty string. + """ + await self._connection.send( + cast( + RealtimeClientEventParam, + strip_not_given({"type": "session.update", "session": session, "event_id": event_id}), + ) + ) + + +class AsyncRealtimeResponseResource(BaseAsyncRealtimeConnectionResource): + async def cancel(self, *, event_id: str | NotGiven = NOT_GIVEN, response_id: str | NotGiven = NOT_GIVEN) -> None: + """Send this event to cancel an in-progress response. + + The server will respond + with a `response.cancelled` event or an error if there is no response to + cancel. + """ + await self._connection.send( + cast( + RealtimeClientEventParam, + strip_not_given({"type": "response.cancel", "event_id": event_id, "response_id": response_id}), + ) + ) + + async def create( + self, + *, + event_id: str | NotGiven = NOT_GIVEN, + response: response_create_event_param.Response | NotGiven = NOT_GIVEN, + ) -> None: + """ + This event instructs the server to create a Response, which means triggering + model inference. When in Server VAD mode, the server will create Responses + automatically. + + A Response will include at least one Item, and may have two, in which case + the second will be a function call. These Items will be appended to the + conversation history. + + The server will respond with a `response.created` event, events for Items + and content created, and finally a `response.done` event to indicate the + Response is complete. + + The `response.create` event includes inference configuration like + `instructions`, and `temperature`. These fields will override the Session's + configuration for this Response only. + """ + await self._connection.send( + cast( + RealtimeClientEventParam, + strip_not_given({"type": "response.create", "event_id": event_id, "response": response}), + ) + ) + + +class AsyncRealtimeConversationResource(BaseAsyncRealtimeConnectionResource): + @cached_property + def item(self) -> AsyncRealtimeConversationItemResource: + return AsyncRealtimeConversationItemResource(self._connection) + + +class AsyncRealtimeConversationItemResource(BaseAsyncRealtimeConnectionResource): + async def delete(self, *, item_id: str, event_id: str | NotGiven = NOT_GIVEN) -> None: + """Send this event when you want to remove any item from the conversation + history. + + The server will respond with a `conversation.item.deleted` event, + unless the item does not exist in the conversation history, in which case the + server will respond with an error. + """ + await self._connection.send( + cast( + RealtimeClientEventParam, + strip_not_given({"type": "conversation.item.delete", "item_id": item_id, "event_id": event_id}), + ) + ) + + async def create( + self, + *, + item: ConversationItemParam, + event_id: str | NotGiven = NOT_GIVEN, + previous_item_id: str | NotGiven = NOT_GIVEN, + ) -> None: + """ + Add a new Item to the Conversation's context, including messages, function + calls, and function call responses. This event can be used both to populate a + "history" of the conversation and to add new items mid-stream, but has the + current limitation that it cannot populate assistant audio messages. + + If successful, the server will respond with a `conversation.item.created` + event, otherwise an `error` event will be sent. + """ + await self._connection.send( + cast( + RealtimeClientEventParam, + strip_not_given( + { + "type": "conversation.item.create", + "item": item, + "event_id": event_id, + "previous_item_id": previous_item_id, + } + ), + ) + ) + + async def truncate( + self, *, audio_end_ms: int, content_index: int, item_id: str, event_id: str | NotGiven = NOT_GIVEN + ) -> None: + """Send this event to truncate a previous assistant message’s audio. + + The server + will produce audio faster than realtime, so this event is useful when the user + interrupts to truncate audio that has already been sent to the client but not + yet played. This will synchronize the server's understanding of the audio with + the client's playback. + + Truncating audio will delete the server-side text transcript to ensure there + is not text in the context that hasn't been heard by the user. + + If successful, the server will respond with a `conversation.item.truncated` + event. + """ + await self._connection.send( + cast( + RealtimeClientEventParam, + strip_not_given( + { + "type": "conversation.item.truncate", + "audio_end_ms": audio_end_ms, + "content_index": content_index, + "item_id": item_id, + "event_id": event_id, + } + ), + ) + ) + + +class AsyncRealtimeInputAudioBufferResource(BaseAsyncRealtimeConnectionResource): + async def clear(self, *, event_id: str | NotGiven = NOT_GIVEN) -> None: + """Send this event to clear the audio bytes in the buffer. + + The server will + respond with an `input_audio_buffer.cleared` event. + """ + await self._connection.send( + cast(RealtimeClientEventParam, strip_not_given({"type": "input_audio_buffer.clear", "event_id": event_id})) + ) + + async def commit(self, *, event_id: str | NotGiven = NOT_GIVEN) -> None: + """ + Send this event to commit the user input audio buffer, which will create a + new user message item in the conversation. This event will produce an error + if the input audio buffer is empty. When in Server VAD mode, the client does + not need to send this event, the server will commit the audio buffer + automatically. + + Committing the input audio buffer will trigger input audio transcription + (if enabled in session configuration), but it will not create a response + from the model. The server will respond with an `input_audio_buffer.committed` + event. + """ + await self._connection.send( + cast(RealtimeClientEventParam, strip_not_given({"type": "input_audio_buffer.commit", "event_id": event_id})) + ) + + async def append(self, *, audio: str, event_id: str | NotGiven = NOT_GIVEN) -> None: + """Send this event to append audio bytes to the input audio buffer. + + The audio + buffer is temporary storage you can write to and later commit. In Server VAD + mode, the audio buffer is used to detect speech and the server will decide + when to commit. When Server VAD is disabled, you must commit the audio buffer + manually. + + The client may choose how much audio to place in each event up to a maximum + of 15 MiB, for example streaming smaller chunks from the client may allow the + VAD to be more responsive. Unlike made other client events, the server will + not send a confirmation response to this event. + """ + await self._connection.send( + cast( + RealtimeClientEventParam, + strip_not_given({"type": "input_audio_buffer.append", "audio": audio, "event_id": event_id}), + ) + ) diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index 7677be01b2..72950f2491 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -47,6 +47,7 @@ from .create_embedding_response import CreateEmbeddingResponse as CreateEmbeddingResponse from .moderation_create_response import ModerationCreateResponse as ModerationCreateResponse from .moderation_text_input_param import ModerationTextInputParam as ModerationTextInputParam +from .websocket_connection_options import WebsocketConnectionOptions as WebsocketConnectionOptions from .image_create_variation_params import ImageCreateVariationParams as ImageCreateVariationParams from .moderation_image_url_input_param import ModerationImageURLInputParam as ModerationImageURLInputParam from .moderation_multi_modal_input_param import ModerationMultiModalInputParam as ModerationMultiModalInputParam diff --git a/src/openai/types/beta/realtime/__init__.py b/src/openai/types/beta/realtime/__init__.py index 1c5246db7a..372d4ec19d 100644 --- a/src/openai/types/beta/realtime/__init__.py +++ b/src/openai/types/beta/realtime/__init__.py @@ -2,5 +2,79 @@ from __future__ import annotations +from .session import Session as Session +from .error_event import ErrorEvent as ErrorEvent +from .conversation_item import ConversationItem as ConversationItem +from .realtime_response import RealtimeResponse as RealtimeResponse +from .response_done_event import ResponseDoneEvent as ResponseDoneEvent +from .session_update_event import SessionUpdateEvent as SessionUpdateEvent +from .realtime_client_event import RealtimeClientEvent as RealtimeClientEvent +from .realtime_server_event import RealtimeServerEvent as RealtimeServerEvent +from .response_cancel_event import ResponseCancelEvent as ResponseCancelEvent +from .response_create_event import ResponseCreateEvent as ResponseCreateEvent from .session_create_params import SessionCreateParams as SessionCreateParams +from .session_created_event import SessionCreatedEvent as SessionCreatedEvent +from .session_updated_event import SessionUpdatedEvent as SessionUpdatedEvent +from .response_created_event import ResponseCreatedEvent as ResponseCreatedEvent +from .conversation_item_param import ConversationItemParam as ConversationItemParam +from .realtime_connect_params import RealtimeConnectParams as RealtimeConnectParams +from .realtime_response_usage import RealtimeResponseUsage as RealtimeResponseUsage from .session_create_response import SessionCreateResponse as SessionCreateResponse +from .realtime_response_status import RealtimeResponseStatus as RealtimeResponseStatus +from .response_text_done_event import ResponseTextDoneEvent as ResponseTextDoneEvent +from .conversation_item_content import ConversationItemContent as ConversationItemContent +from .rate_limits_updated_event import RateLimitsUpdatedEvent as RateLimitsUpdatedEvent +from .response_audio_done_event import ResponseAudioDoneEvent as ResponseAudioDoneEvent +from .response_text_delta_event import ResponseTextDeltaEvent as ResponseTextDeltaEvent +from .conversation_created_event import ConversationCreatedEvent as ConversationCreatedEvent +from .response_audio_delta_event import ResponseAudioDeltaEvent as ResponseAudioDeltaEvent +from .session_update_event_param import SessionUpdateEventParam as SessionUpdateEventParam +from .realtime_client_event_param import RealtimeClientEventParam as RealtimeClientEventParam +from .response_cancel_event_param import ResponseCancelEventParam as ResponseCancelEventParam +from .response_create_event_param import ResponseCreateEventParam as ResponseCreateEventParam +from .conversation_item_create_event import ConversationItemCreateEvent as ConversationItemCreateEvent +from .conversation_item_delete_event import ConversationItemDeleteEvent as ConversationItemDeleteEvent +from .input_audio_buffer_clear_event import InputAudioBufferClearEvent as InputAudioBufferClearEvent +from .conversation_item_content_param import ConversationItemContentParam as ConversationItemContentParam +from .conversation_item_created_event import ConversationItemCreatedEvent as ConversationItemCreatedEvent +from .conversation_item_deleted_event import ConversationItemDeletedEvent as ConversationItemDeletedEvent +from .input_audio_buffer_append_event import InputAudioBufferAppendEvent as InputAudioBufferAppendEvent +from .input_audio_buffer_commit_event import InputAudioBufferCommitEvent as InputAudioBufferCommitEvent +from .response_output_item_done_event import ResponseOutputItemDoneEvent as ResponseOutputItemDoneEvent +from .conversation_item_truncate_event import ConversationItemTruncateEvent as ConversationItemTruncateEvent +from .input_audio_buffer_cleared_event import InputAudioBufferClearedEvent as InputAudioBufferClearedEvent +from .response_content_part_done_event import ResponseContentPartDoneEvent as ResponseContentPartDoneEvent +from .response_output_item_added_event import ResponseOutputItemAddedEvent as ResponseOutputItemAddedEvent +from .conversation_item_truncated_event import ConversationItemTruncatedEvent as ConversationItemTruncatedEvent +from .response_content_part_added_event import ResponseContentPartAddedEvent as ResponseContentPartAddedEvent +from .input_audio_buffer_committed_event import InputAudioBufferCommittedEvent as InputAudioBufferCommittedEvent +from .conversation_item_create_event_param import ConversationItemCreateEventParam as ConversationItemCreateEventParam +from .conversation_item_delete_event_param import ConversationItemDeleteEventParam as ConversationItemDeleteEventParam +from .input_audio_buffer_clear_event_param import InputAudioBufferClearEventParam as InputAudioBufferClearEventParam +from .response_audio_transcript_done_event import ResponseAudioTranscriptDoneEvent as ResponseAudioTranscriptDoneEvent +from .input_audio_buffer_append_event_param import InputAudioBufferAppendEventParam as InputAudioBufferAppendEventParam +from .input_audio_buffer_commit_event_param import InputAudioBufferCommitEventParam as InputAudioBufferCommitEventParam +from .response_audio_transcript_delta_event import ( + ResponseAudioTranscriptDeltaEvent as ResponseAudioTranscriptDeltaEvent, +) +from .conversation_item_truncate_event_param import ( + ConversationItemTruncateEventParam as ConversationItemTruncateEventParam, +) +from .input_audio_buffer_speech_started_event import ( + InputAudioBufferSpeechStartedEvent as InputAudioBufferSpeechStartedEvent, +) +from .input_audio_buffer_speech_stopped_event import ( + InputAudioBufferSpeechStoppedEvent as InputAudioBufferSpeechStoppedEvent, +) +from .response_function_call_arguments_done_event import ( + ResponseFunctionCallArgumentsDoneEvent as ResponseFunctionCallArgumentsDoneEvent, +) +from .response_function_call_arguments_delta_event import ( + ResponseFunctionCallArgumentsDeltaEvent as ResponseFunctionCallArgumentsDeltaEvent, +) +from .conversation_item_input_audio_transcription_failed_event import ( + ConversationItemInputAudioTranscriptionFailedEvent as ConversationItemInputAudioTranscriptionFailedEvent, +) +from .conversation_item_input_audio_transcription_completed_event import ( + ConversationItemInputAudioTranscriptionCompletedEvent as ConversationItemInputAudioTranscriptionCompletedEvent, +) diff --git a/src/openai/types/beta/realtime/conversation_created_event.py b/src/openai/types/beta/realtime/conversation_created_event.py new file mode 100644 index 0000000000..4ba0540867 --- /dev/null +++ b/src/openai/types/beta/realtime/conversation_created_event.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["ConversationCreatedEvent", "Conversation"] + + +class Conversation(BaseModel): + id: Optional[str] = None + """The unique ID of the conversation.""" + + object: Optional[Literal["realtime.conversation"]] = None + """The object type, must be `realtime.conversation`.""" + + +class ConversationCreatedEvent(BaseModel): + conversation: Conversation + """The conversation resource.""" + + event_id: str + """The unique ID of the server event.""" + + type: Literal["conversation.created"] + """The event type, must be `conversation.created`.""" diff --git a/src/openai/types/beta/realtime/conversation_item.py b/src/openai/types/beta/realtime/conversation_item.py new file mode 100644 index 0000000000..4edf6c4d5f --- /dev/null +++ b/src/openai/types/beta/realtime/conversation_item.py @@ -0,0 +1,61 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from ...._models import BaseModel +from .conversation_item_content import ConversationItemContent + +__all__ = ["ConversationItem"] + + +class ConversationItem(BaseModel): + id: Optional[str] = None + """ + The unique ID of the item, this can be generated by the client to help manage + server-side context, but is not required because the server will generate one if + not provided. + """ + + arguments: Optional[str] = None + """The arguments of the function call (for `function_call` items).""" + + call_id: Optional[str] = None + """ + The ID of the function call (for `function_call` and `function_call_output` + items). If passed on a `function_call_output` item, the server will check that a + `function_call` item with the same ID exists in the conversation history. + """ + + content: Optional[List[ConversationItemContent]] = None + """The content of the message, applicable for `message` items. + + - Message items of role `system` support only `input_text` content + - Message items of role `user` support `input_text` and `input_audio` content + - Message items of role `assistant` support `text` content. + """ + + name: Optional[str] = None + """The name of the function being called (for `function_call` items).""" + + object: Optional[Literal["realtime.item"]] = None + """Identifier for the API object being returned - always `realtime.item`.""" + + output: Optional[str] = None + """The output of the function call (for `function_call_output` items).""" + + role: Optional[Literal["user", "assistant", "system"]] = None + """ + The role of the message sender (`user`, `assistant`, `system`), only applicable + for `message` items. + """ + + status: Optional[Literal["completed", "incomplete"]] = None + """The status of the item (`completed`, `incomplete`). + + These have no effect on the conversation, but are accepted for consistency with + the `conversation.item.created` event. + """ + + type: Optional[Literal["message", "function_call", "function_call_output"]] = None + """The type of the item (`message`, `function_call`, `function_call_output`).""" diff --git a/src/openai/types/beta/realtime/conversation_item_content.py b/src/openai/types/beta/realtime/conversation_item_content.py new file mode 100644 index 0000000000..b854aa0e0f --- /dev/null +++ b/src/openai/types/beta/realtime/conversation_item_content.py @@ -0,0 +1,28 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["ConversationItemContent"] + + +class ConversationItemContent(BaseModel): + id: Optional[str] = None + """ + ID of a previous conversation item (like a model response), used for + `item_reference` content types. + """ + + audio: Optional[str] = None + """Base64-encoded audio bytes, used for `input_audio` content type.""" + + text: Optional[str] = None + """The text content, used for `input_text` and `text` content types.""" + + transcript: Optional[str] = None + """The transcript of the audio, used for `input_audio` content type.""" + + type: Optional[Literal["input_text", "input_audio", "item_reference", "text"]] = None + """The content type (`input_text`, `input_audio`, `item_reference`, `text`).""" diff --git a/src/openai/types/beta/realtime/conversation_item_content_param.py b/src/openai/types/beta/realtime/conversation_item_content_param.py new file mode 100644 index 0000000000..b354d78971 --- /dev/null +++ b/src/openai/types/beta/realtime/conversation_item_content_param.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, TypedDict + +__all__ = ["ConversationItemContentParam"] + + +class ConversationItemContentParam(TypedDict, total=False): + id: str + """ + ID of a previous conversation item (like a model response), used for + `item_reference` content types. + """ + + audio: str + """Base64-encoded audio bytes, used for `input_audio` content type.""" + + text: str + """The text content, used for `input_text` and `text` content types.""" + + transcript: str + """The transcript of the audio, used for `input_audio` content type.""" + + type: Literal["input_text", "input_audio", "item_reference", "text"] + """The content type (`input_text`, `input_audio`, `item_reference`, `text`).""" diff --git a/src/openai/types/beta/realtime/conversation_item_create_event.py b/src/openai/types/beta/realtime/conversation_item_create_event.py new file mode 100644 index 0000000000..50d309675b --- /dev/null +++ b/src/openai/types/beta/realtime/conversation_item_create_event.py @@ -0,0 +1,28 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel +from .conversation_item import ConversationItem + +__all__ = ["ConversationItemCreateEvent"] + + +class ConversationItemCreateEvent(BaseModel): + item: ConversationItem + """The item to add to the conversation.""" + + type: Literal["conversation.item.create"] + """The event type, must be `conversation.item.create`.""" + + event_id: Optional[str] = None + """Optional client-generated ID used to identify this event.""" + + previous_item_id: Optional[str] = None + """The ID of the preceding item after which the new item will be inserted. + + If not set, the new item will be appended to the end of the conversation. If + set, it allows an item to be inserted mid-conversation. If the ID cannot be + found, an error will be returned and the item will not be added. + """ diff --git a/src/openai/types/beta/realtime/conversation_item_create_event_param.py b/src/openai/types/beta/realtime/conversation_item_create_event_param.py new file mode 100644 index 0000000000..b8c8bbc251 --- /dev/null +++ b/src/openai/types/beta/realtime/conversation_item_create_event_param.py @@ -0,0 +1,28 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +from .conversation_item_param import ConversationItemParam + +__all__ = ["ConversationItemCreateEventParam"] + + +class ConversationItemCreateEventParam(TypedDict, total=False): + item: Required[ConversationItemParam] + """The item to add to the conversation.""" + + type: Required[Literal["conversation.item.create"]] + """The event type, must be `conversation.item.create`.""" + + event_id: str + """Optional client-generated ID used to identify this event.""" + + previous_item_id: str + """The ID of the preceding item after which the new item will be inserted. + + If not set, the new item will be appended to the end of the conversation. If + set, it allows an item to be inserted mid-conversation. If the ID cannot be + found, an error will be returned and the item will not be added. + """ diff --git a/src/openai/types/beta/realtime/conversation_item_created_event.py b/src/openai/types/beta/realtime/conversation_item_created_event.py new file mode 100644 index 0000000000..2f20388246 --- /dev/null +++ b/src/openai/types/beta/realtime/conversation_item_created_event.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel +from .conversation_item import ConversationItem + +__all__ = ["ConversationItemCreatedEvent"] + + +class ConversationItemCreatedEvent(BaseModel): + event_id: str + """The unique ID of the server event.""" + + item: ConversationItem + """The item to add to the conversation.""" + + previous_item_id: str + """ + The ID of the preceding item in the Conversation context, allows the client to + understand the order of the conversation. + """ + + type: Literal["conversation.item.created"] + """The event type, must be `conversation.item.created`.""" diff --git a/src/openai/types/beta/realtime/conversation_item_delete_event.py b/src/openai/types/beta/realtime/conversation_item_delete_event.py new file mode 100644 index 0000000000..02ca8250ce --- /dev/null +++ b/src/openai/types/beta/realtime/conversation_item_delete_event.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["ConversationItemDeleteEvent"] + + +class ConversationItemDeleteEvent(BaseModel): + item_id: str + """The ID of the item to delete.""" + + type: Literal["conversation.item.delete"] + """The event type, must be `conversation.item.delete`.""" + + event_id: Optional[str] = None + """Optional client-generated ID used to identify this event.""" diff --git a/src/openai/types/beta/realtime/conversation_item_delete_event_param.py b/src/openai/types/beta/realtime/conversation_item_delete_event_param.py new file mode 100644 index 0000000000..c3f88d6627 --- /dev/null +++ b/src/openai/types/beta/realtime/conversation_item_delete_event_param.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ConversationItemDeleteEventParam"] + + +class ConversationItemDeleteEventParam(TypedDict, total=False): + item_id: Required[str] + """The ID of the item to delete.""" + + type: Required[Literal["conversation.item.delete"]] + """The event type, must be `conversation.item.delete`.""" + + event_id: str + """Optional client-generated ID used to identify this event.""" diff --git a/src/openai/types/beta/realtime/conversation_item_deleted_event.py b/src/openai/types/beta/realtime/conversation_item_deleted_event.py new file mode 100644 index 0000000000..a35a97817a --- /dev/null +++ b/src/openai/types/beta/realtime/conversation_item_deleted_event.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["ConversationItemDeletedEvent"] + + +class ConversationItemDeletedEvent(BaseModel): + event_id: str + """The unique ID of the server event.""" + + item_id: str + """The ID of the item that was deleted.""" + + type: Literal["conversation.item.deleted"] + """The event type, must be `conversation.item.deleted`.""" diff --git a/src/openai/types/beta/realtime/conversation_item_input_audio_transcription_completed_event.py b/src/openai/types/beta/realtime/conversation_item_input_audio_transcription_completed_event.py new file mode 100644 index 0000000000..ded79cc0f7 --- /dev/null +++ b/src/openai/types/beta/realtime/conversation_item_input_audio_transcription_completed_event.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["ConversationItemInputAudioTranscriptionCompletedEvent"] + + +class ConversationItemInputAudioTranscriptionCompletedEvent(BaseModel): + content_index: int + """The index of the content part containing the audio.""" + + event_id: str + """The unique ID of the server event.""" + + item_id: str + """The ID of the user message item containing the audio.""" + + transcript: str + """The transcribed text.""" + + type: Literal["conversation.item.input_audio_transcription.completed"] + """ + The event type, must be `conversation.item.input_audio_transcription.completed`. + """ diff --git a/src/openai/types/beta/realtime/conversation_item_input_audio_transcription_failed_event.py b/src/openai/types/beta/realtime/conversation_item_input_audio_transcription_failed_event.py new file mode 100644 index 0000000000..cecac93e64 --- /dev/null +++ b/src/openai/types/beta/realtime/conversation_item_input_audio_transcription_failed_event.py @@ -0,0 +1,39 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["ConversationItemInputAudioTranscriptionFailedEvent", "Error"] + + +class Error(BaseModel): + code: Optional[str] = None + """Error code, if any.""" + + message: Optional[str] = None + """A human-readable error message.""" + + param: Optional[str] = None + """Parameter related to the error, if any.""" + + type: Optional[str] = None + """The type of error.""" + + +class ConversationItemInputAudioTranscriptionFailedEvent(BaseModel): + content_index: int + """The index of the content part containing the audio.""" + + error: Error + """Details of the transcription error.""" + + event_id: str + """The unique ID of the server event.""" + + item_id: str + """The ID of the user message item.""" + + type: Literal["conversation.item.input_audio_transcription.failed"] + """The event type, must be `conversation.item.input_audio_transcription.failed`.""" diff --git a/src/openai/types/beta/realtime/conversation_item_param.py b/src/openai/types/beta/realtime/conversation_item_param.py new file mode 100644 index 0000000000..ac0f8431e5 --- /dev/null +++ b/src/openai/types/beta/realtime/conversation_item_param.py @@ -0,0 +1,62 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Literal, TypedDict + +from .conversation_item_content_param import ConversationItemContentParam + +__all__ = ["ConversationItemParam"] + + +class ConversationItemParam(TypedDict, total=False): + id: str + """ + The unique ID of the item, this can be generated by the client to help manage + server-side context, but is not required because the server will generate one if + not provided. + """ + + arguments: str + """The arguments of the function call (for `function_call` items).""" + + call_id: str + """ + The ID of the function call (for `function_call` and `function_call_output` + items). If passed on a `function_call_output` item, the server will check that a + `function_call` item with the same ID exists in the conversation history. + """ + + content: Iterable[ConversationItemContentParam] + """The content of the message, applicable for `message` items. + + - Message items of role `system` support only `input_text` content + - Message items of role `user` support `input_text` and `input_audio` content + - Message items of role `assistant` support `text` content. + """ + + name: str + """The name of the function being called (for `function_call` items).""" + + object: Literal["realtime.item"] + """Identifier for the API object being returned - always `realtime.item`.""" + + output: str + """The output of the function call (for `function_call_output` items).""" + + role: Literal["user", "assistant", "system"] + """ + The role of the message sender (`user`, `assistant`, `system`), only applicable + for `message` items. + """ + + status: Literal["completed", "incomplete"] + """The status of the item (`completed`, `incomplete`). + + These have no effect on the conversation, but are accepted for consistency with + the `conversation.item.created` event. + """ + + type: Literal["message", "function_call", "function_call_output"] + """The type of the item (`message`, `function_call`, `function_call_output`).""" diff --git a/src/openai/types/beta/realtime/conversation_item_truncate_event.py b/src/openai/types/beta/realtime/conversation_item_truncate_event.py new file mode 100644 index 0000000000..cb336bba2c --- /dev/null +++ b/src/openai/types/beta/realtime/conversation_item_truncate_event.py @@ -0,0 +1,32 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["ConversationItemTruncateEvent"] + + +class ConversationItemTruncateEvent(BaseModel): + audio_end_ms: int + """Inclusive duration up to which audio is truncated, in milliseconds. + + If the audio_end_ms is greater than the actual audio duration, the server will + respond with an error. + """ + + content_index: int + """The index of the content part to truncate. Set this to 0.""" + + item_id: str + """The ID of the assistant message item to truncate. + + Only assistant message items can be truncated. + """ + + type: Literal["conversation.item.truncate"] + """The event type, must be `conversation.item.truncate`.""" + + event_id: Optional[str] = None + """Optional client-generated ID used to identify this event.""" diff --git a/src/openai/types/beta/realtime/conversation_item_truncate_event_param.py b/src/openai/types/beta/realtime/conversation_item_truncate_event_param.py new file mode 100644 index 0000000000..d3ad1e1e25 --- /dev/null +++ b/src/openai/types/beta/realtime/conversation_item_truncate_event_param.py @@ -0,0 +1,31 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ConversationItemTruncateEventParam"] + + +class ConversationItemTruncateEventParam(TypedDict, total=False): + audio_end_ms: Required[int] + """Inclusive duration up to which audio is truncated, in milliseconds. + + If the audio_end_ms is greater than the actual audio duration, the server will + respond with an error. + """ + + content_index: Required[int] + """The index of the content part to truncate. Set this to 0.""" + + item_id: Required[str] + """The ID of the assistant message item to truncate. + + Only assistant message items can be truncated. + """ + + type: Required[Literal["conversation.item.truncate"]] + """The event type, must be `conversation.item.truncate`.""" + + event_id: str + """Optional client-generated ID used to identify this event.""" diff --git a/src/openai/types/beta/realtime/conversation_item_truncated_event.py b/src/openai/types/beta/realtime/conversation_item_truncated_event.py new file mode 100644 index 0000000000..36368fa28f --- /dev/null +++ b/src/openai/types/beta/realtime/conversation_item_truncated_event.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["ConversationItemTruncatedEvent"] + + +class ConversationItemTruncatedEvent(BaseModel): + audio_end_ms: int + """The duration up to which the audio was truncated, in milliseconds.""" + + content_index: int + """The index of the content part that was truncated.""" + + event_id: str + """The unique ID of the server event.""" + + item_id: str + """The ID of the assistant message item that was truncated.""" + + type: Literal["conversation.item.truncated"] + """The event type, must be `conversation.item.truncated`.""" diff --git a/src/openai/types/beta/realtime/error_event.py b/src/openai/types/beta/realtime/error_event.py new file mode 100644 index 0000000000..e020fc3848 --- /dev/null +++ b/src/openai/types/beta/realtime/error_event.py @@ -0,0 +1,36 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["ErrorEvent", "Error"] + + +class Error(BaseModel): + message: str + """A human-readable error message.""" + + type: str + """The type of error (e.g., "invalid_request_error", "server_error").""" + + code: Optional[str] = None + """Error code, if any.""" + + event_id: Optional[str] = None + """The event_id of the client event that caused the error, if applicable.""" + + param: Optional[str] = None + """Parameter related to the error, if any.""" + + +class ErrorEvent(BaseModel): + error: Error + """Details of the error.""" + + event_id: str + """The unique ID of the server event.""" + + type: Literal["error"] + """The event type, must be `error`.""" diff --git a/src/openai/types/beta/realtime/input_audio_buffer_append_event.py b/src/openai/types/beta/realtime/input_audio_buffer_append_event.py new file mode 100644 index 0000000000..a253a6488c --- /dev/null +++ b/src/openai/types/beta/realtime/input_audio_buffer_append_event.py @@ -0,0 +1,23 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["InputAudioBufferAppendEvent"] + + +class InputAudioBufferAppendEvent(BaseModel): + audio: str + """Base64-encoded audio bytes. + + This must be in the format specified by the `input_audio_format` field in the + session configuration. + """ + + type: Literal["input_audio_buffer.append"] + """The event type, must be `input_audio_buffer.append`.""" + + event_id: Optional[str] = None + """Optional client-generated ID used to identify this event.""" diff --git a/src/openai/types/beta/realtime/input_audio_buffer_append_event_param.py b/src/openai/types/beta/realtime/input_audio_buffer_append_event_param.py new file mode 100644 index 0000000000..3ad0bc737d --- /dev/null +++ b/src/openai/types/beta/realtime/input_audio_buffer_append_event_param.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["InputAudioBufferAppendEventParam"] + + +class InputAudioBufferAppendEventParam(TypedDict, total=False): + audio: Required[str] + """Base64-encoded audio bytes. + + This must be in the format specified by the `input_audio_format` field in the + session configuration. + """ + + type: Required[Literal["input_audio_buffer.append"]] + """The event type, must be `input_audio_buffer.append`.""" + + event_id: str + """Optional client-generated ID used to identify this event.""" diff --git a/src/openai/types/beta/realtime/input_audio_buffer_clear_event.py b/src/openai/types/beta/realtime/input_audio_buffer_clear_event.py new file mode 100644 index 0000000000..b0624d34df --- /dev/null +++ b/src/openai/types/beta/realtime/input_audio_buffer_clear_event.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["InputAudioBufferClearEvent"] + + +class InputAudioBufferClearEvent(BaseModel): + type: Literal["input_audio_buffer.clear"] + """The event type, must be `input_audio_buffer.clear`.""" + + event_id: Optional[str] = None + """Optional client-generated ID used to identify this event.""" diff --git a/src/openai/types/beta/realtime/input_audio_buffer_clear_event_param.py b/src/openai/types/beta/realtime/input_audio_buffer_clear_event_param.py new file mode 100644 index 0000000000..2bd6bc5a02 --- /dev/null +++ b/src/openai/types/beta/realtime/input_audio_buffer_clear_event_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["InputAudioBufferClearEventParam"] + + +class InputAudioBufferClearEventParam(TypedDict, total=False): + type: Required[Literal["input_audio_buffer.clear"]] + """The event type, must be `input_audio_buffer.clear`.""" + + event_id: str + """Optional client-generated ID used to identify this event.""" diff --git a/src/openai/types/beta/realtime/input_audio_buffer_cleared_event.py b/src/openai/types/beta/realtime/input_audio_buffer_cleared_event.py new file mode 100644 index 0000000000..632e1b94bc --- /dev/null +++ b/src/openai/types/beta/realtime/input_audio_buffer_cleared_event.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["InputAudioBufferClearedEvent"] + + +class InputAudioBufferClearedEvent(BaseModel): + event_id: str + """The unique ID of the server event.""" + + type: Literal["input_audio_buffer.cleared"] + """The event type, must be `input_audio_buffer.cleared`.""" diff --git a/src/openai/types/beta/realtime/input_audio_buffer_commit_event.py b/src/openai/types/beta/realtime/input_audio_buffer_commit_event.py new file mode 100644 index 0000000000..7b6f5e46b7 --- /dev/null +++ b/src/openai/types/beta/realtime/input_audio_buffer_commit_event.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["InputAudioBufferCommitEvent"] + + +class InputAudioBufferCommitEvent(BaseModel): + type: Literal["input_audio_buffer.commit"] + """The event type, must be `input_audio_buffer.commit`.""" + + event_id: Optional[str] = None + """Optional client-generated ID used to identify this event.""" diff --git a/src/openai/types/beta/realtime/input_audio_buffer_commit_event_param.py b/src/openai/types/beta/realtime/input_audio_buffer_commit_event_param.py new file mode 100644 index 0000000000..c9c927ab98 --- /dev/null +++ b/src/openai/types/beta/realtime/input_audio_buffer_commit_event_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["InputAudioBufferCommitEventParam"] + + +class InputAudioBufferCommitEventParam(TypedDict, total=False): + type: Required[Literal["input_audio_buffer.commit"]] + """The event type, must be `input_audio_buffer.commit`.""" + + event_id: str + """Optional client-generated ID used to identify this event.""" diff --git a/src/openai/types/beta/realtime/input_audio_buffer_committed_event.py b/src/openai/types/beta/realtime/input_audio_buffer_committed_event.py new file mode 100644 index 0000000000..3071eff357 --- /dev/null +++ b/src/openai/types/beta/realtime/input_audio_buffer_committed_event.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["InputAudioBufferCommittedEvent"] + + +class InputAudioBufferCommittedEvent(BaseModel): + event_id: str + """The unique ID of the server event.""" + + item_id: str + """The ID of the user message item that will be created.""" + + previous_item_id: str + """The ID of the preceding item after which the new item will be inserted.""" + + type: Literal["input_audio_buffer.committed"] + """The event type, must be `input_audio_buffer.committed`.""" diff --git a/src/openai/types/beta/realtime/input_audio_buffer_speech_started_event.py b/src/openai/types/beta/realtime/input_audio_buffer_speech_started_event.py new file mode 100644 index 0000000000..4f3ab082c4 --- /dev/null +++ b/src/openai/types/beta/realtime/input_audio_buffer_speech_started_event.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["InputAudioBufferSpeechStartedEvent"] + + +class InputAudioBufferSpeechStartedEvent(BaseModel): + audio_start_ms: int + """ + Milliseconds from the start of all audio written to the buffer during the + session when speech was first detected. This will correspond to the beginning of + audio sent to the model, and thus includes the `prefix_padding_ms` configured in + the Session. + """ + + event_id: str + """The unique ID of the server event.""" + + item_id: str + """The ID of the user message item that will be created when speech stops.""" + + type: Literal["input_audio_buffer.speech_started"] + """The event type, must be `input_audio_buffer.speech_started`.""" diff --git a/src/openai/types/beta/realtime/input_audio_buffer_speech_stopped_event.py b/src/openai/types/beta/realtime/input_audio_buffer_speech_stopped_event.py new file mode 100644 index 0000000000..40568170f2 --- /dev/null +++ b/src/openai/types/beta/realtime/input_audio_buffer_speech_stopped_event.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["InputAudioBufferSpeechStoppedEvent"] + + +class InputAudioBufferSpeechStoppedEvent(BaseModel): + audio_end_ms: int + """Milliseconds since the session started when speech stopped. + + This will correspond to the end of audio sent to the model, and thus includes + the `min_silence_duration_ms` configured in the Session. + """ + + event_id: str + """The unique ID of the server event.""" + + item_id: str + """The ID of the user message item that will be created.""" + + type: Literal["input_audio_buffer.speech_stopped"] + """The event type, must be `input_audio_buffer.speech_stopped`.""" diff --git a/src/openai/types/beta/realtime/rate_limits_updated_event.py b/src/openai/types/beta/realtime/rate_limits_updated_event.py new file mode 100644 index 0000000000..7e12283c46 --- /dev/null +++ b/src/openai/types/beta/realtime/rate_limits_updated_event.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["RateLimitsUpdatedEvent", "RateLimit"] + + +class RateLimit(BaseModel): + limit: Optional[int] = None + """The maximum allowed value for the rate limit.""" + + name: Optional[Literal["requests", "tokens"]] = None + """The name of the rate limit (`requests`, `tokens`).""" + + remaining: Optional[int] = None + """The remaining value before the limit is reached.""" + + reset_seconds: Optional[float] = None + """Seconds until the rate limit resets.""" + + +class RateLimitsUpdatedEvent(BaseModel): + event_id: str + """The unique ID of the server event.""" + + rate_limits: List[RateLimit] + """List of rate limit information.""" + + type: Literal["rate_limits.updated"] + """The event type, must be `rate_limits.updated`.""" diff --git a/src/openai/types/beta/realtime/realtime_client_event.py b/src/openai/types/beta/realtime/realtime_client_event.py new file mode 100644 index 0000000000..0769184cd0 --- /dev/null +++ b/src/openai/types/beta/realtime/realtime_client_event.py @@ -0,0 +1,32 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Annotated, TypeAlias + +from ...._utils import PropertyInfo +from .session_update_event import SessionUpdateEvent +from .response_cancel_event import ResponseCancelEvent +from .response_create_event import ResponseCreateEvent +from .conversation_item_create_event import ConversationItemCreateEvent +from .conversation_item_delete_event import ConversationItemDeleteEvent +from .input_audio_buffer_clear_event import InputAudioBufferClearEvent +from .input_audio_buffer_append_event import InputAudioBufferAppendEvent +from .input_audio_buffer_commit_event import InputAudioBufferCommitEvent +from .conversation_item_truncate_event import ConversationItemTruncateEvent + +__all__ = ["RealtimeClientEvent"] + +RealtimeClientEvent: TypeAlias = Annotated[ + Union[ + SessionUpdateEvent, + InputAudioBufferAppendEvent, + InputAudioBufferCommitEvent, + InputAudioBufferClearEvent, + ConversationItemCreateEvent, + ConversationItemTruncateEvent, + ConversationItemDeleteEvent, + ResponseCreateEvent, + ResponseCancelEvent, + ], + PropertyInfo(discriminator="type"), +] diff --git a/src/openai/types/beta/realtime/realtime_client_event_param.py b/src/openai/types/beta/realtime/realtime_client_event_param.py new file mode 100644 index 0000000000..4020892c33 --- /dev/null +++ b/src/openai/types/beta/realtime/realtime_client_event_param.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import TypeAlias + +from .session_update_event_param import SessionUpdateEventParam +from .response_cancel_event_param import ResponseCancelEventParam +from .response_create_event_param import ResponseCreateEventParam +from .conversation_item_create_event_param import ConversationItemCreateEventParam +from .conversation_item_delete_event_param import ConversationItemDeleteEventParam +from .input_audio_buffer_clear_event_param import InputAudioBufferClearEventParam +from .input_audio_buffer_append_event_param import InputAudioBufferAppendEventParam +from .input_audio_buffer_commit_event_param import InputAudioBufferCommitEventParam +from .conversation_item_truncate_event_param import ConversationItemTruncateEventParam + +__all__ = ["RealtimeClientEventParam"] + +RealtimeClientEventParam: TypeAlias = Union[ + SessionUpdateEventParam, + InputAudioBufferAppendEventParam, + InputAudioBufferCommitEventParam, + InputAudioBufferClearEventParam, + ConversationItemCreateEventParam, + ConversationItemTruncateEventParam, + ConversationItemDeleteEventParam, + ResponseCreateEventParam, + ResponseCancelEventParam, +] diff --git a/src/openai/types/beta/realtime/realtime_connect_params.py b/src/openai/types/beta/realtime/realtime_connect_params.py new file mode 100644 index 0000000000..76474f3de4 --- /dev/null +++ b/src/openai/types/beta/realtime/realtime_connect_params.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +__all__ = ["RealtimeConnectParams"] + + +class RealtimeConnectParams(TypedDict, total=False): + model: Required[str] diff --git a/src/openai/types/beta/realtime/realtime_response.py b/src/openai/types/beta/realtime/realtime_response.py new file mode 100644 index 0000000000..3e1b1406c0 --- /dev/null +++ b/src/openai/types/beta/realtime/realtime_response.py @@ -0,0 +1,42 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from ...._models import BaseModel +from .conversation_item import ConversationItem +from .realtime_response_usage import RealtimeResponseUsage +from .realtime_response_status import RealtimeResponseStatus + +__all__ = ["RealtimeResponse"] + + +class RealtimeResponse(BaseModel): + id: Optional[str] = None + """The unique ID of the response.""" + + metadata: Optional[object] = None + """Developer-provided string key-value pairs associated with this response.""" + + object: Optional[Literal["realtime.response"]] = None + """The object type, must be `realtime.response`.""" + + output: Optional[List[ConversationItem]] = None + """The list of output items generated by the response.""" + + status: Optional[Literal["completed", "cancelled", "failed", "incomplete"]] = None + """ + The final status of the response (`completed`, `cancelled`, `failed`, or + `incomplete`). + """ + + status_details: Optional[RealtimeResponseStatus] = None + """Additional details about the status.""" + + usage: Optional[RealtimeResponseUsage] = None + """Usage statistics for the Response, this will correspond to billing. + + A Realtime API session will maintain a conversation context and append new Items + to the Conversation, thus output from previous turns (text and audio tokens) + will become the input for later turns. + """ diff --git a/src/openai/types/beta/realtime/realtime_response_status.py b/src/openai/types/beta/realtime/realtime_response_status.py new file mode 100644 index 0000000000..7189cd58a1 --- /dev/null +++ b/src/openai/types/beta/realtime/realtime_response_status.py @@ -0,0 +1,39 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["RealtimeResponseStatus", "Error"] + + +class Error(BaseModel): + code: Optional[str] = None + """Error code, if any.""" + + type: Optional[str] = None + """The type of error.""" + + +class RealtimeResponseStatus(BaseModel): + error: Optional[Error] = None + """ + A description of the error that caused the response to fail, populated when the + `status` is `failed`. + """ + + reason: Optional[Literal["turn_detected", "client_cancelled", "max_output_tokens", "content_filter"]] = None + """The reason the Response did not complete. + + For a `cancelled` Response, one of `turn_detected` (the server VAD detected a + new start of speech) or `client_cancelled` (the client sent a cancel event). For + an `incomplete` Response, one of `max_output_tokens` or `content_filter` (the + server-side safety filter activated and cut off the response). + """ + + type: Optional[Literal["completed", "cancelled", "incomplete", "failed"]] = None + """ + The type of error that caused the response to fail, corresponding with the + `status` field (`completed`, `cancelled`, `incomplete`, `failed`). + """ diff --git a/src/openai/types/beta/realtime/realtime_response_usage.py b/src/openai/types/beta/realtime/realtime_response_usage.py new file mode 100644 index 0000000000..7ca822e25e --- /dev/null +++ b/src/openai/types/beta/realtime/realtime_response_usage.py @@ -0,0 +1,52 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from ...._models import BaseModel + +__all__ = ["RealtimeResponseUsage", "InputTokenDetails", "OutputTokenDetails"] + + +class InputTokenDetails(BaseModel): + audio_tokens: Optional[int] = None + """The number of audio tokens used in the Response.""" + + cached_tokens: Optional[int] = None + """The number of cached tokens used in the Response.""" + + text_tokens: Optional[int] = None + """The number of text tokens used in the Response.""" + + +class OutputTokenDetails(BaseModel): + audio_tokens: Optional[int] = None + """The number of audio tokens used in the Response.""" + + text_tokens: Optional[int] = None + """The number of text tokens used in the Response.""" + + +class RealtimeResponseUsage(BaseModel): + input_token_details: Optional[InputTokenDetails] = None + """Details about the input tokens used in the Response.""" + + input_tokens: Optional[int] = None + """ + The number of input tokens used in the Response, including text and audio + tokens. + """ + + output_token_details: Optional[OutputTokenDetails] = None + """Details about the output tokens used in the Response.""" + + output_tokens: Optional[int] = None + """ + The number of output tokens sent in the Response, including text and audio + tokens. + """ + + total_tokens: Optional[int] = None + """ + The total number of tokens in the Response including input and output text and + audio tokens. + """ diff --git a/src/openai/types/beta/realtime/realtime_server_event.py b/src/openai/types/beta/realtime/realtime_server_event.py new file mode 100644 index 0000000000..5f8ed55b13 --- /dev/null +++ b/src/openai/types/beta/realtime/realtime_server_event.py @@ -0,0 +1,72 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Annotated, TypeAlias + +from ...._utils import PropertyInfo +from .error_event import ErrorEvent +from .response_done_event import ResponseDoneEvent +from .session_created_event import SessionCreatedEvent +from .session_updated_event import SessionUpdatedEvent +from .response_created_event import ResponseCreatedEvent +from .response_text_done_event import ResponseTextDoneEvent +from .rate_limits_updated_event import RateLimitsUpdatedEvent +from .response_audio_done_event import ResponseAudioDoneEvent +from .response_text_delta_event import ResponseTextDeltaEvent +from .conversation_created_event import ConversationCreatedEvent +from .response_audio_delta_event import ResponseAudioDeltaEvent +from .conversation_item_created_event import ConversationItemCreatedEvent +from .conversation_item_deleted_event import ConversationItemDeletedEvent +from .response_output_item_done_event import ResponseOutputItemDoneEvent +from .input_audio_buffer_cleared_event import InputAudioBufferClearedEvent +from .response_content_part_done_event import ResponseContentPartDoneEvent +from .response_output_item_added_event import ResponseOutputItemAddedEvent +from .conversation_item_truncated_event import ConversationItemTruncatedEvent +from .response_content_part_added_event import ResponseContentPartAddedEvent +from .input_audio_buffer_committed_event import InputAudioBufferCommittedEvent +from .response_audio_transcript_done_event import ResponseAudioTranscriptDoneEvent +from .response_audio_transcript_delta_event import ResponseAudioTranscriptDeltaEvent +from .input_audio_buffer_speech_started_event import InputAudioBufferSpeechStartedEvent +from .input_audio_buffer_speech_stopped_event import InputAudioBufferSpeechStoppedEvent +from .response_function_call_arguments_done_event import ResponseFunctionCallArgumentsDoneEvent +from .response_function_call_arguments_delta_event import ResponseFunctionCallArgumentsDeltaEvent +from .conversation_item_input_audio_transcription_failed_event import ConversationItemInputAudioTranscriptionFailedEvent +from .conversation_item_input_audio_transcription_completed_event import ( + ConversationItemInputAudioTranscriptionCompletedEvent, +) + +__all__ = ["RealtimeServerEvent"] + +RealtimeServerEvent: TypeAlias = Annotated[ + Union[ + ErrorEvent, + SessionCreatedEvent, + SessionUpdatedEvent, + ConversationCreatedEvent, + InputAudioBufferCommittedEvent, + InputAudioBufferClearedEvent, + InputAudioBufferSpeechStartedEvent, + InputAudioBufferSpeechStoppedEvent, + ConversationItemCreatedEvent, + ConversationItemInputAudioTranscriptionCompletedEvent, + ConversationItemInputAudioTranscriptionFailedEvent, + ConversationItemTruncatedEvent, + ConversationItemDeletedEvent, + ResponseCreatedEvent, + ResponseDoneEvent, + ResponseOutputItemAddedEvent, + ResponseOutputItemDoneEvent, + ResponseContentPartAddedEvent, + ResponseContentPartDoneEvent, + ResponseTextDeltaEvent, + ResponseTextDoneEvent, + ResponseAudioTranscriptDeltaEvent, + ResponseAudioTranscriptDoneEvent, + ResponseAudioDeltaEvent, + ResponseAudioDoneEvent, + ResponseFunctionCallArgumentsDeltaEvent, + ResponseFunctionCallArgumentsDoneEvent, + RateLimitsUpdatedEvent, + ], + PropertyInfo(discriminator="type"), +] diff --git a/src/openai/types/beta/realtime/response_audio_delta_event.py b/src/openai/types/beta/realtime/response_audio_delta_event.py new file mode 100644 index 0000000000..8e0128d942 --- /dev/null +++ b/src/openai/types/beta/realtime/response_audio_delta_event.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["ResponseAudioDeltaEvent"] + + +class ResponseAudioDeltaEvent(BaseModel): + content_index: int + """The index of the content part in the item's content array.""" + + delta: str + """Base64-encoded audio data delta.""" + + event_id: str + """The unique ID of the server event.""" + + item_id: str + """The ID of the item.""" + + output_index: int + """The index of the output item in the response.""" + + response_id: str + """The ID of the response.""" + + type: Literal["response.audio.delta"] + """The event type, must be `response.audio.delta`.""" diff --git a/src/openai/types/beta/realtime/response_audio_done_event.py b/src/openai/types/beta/realtime/response_audio_done_event.py new file mode 100644 index 0000000000..68e78bc778 --- /dev/null +++ b/src/openai/types/beta/realtime/response_audio_done_event.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["ResponseAudioDoneEvent"] + + +class ResponseAudioDoneEvent(BaseModel): + content_index: int + """The index of the content part in the item's content array.""" + + event_id: str + """The unique ID of the server event.""" + + item_id: str + """The ID of the item.""" + + output_index: int + """The index of the output item in the response.""" + + response_id: str + """The ID of the response.""" + + type: Literal["response.audio.done"] + """The event type, must be `response.audio.done`.""" diff --git a/src/openai/types/beta/realtime/response_audio_transcript_delta_event.py b/src/openai/types/beta/realtime/response_audio_transcript_delta_event.py new file mode 100644 index 0000000000..3609948d10 --- /dev/null +++ b/src/openai/types/beta/realtime/response_audio_transcript_delta_event.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["ResponseAudioTranscriptDeltaEvent"] + + +class ResponseAudioTranscriptDeltaEvent(BaseModel): + content_index: int + """The index of the content part in the item's content array.""" + + delta: str + """The transcript delta.""" + + event_id: str + """The unique ID of the server event.""" + + item_id: str + """The ID of the item.""" + + output_index: int + """The index of the output item in the response.""" + + response_id: str + """The ID of the response.""" + + type: Literal["response.audio_transcript.delta"] + """The event type, must be `response.audio_transcript.delta`.""" diff --git a/src/openai/types/beta/realtime/response_audio_transcript_done_event.py b/src/openai/types/beta/realtime/response_audio_transcript_done_event.py new file mode 100644 index 0000000000..4e4436a95f --- /dev/null +++ b/src/openai/types/beta/realtime/response_audio_transcript_done_event.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["ResponseAudioTranscriptDoneEvent"] + + +class ResponseAudioTranscriptDoneEvent(BaseModel): + content_index: int + """The index of the content part in the item's content array.""" + + event_id: str + """The unique ID of the server event.""" + + item_id: str + """The ID of the item.""" + + output_index: int + """The index of the output item in the response.""" + + response_id: str + """The ID of the response.""" + + transcript: str + """The final transcript of the audio.""" + + type: Literal["response.audio_transcript.done"] + """The event type, must be `response.audio_transcript.done`.""" diff --git a/src/openai/types/beta/realtime/response_cancel_event.py b/src/openai/types/beta/realtime/response_cancel_event.py new file mode 100644 index 0000000000..c5ff991e9a --- /dev/null +++ b/src/openai/types/beta/realtime/response_cancel_event.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["ResponseCancelEvent"] + + +class ResponseCancelEvent(BaseModel): + type: Literal["response.cancel"] + """The event type, must be `response.cancel`.""" + + event_id: Optional[str] = None + """Optional client-generated ID used to identify this event.""" + + response_id: Optional[str] = None + """ + A specific response ID to cancel - if not provided, will cancel an in-progress + response in the default conversation. + """ diff --git a/src/openai/types/beta/realtime/response_cancel_event_param.py b/src/openai/types/beta/realtime/response_cancel_event_param.py new file mode 100644 index 0000000000..f33740730a --- /dev/null +++ b/src/openai/types/beta/realtime/response_cancel_event_param.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ResponseCancelEventParam"] + + +class ResponseCancelEventParam(TypedDict, total=False): + type: Required[Literal["response.cancel"]] + """The event type, must be `response.cancel`.""" + + event_id: str + """Optional client-generated ID used to identify this event.""" + + response_id: str + """ + A specific response ID to cancel - if not provided, will cancel an in-progress + response in the default conversation. + """ diff --git a/src/openai/types/beta/realtime/response_content_part_added_event.py b/src/openai/types/beta/realtime/response_content_part_added_event.py new file mode 100644 index 0000000000..45c8f20f97 --- /dev/null +++ b/src/openai/types/beta/realtime/response_content_part_added_event.py @@ -0,0 +1,45 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["ResponseContentPartAddedEvent", "Part"] + + +class Part(BaseModel): + audio: Optional[str] = None + """Base64-encoded audio data (if type is "audio").""" + + text: Optional[str] = None + """The text content (if type is "text").""" + + transcript: Optional[str] = None + """The transcript of the audio (if type is "audio").""" + + type: Optional[Literal["text", "audio"]] = None + """The content type ("text", "audio").""" + + +class ResponseContentPartAddedEvent(BaseModel): + content_index: int + """The index of the content part in the item's content array.""" + + event_id: str + """The unique ID of the server event.""" + + item_id: str + """The ID of the item to which the content part was added.""" + + output_index: int + """The index of the output item in the response.""" + + part: Part + """The content part that was added.""" + + response_id: str + """The ID of the response.""" + + type: Literal["response.content_part.added"] + """The event type, must be `response.content_part.added`.""" diff --git a/src/openai/types/beta/realtime/response_content_part_done_event.py b/src/openai/types/beta/realtime/response_content_part_done_event.py new file mode 100644 index 0000000000..3d16116106 --- /dev/null +++ b/src/openai/types/beta/realtime/response_content_part_done_event.py @@ -0,0 +1,45 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["ResponseContentPartDoneEvent", "Part"] + + +class Part(BaseModel): + audio: Optional[str] = None + """Base64-encoded audio data (if type is "audio").""" + + text: Optional[str] = None + """The text content (if type is "text").""" + + transcript: Optional[str] = None + """The transcript of the audio (if type is "audio").""" + + type: Optional[Literal["text", "audio"]] = None + """The content type ("text", "audio").""" + + +class ResponseContentPartDoneEvent(BaseModel): + content_index: int + """The index of the content part in the item's content array.""" + + event_id: str + """The unique ID of the server event.""" + + item_id: str + """The ID of the item.""" + + output_index: int + """The index of the output item in the response.""" + + part: Part + """The content part that is done.""" + + response_id: str + """The ID of the response.""" + + type: Literal["response.content_part.done"] + """The event type, must be `response.content_part.done`.""" diff --git a/src/openai/types/beta/realtime/response_create_event.py b/src/openai/types/beta/realtime/response_create_event.py new file mode 100644 index 0000000000..00ba1e5dad --- /dev/null +++ b/src/openai/types/beta/realtime/response_create_event.py @@ -0,0 +1,115 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from typing_extensions import Literal + +from ...._models import BaseModel +from .conversation_item import ConversationItem + +__all__ = ["ResponseCreateEvent", "Response", "ResponseTool"] + + +class ResponseTool(BaseModel): + description: Optional[str] = None + """ + The description of the function, including guidance on when and how to call it, + and guidance about what to tell the user when calling (if anything). + """ + + name: Optional[str] = None + """The name of the function.""" + + parameters: Optional[object] = None + """Parameters of the function in JSON Schema.""" + + type: Optional[Literal["function"]] = None + """The type of the tool, i.e. `function`.""" + + +class Response(BaseModel): + conversation: Union[str, Literal["auto", "none"], None] = None + """Controls which conversation the response is added to. + + Currently supports `auto` and `none`, with `auto` as the default value. The + `auto` value means that the contents of the response will be added to the + default conversation. Set this to `none` to create an out-of-band response which + will not add items to default conversation. + """ + + input: Optional[List[ConversationItem]] = None + """Input items to include in the prompt for the model. + + Creates a new context for this response, without including the default + conversation. Can include references to items from the default conversation. + """ + + instructions: Optional[str] = None + """The default system instructions (i.e. + + system message) prepended to model calls. This field allows the client to guide + the model on desired responses. The model can be instructed on response content + and format, (e.g. "be extremely succinct", "act friendly", "here are examples of + good responses") and on audio behavior (e.g. "talk quickly", "inject emotion + into your voice", "laugh frequently"). The instructions are not guaranteed to be + followed by the model, but they provide guidance to the model on the desired + behavior. + + Note that the server sets default instructions which will be used if this field + is not set and are visible in the `session.created` event at the start of the + session. + """ + + max_response_output_tokens: Union[int, Literal["inf"], None] = None + """ + Maximum number of output tokens for a single assistant response, inclusive of + tool calls. Provide an integer between 1 and 4096 to limit output tokens, or + `inf` for the maximum available tokens for a given model. Defaults to `inf`. + """ + + metadata: Optional[object] = None + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format. Keys can be a maximum of 64 characters long and values can be + a maximum of 512 characters long. + """ + + modalities: Optional[List[Literal["text", "audio"]]] = None + """The set of modalities the model can respond with. + + To disable audio, set this to ["text"]. + """ + + output_audio_format: Optional[Literal["pcm16", "g711_ulaw", "g711_alaw"]] = None + """The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.""" + + temperature: Optional[float] = None + """Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.""" + + tool_choice: Optional[str] = None + """How the model chooses tools. + + Options are `auto`, `none`, `required`, or specify a function. + """ + + tools: Optional[List[ResponseTool]] = None + """Tools (functions) available to the model.""" + + voice: Optional[Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"]] = None + """The voice the model uses to respond. + + Voice cannot be changed during the session once the model has responded with + audio at least once. Current voice options are `alloy`, `ash`, `ballad`, + `coral`, `echo` `sage`, `shimmer` and `verse`. + """ + + +class ResponseCreateEvent(BaseModel): + type: Literal["response.create"] + """The event type, must be `response.create`.""" + + event_id: Optional[str] = None + """Optional client-generated ID used to identify this event.""" + + response: Optional[Response] = None + """Create a new Realtime response with these parameters""" diff --git a/src/openai/types/beta/realtime/response_create_event_param.py b/src/openai/types/beta/realtime/response_create_event_param.py new file mode 100644 index 0000000000..7c92b32df1 --- /dev/null +++ b/src/openai/types/beta/realtime/response_create_event_param.py @@ -0,0 +1,116 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Union, Iterable, Optional +from typing_extensions import Literal, Required, TypedDict + +from .conversation_item_param import ConversationItemParam + +__all__ = ["ResponseCreateEventParam", "Response", "ResponseTool"] + + +class ResponseTool(TypedDict, total=False): + description: str + """ + The description of the function, including guidance on when and how to call it, + and guidance about what to tell the user when calling (if anything). + """ + + name: str + """The name of the function.""" + + parameters: object + """Parameters of the function in JSON Schema.""" + + type: Literal["function"] + """The type of the tool, i.e. `function`.""" + + +class Response(TypedDict, total=False): + conversation: Union[str, Literal["auto", "none"]] + """Controls which conversation the response is added to. + + Currently supports `auto` and `none`, with `auto` as the default value. The + `auto` value means that the contents of the response will be added to the + default conversation. Set this to `none` to create an out-of-band response which + will not add items to default conversation. + """ + + input: Iterable[ConversationItemParam] + """Input items to include in the prompt for the model. + + Creates a new context for this response, without including the default + conversation. Can include references to items from the default conversation. + """ + + instructions: str + """The default system instructions (i.e. + + system message) prepended to model calls. This field allows the client to guide + the model on desired responses. The model can be instructed on response content + and format, (e.g. "be extremely succinct", "act friendly", "here are examples of + good responses") and on audio behavior (e.g. "talk quickly", "inject emotion + into your voice", "laugh frequently"). The instructions are not guaranteed to be + followed by the model, but they provide guidance to the model on the desired + behavior. + + Note that the server sets default instructions which will be used if this field + is not set and are visible in the `session.created` event at the start of the + session. + """ + + max_response_output_tokens: Union[int, Literal["inf"]] + """ + Maximum number of output tokens for a single assistant response, inclusive of + tool calls. Provide an integer between 1 and 4096 to limit output tokens, or + `inf` for the maximum available tokens for a given model. Defaults to `inf`. + """ + + metadata: Optional[object] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format. Keys can be a maximum of 64 characters long and values can be + a maximum of 512 characters long. + """ + + modalities: List[Literal["text", "audio"]] + """The set of modalities the model can respond with. + + To disable audio, set this to ["text"]. + """ + + output_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"] + """The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.""" + + temperature: float + """Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.""" + + tool_choice: str + """How the model chooses tools. + + Options are `auto`, `none`, `required`, or specify a function. + """ + + tools: Iterable[ResponseTool] + """Tools (functions) available to the model.""" + + voice: Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"] + """The voice the model uses to respond. + + Voice cannot be changed during the session once the model has responded with + audio at least once. Current voice options are `alloy`, `ash`, `ballad`, + `coral`, `echo` `sage`, `shimmer` and `verse`. + """ + + +class ResponseCreateEventParam(TypedDict, total=False): + type: Required[Literal["response.create"]] + """The event type, must be `response.create`.""" + + event_id: str + """Optional client-generated ID used to identify this event.""" + + response: Response + """Create a new Realtime response with these parameters""" diff --git a/src/openai/types/beta/realtime/response_created_event.py b/src/openai/types/beta/realtime/response_created_event.py new file mode 100644 index 0000000000..a4990cf095 --- /dev/null +++ b/src/openai/types/beta/realtime/response_created_event.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel +from .realtime_response import RealtimeResponse + +__all__ = ["ResponseCreatedEvent"] + + +class ResponseCreatedEvent(BaseModel): + event_id: str + """The unique ID of the server event.""" + + response: RealtimeResponse + """The response resource.""" + + type: Literal["response.created"] + """The event type, must be `response.created`.""" diff --git a/src/openai/types/beta/realtime/response_done_event.py b/src/openai/types/beta/realtime/response_done_event.py new file mode 100644 index 0000000000..9e655184b6 --- /dev/null +++ b/src/openai/types/beta/realtime/response_done_event.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel +from .realtime_response import RealtimeResponse + +__all__ = ["ResponseDoneEvent"] + + +class ResponseDoneEvent(BaseModel): + event_id: str + """The unique ID of the server event.""" + + response: RealtimeResponse + """The response resource.""" + + type: Literal["response.done"] + """The event type, must be `response.done`.""" diff --git a/src/openai/types/beta/realtime/response_function_call_arguments_delta_event.py b/src/openai/types/beta/realtime/response_function_call_arguments_delta_event.py new file mode 100644 index 0000000000..cdbb64e658 --- /dev/null +++ b/src/openai/types/beta/realtime/response_function_call_arguments_delta_event.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["ResponseFunctionCallArgumentsDeltaEvent"] + + +class ResponseFunctionCallArgumentsDeltaEvent(BaseModel): + call_id: str + """The ID of the function call.""" + + delta: str + """The arguments delta as a JSON string.""" + + event_id: str + """The unique ID of the server event.""" + + item_id: str + """The ID of the function call item.""" + + output_index: int + """The index of the output item in the response.""" + + response_id: str + """The ID of the response.""" + + type: Literal["response.function_call_arguments.delta"] + """The event type, must be `response.function_call_arguments.delta`.""" diff --git a/src/openai/types/beta/realtime/response_function_call_arguments_done_event.py b/src/openai/types/beta/realtime/response_function_call_arguments_done_event.py new file mode 100644 index 0000000000..0a5db53323 --- /dev/null +++ b/src/openai/types/beta/realtime/response_function_call_arguments_done_event.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["ResponseFunctionCallArgumentsDoneEvent"] + + +class ResponseFunctionCallArgumentsDoneEvent(BaseModel): + arguments: str + """The final arguments as a JSON string.""" + + call_id: str + """The ID of the function call.""" + + event_id: str + """The unique ID of the server event.""" + + item_id: str + """The ID of the function call item.""" + + output_index: int + """The index of the output item in the response.""" + + response_id: str + """The ID of the response.""" + + type: Literal["response.function_call_arguments.done"] + """The event type, must be `response.function_call_arguments.done`.""" diff --git a/src/openai/types/beta/realtime/response_output_item_added_event.py b/src/openai/types/beta/realtime/response_output_item_added_event.py new file mode 100644 index 0000000000..c89bfdc3be --- /dev/null +++ b/src/openai/types/beta/realtime/response_output_item_added_event.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel +from .conversation_item import ConversationItem + +__all__ = ["ResponseOutputItemAddedEvent"] + + +class ResponseOutputItemAddedEvent(BaseModel): + event_id: str + """The unique ID of the server event.""" + + item: ConversationItem + """The item to add to the conversation.""" + + output_index: int + """The index of the output item in the Response.""" + + response_id: str + """The ID of the Response to which the item belongs.""" + + type: Literal["response.output_item.added"] + """The event type, must be `response.output_item.added`.""" diff --git a/src/openai/types/beta/realtime/response_output_item_done_event.py b/src/openai/types/beta/realtime/response_output_item_done_event.py new file mode 100644 index 0000000000..b5910e22aa --- /dev/null +++ b/src/openai/types/beta/realtime/response_output_item_done_event.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel +from .conversation_item import ConversationItem + +__all__ = ["ResponseOutputItemDoneEvent"] + + +class ResponseOutputItemDoneEvent(BaseModel): + event_id: str + """The unique ID of the server event.""" + + item: ConversationItem + """The item to add to the conversation.""" + + output_index: int + """The index of the output item in the Response.""" + + response_id: str + """The ID of the Response to which the item belongs.""" + + type: Literal["response.output_item.done"] + """The event type, must be `response.output_item.done`.""" diff --git a/src/openai/types/beta/realtime/response_text_delta_event.py b/src/openai/types/beta/realtime/response_text_delta_event.py new file mode 100644 index 0000000000..c463b3c3d0 --- /dev/null +++ b/src/openai/types/beta/realtime/response_text_delta_event.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["ResponseTextDeltaEvent"] + + +class ResponseTextDeltaEvent(BaseModel): + content_index: int + """The index of the content part in the item's content array.""" + + delta: str + """The text delta.""" + + event_id: str + """The unique ID of the server event.""" + + item_id: str + """The ID of the item.""" + + output_index: int + """The index of the output item in the response.""" + + response_id: str + """The ID of the response.""" + + type: Literal["response.text.delta"] + """The event type, must be `response.text.delta`.""" diff --git a/src/openai/types/beta/realtime/response_text_done_event.py b/src/openai/types/beta/realtime/response_text_done_event.py new file mode 100644 index 0000000000..020ff41d58 --- /dev/null +++ b/src/openai/types/beta/realtime/response_text_done_event.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["ResponseTextDoneEvent"] + + +class ResponseTextDoneEvent(BaseModel): + content_index: int + """The index of the content part in the item's content array.""" + + event_id: str + """The unique ID of the server event.""" + + item_id: str + """The ID of the item.""" + + output_index: int + """The index of the output item in the response.""" + + response_id: str + """The ID of the response.""" + + text: str + """The final text content.""" + + type: Literal["response.text.done"] + """The event type, must be `response.text.done`.""" diff --git a/src/openai/types/beta/realtime/session.py b/src/openai/types/beta/realtime/session.py new file mode 100644 index 0000000000..09cdbb02bc --- /dev/null +++ b/src/openai/types/beta/realtime/session.py @@ -0,0 +1,148 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["Session", "InputAudioTranscription", "Tool", "TurnDetection"] + + +class InputAudioTranscription(BaseModel): + model: Optional[str] = None + """ + The model to use for transcription, `whisper-1` is the only currently supported + model. + """ + + +class Tool(BaseModel): + description: Optional[str] = None + """ + The description of the function, including guidance on when and how to call it, + and guidance about what to tell the user when calling (if anything). + """ + + name: Optional[str] = None + """The name of the function.""" + + parameters: Optional[object] = None + """Parameters of the function in JSON Schema.""" + + type: Optional[Literal["function"]] = None + """The type of the tool, i.e. `function`.""" + + +class TurnDetection(BaseModel): + prefix_padding_ms: Optional[int] = None + """Amount of audio to include before the VAD detected speech (in milliseconds). + + Defaults to 300ms. + """ + + silence_duration_ms: Optional[int] = None + """Duration of silence to detect speech stop (in milliseconds). + + Defaults to 500ms. With shorter values the model will respond more quickly, but + may jump in on short pauses from the user. + """ + + threshold: Optional[float] = None + """Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. + + A higher threshold will require louder audio to activate the model, and thus + might perform better in noisy environments. + """ + + type: Optional[Literal["server_vad"]] = None + """Type of turn detection, only `server_vad` is currently supported.""" + + +class Session(BaseModel): + id: Optional[str] = None + """Unique identifier for the session object.""" + + input_audio_format: Optional[Literal["pcm16", "g711_ulaw", "g711_alaw"]] = None + """The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.""" + + input_audio_transcription: Optional[InputAudioTranscription] = None + """ + Configuration for input audio transcription, defaults to off and can be set to + `null` to turn off once on. Input audio transcription is not native to the + model, since the model consumes audio directly. Transcription runs + asynchronously through Whisper and should be treated as rough guidance rather + than the representation understood by the model. + """ + + instructions: Optional[str] = None + """The default system instructions (i.e. + + system message) prepended to model calls. This field allows the client to guide + the model on desired responses. The model can be instructed on response content + and format, (e.g. "be extremely succinct", "act friendly", "here are examples of + good responses") and on audio behavior (e.g. "talk quickly", "inject emotion + into your voice", "laugh frequently"). The instructions are not guaranteed to be + followed by the model, but they provide guidance to the model on the desired + behavior. + + Note that the server sets default instructions which will be used if this field + is not set and are visible in the `session.created` event at the start of the + session. + """ + + max_response_output_tokens: Union[int, Literal["inf"], None] = None + """ + Maximum number of output tokens for a single assistant response, inclusive of + tool calls. Provide an integer between 1 and 4096 to limit output tokens, or + `inf` for the maximum available tokens for a given model. Defaults to `inf`. + """ + + modalities: Optional[List[Literal["text", "audio"]]] = None + """The set of modalities the model can respond with. + + To disable audio, set this to ["text"]. + """ + + model: Union[ + str, + Literal[ + "gpt-4o-realtime-preview", + "gpt-4o-realtime-preview-2024-10-01", + "gpt-4o-realtime-preview-2024-12-17", + "gpt-4o-mini-realtime-preview", + "gpt-4o-mini-realtime-preview-2024-12-17", + ], + None, + ] = None + """The Realtime model used for this session.""" + + output_audio_format: Optional[Literal["pcm16", "g711_ulaw", "g711_alaw"]] = None + """The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.""" + + temperature: Optional[float] = None + """Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.""" + + tool_choice: Optional[str] = None + """How the model chooses tools. + + Options are `auto`, `none`, `required`, or specify a function. + """ + + tools: Optional[List[Tool]] = None + """Tools (functions) available to the model.""" + + turn_detection: Optional[TurnDetection] = None + """Configuration for turn detection. + + Can be set to `null` to turn off. Server VAD means that the model will detect + the start and end of speech based on audio volume and respond at the end of user + speech. + """ + + voice: Optional[Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"]] = None + """The voice the model uses to respond. + + Voice cannot be changed during the session once the model has responded with + audio at least once. Current voice options are `alloy`, `ash`, `ballad`, + `coral`, `echo` `sage`, `shimmer` and `verse`. + """ diff --git a/src/openai/types/beta/realtime/session_created_event.py b/src/openai/types/beta/realtime/session_created_event.py new file mode 100644 index 0000000000..baf6af388b --- /dev/null +++ b/src/openai/types/beta/realtime/session_created_event.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from .session import Session +from ...._models import BaseModel + +__all__ = ["SessionCreatedEvent"] + + +class SessionCreatedEvent(BaseModel): + event_id: str + """The unique ID of the server event.""" + + session: Session + """Realtime session object configuration.""" + + type: Literal["session.created"] + """The event type, must be `session.created`.""" diff --git a/src/openai/types/beta/realtime/session_update_event.py b/src/openai/types/beta/realtime/session_update_event.py new file mode 100644 index 0000000000..c04220aa25 --- /dev/null +++ b/src/openai/types/beta/realtime/session_update_event.py @@ -0,0 +1,158 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["SessionUpdateEvent", "Session", "SessionInputAudioTranscription", "SessionTool", "SessionTurnDetection"] + + +class SessionInputAudioTranscription(BaseModel): + model: Optional[str] = None + """ + The model to use for transcription, `whisper-1` is the only currently supported + model. + """ + + +class SessionTool(BaseModel): + description: Optional[str] = None + """ + The description of the function, including guidance on when and how to call it, + and guidance about what to tell the user when calling (if anything). + """ + + name: Optional[str] = None + """The name of the function.""" + + parameters: Optional[object] = None + """Parameters of the function in JSON Schema.""" + + type: Optional[Literal["function"]] = None + """The type of the tool, i.e. `function`.""" + + +class SessionTurnDetection(BaseModel): + create_response: Optional[bool] = None + """Whether or not to automatically generate a response when VAD is enabled. + + `true` by default. + """ + + prefix_padding_ms: Optional[int] = None + """Amount of audio to include before the VAD detected speech (in milliseconds). + + Defaults to 300ms. + """ + + silence_duration_ms: Optional[int] = None + """Duration of silence to detect speech stop (in milliseconds). + + Defaults to 500ms. With shorter values the model will respond more quickly, but + may jump in on short pauses from the user. + """ + + threshold: Optional[float] = None + """Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. + + A higher threshold will require louder audio to activate the model, and thus + might perform better in noisy environments. + """ + + type: Optional[str] = None + """Type of turn detection, only `server_vad` is currently supported.""" + + +class Session(BaseModel): + model: Literal[ + "gpt-4o-realtime-preview", + "gpt-4o-realtime-preview-2024-10-01", + "gpt-4o-realtime-preview-2024-12-17", + "gpt-4o-mini-realtime-preview", + "gpt-4o-mini-realtime-preview-2024-12-17", + ] + """The Realtime model used for this session.""" + + input_audio_format: Optional[Literal["pcm16", "g711_ulaw", "g711_alaw"]] = None + """The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.""" + + input_audio_transcription: Optional[SessionInputAudioTranscription] = None + """ + Configuration for input audio transcription, defaults to off and can be set to + `null` to turn off once on. Input audio transcription is not native to the + model, since the model consumes audio directly. Transcription runs + asynchronously through Whisper and should be treated as rough guidance rather + than the representation understood by the model. + """ + + instructions: Optional[str] = None + """The default system instructions (i.e. + + system message) prepended to model calls. This field allows the client to guide + the model on desired responses. The model can be instructed on response content + and format, (e.g. "be extremely succinct", "act friendly", "here are examples of + good responses") and on audio behavior (e.g. "talk quickly", "inject emotion + into your voice", "laugh frequently"). The instructions are not guaranteed to be + followed by the model, but they provide guidance to the model on the desired + behavior. + + Note that the server sets default instructions which will be used if this field + is not set and are visible in the `session.created` event at the start of the + session. + """ + + max_response_output_tokens: Union[int, Literal["inf"], None] = None + """ + Maximum number of output tokens for a single assistant response, inclusive of + tool calls. Provide an integer between 1 and 4096 to limit output tokens, or + `inf` for the maximum available tokens for a given model. Defaults to `inf`. + """ + + modalities: Optional[List[Literal["text", "audio"]]] = None + """The set of modalities the model can respond with. + + To disable audio, set this to ["text"]. + """ + + output_audio_format: Optional[Literal["pcm16", "g711_ulaw", "g711_alaw"]] = None + """The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.""" + + temperature: Optional[float] = None + """Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.""" + + tool_choice: Optional[str] = None + """How the model chooses tools. + + Options are `auto`, `none`, `required`, or specify a function. + """ + + tools: Optional[List[SessionTool]] = None + """Tools (functions) available to the model.""" + + turn_detection: Optional[SessionTurnDetection] = None + """Configuration for turn detection. + + Can be set to `null` to turn off. Server VAD means that the model will detect + the start and end of speech based on audio volume and respond at the end of user + speech. + """ + + voice: Optional[Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"]] = None + """The voice the model uses to respond. + + Voice cannot be changed during the session once the model has responded with + audio at least once. Current voice options are `alloy`, `ash`, `ballad`, + `coral`, `echo` `sage`, `shimmer` and `verse`. + """ + + +class SessionUpdateEvent(BaseModel): + session: Session + """Realtime session object configuration.""" + + type: Literal["session.update"] + """The event type, must be `session.update`.""" + + event_id: Optional[str] = None + """Optional client-generated ID used to identify this event.""" diff --git a/src/openai/types/beta/realtime/session_update_event_param.py b/src/openai/types/beta/realtime/session_update_event_param.py new file mode 100644 index 0000000000..aa06069b04 --- /dev/null +++ b/src/openai/types/beta/realtime/session_update_event_param.py @@ -0,0 +1,166 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Union, Iterable +from typing_extensions import Literal, Required, TypedDict + +__all__ = [ + "SessionUpdateEventParam", + "Session", + "SessionInputAudioTranscription", + "SessionTool", + "SessionTurnDetection", +] + + +class SessionInputAudioTranscription(TypedDict, total=False): + model: str + """ + The model to use for transcription, `whisper-1` is the only currently supported + model. + """ + + +class SessionTool(TypedDict, total=False): + description: str + """ + The description of the function, including guidance on when and how to call it, + and guidance about what to tell the user when calling (if anything). + """ + + name: str + """The name of the function.""" + + parameters: object + """Parameters of the function in JSON Schema.""" + + type: Literal["function"] + """The type of the tool, i.e. `function`.""" + + +class SessionTurnDetection(TypedDict, total=False): + create_response: bool + """Whether or not to automatically generate a response when VAD is enabled. + + `true` by default. + """ + + prefix_padding_ms: int + """Amount of audio to include before the VAD detected speech (in milliseconds). + + Defaults to 300ms. + """ + + silence_duration_ms: int + """Duration of silence to detect speech stop (in milliseconds). + + Defaults to 500ms. With shorter values the model will respond more quickly, but + may jump in on short pauses from the user. + """ + + threshold: float + """Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. + + A higher threshold will require louder audio to activate the model, and thus + might perform better in noisy environments. + """ + + type: str + """Type of turn detection, only `server_vad` is currently supported.""" + + +class Session(TypedDict, total=False): + model: Required[ + Literal[ + "gpt-4o-realtime-preview", + "gpt-4o-realtime-preview-2024-10-01", + "gpt-4o-realtime-preview-2024-12-17", + "gpt-4o-mini-realtime-preview", + "gpt-4o-mini-realtime-preview-2024-12-17", + ] + ] + """The Realtime model used for this session.""" + + input_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"] + """The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.""" + + input_audio_transcription: SessionInputAudioTranscription + """ + Configuration for input audio transcription, defaults to off and can be set to + `null` to turn off once on. Input audio transcription is not native to the + model, since the model consumes audio directly. Transcription runs + asynchronously through Whisper and should be treated as rough guidance rather + than the representation understood by the model. + """ + + instructions: str + """The default system instructions (i.e. + + system message) prepended to model calls. This field allows the client to guide + the model on desired responses. The model can be instructed on response content + and format, (e.g. "be extremely succinct", "act friendly", "here are examples of + good responses") and on audio behavior (e.g. "talk quickly", "inject emotion + into your voice", "laugh frequently"). The instructions are not guaranteed to be + followed by the model, but they provide guidance to the model on the desired + behavior. + + Note that the server sets default instructions which will be used if this field + is not set and are visible in the `session.created` event at the start of the + session. + """ + + max_response_output_tokens: Union[int, Literal["inf"]] + """ + Maximum number of output tokens for a single assistant response, inclusive of + tool calls. Provide an integer between 1 and 4096 to limit output tokens, or + `inf` for the maximum available tokens for a given model. Defaults to `inf`. + """ + + modalities: List[Literal["text", "audio"]] + """The set of modalities the model can respond with. + + To disable audio, set this to ["text"]. + """ + + output_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"] + """The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.""" + + temperature: float + """Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.""" + + tool_choice: str + """How the model chooses tools. + + Options are `auto`, `none`, `required`, or specify a function. + """ + + tools: Iterable[SessionTool] + """Tools (functions) available to the model.""" + + turn_detection: SessionTurnDetection + """Configuration for turn detection. + + Can be set to `null` to turn off. Server VAD means that the model will detect + the start and end of speech based on audio volume and respond at the end of user + speech. + """ + + voice: Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"] + """The voice the model uses to respond. + + Voice cannot be changed during the session once the model has responded with + audio at least once. Current voice options are `alloy`, `ash`, `ballad`, + `coral`, `echo` `sage`, `shimmer` and `verse`. + """ + + +class SessionUpdateEventParam(TypedDict, total=False): + session: Required[Session] + """Realtime session object configuration.""" + + type: Required[Literal["session.update"]] + """The event type, must be `session.update`.""" + + event_id: str + """Optional client-generated ID used to identify this event.""" diff --git a/src/openai/types/beta/realtime/session_updated_event.py b/src/openai/types/beta/realtime/session_updated_event.py new file mode 100644 index 0000000000..b9b6488eb3 --- /dev/null +++ b/src/openai/types/beta/realtime/session_updated_event.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from .session import Session +from ...._models import BaseModel + +__all__ = ["SessionUpdatedEvent"] + + +class SessionUpdatedEvent(BaseModel): + event_id: str + """The unique ID of the server event.""" + + session: Session + """Realtime session object configuration.""" + + type: Literal["session.updated"] + """The event type, must be `session.updated`.""" diff --git a/src/openai/types/websocket_connection_options.py b/src/openai/types/websocket_connection_options.py new file mode 100644 index 0000000000..40fd24ab03 --- /dev/null +++ b/src/openai/types/websocket_connection_options.py @@ -0,0 +1,36 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import TYPE_CHECKING +from typing_extensions import Sequence, TypedDict + +if TYPE_CHECKING: + from websockets import Subprotocol + from websockets.extensions import ClientExtensionFactory + + +class WebsocketConnectionOptions(TypedDict, total=False): + """Websocket connection options copied from `websockets`. + + For example: https://websockets.readthedocs.io/en/stable/reference/asyncio/client.html#websockets.asyncio.client.connect + """ + + extensions: Sequence[ClientExtensionFactory] | None + """List of supported extensions, in order in which they should be negotiated and run.""" + + subprotocols: Sequence[Subprotocol] | None + """List of supported subprotocols, in order of decreasing preference.""" + + compression: str | None + """The “permessage-deflate” extension is enabled by default. Set compression to None to disable it. See the [compression guide](https://websockets.readthedocs.io/en/stable/topics/compression.html) for details.""" + + # limits + max_size: int | None + """Maximum size of incoming messages in bytes. None disables the limit.""" + + max_queue: int | None | tuple[int | None, int | None] + """High-water mark of the buffer where frames are received. It defaults to 16 frames. The low-water mark defaults to max_queue // 4. You may pass a (high, low) tuple to set the high-water and low-water marks. If you want to disable flow control entirely, you may set it to None, although that’s a bad idea.""" + + write_limit: int | tuple[int, int | None] + """High-water mark of write buffer in bytes. It is passed to set_write_buffer_limits(). It defaults to 32 KiB. You may pass a (high, low) tuple to set the high-water and low-water marks.""" diff --git a/tests/api_resources/beta/test_realtime.py b/tests/api_resources/beta/test_realtime.py new file mode 100644 index 0000000000..537017ffd3 --- /dev/null +++ b/tests/api_resources/beta/test_realtime.py @@ -0,0 +1,17 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os + +import pytest + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") + + +class TestRealtime: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + +class TestAsyncRealtime: + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) From a6a94e08741acdfc9b371dc4c47cbc7b8613cd88 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Tue, 17 Dec 2024 18:06:18 +0000 Subject: [PATCH 614/816] fix: add reasoning_effort to all methods --- src/openai/resources/beta/chat/completions.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/openai/resources/beta/chat/completions.py b/src/openai/resources/beta/chat/completions.py index 38c09ce8dd..48cb13f7a6 100644 --- a/src/openai/resources/beta/chat/completions.py +++ b/src/openai/resources/beta/chat/completions.py @@ -15,7 +15,10 @@ from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ...._streaming import Stream -from ....types.chat import completion_create_params +from ....types.chat import ( + ChatCompletionReasoningEffort, + completion_create_params, +) from ...._base_client import make_request_options from ....lib._parsing import ( ResponseFormatT, @@ -79,6 +82,7 @@ def parse( parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + reasoning_effort: ChatCompletionReasoningEffort | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, @@ -173,6 +177,7 @@ def parser(raw_completion: ChatCompletion) -> ParsedChatCompletion[ResponseForma "parallel_tool_calls": parallel_tool_calls, "prediction": prediction, "presence_penalty": presence_penalty, + "reasoning_effort": reasoning_effort, "response_format": _type_to_response_format(response_format), "seed": seed, "service_tier": service_tier, @@ -222,6 +227,7 @@ def stream( parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + reasoning_effort: ChatCompletionReasoningEffort | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, @@ -287,6 +293,7 @@ def stream( parallel_tool_calls=parallel_tool_calls, prediction=prediction, presence_penalty=presence_penalty, + reasoning_effort=reasoning_effort, seed=seed, service_tier=service_tier, store=store, @@ -350,6 +357,7 @@ async def parse( parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + reasoning_effort: ChatCompletionReasoningEffort | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, @@ -444,6 +452,7 @@ def parser(raw_completion: ChatCompletion) -> ParsedChatCompletion[ResponseForma "parallel_tool_calls": parallel_tool_calls, "prediction": prediction, "presence_penalty": presence_penalty, + "reasoning_effort": reasoning_effort, "response_format": _type_to_response_format(response_format), "seed": seed, "service_tier": service_tier, @@ -493,6 +502,7 @@ def stream( parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, + reasoning_effort: ChatCompletionReasoningEffort | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, @@ -559,6 +569,7 @@ def stream( parallel_tool_calls=parallel_tool_calls, prediction=prediction, presence_penalty=presence_penalty, + reasoning_effort=reasoning_effort, seed=seed, service_tier=service_tier, stop=stop, From 488ec04b7b79d3a5597c910fd585df18e922665f Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 16 Dec 2024 19:16:25 +0000 Subject: [PATCH 615/816] docs: add examples + guidance on Realtime API support --- README.md | 61 ++++++ examples/realtime/audio_util.py | 142 +++++++++++++ examples/realtime/push_to_talk_app.py | 281 ++++++++++++++++++++++++++ mypy.ini | 5 +- pyproject.toml | 5 + 5 files changed, 493 insertions(+), 1 deletion(-) create mode 100644 examples/realtime/audio_util.py create mode 100755 examples/realtime/push_to_talk_app.py diff --git a/README.md b/README.md index cbcfdb4447..4c3ba87c97 100644 --- a/README.md +++ b/README.md @@ -258,6 +258,67 @@ We recommend that you always instantiate a client (e.g., with `client = OpenAI() - It's harder to mock for testing purposes - It's not possible to control cleanup of network connections +## Realtime API beta + +The Realtime API enables you to build low-latency, multi-modal conversational experiences. It currently supports text and audio as both input and output, as well as [function calling](https://platform.openai.com/docs/guides/function-calling) through a WebSocket connection. + +Under the hood the SDK uses the [`websockets`](https://websockets.readthedocs.io/en/stable/) library to manage connections. + +The Realtime API works through a combination of client-sent events and server-sent events. Clients can send events to do things like update session configuration or send text and audio inputs. Server events confirm when audio responses have completed, or when a text response from the model has been received. A full event reference can be found [here](platform.openai.com/docs/api-reference/realtime-client-events) and a guide can be found [here](https://platform.openai.com/docs/guides/realtime). + +Basic text based example: + +```py +import asyncio +from openai import AsyncOpenAI + +async def main(): + client = AsyncOpenAI() + + async with client.beta.realtime.connect(model="gpt-4o-realtime-preview-2024-10-01") as connection: + await connection.session.update(session={'modalities': ['text']}) + + await connection.conversation.item.create( + item={ + "type": "message", + "role": "user", + "content": [{"type": "input_text", "text": "Say hello!"}], + } + ) + await connection.response.create() + + async for event in connection: + if event.type == 'response.text.delta': + print(event.delta, flush=True, end="") + + elif event.type == 'response.text.done': + print() + + elif event.type == "response.done": + break + +asyncio.run(main()) +``` + +However the real magic of the Realtime API is handling audio inputs / outputs, see this example [TUI script](https://github.com/stainless-sdks/openai-python/blob/robert/realtime-docs-preview/examples/realtime/push_to_talk_app.py) for a fully fledged example. + +### Realtime error handling + +Whenever an error occurs, the Realtime API will send an [`error` event](https://platform.openai.com/docs/guides/realtime/realtime-api-beta#handling-errors) and the connection will stay open and remain usable. This means you need to handle it yourself, as *no errors are raised directly* by the SDK when an `error` event comes in. + +```py +client = AsyncOpenAI() + +async with client.beta.realtime.connect(model="gpt-4o-realtime-preview-2024-10-01") as connection: + ... + async for event in connection: + if event.type == 'error': + print(event.error.type) + print(event.error.code) + print(event.error.event_id) + print(event.error.message) +``` + ## Using types Nested request parameters are [TypedDicts](https://docs.python.org/3/library/typing.html#typing.TypedDict). Responses are [Pydantic models](https://docs.pydantic.dev) which also provide helper methods for things like: diff --git a/examples/realtime/audio_util.py b/examples/realtime/audio_util.py new file mode 100644 index 0000000000..b073cc45be --- /dev/null +++ b/examples/realtime/audio_util.py @@ -0,0 +1,142 @@ +from __future__ import annotations + +import io +import base64 +import asyncio +import threading +from typing import Callable, Awaitable + +import numpy as np +import pyaudio +import sounddevice as sd +from pydub import AudioSegment + +from openai.resources.beta.realtime.realtime import AsyncRealtimeConnection + +CHUNK_LENGTH_S = 0.05 # 100ms +SAMPLE_RATE = 24000 +FORMAT = pyaudio.paInt16 +CHANNELS = 1 + +# pyright: reportUnknownMemberType=false, reportUnknownVariableType=false, reportUnknownArgumentType=false + + +def audio_to_pcm16_base64(audio_bytes: bytes) -> bytes: + # load the audio file from the byte stream + audio = AudioSegment.from_file(io.BytesIO(audio_bytes)) + print(f"Loaded audio: {audio.frame_rate=} {audio.channels=} {audio.sample_width=} {audio.frame_width=}") + # resample to 24kHz mono pcm16 + pcm_audio = audio.set_frame_rate(SAMPLE_RATE).set_channels(CHANNELS).set_sample_width(2).raw_data + return pcm_audio + + +class AudioPlayerAsync: + def __init__(self): + self.queue = [] + self.lock = threading.Lock() + self.stream = sd.OutputStream( + callback=self.callback, + samplerate=SAMPLE_RATE, + channels=CHANNELS, + dtype=np.int16, + blocksize=int(CHUNK_LENGTH_S * SAMPLE_RATE), + ) + self.playing = False + self._frame_count = 0 + + def callback(self, outdata, frames, time, status): # noqa + with self.lock: + data = np.empty(0, dtype=np.int16) + + # get next item from queue if there is still space in the buffer + while len(data) < frames and len(self.queue) > 0: + item = self.queue.pop(0) + frames_needed = frames - len(data) + data = np.concatenate((data, item[:frames_needed])) + if len(item) > frames_needed: + self.queue.insert(0, item[frames_needed:]) + + self._frame_count += len(data) + + # fill the rest of the frames with zeros if there is no more data + if len(data) < frames: + data = np.concatenate((data, np.zeros(frames - len(data), dtype=np.int16))) + + outdata[:] = data.reshape(-1, 1) + + def reset_frame_count(self): + self._frame_count = 0 + + def get_frame_count(self): + return self._frame_count + + def add_data(self, data: bytes): + with self.lock: + # bytes is pcm16 single channel audio data, convert to numpy array + np_data = np.frombuffer(data, dtype=np.int16) + self.queue.append(np_data) + if not self.playing: + self.start() + + def start(self): + self.playing = True + self.stream.start() + + def stop(self): + self.playing = False + self.stream.stop() + with self.lock: + self.queue = [] + + def terminate(self): + self.stream.close() + + +async def send_audio_worker_sounddevice( + connection: AsyncRealtimeConnection, + should_send: Callable[[], bool] | None = None, + start_send: Callable[[], Awaitable[None]] | None = None, +): + sent_audio = False + + device_info = sd.query_devices() + print(device_info) + + read_size = int(SAMPLE_RATE * 0.02) + + stream = sd.InputStream( + channels=CHANNELS, + samplerate=SAMPLE_RATE, + dtype="int16", + ) + stream.start() + + try: + while True: + if stream.read_available < read_size: + await asyncio.sleep(0) + continue + + data, _ = stream.read(read_size) + + if should_send() if should_send else True: + if not sent_audio and start_send: + await start_send() + await connection.send( + {"type": "input_audio_buffer.append", "audio": base64.b64encode(data).decode("utf-8")} + ) + sent_audio = True + + elif sent_audio: + print("Done, triggering inference") + await connection.send({"type": "input_audio_buffer.commit"}) + await connection.send({"type": "response.create", "response": {}}) + sent_audio = False + + await asyncio.sleep(0) + + except KeyboardInterrupt: + pass + finally: + stream.stop() + stream.close() diff --git a/examples/realtime/push_to_talk_app.py b/examples/realtime/push_to_talk_app.py new file mode 100755 index 0000000000..d46945a8ed --- /dev/null +++ b/examples/realtime/push_to_talk_app.py @@ -0,0 +1,281 @@ +#!/usr/bin/env uv run +#################################################################### +# Sample TUI app with a push to talk interface to the Realtime API # +# If you have `uv` installed and the `OPENAI_API_KEY` # +# environment variable set, you can run this example with just # +# # +# `./examples/realtime/push_to_talk_app.py` # +#################################################################### +# +# /// script +# requires-python = ">=3.9" +# dependencies = [ +# "textual", +# "numpy", +# "pyaudio", +# "pydub", +# "sounddevice", +# "openai[realtime]", +# ] +# +# [tool.uv.sources] +# openai = { path = "../../", editable = true } +# /// +from __future__ import annotations + +import base64 +import asyncio +from typing import Any, cast +from typing_extensions import override + +from textual import events +from audio_util import CHANNELS, SAMPLE_RATE, AudioPlayerAsync +from textual.app import App, ComposeResult +from textual.widgets import Button, Static, RichLog +from textual.reactive import reactive +from textual.containers import Container + +from openai import AsyncOpenAI +from openai.types.beta.realtime.session import Session +from openai.resources.beta.realtime.realtime import AsyncRealtimeConnection + + +class SessionDisplay(Static): + """A widget that shows the current session ID.""" + + session_id = reactive("") + + @override + def render(self) -> str: + return f"Session ID: {self.session_id}" if self.session_id else "Connecting..." + + +class AudioStatusIndicator(Static): + """A widget that shows the current audio recording status.""" + + is_recording = reactive(False) + + @override + def render(self) -> str: + status = ( + "🔴 Recording... (Press K to stop)" if self.is_recording else "⚪ Press K to start recording (Q to quit)" + ) + return status + + +class RealtimeApp(App[None]): + CSS = """ + Screen { + background: #1a1b26; /* Dark blue-grey background */ + } + + Container { + border: double rgb(91, 164, 91); + } + + Horizontal { + width: 100%; + } + + #input-container { + height: 5; /* Explicit height for input container */ + margin: 1 1; + padding: 1 2; + } + + Input { + width: 80%; + height: 3; /* Explicit height for input */ + } + + Button { + width: 20%; + height: 3; /* Explicit height for button */ + } + + #bottom-pane { + width: 100%; + height: 82%; /* Reduced to make room for session display */ + border: round rgb(205, 133, 63); + content-align: center middle; + } + + #status-indicator { + height: 3; + content-align: center middle; + background: #2a2b36; + border: solid rgb(91, 164, 91); + margin: 1 1; + } + + #session-display { + height: 3; + content-align: center middle; + background: #2a2b36; + border: solid rgb(91, 164, 91); + margin: 1 1; + } + + Static { + color: white; + } + """ + + client: AsyncOpenAI + should_send_audio: asyncio.Event + audio_player: AudioPlayerAsync + last_audio_item_id: str | None + connection: AsyncRealtimeConnection | None + session: Session | None + connected: asyncio.Event + + def __init__(self) -> None: + super().__init__() + self.connection = None + self.session = None + self.client = AsyncOpenAI() + self.audio_player = AudioPlayerAsync() + self.last_audio_item_id = None + self.should_send_audio = asyncio.Event() + self.connected = asyncio.Event() + + @override + def compose(self) -> ComposeResult: + """Create child widgets for the app.""" + with Container(): + yield SessionDisplay(id="session-display") + yield AudioStatusIndicator(id="status-indicator") + yield RichLog(id="bottom-pane", wrap=True, highlight=True, markup=True) + + async def on_mount(self) -> None: + self.run_worker(self.handle_realtime_connection()) + self.run_worker(self.send_mic_audio()) + + async def handle_realtime_connection(self) -> None: + async with self.client.beta.realtime.connect(model="gpt-4o-realtime-preview-2024-10-01") as conn: + self.connection = conn + self.connected.set() + + # note: this is the default and can be omitted + # if you want to manually handle VAD yourself, then set `'turn_detection': None` + await conn.session.update(session={"turn_detection": {"type": "server_vad"}}) + + acc_items: dict[str, Any] = {} + + async for event in conn: + if event.type == "session.created": + self.session = event.session + session_display = self.query_one(SessionDisplay) + assert event.session.id is not None + session_display.session_id = event.session.id + continue + + if event.type == "session.updated": + self.session = event.session + continue + + if event.type == "response.audio.delta": + if event.item_id != self.last_audio_item_id: + self.audio_player.reset_frame_count() + self.last_audio_item_id = event.item_id + + bytes_data = base64.b64decode(event.delta) + self.audio_player.add_data(bytes_data) + continue + + if event.type == "response.audio_transcript.delta": + try: + text = acc_items[event.item_id] + except KeyError: + acc_items[event.item_id] = event.delta + else: + acc_items[event.item_id] = text + event.delta + + # Clear and update the entire content because RichLog otherwise treats each delta as a new line + bottom_pane = self.query_one("#bottom-pane", RichLog) + bottom_pane.clear() + bottom_pane.write(acc_items[event.item_id]) + continue + + async def _get_connection(self) -> AsyncRealtimeConnection: + await self.connected.wait() + assert self.connection is not None + return self.connection + + async def send_mic_audio(self) -> None: + import sounddevice as sd # type: ignore + + sent_audio = False + + device_info = sd.query_devices() + print(device_info) + + read_size = int(SAMPLE_RATE * 0.02) + + stream = sd.InputStream( + channels=CHANNELS, + samplerate=SAMPLE_RATE, + dtype="int16", + ) + stream.start() + + status_indicator = self.query_one(AudioStatusIndicator) + + try: + while True: + if stream.read_available < read_size: + await asyncio.sleep(0) + continue + + await self.should_send_audio.wait() + status_indicator.is_recording = True + + data, _ = stream.read(read_size) + + connection = await self._get_connection() + if not sent_audio: + asyncio.create_task(connection.send({"type": "response.cancel"})) + sent_audio = True + + await connection.input_audio_buffer.append(audio=base64.b64encode(cast(Any, data)).decode("utf-8")) + + await asyncio.sleep(0) + except KeyboardInterrupt: + pass + finally: + stream.stop() + stream.close() + + async def on_key(self, event: events.Key) -> None: + """Handle key press events.""" + if event.key == "enter": + self.query_one(Button).press() + return + + if event.key == "q": + self.exit() + return + + if event.key == "k": + status_indicator = self.query_one(AudioStatusIndicator) + if status_indicator.is_recording: + self.should_send_audio.clear() + status_indicator.is_recording = False + + if self.session and self.session.turn_detection is None: + # The default in the API is that the model will automatically detect when the user has + # stopped talking and then start responding itself. + # + # However if we're in manual `turn_detection` mode then we need to + # manually tell the model to commit the audio buffer and start responding. + conn = await self._get_connection() + await conn.input_audio_buffer.commit() + await conn.response.create() + else: + self.should_send_audio.set() + status_indicator.is_recording = True + + +if __name__ == "__main__": + app = RealtimeApp() + app.run() diff --git a/mypy.ini b/mypy.ini index 50e5add04b..1ea1fe909d 100644 --- a/mypy.ini +++ b/mypy.ini @@ -8,7 +8,10 @@ show_error_codes = True # # We also exclude our `tests` as mypy doesn't always infer # types correctly and Pyright will still catch any type errors. -exclude = ^(src/openai/_files\.py|src/openai/_utils/_logs\.py|_dev/.*\.py|tests/.*)$ + +# realtime examples use inline `uv` script dependencies +# which means it can't be type checked +exclude = ^(src/openai/_files\.py|_dev/.*\.py|tests/.*|src/openai/_utils/_logs\.py|examples/realtime/audio_util\.py|examples/realtime/push_to_talk_app\.py)$ strict_equality = True implicit_reexport = True diff --git a/pyproject.toml b/pyproject.toml index f83aff6fee..8e78257e67 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -157,6 +157,11 @@ exclude = [ "_dev", ".venv", ".nox", + + # uses inline `uv` script dependencies + # which means it can't be type checked + "examples/realtime/audio_util.py", + "examples/realtime/push_to_talk_app.py" ] reportImplicitOverride = true From 1b78f22ddf4b64542b39804882fca388a62355fb Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 17 Dec 2024 18:19:24 +0000 Subject: [PATCH 616/816] release: 1.58.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 27 +++++++++++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 30 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index f9ae229e1a..452fa092bd 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.57.4" + ".": "1.58.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 02b7d0271d..5699c0cec2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,32 @@ # Changelog +## 1.58.0 (2024-12-17) + +Full Changelog: [v1.57.4...v1.58.0](https://github.com/openai/openai-python/compare/v1.57.4...v1.58.0) + +### Features + +* add Realtime API support ([#1958](https://github.com/openai/openai-python/issues/1958)) ([97d73cf](https://github.com/openai/openai-python/commit/97d73cf89935ca6098bb889a92f0ec2cdff16989)) +* **api:** new o1 and GPT-4o models + preference fine-tuning ([#1956](https://github.com/openai/openai-python/issues/1956)) ([ec22ffb](https://github.com/openai/openai-python/commit/ec22ffb129c524525caa33b088405d27c271e631)) + + +### Bug Fixes + +* add reasoning_effort to all methods ([8829c32](https://github.com/openai/openai-python/commit/8829c3202dbe790ca3646476c802ec55ed47d864)) +* **assistants:** correctly send `include` query param ([9a4c69c](https://github.com/openai/openai-python/commit/9a4c69c383bc6719b6521a485f2c7e62a9c036a9)) +* **cli/migrate:** change grit binaries prefix ([#1951](https://github.com/openai/openai-python/issues/1951)) ([1c396c9](https://github.com/openai/openai-python/commit/1c396c95b040fb3d1a2523b09eaad4ff62d96846)) + + +### Chores + +* **internal:** fix some typos ([#1955](https://github.com/openai/openai-python/issues/1955)) ([628dead](https://github.com/openai/openai-python/commit/628dead660c00435bf46e09081c7b90b7bbe4a8a)) + + +### Documentation + +* add examples + guidance on Realtime API support ([1cb00f8](https://github.com/openai/openai-python/commit/1cb00f8fed78052aacbb9e0fac997b6ba0d44d2a)) +* **readme:** example snippet for client context manager ([#1953](https://github.com/openai/openai-python/issues/1953)) ([ad80255](https://github.com/openai/openai-python/commit/ad802551d8aaf4e6eff711118676ec4e64392638)) + ## 1.57.4 (2024-12-13) Full Changelog: [v1.57.3...v1.57.4](https://github.com/openai/openai-python/compare/v1.57.3...v1.57.4) diff --git a/pyproject.toml b/pyproject.toml index 8e78257e67..1f2c9fe6c4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.57.4" +version = "1.58.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 5b82015017..7f2f4cafb8 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.57.4" # x-release-please-version +__version__ = "1.58.0" # x-release-please-version From 6935dfdcce9195a26e9ea83597d0c4f5c7631254 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Tue, 17 Dec 2024 19:54:33 +0000 Subject: [PATCH 617/816] docs(readme): fix example script link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4c3ba87c97..87837db175 100644 --- a/README.md +++ b/README.md @@ -300,7 +300,7 @@ async def main(): asyncio.run(main()) ``` -However the real magic of the Realtime API is handling audio inputs / outputs, see this example [TUI script](https://github.com/stainless-sdks/openai-python/blob/robert/realtime-docs-preview/examples/realtime/push_to_talk_app.py) for a fully fledged example. +However the real magic of the Realtime API is handling audio inputs / outputs, see this example [TUI script](https://github.com/openai/openai-python/blob/main/examples/realtime/push_to_talk_app.py) for a fully fledged example. ### Realtime error handling From 19ecaafeda91480d0dfd7ce44e7317220b9d48b6 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 17 Dec 2024 19:55:01 +0000 Subject: [PATCH 618/816] release: 1.58.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 452fa092bd..73a4167d2d 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.58.0" + ".": "1.58.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 5699c0cec2..6519747179 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.58.1 (2024-12-17) + +Full Changelog: [v1.58.0...v1.58.1](https://github.com/openai/openai-python/compare/v1.58.0...v1.58.1) + +### Documentation + +* **readme:** fix example script link ([23ba877](https://github.com/openai/openai-python/commit/23ba8778fd55e0f54f36685e9c5950b452d8e10c)) + ## 1.58.0 (2024-12-17) Full Changelog: [v1.57.4...v1.58.0](https://github.com/openai/openai-python/compare/v1.57.4...v1.58.0) diff --git a/pyproject.toml b/pyproject.toml index 1f2c9fe6c4..fd55cf2b5d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.58.0" +version = "1.58.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 7f2f4cafb8..c08e68e11b 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.58.0" # x-release-please-version +__version__ = "1.58.1" # x-release-please-version From cacd374b850407b211d1f1e7740da0cf4e4d68d1 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 18 Dec 2024 22:17:00 +0000 Subject: [PATCH 619/816] chore(realtime): update docstrings (#1964) --- .stats.yml | 2 +- src/openai/types/beta/realtime/conversation_item_content.py | 5 +++-- .../types/beta/realtime/conversation_item_content_param.py | 5 +++-- src/openai/types/beta/realtime/response_create_event.py | 3 ++- .../types/beta/realtime/response_create_event_param.py | 3 ++- 5 files changed, 11 insertions(+), 7 deletions(-) diff --git a/.stats.yml b/.stats.yml index 12219ccaa1..1a7a7a5269 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 69 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-0d64ca9e45f51b4279f87b205eeb3a3576df98407698ce053f2e2302c1c08df1.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-a39aca84ed97ebafb707ebd5221e2787c5a42ff3d98f2ffaea8a0dcd84cbcbcb.yml diff --git a/src/openai/types/beta/realtime/conversation_item_content.py b/src/openai/types/beta/realtime/conversation_item_content.py index b854aa0e0f..ab40a4a1a7 100644 --- a/src/openai/types/beta/realtime/conversation_item_content.py +++ b/src/openai/types/beta/realtime/conversation_item_content.py @@ -11,8 +11,9 @@ class ConversationItemContent(BaseModel): id: Optional[str] = None """ - ID of a previous conversation item (like a model response), used for - `item_reference` content types. + ID of a previous conversation item to reference (for `item_reference` content + types in `response.create` events). These can reference both client and server + created items. """ audio: Optional[str] = None diff --git a/src/openai/types/beta/realtime/conversation_item_content_param.py b/src/openai/types/beta/realtime/conversation_item_content_param.py index b354d78971..7a3a92a39d 100644 --- a/src/openai/types/beta/realtime/conversation_item_content_param.py +++ b/src/openai/types/beta/realtime/conversation_item_content_param.py @@ -10,8 +10,9 @@ class ConversationItemContentParam(TypedDict, total=False): id: str """ - ID of a previous conversation item (like a model response), used for - `item_reference` content types. + ID of a previous conversation item to reference (for `item_reference` content + types in `response.create` events). These can reference both client and server + created items. """ audio: str diff --git a/src/openai/types/beta/realtime/response_create_event.py b/src/openai/types/beta/realtime/response_create_event.py index 00ba1e5dad..e4e5e7c68f 100644 --- a/src/openai/types/beta/realtime/response_create_event.py +++ b/src/openai/types/beta/realtime/response_create_event.py @@ -89,7 +89,8 @@ class Response(BaseModel): tool_choice: Optional[str] = None """How the model chooses tools. - Options are `auto`, `none`, `required`, or specify a function. + Options are `auto`, `none`, `required`, or specify a function, like + `{"type": "function", "function": {"name": "my_function"}}`. """ tools: Optional[List[ResponseTool]] = None diff --git a/src/openai/types/beta/realtime/response_create_event_param.py b/src/openai/types/beta/realtime/response_create_event_param.py index 7c92b32df1..7a4b5f086a 100644 --- a/src/openai/types/beta/realtime/response_create_event_param.py +++ b/src/openai/types/beta/realtime/response_create_event_param.py @@ -90,7 +90,8 @@ class Response(TypedDict, total=False): tool_choice: str """How the model chooses tools. - Options are `auto`, `none`, `required`, or specify a function. + Options are `auto`, `none`, `required`, or specify a function, like + `{"type": "function", "function": {"name": "my_function"}}`. """ tools: Iterable[ResponseTool] From 5481c2ecd44044eeddbda479abb19ba9f9766fc2 Mon Sep 17 00:00:00 2001 From: Krista Pratico Date: Thu, 19 Dec 2024 09:28:52 -0800 Subject: [PATCH 620/816] feat(azure): support for the Realtime API (#1963) --- src/openai/_utils/__init__.py | 2 ++ src/openai/_utils/_utils.py | 16 ++++++++++ src/openai/lib/azure.py | 32 ++++++++++++++++++- .../resources/beta/realtime/realtime.py | 20 +++++++++--- 4 files changed, 65 insertions(+), 5 deletions(-) diff --git a/src/openai/_utils/__init__.py b/src/openai/_utils/__init__.py index af2c9bb77e..bd01c088dc 100644 --- a/src/openai/_utils/__init__.py +++ b/src/openai/_utils/__init__.py @@ -25,6 +25,7 @@ coerce_integer as coerce_integer, file_from_path as file_from_path, parse_datetime as parse_datetime, + is_azure_client as is_azure_client, strip_not_given as strip_not_given, deepcopy_minimal as deepcopy_minimal, get_async_library as get_async_library, @@ -32,6 +33,7 @@ get_required_header as get_required_header, maybe_coerce_boolean as maybe_coerce_boolean, maybe_coerce_integer as maybe_coerce_integer, + is_async_azure_client as is_async_azure_client, ) from ._typing import ( is_list_type as is_list_type, diff --git a/src/openai/_utils/_utils.py b/src/openai/_utils/_utils.py index e5811bba42..d6734e6b8f 100644 --- a/src/openai/_utils/_utils.py +++ b/src/openai/_utils/_utils.py @@ -5,6 +5,7 @@ import inspect import functools from typing import ( + TYPE_CHECKING, Any, Tuple, Mapping, @@ -30,6 +31,9 @@ _SequenceT = TypeVar("_SequenceT", bound=Sequence[object]) CallableT = TypeVar("CallableT", bound=Callable[..., Any]) +if TYPE_CHECKING: + from ..lib.azure import AzureOpenAI, AsyncAzureOpenAI + def flatten(t: Iterable[Iterable[_T]]) -> list[_T]: return [item for sublist in t for item in sublist] @@ -412,3 +416,15 @@ def json_safe(data: object) -> object: return data.isoformat() return data + + +def is_azure_client(client: object) -> TypeGuard[AzureOpenAI]: + from ..lib.azure import AzureOpenAI + + return isinstance(client, AzureOpenAI) + + +def is_async_azure_client(client: object) -> TypeGuard[AsyncAzureOpenAI]: + from ..lib.azure import AsyncAzureOpenAI + + return isinstance(client, AsyncAzureOpenAI) diff --git a/src/openai/lib/azure.py b/src/openai/lib/azure.py index 13d9f31838..f857d76e51 100644 --- a/src/openai/lib/azure.py +++ b/src/openai/lib/azure.py @@ -7,7 +7,7 @@ import httpx -from .._types import NOT_GIVEN, Omit, Timeout, NotGiven +from .._types import NOT_GIVEN, Omit, Query, Timeout, NotGiven from .._utils import is_given, is_mapping from .._client import OpenAI, AsyncOpenAI from .._compat import model_copy @@ -307,6 +307,21 @@ def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions: return options + def _configure_realtime(self, model: str, extra_query: Query) -> tuple[Query, dict[str, str]]: + auth_headers = {} + query = { + **extra_query, + "api-version": self._api_version, + "deployment": model, + } + if self.api_key != "": + auth_headers = {"api-key": self.api_key} + else: + token = self._get_azure_ad_token() + if token: + auth_headers = {"Authorization": f"Bearer {token}"} + return query, auth_headers + class AsyncAzureOpenAI(BaseAzureClient[httpx.AsyncClient, AsyncStream[Any]], AsyncOpenAI): @overload @@ -555,3 +570,18 @@ async def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOp raise ValueError("Unable to handle auth") return options + + async def _configure_realtime(self, model: str, extra_query: Query) -> tuple[Query, dict[str, str]]: + auth_headers = {} + query = { + **extra_query, + "api-version": self._api_version, + "deployment": model, + } + if self.api_key != "": + auth_headers = {"api-key": self.api_key} + else: + token = await self._get_azure_ad_token() + if token: + auth_headers = {"Authorization": f"Bearer {token}"} + return query, auth_headers diff --git a/src/openai/resources/beta/realtime/realtime.py b/src/openai/resources/beta/realtime/realtime.py index c79fd46217..b39b410ecf 100644 --- a/src/openai/resources/beta/realtime/realtime.py +++ b/src/openai/resources/beta/realtime/realtime.py @@ -21,9 +21,11 @@ ) from ...._types import NOT_GIVEN, Query, Headers, NotGiven from ...._utils import ( + is_azure_client, maybe_transform, strip_not_given, async_maybe_transform, + is_async_azure_client, ) from ...._compat import cached_property from ...._models import construct_type_unchecked @@ -319,11 +321,16 @@ async def __aenter__(self) -> AsyncRealtimeConnection: except ImportError as exc: raise OpenAIError("You need to install `openai[realtime]` to use this method") from exc + extra_query = self.__extra_query + auth_headers = self.__client.auth_headers + if is_async_azure_client(self.__client): + extra_query, auth_headers = await self.__client._configure_realtime(self.__model, extra_query) + url = self._prepare_url().copy_with( params={ **self.__client.base_url.params, "model": self.__model, - **self.__extra_query, + **extra_query, }, ) log.debug("Connecting to %s", url) @@ -336,7 +343,7 @@ async def __aenter__(self) -> AsyncRealtimeConnection: user_agent_header=self.__client.user_agent, additional_headers=_merge_mappings( { - **self.__client.auth_headers, + **auth_headers, "OpenAI-Beta": "realtime=v1", }, self.__extra_headers, @@ -496,11 +503,16 @@ def __enter__(self) -> RealtimeConnection: except ImportError as exc: raise OpenAIError("You need to install `openai[realtime]` to use this method") from exc + extra_query = self.__extra_query + auth_headers = self.__client.auth_headers + if is_azure_client(self.__client): + extra_query, auth_headers = self.__client._configure_realtime(self.__model, extra_query) + url = self._prepare_url().copy_with( params={ **self.__client.base_url.params, "model": self.__model, - **self.__extra_query, + **extra_query, }, ) log.debug("Connecting to %s", url) @@ -513,7 +525,7 @@ def __enter__(self) -> RealtimeConnection: user_agent_header=self.__client.user_agent, additional_headers=_merge_mappings( { - **self.__client.auth_headers, + **auth_headers, "OpenAI-Beta": "realtime=v1", }, self.__extra_headers, From 89d49335a02ac231925e5a514659c93322f29526 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Sat, 21 Dec 2024 05:03:53 +0000 Subject: [PATCH 621/816] release: 1.59.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 73a4167d2d..451b00c101 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.58.1" + ".": "1.59.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 6519747179..1f411fc397 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.59.0 (2024-12-21) + +Full Changelog: [v1.58.1...v1.59.0](https://github.com/openai/openai-python/compare/v1.58.1...v1.59.0) + +### Features + +* **azure:** support for the Realtime API ([#1963](https://github.com/openai/openai-python/issues/1963)) ([9fda141](https://github.com/openai/openai-python/commit/9fda14172abdb66fe240aa7b4dc7cfae4faf1d73)) + + +### Chores + +* **realtime:** update docstrings ([#1964](https://github.com/openai/openai-python/issues/1964)) ([3dee863](https://github.com/openai/openai-python/commit/3dee863554d28272103e90a6a199ac196e92ff05)) + ## 1.58.1 (2024-12-17) Full Changelog: [v1.58.0...v1.58.1](https://github.com/openai/openai-python/compare/v1.58.0...v1.58.1) diff --git a/pyproject.toml b/pyproject.toml index fd55cf2b5d..127213c372 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.58.1" +version = "1.59.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index c08e68e11b..7719866b19 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.58.1" # x-release-please-version +__version__ = "1.59.0" # x-release-please-version From 99861632e9bdb1a480d92913d621bded574bf797 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 2 Jan 2025 01:44:32 +0000 Subject: [PATCH 622/816] chore: bump license year (#1981) --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index 621a6becfb..f011417af6 100644 --- a/LICENSE +++ b/LICENSE @@ -186,7 +186,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright 2024 OpenAI + Copyright 2025 OpenAI Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. From 44d6210f101abedeb2dd68507fcffcb329df70ea Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 2 Jan 2025 05:04:23 +0000 Subject: [PATCH 623/816] release: 1.59.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 451b00c101..8dcb014faf 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.59.0" + ".": "1.59.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f411fc397..4f029bf1f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.59.1 (2025-01-02) + +Full Changelog: [v1.59.0...v1.59.1](https://github.com/openai/openai-python/compare/v1.59.0...v1.59.1) + +### Chores + +* bump license year ([#1981](https://github.com/openai/openai-python/issues/1981)) ([f29011a](https://github.com/openai/openai-python/commit/f29011a6426d3fa4844ecd723ee20561ee60c665)) + ## 1.59.0 (2024-12-21) Full Changelog: [v1.58.1...v1.59.0](https://github.com/openai/openai-python/compare/v1.58.1...v1.59.0) diff --git a/pyproject.toml b/pyproject.toml index 127213c372..51166e5eca 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.59.0" +version = "1.59.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 7719866b19..98a34f1356 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.59.0" # x-release-please-version +__version__ = "1.59.1" # x-release-please-version From ccf5753ae01ddee52f102544d992b51e333cb669 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Fri, 3 Jan 2025 16:01:50 +0000 Subject: [PATCH 624/816] chore(ci): fix publish workflow --- .github/workflows/publish-pypi.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml index 44027a3c4c..76d0efca80 100644 --- a/.github/workflows/publish-pypi.yml +++ b/.github/workflows/publish-pypi.yml @@ -8,6 +8,7 @@ jobs: publish: name: publish runs-on: ubuntu-latest + environment: publish steps: - uses: actions/checkout@v4 From b3fc5b39594d30e7dc73813ce88c64796b0e8b96 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 3 Jan 2025 16:02:21 +0000 Subject: [PATCH 625/816] release: 1.59.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 9 +++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 8dcb014faf..7676e15413 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.59.1" + ".": "1.59.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f029bf1f2..2b410e0a5f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 1.59.2 (2025-01-03) + +Full Changelog: [v1.59.1...v1.59.2](https://github.com/openai/openai-python/compare/v1.59.1...v1.59.2) + +### Chores + +* **ci:** fix publish workflow ([0be1f5d](https://github.com/openai/openai-python/commit/0be1f5de0daf807cece564abf061c8bb188bb9aa)) +* **internal:** empty commit ([fe8dc2e](https://github.com/openai/openai-python/commit/fe8dc2e97fc430ea2433ed28cfaa79425af223ec)) + ## 1.59.1 (2025-01-02) Full Changelog: [v1.59.0...v1.59.1](https://github.com/openai/openai-python/compare/v1.59.0...v1.59.1) diff --git a/pyproject.toml b/pyproject.toml index 51166e5eca..7d7c59fa0b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.59.1" +version = "1.59.2" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 98a34f1356..866a882fc2 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.59.1" # x-release-please-version +__version__ = "1.59.2" # x-release-please-version From 0189770e1d5ba0db18d7a923e1d562df0ff4fe6d Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 3 Jan 2025 22:57:16 +0000 Subject: [PATCH 626/816] chore(api): bump spec version (#1985) --- .stats.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index 1a7a7a5269..1ac7a94471 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 69 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-a39aca84ed97ebafb707ebd5221e2787c5a42ff3d98f2ffaea8a0dcd84cbcbcb.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-02200a58ed631064b6419711da99fefd6e97bdbbeb577a80a1a6e0c8dbcb18f5.yml From 1e07c9d839e7e96f02d0a4b745f379a43086334c Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 3 Jan 2025 22:57:52 +0000 Subject: [PATCH 627/816] release: 1.59.3 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 7676e15413..f701c8396e 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.59.2" + ".": "1.59.3" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b410e0a5f..75d144cca6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.59.3 (2025-01-03) + +Full Changelog: [v1.59.2...v1.59.3](https://github.com/openai/openai-python/compare/v1.59.2...v1.59.3) + +### Chores + +* **api:** bump spec version ([#1985](https://github.com/openai/openai-python/issues/1985)) ([c6f1b35](https://github.com/openai/openai-python/commit/c6f1b357fcf669065f4ed6819d47a528b0787128)) + ## 1.59.2 (2025-01-03) Full Changelog: [v1.59.1...v1.59.2](https://github.com/openai/openai-python/compare/v1.59.1...v1.59.2) diff --git a/pyproject.toml b/pyproject.toml index 7d7c59fa0b..b9d4abf59a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.59.2" +version = "1.59.3" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 866a882fc2..342d208d2b 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.59.2" # x-release-please-version +__version__ = "1.59.3" # x-release-please-version From 7117a18f4f25c5d07db8d96dd2930f0381f2309f Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 6 Jan 2025 16:50:25 +0000 Subject: [PATCH 628/816] chore: add missing isclass check for structured outputs --- src/openai/lib/_pydantic.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/openai/lib/_pydantic.py b/src/openai/lib/_pydantic.py index 22c7a1f3cd..4e8bc772be 100644 --- a/src/openai/lib/_pydantic.py +++ b/src/openai/lib/_pydantic.py @@ -127,6 +127,8 @@ def resolve_ref(*, root: dict[str, object], ref: str) -> object: def is_basemodel_type(typ: type) -> TypeGuard[type[pydantic.BaseModel]]: + if not inspect.isclass(typ): + return False return issubclass(typ, pydantic.BaseModel) From f5436b147421296c22269e2fe4081c917d7b1658 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 6 Jan 2025 17:15:50 +0000 Subject: [PATCH 629/816] chore: add missing isclass check (#1988) --- src/openai/_models.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/openai/_models.py b/src/openai/_models.py index 2f67e5eb4d..1bbc5fa4cc 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -513,7 +513,11 @@ def construct_type(*, value: object, type_: object) -> object: _, items_type = get_args(type_) # Dict[_, items_type] return {key: construct_type(value=item, type_=items_type) for key, item in value.items()} - if not is_literal_type(type_) and (issubclass(origin, BaseModel) or issubclass(origin, GenericModel)): + if ( + not is_literal_type(type_) + and inspect.isclass(origin) + and (issubclass(origin, BaseModel) or issubclass(origin, GenericModel)) + ): if is_list(value): return [cast(Any, type_).construct(**entry) if is_mapping(entry) else entry for entry in value] From 255677d7091313d2ef32316c6c64983673e077d0 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 6 Jan 2025 17:41:56 +0000 Subject: [PATCH 630/816] docs(realtime): fix event reference link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 87837db175..cc1eb1a4f7 100644 --- a/README.md +++ b/README.md @@ -264,7 +264,7 @@ The Realtime API enables you to build low-latency, multi-modal conversational ex Under the hood the SDK uses the [`websockets`](https://websockets.readthedocs.io/en/stable/) library to manage connections. -The Realtime API works through a combination of client-sent events and server-sent events. Clients can send events to do things like update session configuration or send text and audio inputs. Server events confirm when audio responses have completed, or when a text response from the model has been received. A full event reference can be found [here](platform.openai.com/docs/api-reference/realtime-client-events) and a guide can be found [here](https://platform.openai.com/docs/guides/realtime). +The Realtime API works through a combination of client-sent events and server-sent events. Clients can send events to do things like update session configuration or send text and audio inputs. Server events confirm when audio responses have completed, or when a text response from the model has been received. A full event reference can be found [here](https://platform.openai.com/docs/api-reference/realtime-client-events) and a guide can be found [here](https://platform.openai.com/docs/guides/realtime). Basic text based example: From 1fb671ea97b51918fdcdbac8bc9abb68fc6b7506 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 7 Jan 2025 09:49:30 +0000 Subject: [PATCH 631/816] chore(internal): bump httpx dependency (#1990) --- pyproject.toml | 3 +-- requirements-dev.lock | 5 ++--- requirements.lock | 3 +-- 3 files changed, 4 insertions(+), 7 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index b9d4abf59a..3a683b0eef 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -66,8 +66,7 @@ dev-dependencies = [ "types-tqdm > 4", "types-pyaudio > 0", "trio >=0.22.2", - "nest_asyncio==1.6.0" - + "nest_asyncio==1.6.0", ] [tool.rye.scripts] diff --git a/requirements-dev.lock b/requirements-dev.lock index 94cf6aca07..15ecbf081a 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -60,7 +60,7 @@ h11==0.14.0 # via httpcore httpcore==1.0.2 # via httpx -httpx==0.25.2 +httpx==0.28.1 # via openai # via respx idna==3.4 @@ -137,7 +137,7 @@ pytz==2023.3.post1 requests==2.31.0 # via azure-core # via msal -respx==0.20.2 +respx==0.22.0 rich==13.7.1 # via inline-snapshot ruff==0.6.9 @@ -149,7 +149,6 @@ six==1.16.0 # via python-dateutil sniffio==1.3.0 # via anyio - # via httpx # via openai # via trio sortedcontainers==2.4.0 diff --git a/requirements.lock b/requirements.lock index c10449ac20..a3e3602abe 100644 --- a/requirements.lock +++ b/requirements.lock @@ -25,7 +25,7 @@ h11==0.14.0 # via httpcore httpcore==1.0.2 # via httpx -httpx==0.25.2 +httpx==0.28.1 # via openai idna==3.4 # via anyio @@ -52,7 +52,6 @@ six==1.16.0 # via python-dateutil sniffio==1.3.0 # via anyio - # via httpx # via openai tqdm==4.66.5 # via openai From 728100cf7a7aff90bbe274e593bc726030e392ec Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 7 Jan 2025 09:50:04 +0000 Subject: [PATCH 632/816] release: 1.59.4 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 15 +++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 18 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index f701c8396e..b58729ff4e 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.59.3" + ".": "1.59.4" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 75d144cca6..78a1f2a1cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## 1.59.4 (2025-01-07) + +Full Changelog: [v1.59.3...v1.59.4](https://github.com/openai/openai-python/compare/v1.59.3...v1.59.4) + +### Chores + +* add missing isclass check ([#1988](https://github.com/openai/openai-python/issues/1988)) ([61d9072](https://github.com/openai/openai-python/commit/61d9072fbace58d64910ec7378c3686ac555972e)) +* add missing isclass check for structured outputs ([bcbf013](https://github.com/openai/openai-python/commit/bcbf013e8d825b8b5f88172313dfb6e0313ca34c)) +* **internal:** bump httpx dependency ([#1990](https://github.com/openai/openai-python/issues/1990)) ([288c2c3](https://github.com/openai/openai-python/commit/288c2c30dc405cbaa89924f9243442300e95e100)) + + +### Documentation + +* **realtime:** fix event reference link ([9b6885d](https://github.com/openai/openai-python/commit/9b6885d50f8d65ba5009642046727d291e0f14fa)) + ## 1.59.3 (2025-01-03) Full Changelog: [v1.59.2...v1.59.3](https://github.com/openai/openai-python/compare/v1.59.2...v1.59.3) diff --git a/pyproject.toml b/pyproject.toml index 3a683b0eef..f5309b299a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.59.3" +version = "1.59.4" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 342d208d2b..86545ed82a 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.59.3" # x-release-please-version +__version__ = "1.59.4" # x-release-please-version From bd49dd156f2654a14fea2a26fc39b33a068d7900 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 7 Jan 2025 20:09:36 +0000 Subject: [PATCH 633/816] fix(client): only call .close() when needed (#1992) --- src/openai/_base_client.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index cceec903d9..1fa039c0b1 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -769,6 +769,9 @@ def __init__(self, **kwargs: Any) -> None: class SyncHttpxClientWrapper(DefaultHttpxClient): def __del__(self) -> None: + if self.is_closed: + return + try: self.close() except Exception: @@ -1351,6 +1354,9 @@ def __init__(self, **kwargs: Any) -> None: class AsyncHttpxClientWrapper(DefaultAsyncHttpxClient): def __del__(self) -> None: + if self.is_closed: + return + try: # TODO(someday): support non asyncio runtimes here asyncio.get_running_loop().create_task(self.aclose()) From eb02a2c2a7bcd81cc00836c36f178b028df96c33 Mon Sep 17 00:00:00 2001 From: Mustafa <66224841+mustafa-nom@users.noreply.github.com> Date: Wed, 8 Jan 2025 05:22:24 -0800 Subject: [PATCH 634/816] docs: fix typos (#1995) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cc1eb1a4f7..3ab509ce42 100644 --- a/README.md +++ b/README.md @@ -655,7 +655,7 @@ If you need to access undocumented endpoints, params, or response properties, th #### Undocumented endpoints To make requests to undocumented endpoints, you can make requests using `client.get`, `client.post`, and other -http verbs. Options on the client will be respected (such as retries) will be respected when making this +http verbs. Options on the client (such as retries) will be respected when making this request. ```py From fee9c81bece28f2e145c7abf357a93f52983e119 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 8 Jan 2025 13:50:20 +0000 Subject: [PATCH 635/816] docs: fix typos (#1996) --- README.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 3ab509ce42..32095a22d2 100644 --- a/README.md +++ b/README.md @@ -469,7 +469,7 @@ except openai.APIStatusError as e: print(e.response) ``` -Error codes are as followed: +Error codes are as follows: | Status Code | Error Type | | ----------- | -------------------------- | @@ -611,7 +611,7 @@ completion = response.parse() # get the object that `chat.completions.create()` print(completion) ``` -These methods return an [`LegacyAPIResponse`](https://github.com/openai/openai-python/tree/main/src/openai/_legacy_response.py) object. This is a legacy class as we're changing it slightly in the next major version. +These methods return a [`LegagcyAPIResponse`](https://github.com/openai/openai-python/tree/main/src/openai/_legacy_response.py) object. This is a legacy class as we're changing it slightly in the next major version. For the sync client this will mostly be the same with the exception of `content` & `text` will be methods instead of properties. In the @@ -655,8 +655,7 @@ If you need to access undocumented endpoints, params, or response properties, th #### Undocumented endpoints To make requests to undocumented endpoints, you can make requests using `client.get`, `client.post`, and other -http verbs. Options on the client (such as retries) will be respected when making this -request. +http verbs. Options on the client will be respected (such as retries) when making this request. ```py import httpx From 16315f22b459f96d4785ff5800712e8349811d57 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 8 Jan 2025 14:08:24 +0000 Subject: [PATCH 636/816] docs: more typo fixes (#1998) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 32095a22d2..42f69f5401 100644 --- a/README.md +++ b/README.md @@ -611,7 +611,7 @@ completion = response.parse() # get the object that `chat.completions.create()` print(completion) ``` -These methods return a [`LegagcyAPIResponse`](https://github.com/openai/openai-python/tree/main/src/openai/_legacy_response.py) object. This is a legacy class as we're changing it slightly in the next major version. +These methods return a [`LegacyAPIResponse`](https://github.com/openai/openai-python/tree/main/src/openai/_legacy_response.py) object. This is a legacy class as we're changing it slightly in the next major version. For the sync client this will mostly be the same with the exception of `content` & `text` will be methods instead of properties. In the From e502d3014d8520ce3b29c59abf0fe4a27d447163 Mon Sep 17 00:00:00 2001 From: Josiah Altschuler Date: Wed, 8 Jan 2025 09:00:17 -0600 Subject: [PATCH 637/816] docs(readme): moved period to inside parentheses (#1980) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 42f69f5401..ad1c9afd10 100644 --- a/README.md +++ b/README.md @@ -769,7 +769,7 @@ An example of using the client with Microsoft Entra ID (formerly known as Azure This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions: 1. Changes that only affect static types, without breaking runtime behavior. -2. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals)_. +2. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_ 3. Changes that we do not expect to impact the vast majority of users in practice. We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience. From 52f49794b6ea7c243372870d09a23deae8d019cf Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 8 Jan 2025 15:00:53 +0000 Subject: [PATCH 638/816] release: 1.59.5 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 16 ++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 19 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index b58729ff4e..802e19924e 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.59.4" + ".": "1.59.5" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 78a1f2a1cb..e3a67b7ac9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## 1.59.5 (2025-01-08) + +Full Changelog: [v1.59.4...v1.59.5](https://github.com/openai/openai-python/compare/v1.59.4...v1.59.5) + +### Bug Fixes + +* **client:** only call .close() when needed ([#1992](https://github.com/openai/openai-python/issues/1992)) ([bdfd699](https://github.com/openai/openai-python/commit/bdfd699b99522e83f7610b5f98e36fe43ddf8338)) + + +### Documentation + +* fix typos ([#1995](https://github.com/openai/openai-python/issues/1995)) ([be694a0](https://github.com/openai/openai-python/commit/be694a097d6cf2668f08ecf94c882773b2ee1f84)) +* fix typos ([#1996](https://github.com/openai/openai-python/issues/1996)) ([714aed9](https://github.com/openai/openai-python/commit/714aed9d7eb74a19f6e502fb6d4fe83399f82851)) +* more typo fixes ([#1998](https://github.com/openai/openai-python/issues/1998)) ([7bd92f0](https://github.com/openai/openai-python/commit/7bd92f06a75f11f6afc2d1223d2426e186cc74cb)) +* **readme:** moved period to inside parentheses ([#1980](https://github.com/openai/openai-python/issues/1980)) ([e7fae94](https://github.com/openai/openai-python/commit/e7fae948f2ba8db23461e4374308417570196847)) + ## 1.59.4 (2025-01-07) Full Changelog: [v1.59.3...v1.59.4](https://github.com/openai/openai-python/compare/v1.59.3...v1.59.4) diff --git a/pyproject.toml b/pyproject.toml index f5309b299a..7529b69960 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.59.4" +version = "1.59.5" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 86545ed82a..f8a67d7937 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.59.4" # x-release-please-version +__version__ = "1.59.5" # x-release-please-version From 020385c075aa04e4adc284efabb14e38c23d16d5 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 8 Jan 2025 16:41:34 +0000 Subject: [PATCH 639/816] chore(internal): spec update (#2000) --- .stats.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index 1ac7a94471..9600edae3b 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 69 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-02200a58ed631064b6419711da99fefd6e97bdbbeb577a80a1a6e0c8dbcb18f5.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-b5b0e2c794b012919701c3fd43286af10fa25d33ceb8a881bec2636028f446e0.yml From 5ca7876e6a99c0d47bffc2c4167a5faf58673384 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 9 Jan 2025 10:56:47 +0000 Subject: [PATCH 640/816] fix: correctly handle deserialising `cls` fields (#2002) --- src/openai/_models.py | 8 ++++---- tests/test_models.py | 10 ++++++++++ 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/openai/_models.py b/src/openai/_models.py index 1bbc5fa4cc..23456d9f80 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -204,14 +204,14 @@ def __str__(self) -> str: @classmethod @override def construct( # pyright: ignore[reportIncompatibleMethodOverride] - cls: Type[ModelT], + __cls: Type[ModelT], _fields_set: set[str] | None = None, **values: object, ) -> ModelT: - m = cls.__new__(cls) + m = __cls.__new__(__cls) fields_values: dict[str, object] = {} - config = get_model_config(cls) + config = get_model_config(__cls) populate_by_name = ( config.allow_population_by_field_name if isinstance(config, _ConfigProtocol) @@ -221,7 +221,7 @@ def construct( # pyright: ignore[reportIncompatibleMethodOverride] if _fields_set is None: _fields_set = set() - model_fields = get_model_fields(cls) + model_fields = get_model_fields(__cls) for name, field in model_fields.items(): key = field.alias if key is None or (key not in values and populate_by_name): diff --git a/tests/test_models.py b/tests/test_models.py index 19a71f13ba..30b17e3ac0 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -844,3 +844,13 @@ class Model(BaseModel): assert m.alias == "foo" assert isinstance(m.union, str) assert m.union == "bar" + + +@pytest.mark.skipif(not PYDANTIC_V2, reason="TypeAliasType is not supported in Pydantic v1") +def test_field_named_cls() -> None: + class Model(BaseModel): + cls: str + + m = construct_type(value={"cls": "foo"}, type_=Model) + assert isinstance(m, Model) + assert isinstance(m.cls, str) From 33e40854beef0cb18c0790bea953678c30b6fb5c Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 9 Jan 2025 10:57:26 +0000 Subject: [PATCH 641/816] release: 1.59.6 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 802e19924e..fc624851e9 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.59.5" + ".": "1.59.6" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index e3a67b7ac9..e65def028e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.59.6 (2025-01-09) + +Full Changelog: [v1.59.5...v1.59.6](https://github.com/openai/openai-python/compare/v1.59.5...v1.59.6) + +### Bug Fixes + +* correctly handle deserialising `cls` fields ([#2002](https://github.com/openai/openai-python/issues/2002)) ([089c820](https://github.com/openai/openai-python/commit/089c820c8a5d20e9db6a171f0a4f11b481fe8465)) + + +### Chores + +* **internal:** spec update ([#2000](https://github.com/openai/openai-python/issues/2000)) ([36548f8](https://github.com/openai/openai-python/commit/36548f871763fdd7b5ce44903d186bc916331549)) + ## 1.59.5 (2025-01-08) Full Changelog: [v1.59.4...v1.59.5](https://github.com/openai/openai-python/compare/v1.59.4...v1.59.5) diff --git a/pyproject.toml b/pyproject.toml index 7529b69960..4131e9c1fd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.59.5" +version = "1.59.6" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index f8a67d7937..fa93e603a6 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.59.5" # x-release-please-version +__version__ = "1.59.6" # x-release-please-version From b2dd5e04d6136856c4c00e4ce9af10e45af5f7aa Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 13 Jan 2025 13:29:41 +0000 Subject: [PATCH 642/816] chore: export HttpxBinaryResponseContent class --- src/openai/__init__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/openai/__init__.py b/src/openai/__init__.py index 21c60f7e87..fe85956a4a 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -33,6 +33,7 @@ ) from ._base_client import DefaultHttpxClient, DefaultAsyncHttpxClient from ._utils._logs import setup_logging as _setup_logging +from ._legacy_response import HttpxBinaryResponseContent as HttpxBinaryResponseContent __all__ = [ "types", From d9c966dea77fa3493114865a7f785f3134f1cc1e Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 13 Jan 2025 13:30:18 +0000 Subject: [PATCH 643/816] release: 1.59.7 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index fc624851e9..7da3bd4caf 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.59.6" + ".": "1.59.7" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index e65def028e..08674b4a36 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.59.7 (2025-01-13) + +Full Changelog: [v1.59.6...v1.59.7](https://github.com/openai/openai-python/compare/v1.59.6...v1.59.7) + +### Chores + +* export HttpxBinaryResponseContent class ([7191b71](https://github.com/openai/openai-python/commit/7191b71f3dcbbfcb2f2bec855c3bba93c956384e)) + ## 1.59.6 (2025-01-09) Full Changelog: [v1.59.5...v1.59.6](https://github.com/openai/openai-python/compare/v1.59.5...v1.59.6) diff --git a/pyproject.toml b/pyproject.toml index 4131e9c1fd..e769f4a95f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.59.6" +version = "1.59.7" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index fa93e603a6..656d17ff63 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.59.6" # x-release-please-version +__version__ = "1.59.7" # x-release-please-version From babe65f92c8a71efdc8adb7e68205d5906f571cf Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 13 Jan 2025 16:20:02 +0000 Subject: [PATCH 644/816] chore(internal): streaming refactors (#2012) --- src/openai/_streaming.py | 66 +++++++++++++++++++--------------------- 1 file changed, 32 insertions(+), 34 deletions(-) diff --git a/src/openai/_streaming.py b/src/openai/_streaming.py index 0fda992cff..b275986a46 100644 --- a/src/openai/_streaming.py +++ b/src/openai/_streaming.py @@ -59,23 +59,22 @@ def __stream__(self) -> Iterator[_T]: if sse.data.startswith("[DONE]"): break - if sse.event is None: - data = sse.json() - if is_mapping(data) and data.get("error"): - message = None - error = data.get("error") - if is_mapping(error): - message = error.get("message") - if not message or not isinstance(message, str): - message = "An error occurred during streaming" - - raise APIError( - message=message, - request=self.response.request, - body=data["error"], - ) - - yield process_data(data=data, cast_to=cast_to, response=response) + data = sse.json() + if is_mapping(data) and data.get("error"): + message = None + error = data.get("error") + if is_mapping(error): + message = error.get("message") + if not message or not isinstance(message, str): + message = "An error occurred during streaming" + + raise APIError( + message=message, + request=self.response.request, + body=data["error"], + ) + + yield process_data(data=data, cast_to=cast_to, response=response) else: data = sse.json() @@ -161,23 +160,22 @@ async def __stream__(self) -> AsyncIterator[_T]: if sse.data.startswith("[DONE]"): break - if sse.event is None: - data = sse.json() - if is_mapping(data) and data.get("error"): - message = None - error = data.get("error") - if is_mapping(error): - message = error.get("message") - if not message or not isinstance(message, str): - message = "An error occurred during streaming" - - raise APIError( - message=message, - request=self.response.request, - body=data["error"], - ) - - yield process_data(data=data, cast_to=cast_to, response=response) + data = sse.json() + if is_mapping(data) and data.get("error"): + message = None + error = data.get("error") + if is_mapping(error): + message = error.get("message") + if not message or not isinstance(message, str): + message = "An error occurred during streaming" + + raise APIError( + message=message, + request=self.response.request, + body=data["error"], + ) + + yield process_data(data=data, cast_to=cast_to, response=response) else: data = sse.json() From 7e88d42289f1327540c3d3f9210fae3c61474053 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 13 Jan 2025 16:59:43 +0000 Subject: [PATCH 645/816] fix: streaming --- src/openai/_streaming.py | 38 -------------------------------------- 1 file changed, 38 deletions(-) diff --git a/src/openai/_streaming.py b/src/openai/_streaming.py index b275986a46..7aa7b62f6b 100644 --- a/src/openai/_streaming.py +++ b/src/openai/_streaming.py @@ -76,25 +76,6 @@ def __stream__(self) -> Iterator[_T]: yield process_data(data=data, cast_to=cast_to, response=response) - else: - data = sse.json() - - if sse.event == "error" and is_mapping(data) and data.get("error"): - message = None - error = data.get("error") - if is_mapping(error): - message = error.get("message") - if not message or not isinstance(message, str): - message = "An error occurred during streaming" - - raise APIError( - message=message, - request=self.response.request, - body=data["error"], - ) - - yield process_data(data={"data": data, "event": sse.event}, cast_to=cast_to, response=response) - # Ensure the entire stream is consumed for _sse in iterator: ... @@ -177,25 +158,6 @@ async def __stream__(self) -> AsyncIterator[_T]: yield process_data(data=data, cast_to=cast_to, response=response) - else: - data = sse.json() - - if sse.event == "error" and is_mapping(data) and data.get("error"): - message = None - error = data.get("error") - if is_mapping(error): - message = error.get("message") - if not message or not isinstance(message, str): - message = "An error occurred during streaming" - - raise APIError( - message=message, - request=self.response.request, - body=data["error"], - ) - - yield process_data(data={"data": data, "event": sse.event}, cast_to=cast_to, response=response) - # Ensure the entire stream is consumed async for _sse in iterator: ... From 82ccc9858ac0de22ac874dcf796c17a333ce7b00 Mon Sep 17 00:00:00 2001 From: Krista Pratico Date: Mon, 13 Jan 2025 10:08:10 -0800 Subject: [PATCH 646/816] docs(examples/azure): example script with realtime API (#1967) --- examples/realtime/azure_realtime.py | 57 +++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 examples/realtime/azure_realtime.py diff --git a/examples/realtime/azure_realtime.py b/examples/realtime/azure_realtime.py new file mode 100644 index 0000000000..de88d47052 --- /dev/null +++ b/examples/realtime/azure_realtime.py @@ -0,0 +1,57 @@ +import os +import asyncio + +from azure.identity.aio import DefaultAzureCredential, get_bearer_token_provider + +from openai import AsyncAzureOpenAI + +# Azure OpenAI Realtime Docs + +# How-to: https://learn.microsoft.com/azure/ai-services/openai/how-to/realtime-audio +# Supported models and API versions: https://learn.microsoft.com/azure/ai-services/openai/how-to/realtime-audio#supported-models +# Entra ID auth: https://learn.microsoft.com/azure/ai-services/openai/how-to/managed-identity + + +async def main() -> None: + """The following example demonstrates how to configure Azure OpenAI to use the Realtime API. + For an audio example, see push_to_talk_app.py and update the client and model parameter accordingly. + + When prompted for user input, type a message and hit enter to send it to the model. + Enter "q" to quit the conversation. + """ + + credential = DefaultAzureCredential() + client = AsyncAzureOpenAI( + azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"], + azure_ad_token_provider=get_bearer_token_provider(credential, "https://cognitiveservices.azure.com/.default"), + api_version="2024-10-01-preview", + ) + async with client.beta.realtime.connect( + model="gpt-4o-realtime-preview", # deployment name for your model + ) as connection: + await connection.session.update(session={"modalities": ["text"]}) # type: ignore + while True: + user_input = input("Enter a message: ") + if user_input == "q": + break + + await connection.conversation.item.create( + item={ + "type": "message", + "role": "user", + "content": [{"type": "input_text", "text": user_input}], + } + ) + await connection.response.create() + async for event in connection: + if event.type == "response.text.delta": + print(event.delta, flush=True, end="") + elif event.type == "response.text.done": + print() + elif event.type == "response.done": + break + + await credential.close() + + +asyncio.run(main()) From e081d99e16835a038ef0dbb68500e562e021291f Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 13 Jan 2025 20:23:17 +0000 Subject: [PATCH 647/816] Revert "chore(internal): streaming refactors (#2012)" This reverts commit d76a748f606743407f94dfc26758095560e2082a. --- src/openai/_streaming.py | 104 +++++++++++++++++++++++++++------------ 1 file changed, 72 insertions(+), 32 deletions(-) diff --git a/src/openai/_streaming.py b/src/openai/_streaming.py index 7aa7b62f6b..0fda992cff 100644 --- a/src/openai/_streaming.py +++ b/src/openai/_streaming.py @@ -59,22 +59,42 @@ def __stream__(self) -> Iterator[_T]: if sse.data.startswith("[DONE]"): break - data = sse.json() - if is_mapping(data) and data.get("error"): - message = None - error = data.get("error") - if is_mapping(error): - message = error.get("message") - if not message or not isinstance(message, str): - message = "An error occurred during streaming" - - raise APIError( - message=message, - request=self.response.request, - body=data["error"], - ) - - yield process_data(data=data, cast_to=cast_to, response=response) + if sse.event is None: + data = sse.json() + if is_mapping(data) and data.get("error"): + message = None + error = data.get("error") + if is_mapping(error): + message = error.get("message") + if not message or not isinstance(message, str): + message = "An error occurred during streaming" + + raise APIError( + message=message, + request=self.response.request, + body=data["error"], + ) + + yield process_data(data=data, cast_to=cast_to, response=response) + + else: + data = sse.json() + + if sse.event == "error" and is_mapping(data) and data.get("error"): + message = None + error = data.get("error") + if is_mapping(error): + message = error.get("message") + if not message or not isinstance(message, str): + message = "An error occurred during streaming" + + raise APIError( + message=message, + request=self.response.request, + body=data["error"], + ) + + yield process_data(data={"data": data, "event": sse.event}, cast_to=cast_to, response=response) # Ensure the entire stream is consumed for _sse in iterator: @@ -141,22 +161,42 @@ async def __stream__(self) -> AsyncIterator[_T]: if sse.data.startswith("[DONE]"): break - data = sse.json() - if is_mapping(data) and data.get("error"): - message = None - error = data.get("error") - if is_mapping(error): - message = error.get("message") - if not message or not isinstance(message, str): - message = "An error occurred during streaming" - - raise APIError( - message=message, - request=self.response.request, - body=data["error"], - ) - - yield process_data(data=data, cast_to=cast_to, response=response) + if sse.event is None: + data = sse.json() + if is_mapping(data) and data.get("error"): + message = None + error = data.get("error") + if is_mapping(error): + message = error.get("message") + if not message or not isinstance(message, str): + message = "An error occurred during streaming" + + raise APIError( + message=message, + request=self.response.request, + body=data["error"], + ) + + yield process_data(data=data, cast_to=cast_to, response=response) + + else: + data = sse.json() + + if sse.event == "error" and is_mapping(data) and data.get("error"): + message = None + error = data.get("error") + if is_mapping(error): + message = error.get("message") + if not message or not isinstance(message, str): + message = "An error occurred during streaming" + + raise APIError( + message=message, + request=self.response.request, + body=data["error"], + ) + + yield process_data(data={"data": data, "event": sse.event}, cast_to=cast_to, response=response) # Ensure the entire stream is consumed async for _sse in iterator: From 83f11490fa291f9814f3dae6a65b1f62d0177675 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 14 Jan 2025 11:56:21 +0000 Subject: [PATCH 648/816] chore(internal): update deps (#2015) --- mypy.ini | 2 +- requirements-dev.lock | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/mypy.ini b/mypy.ini index 1ea1fe909d..660f1a086e 100644 --- a/mypy.ini +++ b/mypy.ini @@ -44,7 +44,7 @@ cache_fine_grained = True # ``` # Changing this codegen to make mypy happy would increase complexity # and would not be worth it. -disable_error_code = func-returns-value +disable_error_code = func-returns-value,overload-cannot-match # https://github.com/python/mypy/issues/12162 [mypy.overrides] diff --git a/requirements-dev.lock b/requirements-dev.lock index 15ecbf081a..8799e10b06 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -83,7 +83,7 @@ msal==1.31.0 # via msal-extensions msal-extensions==1.2.0 # via azure-identity -mypy==1.13.0 +mypy==1.14.1 mypy-extensions==1.0.0 # via black # via mypy @@ -124,7 +124,7 @@ pygments==2.18.0 # via rich pyjwt==2.8.0 # via msal -pyright==1.1.390 +pyright==1.1.391 pytest==8.3.3 # via pytest-asyncio pytest-asyncio==0.24.0 From d256d83589261e3bb2d2778a4f5bd4dda3248ac9 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 14 Jan 2025 11:59:51 +0000 Subject: [PATCH 649/816] fix(types): correct type for vector store chunking strategy (#2017) --- api.md | 2 +- src/openai/types/beta/__init__.py | 3 +++ .../types/beta/file_chunking_strategy_param.py | 4 ++-- ...static_file_chunking_strategy_object_param.py | 16 ++++++++++++++++ 4 files changed, 22 insertions(+), 3 deletions(-) create mode 100644 src/openai/types/beta/static_file_chunking_strategy_object_param.py diff --git a/api.md b/api.md index ace93e0559..1edd3f6589 100644 --- a/api.md +++ b/api.md @@ -314,7 +314,7 @@ from openai.types.beta import ( OtherFileChunkingStrategyObject, StaticFileChunkingStrategy, StaticFileChunkingStrategyObject, - StaticFileChunkingStrategyParam, + StaticFileChunkingStrategyObjectParam, VectorStore, VectorStoreDeleted, ) diff --git a/src/openai/types/beta/__init__.py b/src/openai/types/beta/__init__.py index 7f76fed0cd..b9ea792bfa 100644 --- a/src/openai/types/beta/__init__.py +++ b/src/openai/types/beta/__init__.py @@ -43,3 +43,6 @@ from .assistant_response_format_option_param import ( AssistantResponseFormatOptionParam as AssistantResponseFormatOptionParam, ) +from .static_file_chunking_strategy_object_param import ( + StaticFileChunkingStrategyObjectParam as StaticFileChunkingStrategyObjectParam, +) diff --git a/src/openai/types/beta/file_chunking_strategy_param.py b/src/openai/types/beta/file_chunking_strategy_param.py index 46383358e5..25d94286d8 100644 --- a/src/openai/types/beta/file_chunking_strategy_param.py +++ b/src/openai/types/beta/file_chunking_strategy_param.py @@ -6,8 +6,8 @@ from typing_extensions import TypeAlias from .auto_file_chunking_strategy_param import AutoFileChunkingStrategyParam -from .static_file_chunking_strategy_param import StaticFileChunkingStrategyParam +from .static_file_chunking_strategy_object_param import StaticFileChunkingStrategyObjectParam __all__ = ["FileChunkingStrategyParam"] -FileChunkingStrategyParam: TypeAlias = Union[AutoFileChunkingStrategyParam, StaticFileChunkingStrategyParam] +FileChunkingStrategyParam: TypeAlias = Union[AutoFileChunkingStrategyParam, StaticFileChunkingStrategyObjectParam] diff --git a/src/openai/types/beta/static_file_chunking_strategy_object_param.py b/src/openai/types/beta/static_file_chunking_strategy_object_param.py new file mode 100644 index 0000000000..0cdf35c0df --- /dev/null +++ b/src/openai/types/beta/static_file_chunking_strategy_object_param.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +from .static_file_chunking_strategy_param import StaticFileChunkingStrategyParam + +__all__ = ["StaticFileChunkingStrategyObjectParam"] + + +class StaticFileChunkingStrategyObjectParam(TypedDict, total=False): + static: Required[StaticFileChunkingStrategyParam] + + type: Required[Literal["static"]] + """Always `static`.""" From fd76342499f061bb157e4d5501a1e55f867cbc2c Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Wed, 15 Jan 2025 14:06:06 +0000 Subject: [PATCH 650/816] chore(examples): update realtime model closes #2020 --- README.md | 4 ++-- examples/realtime/push_to_talk_app.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index ad1c9afd10..ec556bd27a 100644 --- a/README.md +++ b/README.md @@ -275,7 +275,7 @@ from openai import AsyncOpenAI async def main(): client = AsyncOpenAI() - async with client.beta.realtime.connect(model="gpt-4o-realtime-preview-2024-10-01") as connection: + async with client.beta.realtime.connect(model="gpt-4o-realtime-preview") as connection: await connection.session.update(session={'modalities': ['text']}) await connection.conversation.item.create( @@ -309,7 +309,7 @@ Whenever an error occurs, the Realtime API will send an [`error` event](https:// ```py client = AsyncOpenAI() -async with client.beta.realtime.connect(model="gpt-4o-realtime-preview-2024-10-01") as connection: +async with client.beta.realtime.connect(model="gpt-4o-realtime-preview") as connection: ... async for event in connection: if event.type == 'error': diff --git a/examples/realtime/push_to_talk_app.py b/examples/realtime/push_to_talk_app.py index d46945a8ed..8dc303a83a 100755 --- a/examples/realtime/push_to_talk_app.py +++ b/examples/realtime/push_to_talk_app.py @@ -152,7 +152,7 @@ async def on_mount(self) -> None: self.run_worker(self.send_mic_audio()) async def handle_realtime_connection(self) -> None: - async with self.client.beta.realtime.connect(model="gpt-4o-realtime-preview-2024-10-01") as conn: + async with self.client.beta.realtime.connect(model="gpt-4o-realtime-preview") as conn: self.connection = conn self.connected.set() From bf5bebb57d74266d3010a72267298c0c832510a9 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 15 Jan 2025 17:51:10 +0000 Subject: [PATCH 651/816] chore(internal): bump pyright dependency (#2021) --- requirements-dev.lock | 2 +- src/openai/_legacy_response.py | 12 ++++++++++-- src/openai/_response.py | 8 +++++++- 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/requirements-dev.lock b/requirements-dev.lock index 8799e10b06..ef26591f12 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -124,7 +124,7 @@ pygments==2.18.0 # via rich pyjwt==2.8.0 # via msal -pyright==1.1.391 +pyright==1.1.392.post0 pytest==8.3.3 # via pytest-asyncio pytest-asyncio==0.24.0 diff --git a/src/openai/_legacy_response.py b/src/openai/_legacy_response.py index 7a14f27adb..25680049dc 100644 --- a/src/openai/_legacy_response.py +++ b/src/openai/_legacy_response.py @@ -269,7 +269,9 @@ def _parse(self, *, to: type[_T] | None = None) -> R | _T: if origin == LegacyAPIResponse: raise RuntimeError("Unexpected state - cast_to is `APIResponse`") - if inspect.isclass(origin) and issubclass(origin, httpx.Response): + if inspect.isclass( + origin # pyright: ignore[reportUnknownArgumentType] + ) and issubclass(origin, httpx.Response): # Because of the invariance of our ResponseT TypeVar, users can subclass httpx.Response # and pass that class to our request functions. We cannot change the variance to be either # covariant or contravariant as that makes our usage of ResponseT illegal. We could construct @@ -279,7 +281,13 @@ def _parse(self, *, to: type[_T] | None = None) -> R | _T: raise ValueError(f"Subclasses of httpx.Response cannot be passed to `cast_to`") return cast(R, response) - if inspect.isclass(origin) and not issubclass(origin, BaseModel) and issubclass(origin, pydantic.BaseModel): + if ( + inspect.isclass( + origin # pyright: ignore[reportUnknownArgumentType] + ) + and not issubclass(origin, BaseModel) + and issubclass(origin, pydantic.BaseModel) + ): raise TypeError("Pydantic models must subclass our base model type, e.g. `from openai import BaseModel`") if ( diff --git a/src/openai/_response.py b/src/openai/_response.py index 1527446585..36c7ea1281 100644 --- a/src/openai/_response.py +++ b/src/openai/_response.py @@ -214,7 +214,13 @@ def _parse(self, *, to: type[_T] | None = None) -> R | _T: raise ValueError(f"Subclasses of httpx.Response cannot be passed to `cast_to`") return cast(R, response) - if inspect.isclass(origin) and not issubclass(origin, BaseModel) and issubclass(origin, pydantic.BaseModel): + if ( + inspect.isclass( + origin # pyright: ignore[reportUnknownArgumentType] + ) + and not issubclass(origin, BaseModel) + and issubclass(origin, pydantic.BaseModel) + ): raise TypeError("Pydantic models must subclass our base model type, e.g. `from openai import BaseModel`") if ( From 08ab62b93a0c7690f00e760172cfefcb81b8e150 Mon Sep 17 00:00:00 2001 From: Rohit Joshi <891456+rjoshi@users.noreply.github.com> Date: Thu, 16 Jan 2025 04:46:22 -0800 Subject: [PATCH 652/816] fix(structured outputs): avoid parsing empty empty content (#2023) Fixing https://github.com/openai/openai-python/issues/1763 where parsing often fails when content is empty string instead of None. --- src/openai/lib/_parsing/_completions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/openai/lib/_parsing/_completions.py b/src/openai/lib/_parsing/_completions.py index f1fa9f2b55..33c4ccb946 100644 --- a/src/openai/lib/_parsing/_completions.py +++ b/src/openai/lib/_parsing/_completions.py @@ -157,7 +157,7 @@ def maybe_parse_content( response_format: type[ResponseFormatT] | ResponseFormatParam | NotGiven, message: ChatCompletionMessage | ParsedChatCompletionMessage[object], ) -> ResponseFormatT | None: - if has_rich_response_format(response_format) and message.content is not None and not message.refusal: + if has_rich_response_format(response_format) and message.content and not message.refusal: return _parse_content(response_format, message.content) return None From 1bdabb489a86bd721a3e237d8556583ed0d8dfa1 Mon Sep 17 00:00:00 2001 From: kanchi <17161397+KanchiShimono@users.noreply.github.com> Date: Fri, 17 Jan 2025 20:40:26 +0900 Subject: [PATCH 653/816] fix(structured outputs): correct schema coercion for inline ref expansion (#2025) --- src/openai/lib/_pydantic.py | 3 + tests/lib/test_pydantic.py | 174 ++++++++++++++++++++++++++++++++++++ 2 files changed, 177 insertions(+) diff --git a/src/openai/lib/_pydantic.py b/src/openai/lib/_pydantic.py index 4e8bc772be..c2d73e5fc6 100644 --- a/src/openai/lib/_pydantic.py +++ b/src/openai/lib/_pydantic.py @@ -108,6 +108,9 @@ def _ensure_strict_json_schema( # properties from the json schema take priority over the ones on the `$ref` json_schema.update({**resolved, **json_schema}) json_schema.pop("$ref") + # Since the schema expanded from `$ref` might not have `additionalProperties: false` applied, + # we call `_ensure_strict_json_schema` again to fix the inlined schema and ensure it's valid. + return _ensure_strict_json_schema(json_schema, path=path, root=root) return json_schema diff --git a/tests/lib/test_pydantic.py b/tests/lib/test_pydantic.py index 99b9e96d21..7e128b70c0 100644 --- a/tests/lib/test_pydantic.py +++ b/tests/lib/test_pydantic.py @@ -7,6 +7,7 @@ import openai from openai._compat import PYDANTIC_V2 +from openai.lib._pydantic import to_strict_json_schema from .schema_types.query import Query @@ -235,3 +236,176 @@ def test_enums() -> None: }, } ) + + +class Star(BaseModel): + name: str = Field(description="The name of the star.") + + +class Galaxy(BaseModel): + name: str = Field(description="The name of the galaxy.") + largest_star: Star = Field(description="The largest star in the galaxy.") + + +class Universe(BaseModel): + name: str = Field(description="The name of the universe.") + galaxy: Galaxy = Field(description="A galaxy in the universe.") + + +def test_nested_inline_ref_expansion() -> None: + if PYDANTIC_V2: + assert to_strict_json_schema(Universe) == snapshot( + { + "title": "Universe", + "type": "object", + "$defs": { + "Star": { + "title": "Star", + "type": "object", + "properties": { + "name": { + "type": "string", + "title": "Name", + "description": "The name of the star.", + } + }, + "required": ["name"], + "additionalProperties": False, + }, + "Galaxy": { + "title": "Galaxy", + "type": "object", + "properties": { + "name": { + "type": "string", + "title": "Name", + "description": "The name of the galaxy.", + }, + "largest_star": { + "title": "Star", + "type": "object", + "properties": { + "name": { + "type": "string", + "title": "Name", + "description": "The name of the star.", + } + }, + "required": ["name"], + "description": "The largest star in the galaxy.", + "additionalProperties": False, + }, + }, + "required": ["name", "largest_star"], + "additionalProperties": False, + }, + }, + "properties": { + "name": { + "type": "string", + "title": "Name", + "description": "The name of the universe.", + }, + "galaxy": { + "title": "Galaxy", + "type": "object", + "properties": { + "name": { + "type": "string", + "title": "Name", + "description": "The name of the galaxy.", + }, + "largest_star": { + "title": "Star", + "type": "object", + "properties": { + "name": { + "type": "string", + "title": "Name", + "description": "The name of the star.", + } + }, + "required": ["name"], + "description": "The largest star in the galaxy.", + "additionalProperties": False, + }, + }, + "required": ["name", "largest_star"], + "description": "A galaxy in the universe.", + "additionalProperties": False, + }, + }, + "required": ["name", "galaxy"], + "additionalProperties": False, + } + ) + else: + assert to_strict_json_schema(Universe) == snapshot( + { + "title": "Universe", + "type": "object", + "definitions": { + "Star": { + "title": "Star", + "type": "object", + "properties": { + "name": {"title": "Name", "description": "The name of the star.", "type": "string"} + }, + "required": ["name"], + "additionalProperties": False, + }, + "Galaxy": { + "title": "Galaxy", + "type": "object", + "properties": { + "name": {"title": "Name", "description": "The name of the galaxy.", "type": "string"}, + "largest_star": { + "title": "Largest Star", + "description": "The largest star in the galaxy.", + "type": "object", + "properties": { + "name": {"title": "Name", "description": "The name of the star.", "type": "string"} + }, + "required": ["name"], + "additionalProperties": False, + }, + }, + "required": ["name", "largest_star"], + "additionalProperties": False, + }, + }, + "properties": { + "name": { + "title": "Name", + "description": "The name of the universe.", + "type": "string", + }, + "galaxy": { + "title": "Galaxy", + "description": "A galaxy in the universe.", + "type": "object", + "properties": { + "name": { + "title": "Name", + "description": "The name of the galaxy.", + "type": "string", + }, + "largest_star": { + "title": "Largest Star", + "description": "The largest star in the galaxy.", + "type": "object", + "properties": { + "name": {"title": "Name", "description": "The name of the star.", "type": "string"} + }, + "required": ["name"], + "additionalProperties": False, + }, + }, + "required": ["name", "largest_star"], + "additionalProperties": False, + }, + }, + "required": ["name", "galaxy"], + "additionalProperties": False, + } + ) From 4dd5cf25fa58076307a5baed0a87f6d765f20100 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 17 Jan 2025 11:40:58 +0000 Subject: [PATCH 654/816] release: 1.59.8 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 24 ++++++++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 27 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 7da3bd4caf..58f8a4601d 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.59.7" + ".": "1.59.8" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 08674b4a36..9f301cedff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,29 @@ # Changelog +## 1.59.8 (2025-01-17) + +Full Changelog: [v1.59.7...v1.59.8](https://github.com/openai/openai-python/compare/v1.59.7...v1.59.8) + +### Bug Fixes + +* streaming ([c16f58e](https://github.com/openai/openai-python/commit/c16f58ead0bc85055b164182689ba74b7e939dfa)) +* **structured outputs:** avoid parsing empty empty content ([#2023](https://github.com/openai/openai-python/issues/2023)) ([6d3513c](https://github.com/openai/openai-python/commit/6d3513c86f6e5800f8f73a45e089b7a205327121)) +* **structured outputs:** correct schema coercion for inline ref expansion ([#2025](https://github.com/openai/openai-python/issues/2025)) ([2f4f0b3](https://github.com/openai/openai-python/commit/2f4f0b374207f162060c328b71ec995049dc42e8)) +* **types:** correct type for vector store chunking strategy ([#2017](https://github.com/openai/openai-python/issues/2017)) ([e389279](https://github.com/openai/openai-python/commit/e38927950a5cdad99065853fe7b72aad6bb322e9)) + + +### Chores + +* **examples:** update realtime model ([f26746c](https://github.com/openai/openai-python/commit/f26746cbcd893d66cf8a3fd68a7c3779dc8c833c)), closes [#2020](https://github.com/openai/openai-python/issues/2020) +* **internal:** bump pyright dependency ([#2021](https://github.com/openai/openai-python/issues/2021)) ([0a9a0f5](https://github.com/openai/openai-python/commit/0a9a0f5d8b9d5457643798287f893305006dd518)) +* **internal:** streaming refactors ([#2012](https://github.com/openai/openai-python/issues/2012)) ([d76a748](https://github.com/openai/openai-python/commit/d76a748f606743407f94dfc26758095560e2082a)) +* **internal:** update deps ([#2015](https://github.com/openai/openai-python/issues/2015)) ([514e0e4](https://github.com/openai/openai-python/commit/514e0e415f87ab4510262d29ed6125384e017b84)) + + +### Documentation + +* **examples/azure:** example script with realtime API ([#1967](https://github.com/openai/openai-python/issues/1967)) ([84f2f9c](https://github.com/openai/openai-python/commit/84f2f9c0439229a7db7136fe78419292d34d1f81)) + ## 1.59.7 (2025-01-13) Full Changelog: [v1.59.6...v1.59.7](https://github.com/openai/openai-python/compare/v1.59.6...v1.59.7) diff --git a/pyproject.toml b/pyproject.toml index e769f4a95f..a75d24e1eb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.59.7" +version = "1.59.8" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 656d17ff63..d6f55997e7 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.59.7" # x-release-please-version +__version__ = "1.59.8" # x-release-please-version From 1e5e19976a02f4f3423cf7e32ad5fa020c857b82 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 20 Jan 2025 09:38:30 +0000 Subject: [PATCH 655/816] chore(internal): update websockets dep (#2036) --- requirements-dev.lock | 2 +- requirements.lock | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/requirements-dev.lock b/requirements-dev.lock index ef26591f12..38cc6e1cf2 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -184,7 +184,7 @@ urllib3==2.2.1 # via requests virtualenv==20.24.5 # via nox -websockets==14.1 +websockets==14.2 # via openai zipp==3.17.0 # via importlib-metadata diff --git a/requirements.lock b/requirements.lock index a3e3602abe..cbdff94fa3 100644 --- a/requirements.lock +++ b/requirements.lock @@ -63,5 +63,5 @@ typing-extensions==4.12.2 # via pydantic-core tzdata==2024.1 # via pandas -websockets==14.1 +websockets==14.2 # via openai From fbc88b6206338761019cb6a4258d7de46f578fcb Mon Sep 17 00:00:00 2001 From: Nino Risteski <95188570+NinoRisteski@users.noreply.github.com> Date: Mon, 20 Jan 2025 10:53:29 +0100 Subject: [PATCH 656/816] docs: fix typo (#2031) removed duplicate 'the' twice --- src/openai/resources/chat/chat.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/openai/resources/chat/chat.py b/src/openai/resources/chat/chat.py index dc23a15a8e..9c4aacc953 100644 --- a/src/openai/resources/chat/chat.py +++ b/src/openai/resources/chat/chat.py @@ -24,7 +24,7 @@ def completions(self) -> Completions: @cached_property def with_raw_response(self) -> ChatWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -49,7 +49,7 @@ def completions(self) -> AsyncCompletions: @cached_property def with_raw_response(self) -> AsyncChatWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers From de0550420763b918ffe49d2fffd7b76b2dd00ba8 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 20 Jan 2025 10:13:38 +0000 Subject: [PATCH 657/816] docs(raw responses): fix duplicate `the` (#2039) --- src/openai/resources/audio/audio.py | 4 ++-- src/openai/resources/audio/speech.py | 4 ++-- src/openai/resources/audio/transcriptions.py | 4 ++-- src/openai/resources/audio/translations.py | 4 ++-- src/openai/resources/batches.py | 4 ++-- src/openai/resources/beta/assistants.py | 4 ++-- src/openai/resources/beta/beta.py | 4 ++-- src/openai/resources/beta/realtime/realtime.py | 4 ++-- src/openai/resources/beta/realtime/sessions.py | 4 ++-- src/openai/resources/beta/threads/messages.py | 4 ++-- src/openai/resources/beta/threads/runs/runs.py | 4 ++-- src/openai/resources/beta/threads/runs/steps.py | 4 ++-- src/openai/resources/beta/threads/threads.py | 4 ++-- src/openai/resources/beta/vector_stores/file_batches.py | 4 ++-- src/openai/resources/beta/vector_stores/files.py | 4 ++-- src/openai/resources/beta/vector_stores/vector_stores.py | 4 ++-- src/openai/resources/chat/completions.py | 4 ++-- src/openai/resources/completions.py | 4 ++-- src/openai/resources/embeddings.py | 4 ++-- src/openai/resources/files.py | 4 ++-- src/openai/resources/fine_tuning/fine_tuning.py | 4 ++-- src/openai/resources/fine_tuning/jobs/checkpoints.py | 4 ++-- src/openai/resources/fine_tuning/jobs/jobs.py | 4 ++-- src/openai/resources/images.py | 4 ++-- src/openai/resources/models.py | 4 ++-- src/openai/resources/moderations.py | 4 ++-- src/openai/resources/uploads/parts.py | 4 ++-- src/openai/resources/uploads/uploads.py | 4 ++-- 28 files changed, 56 insertions(+), 56 deletions(-) diff --git a/src/openai/resources/audio/audio.py b/src/openai/resources/audio/audio.py index 18bd7b812c..383b7073bf 100644 --- a/src/openai/resources/audio/audio.py +++ b/src/openai/resources/audio/audio.py @@ -48,7 +48,7 @@ def speech(self) -> Speech: @cached_property def with_raw_response(self) -> AudioWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -81,7 +81,7 @@ def speech(self) -> AsyncSpeech: @cached_property def with_raw_response(self) -> AsyncAudioWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index 09faaddda6..805a8c19c9 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -32,7 +32,7 @@ class Speech(SyncAPIResource): @cached_property def with_raw_response(self) -> SpeechWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -116,7 +116,7 @@ class AsyncSpeech(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncSpeechWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index 8b5f4404fc..341446c43a 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -36,7 +36,7 @@ class Transcriptions(SyncAPIResource): @cached_property def with_raw_response(self) -> TranscriptionsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -200,7 +200,7 @@ class AsyncTranscriptions(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncTranscriptionsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index a2d28afa03..cd3132dc57 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -36,7 +36,7 @@ class Translations(SyncAPIResource): @cached_property def with_raw_response(self) -> TranslationsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -179,7 +179,7 @@ class AsyncTranslations(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncTranslationsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/batches.py b/src/openai/resources/batches.py index 7cab75785d..4a887642e9 100644 --- a/src/openai/resources/batches.py +++ b/src/openai/resources/batches.py @@ -31,7 +31,7 @@ class Batches(SyncAPIResource): @cached_property def with_raw_response(self) -> BatchesWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -236,7 +236,7 @@ class AsyncBatches(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncBatchesWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/beta/assistants.py b/src/openai/resources/beta/assistants.py index 7df212f155..2f2482b648 100644 --- a/src/openai/resources/beta/assistants.py +++ b/src/openai/resources/beta/assistants.py @@ -36,7 +36,7 @@ class Assistants(SyncAPIResource): @cached_property def with_raw_response(self) -> AssistantsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -422,7 +422,7 @@ class AsyncAssistants(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncAssistantsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/beta/beta.py b/src/openai/resources/beta/beta.py index 1ffa6c8e79..5d71cff3f1 100644 --- a/src/openai/resources/beta/beta.py +++ b/src/openai/resources/beta/beta.py @@ -65,7 +65,7 @@ def threads(self) -> Threads: @cached_property def with_raw_response(self) -> BetaWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -106,7 +106,7 @@ def threads(self) -> AsyncThreads: @cached_property def with_raw_response(self) -> AsyncBetaWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/beta/realtime/realtime.py b/src/openai/resources/beta/realtime/realtime.py index b39b410ecf..235790a9f5 100644 --- a/src/openai/resources/beta/realtime/realtime.py +++ b/src/openai/resources/beta/realtime/realtime.py @@ -58,7 +58,7 @@ def sessions(self) -> Sessions: @cached_property def with_raw_response(self) -> RealtimeWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -110,7 +110,7 @@ def sessions(self) -> AsyncSessions: @cached_property def with_raw_response(self) -> AsyncRealtimeWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/beta/realtime/sessions.py b/src/openai/resources/beta/realtime/sessions.py index 1d1ee701e5..8d2df30753 100644 --- a/src/openai/resources/beta/realtime/sessions.py +++ b/src/openai/resources/beta/realtime/sessions.py @@ -27,7 +27,7 @@ class Sessions(SyncAPIResource): @cached_property def with_raw_response(self) -> SessionsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -166,7 +166,7 @@ class AsyncSessions(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncSessionsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/beta/threads/messages.py b/src/openai/resources/beta/threads/messages.py index e848507387..f780f6f558 100644 --- a/src/openai/resources/beta/threads/messages.py +++ b/src/openai/resources/beta/threads/messages.py @@ -33,7 +33,7 @@ class Messages(SyncAPIResource): @cached_property def with_raw_response(self) -> MessagesWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -307,7 +307,7 @@ class AsyncMessages(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncMessagesWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 0418d570ba..f32a08f235 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -64,7 +64,7 @@ def steps(self) -> Steps: @cached_property def with_raw_response(self) -> RunsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -1429,7 +1429,7 @@ def steps(self) -> AsyncSteps: @cached_property def with_raw_response(self) -> AsyncRunsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/beta/threads/runs/steps.py b/src/openai/resources/beta/threads/runs/steps.py index 9bd91e39e0..709c729d45 100644 --- a/src/openai/resources/beta/threads/runs/steps.py +++ b/src/openai/resources/beta/threads/runs/steps.py @@ -29,7 +29,7 @@ class Steps(SyncAPIResource): @cached_property def with_raw_response(self) -> StepsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -183,7 +183,7 @@ class AsyncSteps(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncStepsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index e45090abb0..186b6f63e2 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -72,7 +72,7 @@ def messages(self) -> Messages: @cached_property def with_raw_response(self) -> ThreadsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -906,7 +906,7 @@ def messages(self) -> AsyncMessages: @cached_property def with_raw_response(self) -> AsyncThreadsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/beta/vector_stores/file_batches.py b/src/openai/resources/beta/vector_stores/file_batches.py index 9f9e643bd0..6d61e92c7f 100644 --- a/src/openai/resources/beta/vector_stores/file_batches.py +++ b/src/openai/resources/beta/vector_stores/file_batches.py @@ -36,7 +36,7 @@ class FileBatches(SyncAPIResource): @cached_property def with_raw_response(self) -> FileBatchesWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -365,7 +365,7 @@ class AsyncFileBatches(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncFileBatchesWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/beta/vector_stores/files.py b/src/openai/resources/beta/vector_stores/files.py index 7c155ac917..febf27a753 100644 --- a/src/openai/resources/beta/vector_stores/files.py +++ b/src/openai/resources/beta/vector_stores/files.py @@ -32,7 +32,7 @@ class Files(SyncAPIResource): @cached_property def with_raw_response(self) -> FilesWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -344,7 +344,7 @@ class AsyncFiles(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncFilesWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/beta/vector_stores/vector_stores.py b/src/openai/resources/beta/vector_stores/vector_stores.py index 61a2eadc7b..6b44c602f1 100644 --- a/src/openai/resources/beta/vector_stores/vector_stores.py +++ b/src/openai/resources/beta/vector_stores/vector_stores.py @@ -59,7 +59,7 @@ def file_batches(self) -> FileBatches: @cached_property def with_raw_response(self) -> VectorStoresWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -337,7 +337,7 @@ def file_batches(self) -> AsyncFileBatches: @cached_property def with_raw_response(self) -> AsyncVectorStoresWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index 728c744327..201ae3f4c6 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -45,7 +45,7 @@ class Completions(SyncAPIResource): @cached_property def with_raw_response(self) -> CompletionsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -906,7 +906,7 @@ class AsyncCompletions(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncCompletionsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index 1ac3575fd5..171f509352 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -32,7 +32,7 @@ class Completions(SyncAPIResource): @cached_property def with_raw_response(self) -> CompletionsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -574,7 +574,7 @@ class AsyncCompletions(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncCompletionsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/embeddings.py b/src/openai/resources/embeddings.py index 4ab2278e89..81a3e354e6 100644 --- a/src/openai/resources/embeddings.py +++ b/src/openai/resources/embeddings.py @@ -27,7 +27,7 @@ class Embeddings(SyncAPIResource): @cached_property def with_raw_response(self) -> EmbeddingsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -139,7 +139,7 @@ class AsyncEmbeddings(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncEmbeddingsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index 6eaea1b568..af453e1e21 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -41,7 +41,7 @@ class Files(SyncAPIResource): @cached_property def with_raw_response(self) -> FilesWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -357,7 +357,7 @@ class AsyncFiles(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncFilesWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/fine_tuning/fine_tuning.py b/src/openai/resources/fine_tuning/fine_tuning.py index d2bce87c48..eebde07d81 100644 --- a/src/openai/resources/fine_tuning/fine_tuning.py +++ b/src/openai/resources/fine_tuning/fine_tuning.py @@ -24,7 +24,7 @@ def jobs(self) -> Jobs: @cached_property def with_raw_response(self) -> FineTuningWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -49,7 +49,7 @@ def jobs(self) -> AsyncJobs: @cached_property def with_raw_response(self) -> AsyncFineTuningWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/fine_tuning/jobs/checkpoints.py b/src/openai/resources/fine_tuning/jobs/checkpoints.py index 8b5e905ea5..f86462e513 100644 --- a/src/openai/resources/fine_tuning/jobs/checkpoints.py +++ b/src/openai/resources/fine_tuning/jobs/checkpoints.py @@ -25,7 +25,7 @@ class Checkpoints(SyncAPIResource): @cached_property def with_raw_response(self) -> CheckpointsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -96,7 +96,7 @@ class AsyncCheckpoints(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncCheckpointsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/fine_tuning/jobs/jobs.py b/src/openai/resources/fine_tuning/jobs/jobs.py index 78eefc253c..e023d28fea 100644 --- a/src/openai/resources/fine_tuning/jobs/jobs.py +++ b/src/openai/resources/fine_tuning/jobs/jobs.py @@ -44,7 +44,7 @@ def checkpoints(self) -> Checkpoints: @cached_property def with_raw_response(self) -> JobsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -342,7 +342,7 @@ def checkpoints(self) -> AsyncCheckpoints: @cached_property def with_raw_response(self) -> AsyncJobsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py index 2fbc077dd9..30473c14f7 100644 --- a/src/openai/resources/images.py +++ b/src/openai/resources/images.py @@ -30,7 +30,7 @@ class Images(SyncAPIResource): @cached_property def with_raw_response(self) -> ImagesWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -287,7 +287,7 @@ class AsyncImages(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncImagesWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/models.py b/src/openai/resources/models.py index d6062de230..a9693a6b0a 100644 --- a/src/openai/resources/models.py +++ b/src/openai/resources/models.py @@ -24,7 +24,7 @@ class Models(SyncAPIResource): @cached_property def with_raw_response(self) -> ModelsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -137,7 +137,7 @@ class AsyncModels(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncModelsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/moderations.py b/src/openai/resources/moderations.py index ce80bb7d55..a8f03142bc 100644 --- a/src/openai/resources/moderations.py +++ b/src/openai/resources/moderations.py @@ -28,7 +28,7 @@ class Moderations(SyncAPIResource): @cached_property def with_raw_response(self) -> ModerationsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -98,7 +98,7 @@ class AsyncModerations(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncModerationsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/uploads/parts.py b/src/openai/resources/uploads/parts.py index d46e5ea1bb..777469ac8e 100644 --- a/src/openai/resources/uploads/parts.py +++ b/src/openai/resources/uploads/parts.py @@ -28,7 +28,7 @@ class Parts(SyncAPIResource): @cached_property def with_raw_response(self) -> PartsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -103,7 +103,7 @@ class AsyncParts(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncPartsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers diff --git a/src/openai/resources/uploads/uploads.py b/src/openai/resources/uploads/uploads.py index cfb500b62c..2028decef5 100644 --- a/src/openai/resources/uploads/uploads.py +++ b/src/openai/resources/uploads/uploads.py @@ -51,7 +51,7 @@ def parts(self) -> Parts: @cached_property def with_raw_response(self) -> UploadsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers @@ -344,7 +344,7 @@ def parts(self) -> AsyncParts: @cached_property def with_raw_response(self) -> AsyncUploadsWithRawResponse: """ - This property can be used as a prefix for any HTTP method call to return the + This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers From 14543c59df4f56d2004530dfed411154ffc2f632 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 20 Jan 2025 10:22:16 +0000 Subject: [PATCH 658/816] fix(tests): make test_get_platform less flaky (#2040) --- tests/test_client.py | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/tests/test_client.py b/tests/test_client.py index e0d23403b1..41da2d5d04 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -6,6 +6,7 @@ import os import sys import json +import time import asyncio import inspect import subprocess @@ -1797,10 +1798,20 @@ async def test_main() -> None: [sys.executable, "-c", test_code], text=True, ) as process: - try: - process.wait(2) - if process.returncode: - raise AssertionError("calling get_platform using asyncify resulted in a non-zero exit code") - except subprocess.TimeoutExpired as e: - process.kill() - raise AssertionError("calling get_platform using asyncify resulted in a hung process") from e + timeout = 10 # seconds + + start_time = time.monotonic() + while True: + return_code = process.poll() + if return_code is not None: + if return_code != 0: + raise AssertionError("calling get_platform using asyncify resulted in a non-zero exit code") + + # success + break + + if time.monotonic() - start_time > timeout: + process.kill() + raise AssertionError("calling get_platform using asyncify resulted in a hung process") + + time.sleep(0.1) From 7989b045d2b974e03792e3010d5247b5bbe387fe Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 20 Jan 2025 12:11:31 +0000 Subject: [PATCH 659/816] chore(internal): avoid pytest-asyncio deprecation warning (#2041) --- pyproject.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/pyproject.toml b/pyproject.toml index a75d24e1eb..e5beb93ec5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -141,6 +141,7 @@ testpaths = ["tests"] addopts = "--tb=short" xfail_strict = true asyncio_mode = "auto" +asyncio_default_fixture_loop_scope = "session" filterwarnings = [ "error" ] From 348a783523e36a88e24b92faee693db125efc5bf Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 20 Jan 2025 12:12:04 +0000 Subject: [PATCH 660/816] release: 1.59.9 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 20 ++++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 23 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 58f8a4601d..32b4e18516 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.59.8" + ".": "1.59.9" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f301cedff..86951242c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,25 @@ # Changelog +## 1.59.9 (2025-01-20) + +Full Changelog: [v1.59.8...v1.59.9](https://github.com/openai/openai-python/compare/v1.59.8...v1.59.9) + +### Bug Fixes + +* **tests:** make test_get_platform less flaky ([#2040](https://github.com/openai/openai-python/issues/2040)) ([72ea05c](https://github.com/openai/openai-python/commit/72ea05cf18caaa7a5e6fe7e2251ab93fa0ba3140)) + + +### Chores + +* **internal:** avoid pytest-asyncio deprecation warning ([#2041](https://github.com/openai/openai-python/issues/2041)) ([b901046](https://github.com/openai/openai-python/commit/b901046ddda9c79b7f019e2263c02d126a3b2ee2)) +* **internal:** update websockets dep ([#2036](https://github.com/openai/openai-python/issues/2036)) ([642cd11](https://github.com/openai/openai-python/commit/642cd119482c6fbca925ba702ad2579f9dc47bf9)) + + +### Documentation + +* fix typo ([#2031](https://github.com/openai/openai-python/issues/2031)) ([02fcf15](https://github.com/openai/openai-python/commit/02fcf15611953089826a74725cb96201d94658bb)) +* **raw responses:** fix duplicate `the` ([#2039](https://github.com/openai/openai-python/issues/2039)) ([9b8eab9](https://github.com/openai/openai-python/commit/9b8eab99fdc6a581a1f5cc421c6f74b0e2b30415)) + ## 1.59.8 (2025-01-17) Full Changelog: [v1.59.7...v1.59.8](https://github.com/openai/openai-python/compare/v1.59.7...v1.59.8) diff --git a/pyproject.toml b/pyproject.toml index e5beb93ec5..0b142a6bd8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.59.8" +version = "1.59.9" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index d6f55997e7..7c92c3adf3 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.59.8" # x-release-please-version +__version__ = "1.59.9" # x-release-please-version From a05e8799f9bb5734b46b19d774d808457c737e31 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 21 Jan 2025 16:08:31 +0000 Subject: [PATCH 661/816] chore(internal): minor style changes (#2043) --- src/openai/_legacy_response.py | 4 ++-- src/openai/_response.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/openai/_legacy_response.py b/src/openai/_legacy_response.py index 25680049dc..8880e5f104 100644 --- a/src/openai/_legacy_response.py +++ b/src/openai/_legacy_response.py @@ -205,6 +205,8 @@ def _parse(self, *, to: type[_T] | None = None) -> R | _T: if cast_to and is_annotated_type(cast_to): cast_to = extract_type_arg(cast_to, 0) + origin = get_origin(cast_to) or cast_to + if self._stream: if to: if not is_stream_class_type(to): @@ -261,8 +263,6 @@ def _parse(self, *, to: type[_T] | None = None) -> R | _T: if cast_to == bool: return cast(R, response.text.lower() == "true") - origin = get_origin(cast_to) or cast_to - if inspect.isclass(origin) and issubclass(origin, HttpxBinaryResponseContent): return cast(R, cast_to(response)) # type: ignore diff --git a/src/openai/_response.py b/src/openai/_response.py index 36c7ea1281..95e94e6537 100644 --- a/src/openai/_response.py +++ b/src/openai/_response.py @@ -136,6 +136,8 @@ def _parse(self, *, to: type[_T] | None = None) -> R | _T: if cast_to and is_annotated_type(cast_to): cast_to = extract_type_arg(cast_to, 0) + origin = get_origin(cast_to) or cast_to + if self._is_sse_stream: if to: if not is_stream_class_type(to): @@ -195,8 +197,6 @@ def _parse(self, *, to: type[_T] | None = None) -> R | _T: if cast_to == bool: return cast(R, response.text.lower() == "true") - origin = get_origin(cast_to) or cast_to - # handle the legacy binary response case if inspect.isclass(cast_to) and cast_to.__name__ == "HttpxBinaryResponseContent": return cast(R, cast_to(response)) # type: ignore From 709926fff8761659761c3efb96c1e21a02fc1f5d Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Wed, 22 Jan 2025 10:43:52 +0000 Subject: [PATCH 662/816] docs(readme): mention failed requests in request IDs --- README.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/README.md b/README.md index ec556bd27a..5f7d477cc8 100644 --- a/README.md +++ b/README.md @@ -499,6 +499,21 @@ Note that unlike other properties that use an `_` prefix, the `_request_id` prop *is* public. Unless documented otherwise, *all* other `_` prefix properties, methods and modules are *private*. +> [!IMPORTANT] +> If you need to access request IDs for failed requests you must catch the `APIStatusError` exception + +```python +import openai + +try: + completion = await client.chat.completions.create( + messages=[{"role": "user", "content": "Say this is a test"}], model="gpt-4" + ) +except openai.APIStatusError as exc: + print(exc.request_id) # req_123 + raise exc +``` + ### Retries From 339d3151c5b972af690ab45f1055763c52af0e58 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 22 Jan 2025 13:20:56 +0000 Subject: [PATCH 663/816] feat(api): update enum values, comments, and examples (#2045) --- .stats.yml | 2 +- src/openai/resources/audio/speech.py | 16 +++---- .../resources/beta/realtime/sessions.py | 48 +++++++++++-------- src/openai/resources/chat/completions.py | 18 ------- src/openai/resources/embeddings.py | 6 ++- .../types/audio/speech_create_params.py | 6 +-- .../conversation_item_create_event.py | 11 +++-- .../conversation_item_create_event_param.py | 11 +++-- src/openai/types/beta/realtime/session.py | 13 ++++- .../beta/realtime/session_create_params.py | 35 ++++++++------ .../beta/realtime/session_update_event.py | 33 ++++++++----- .../realtime/session_update_event_param.py | 33 ++++++++----- src/openai/types/chat/chat_completion.py | 6 +-- ...chat_completion_assistant_message_param.py | 4 +- .../types/chat/chat_completion_chunk.py | 6 +-- .../types/chat/completion_create_params.py | 3 -- src/openai/types/embedding_create_params.py | 3 +- .../beta/realtime/test_sessions.py | 28 ++++------- tests/api_resources/chat/test_completions.py | 8 ++-- tests/api_resources/test_completions.py | 8 ++-- 20 files changed, 152 insertions(+), 146 deletions(-) diff --git a/.stats.yml b/.stats.yml index 9600edae3b..d518bac586 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 69 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-b5b0e2c794b012919701c3fd43286af10fa25d33ceb8a881bec2636028f446e0.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-3904ef6b29a89c98f93a9b7da19879695f3c440564be6384db7af1b734611ede.yml diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index 805a8c19c9..ad01118161 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -53,7 +53,7 @@ def create( *, input: str, model: Union[str, SpeechModel], - voice: Literal["alloy", "echo", "fable", "onyx", "nova", "shimmer"], + voice: Literal["alloy", "ash", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer"], response_format: Literal["mp3", "opus", "aac", "flac", "wav", "pcm"] | NotGiven = NOT_GIVEN, speed: float | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -73,9 +73,9 @@ def create( One of the available [TTS models](https://platform.openai.com/docs/models#tts): `tts-1` or `tts-1-hd` - voice: The voice to use when generating the audio. Supported voices are `alloy`, - `echo`, `fable`, `onyx`, `nova`, and `shimmer`. Previews of the voices are - available in the + voice: The voice to use when generating the audio. Supported voices are `alloy`, `ash`, + `coral`, `echo`, `fable`, `onyx`, `nova`, `sage` and `shimmer`. Previews of the + voices are available in the [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech#voice-options). response_format: The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, @@ -137,7 +137,7 @@ async def create( *, input: str, model: Union[str, SpeechModel], - voice: Literal["alloy", "echo", "fable", "onyx", "nova", "shimmer"], + voice: Literal["alloy", "ash", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer"], response_format: Literal["mp3", "opus", "aac", "flac", "wav", "pcm"] | NotGiven = NOT_GIVEN, speed: float | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -157,9 +157,9 @@ async def create( One of the available [TTS models](https://platform.openai.com/docs/models#tts): `tts-1` or `tts-1-hd` - voice: The voice to use when generating the audio. Supported voices are `alloy`, - `echo`, `fable`, `onyx`, `nova`, and `shimmer`. Previews of the voices are - available in the + voice: The voice to use when generating the audio. Supported voices are `alloy`, `ash`, + `coral`, `echo`, `fable`, `onyx`, `nova`, `sage` and `shimmer`. Previews of the + voices are available in the [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech#voice-options). response_format: The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, diff --git a/src/openai/resources/beta/realtime/sessions.py b/src/openai/resources/beta/realtime/sessions.py index 8d2df30753..b920c89207 100644 --- a/src/openai/resources/beta/realtime/sessions.py +++ b/src/openai/resources/beta/realtime/sessions.py @@ -46,18 +46,19 @@ def with_streaming_response(self) -> SessionsWithStreamingResponse: def create( self, *, + input_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"] | NotGiven = NOT_GIVEN, + input_audio_transcription: session_create_params.InputAudioTranscription | NotGiven = NOT_GIVEN, + instructions: str | NotGiven = NOT_GIVEN, + max_response_output_tokens: Union[int, Literal["inf"]] | NotGiven = NOT_GIVEN, + modalities: List[Literal["text", "audio"]] | NotGiven = NOT_GIVEN, model: Literal[ "gpt-4o-realtime-preview", "gpt-4o-realtime-preview-2024-10-01", "gpt-4o-realtime-preview-2024-12-17", "gpt-4o-mini-realtime-preview", "gpt-4o-mini-realtime-preview-2024-12-17", - ], - input_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"] | NotGiven = NOT_GIVEN, - input_audio_transcription: session_create_params.InputAudioTranscription | NotGiven = NOT_GIVEN, - instructions: str | NotGiven = NOT_GIVEN, - max_response_output_tokens: Union[int, Literal["inf"]] | NotGiven = NOT_GIVEN, - modalities: List[Literal["text", "audio"]] | NotGiven = NOT_GIVEN, + ] + | NotGiven = NOT_GIVEN, output_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"] | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, tool_choice: str | NotGiven = NOT_GIVEN, @@ -81,9 +82,9 @@ def create( the Realtime API. Args: - model: The Realtime model used for this session. - - input_audio_format: The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. + input_audio_format: The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For + `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, single channel + (mono), and little-endian byte order. input_audio_transcription: Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the @@ -110,7 +111,10 @@ def create( modalities: The set of modalities the model can respond with. To disable audio, set this to ["text"]. + model: The Realtime model used for this session. + output_audio_format: The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. + For `pcm16`, output audio is sampled at a rate of 24kHz. temperature: Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8. @@ -140,12 +144,12 @@ def create( "/realtime/sessions", body=maybe_transform( { - "model": model, "input_audio_format": input_audio_format, "input_audio_transcription": input_audio_transcription, "instructions": instructions, "max_response_output_tokens": max_response_output_tokens, "modalities": modalities, + "model": model, "output_audio_format": output_audio_format, "temperature": temperature, "tool_choice": tool_choice, @@ -185,18 +189,19 @@ def with_streaming_response(self) -> AsyncSessionsWithStreamingResponse: async def create( self, *, + input_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"] | NotGiven = NOT_GIVEN, + input_audio_transcription: session_create_params.InputAudioTranscription | NotGiven = NOT_GIVEN, + instructions: str | NotGiven = NOT_GIVEN, + max_response_output_tokens: Union[int, Literal["inf"]] | NotGiven = NOT_GIVEN, + modalities: List[Literal["text", "audio"]] | NotGiven = NOT_GIVEN, model: Literal[ "gpt-4o-realtime-preview", "gpt-4o-realtime-preview-2024-10-01", "gpt-4o-realtime-preview-2024-12-17", "gpt-4o-mini-realtime-preview", "gpt-4o-mini-realtime-preview-2024-12-17", - ], - input_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"] | NotGiven = NOT_GIVEN, - input_audio_transcription: session_create_params.InputAudioTranscription | NotGiven = NOT_GIVEN, - instructions: str | NotGiven = NOT_GIVEN, - max_response_output_tokens: Union[int, Literal["inf"]] | NotGiven = NOT_GIVEN, - modalities: List[Literal["text", "audio"]] | NotGiven = NOT_GIVEN, + ] + | NotGiven = NOT_GIVEN, output_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"] | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, tool_choice: str | NotGiven = NOT_GIVEN, @@ -220,9 +225,9 @@ async def create( the Realtime API. Args: - model: The Realtime model used for this session. - - input_audio_format: The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. + input_audio_format: The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For + `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, single channel + (mono), and little-endian byte order. input_audio_transcription: Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the @@ -249,7 +254,10 @@ async def create( modalities: The set of modalities the model can respond with. To disable audio, set this to ["text"]. + model: The Realtime model used for this session. + output_audio_format: The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. + For `pcm16`, output audio is sampled at a rate of 24kHz. temperature: Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8. @@ -279,12 +287,12 @@ async def create( "/realtime/sessions", body=await async_maybe_transform( { - "model": model, "input_audio_format": input_audio_format, "input_audio_transcription": input_audio_transcription, "instructions": instructions, "max_response_output_tokens": max_response_output_tokens, "modalities": modalities, + "model": model, "output_audio_format": output_audio_format, "temperature": temperature, "tool_choice": tool_choice, diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index 201ae3f4c6..a9685c507a 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -251,9 +251,6 @@ def create( tier with a lower uptime SLA and no latency guarentee. - When not set, the default behavior is 'auto'. - When this parameter is set, the response body will include the `service_tier` - utilized. - stop: Up to 4 sequences where the API will stop generating further tokens. store: Whether or not to store the output of this chat completion request for use in @@ -509,9 +506,6 @@ def create( tier with a lower uptime SLA and no latency guarentee. - When not set, the default behavior is 'auto'. - When this parameter is set, the response body will include the `service_tier` - utilized. - stop: Up to 4 sequences where the API will stop generating further tokens. store: Whether or not to store the output of this chat completion request for use in @@ -760,9 +754,6 @@ def create( tier with a lower uptime SLA and no latency guarentee. - When not set, the default behavior is 'auto'. - When this parameter is set, the response body will include the `service_tier` - utilized. - stop: Up to 4 sequences where the API will stop generating further tokens. store: Whether or not to store the output of this chat completion request for use in @@ -1112,9 +1103,6 @@ async def create( tier with a lower uptime SLA and no latency guarentee. - When not set, the default behavior is 'auto'. - When this parameter is set, the response body will include the `service_tier` - utilized. - stop: Up to 4 sequences where the API will stop generating further tokens. store: Whether or not to store the output of this chat completion request for use in @@ -1370,9 +1358,6 @@ async def create( tier with a lower uptime SLA and no latency guarentee. - When not set, the default behavior is 'auto'. - When this parameter is set, the response body will include the `service_tier` - utilized. - stop: Up to 4 sequences where the API will stop generating further tokens. store: Whether or not to store the output of this chat completion request for use in @@ -1621,9 +1606,6 @@ async def create( tier with a lower uptime SLA and no latency guarentee. - When not set, the default behavior is 'auto'. - When this parameter is set, the response body will include the `service_tier` - utilized. - stop: Up to 4 sequences where the API will stop generating further tokens. store: Whether or not to store the output of this chat completion request for use in diff --git a/src/openai/resources/embeddings.py b/src/openai/resources/embeddings.py index 81a3e354e6..382a42340e 100644 --- a/src/openai/resources/embeddings.py +++ b/src/openai/resources/embeddings.py @@ -68,7 +68,8 @@ def create( `text-embedding-ada-002`), cannot be an empty string, and any array must be 2048 dimensions or less. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) - for counting tokens. + for counting tokens. Some models may also impose a limit on total number of + tokens summed across inputs. model: ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to @@ -180,7 +181,8 @@ async def create( `text-embedding-ada-002`), cannot be an empty string, and any array must be 2048 dimensions or less. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) - for counting tokens. + for counting tokens. Some models may also impose a limit on total number of + tokens summed across inputs. model: ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to diff --git a/src/openai/types/audio/speech_create_params.py b/src/openai/types/audio/speech_create_params.py index a60d000708..ed1a1ce748 100644 --- a/src/openai/types/audio/speech_create_params.py +++ b/src/openai/types/audio/speech_create_params.py @@ -20,11 +20,11 @@ class SpeechCreateParams(TypedDict, total=False): `tts-1` or `tts-1-hd` """ - voice: Required[Literal["alloy", "echo", "fable", "onyx", "nova", "shimmer"]] + voice: Required[Literal["alloy", "ash", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer"]] """The voice to use when generating the audio. - Supported voices are `alloy`, `echo`, `fable`, `onyx`, `nova`, and `shimmer`. - Previews of the voices are available in the + Supported voices are `alloy`, `ash`, `coral`, `echo`, `fable`, `onyx`, `nova`, + `sage` and `shimmer`. Previews of the voices are available in the [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech#voice-options). """ diff --git a/src/openai/types/beta/realtime/conversation_item_create_event.py b/src/openai/types/beta/realtime/conversation_item_create_event.py index 50d309675b..c4f72b9aff 100644 --- a/src/openai/types/beta/realtime/conversation_item_create_event.py +++ b/src/openai/types/beta/realtime/conversation_item_create_event.py @@ -20,9 +20,10 @@ class ConversationItemCreateEvent(BaseModel): """Optional client-generated ID used to identify this event.""" previous_item_id: Optional[str] = None - """The ID of the preceding item after which the new item will be inserted. - - If not set, the new item will be appended to the end of the conversation. If - set, it allows an item to be inserted mid-conversation. If the ID cannot be - found, an error will be returned and the item will not be added. + """ + The ID of the preceding item after which the new item will be inserted. If not + set, the new item will be appended to the end of the conversation. If set to + `root`, the new item will be added to the beginning of the conversation. If set + to an existing ID, it allows an item to be inserted mid-conversation. If the ID + cannot be found, an error will be returned and the item will not be added. """ diff --git a/src/openai/types/beta/realtime/conversation_item_create_event_param.py b/src/openai/types/beta/realtime/conversation_item_create_event_param.py index b8c8bbc251..6da5a63a9d 100644 --- a/src/openai/types/beta/realtime/conversation_item_create_event_param.py +++ b/src/openai/types/beta/realtime/conversation_item_create_event_param.py @@ -20,9 +20,10 @@ class ConversationItemCreateEventParam(TypedDict, total=False): """Optional client-generated ID used to identify this event.""" previous_item_id: str - """The ID of the preceding item after which the new item will be inserted. - - If not set, the new item will be appended to the end of the conversation. If - set, it allows an item to be inserted mid-conversation. If the ID cannot be - found, an error will be returned and the item will not be added. + """ + The ID of the preceding item after which the new item will be inserted. If not + set, the new item will be appended to the end of the conversation. If set to + `root`, the new item will be added to the beginning of the conversation. If set + to an existing ID, it allows an item to be inserted mid-conversation. If the ID + cannot be found, an error will be returned and the item will not be added. """ diff --git a/src/openai/types/beta/realtime/session.py b/src/openai/types/beta/realtime/session.py index 09cdbb02bc..2d028f817c 100644 --- a/src/openai/types/beta/realtime/session.py +++ b/src/openai/types/beta/realtime/session.py @@ -63,7 +63,12 @@ class Session(BaseModel): """Unique identifier for the session object.""" input_audio_format: Optional[Literal["pcm16", "g711_ulaw", "g711_alaw"]] = None - """The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.""" + """The format of input audio. + + Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For `pcm16`, input audio must + be 16-bit PCM at a 24kHz sample rate, single channel (mono), and little-endian + byte order. + """ input_audio_transcription: Optional[InputAudioTranscription] = None """ @@ -117,7 +122,11 @@ class Session(BaseModel): """The Realtime model used for this session.""" output_audio_format: Optional[Literal["pcm16", "g711_ulaw", "g711_alaw"]] = None - """The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.""" + """The format of output audio. + + Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For `pcm16`, output audio is + sampled at a rate of 24kHz. + """ temperature: Optional[float] = None """Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.""" diff --git a/src/openai/types/beta/realtime/session_create_params.py b/src/openai/types/beta/realtime/session_create_params.py index f56f2c5c22..3708efeecd 100644 --- a/src/openai/types/beta/realtime/session_create_params.py +++ b/src/openai/types/beta/realtime/session_create_params.py @@ -3,25 +3,19 @@ from __future__ import annotations from typing import List, Union, Iterable -from typing_extensions import Literal, Required, TypedDict +from typing_extensions import Literal, TypedDict __all__ = ["SessionCreateParams", "InputAudioTranscription", "Tool", "TurnDetection"] class SessionCreateParams(TypedDict, total=False): - model: Required[ - Literal[ - "gpt-4o-realtime-preview", - "gpt-4o-realtime-preview-2024-10-01", - "gpt-4o-realtime-preview-2024-12-17", - "gpt-4o-mini-realtime-preview", - "gpt-4o-mini-realtime-preview-2024-12-17", - ] - ] - """The Realtime model used for this session.""" - input_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"] - """The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.""" + """The format of input audio. + + Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For `pcm16`, input audio must + be 16-bit PCM at a 24kHz sample rate, single channel (mono), and little-endian + byte order. + """ input_audio_transcription: InputAudioTranscription """ @@ -61,8 +55,21 @@ class SessionCreateParams(TypedDict, total=False): To disable audio, set this to ["text"]. """ + model: Literal[ + "gpt-4o-realtime-preview", + "gpt-4o-realtime-preview-2024-10-01", + "gpt-4o-realtime-preview-2024-12-17", + "gpt-4o-mini-realtime-preview", + "gpt-4o-mini-realtime-preview-2024-12-17", + ] + """The Realtime model used for this session.""" + output_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"] - """The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.""" + """The format of output audio. + + Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For `pcm16`, output audio is + sampled at a rate of 24kHz. + """ temperature: float """Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.""" diff --git a/src/openai/types/beta/realtime/session_update_event.py b/src/openai/types/beta/realtime/session_update_event.py index c04220aa25..322e588a4e 100644 --- a/src/openai/types/beta/realtime/session_update_event.py +++ b/src/openai/types/beta/realtime/session_update_event.py @@ -65,17 +65,13 @@ class SessionTurnDetection(BaseModel): class Session(BaseModel): - model: Literal[ - "gpt-4o-realtime-preview", - "gpt-4o-realtime-preview-2024-10-01", - "gpt-4o-realtime-preview-2024-12-17", - "gpt-4o-mini-realtime-preview", - "gpt-4o-mini-realtime-preview-2024-12-17", - ] - """The Realtime model used for this session.""" - input_audio_format: Optional[Literal["pcm16", "g711_ulaw", "g711_alaw"]] = None - """The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.""" + """The format of input audio. + + Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For `pcm16`, input audio must + be 16-bit PCM at a 24kHz sample rate, single channel (mono), and little-endian + byte order. + """ input_audio_transcription: Optional[SessionInputAudioTranscription] = None """ @@ -115,8 +111,23 @@ class Session(BaseModel): To disable audio, set this to ["text"]. """ + model: Optional[ + Literal[ + "gpt-4o-realtime-preview", + "gpt-4o-realtime-preview-2024-10-01", + "gpt-4o-realtime-preview-2024-12-17", + "gpt-4o-mini-realtime-preview", + "gpt-4o-mini-realtime-preview-2024-12-17", + ] + ] = None + """The Realtime model used for this session.""" + output_audio_format: Optional[Literal["pcm16", "g711_ulaw", "g711_alaw"]] = None - """The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.""" + """The format of output audio. + + Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For `pcm16`, output audio is + sampled at a rate of 24kHz. + """ temperature: Optional[float] = None """Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.""" diff --git a/src/openai/types/beta/realtime/session_update_event_param.py b/src/openai/types/beta/realtime/session_update_event_param.py index aa06069b04..c01d9b6887 100644 --- a/src/openai/types/beta/realtime/session_update_event_param.py +++ b/src/openai/types/beta/realtime/session_update_event_param.py @@ -71,19 +71,13 @@ class SessionTurnDetection(TypedDict, total=False): class Session(TypedDict, total=False): - model: Required[ - Literal[ - "gpt-4o-realtime-preview", - "gpt-4o-realtime-preview-2024-10-01", - "gpt-4o-realtime-preview-2024-12-17", - "gpt-4o-mini-realtime-preview", - "gpt-4o-mini-realtime-preview-2024-12-17", - ] - ] - """The Realtime model used for this session.""" - input_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"] - """The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.""" + """The format of input audio. + + Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For `pcm16`, input audio must + be 16-bit PCM at a 24kHz sample rate, single channel (mono), and little-endian + byte order. + """ input_audio_transcription: SessionInputAudioTranscription """ @@ -123,8 +117,21 @@ class Session(TypedDict, total=False): To disable audio, set this to ["text"]. """ + model: Literal[ + "gpt-4o-realtime-preview", + "gpt-4o-realtime-preview-2024-10-01", + "gpt-4o-realtime-preview-2024-12-17", + "gpt-4o-mini-realtime-preview", + "gpt-4o-mini-realtime-preview-2024-12-17", + ] + """The Realtime model used for this session.""" + output_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"] - """The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.""" + """The format of output audio. + + Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For `pcm16`, output audio is + sampled at a rate of 24kHz. + """ temperature: float """Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.""" diff --git a/src/openai/types/chat/chat_completion.py b/src/openai/types/chat/chat_completion.py index 4b53e70890..cb812a2702 100644 --- a/src/openai/types/chat/chat_completion.py +++ b/src/openai/types/chat/chat_completion.py @@ -60,11 +60,7 @@ class ChatCompletion(BaseModel): """The object type, which is always `chat.completion`.""" service_tier: Optional[Literal["scale", "default"]] = None - """The service tier used for processing the request. - - This field is only included if the `service_tier` parameter is specified in the - request. - """ + """The service tier used for processing the request.""" system_fingerprint: Optional[str] = None """This fingerprint represents the backend configuration that the model runs with. diff --git a/src/openai/types/chat/chat_completion_assistant_message_param.py b/src/openai/types/chat/chat_completion_assistant_message_param.py index 35e3a3d784..229fb822f4 100644 --- a/src/openai/types/chat/chat_completion_assistant_message_param.py +++ b/src/openai/types/chat/chat_completion_assistant_message_param.py @@ -38,8 +38,8 @@ class ChatCompletionAssistantMessageParam(TypedDict, total=False): """The role of the messages author, in this case `assistant`.""" audio: Optional[Audio] - """Data about a previous audio response from the model. - + """ + Data about a previous audio response from the model. [Learn more](https://platform.openai.com/docs/guides/audio). """ diff --git a/src/openai/types/chat/chat_completion_chunk.py b/src/openai/types/chat/chat_completion_chunk.py index 9ec6dc4bdb..7b0ae2e121 100644 --- a/src/openai/types/chat/chat_completion_chunk.py +++ b/src/openai/types/chat/chat_completion_chunk.py @@ -129,11 +129,7 @@ class ChatCompletionChunk(BaseModel): """The object type, which is always `chat.completion.chunk`.""" service_tier: Optional[Literal["scale", "default"]] = None - """The service tier used for processing the request. - - This field is only included if the `service_tier` parameter is specified in the - request. - """ + """The service tier used for processing the request.""" system_fingerprint: Optional[str] = None """ diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index f168ddea6e..30d930b120 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -220,9 +220,6 @@ class CompletionCreateParamsBase(TypedDict, total=False): - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. - When not set, the default behavior is 'auto'. - - When this parameter is set, the response body will include the `service_tier` - utilized. """ stop: Union[Optional[str], List[str]] diff --git a/src/openai/types/embedding_create_params.py b/src/openai/types/embedding_create_params.py index 1385762885..a90566449b 100644 --- a/src/openai/types/embedding_create_params.py +++ b/src/openai/types/embedding_create_params.py @@ -19,7 +19,8 @@ class EmbeddingCreateParams(TypedDict, total=False): (8192 tokens for `text-embedding-ada-002`), cannot be an empty string, and any array must be 2048 dimensions or less. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) - for counting tokens. + for counting tokens. Some models may also impose a limit on total number of + tokens summed across inputs. """ model: Required[Union[str, EmbeddingModel]] diff --git a/tests/api_resources/beta/realtime/test_sessions.py b/tests/api_resources/beta/realtime/test_sessions.py index 65bfa27572..908aa983be 100644 --- a/tests/api_resources/beta/realtime/test_sessions.py +++ b/tests/api_resources/beta/realtime/test_sessions.py @@ -19,20 +19,18 @@ class TestSessions: @parametrize def test_method_create(self, client: OpenAI) -> None: - session = client.beta.realtime.sessions.create( - model="gpt-4o-realtime-preview", - ) + session = client.beta.realtime.sessions.create() assert_matches_type(SessionCreateResponse, session, path=["response"]) @parametrize def test_method_create_with_all_params(self, client: OpenAI) -> None: session = client.beta.realtime.sessions.create( - model="gpt-4o-realtime-preview", input_audio_format="pcm16", input_audio_transcription={"model": "model"}, instructions="instructions", max_response_output_tokens=0, modalities=["text"], + model="gpt-4o-realtime-preview", output_audio_format="pcm16", temperature=0, tool_choice="tool_choice", @@ -57,9 +55,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: @parametrize def test_raw_response_create(self, client: OpenAI) -> None: - response = client.beta.realtime.sessions.with_raw_response.create( - model="gpt-4o-realtime-preview", - ) + response = client.beta.realtime.sessions.with_raw_response.create() assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -68,9 +64,7 @@ def test_raw_response_create(self, client: OpenAI) -> None: @parametrize def test_streaming_response_create(self, client: OpenAI) -> None: - with client.beta.realtime.sessions.with_streaming_response.create( - model="gpt-4o-realtime-preview", - ) as response: + with client.beta.realtime.sessions.with_streaming_response.create() as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -85,20 +79,18 @@ class TestAsyncSessions: @parametrize async def test_method_create(self, async_client: AsyncOpenAI) -> None: - session = await async_client.beta.realtime.sessions.create( - model="gpt-4o-realtime-preview", - ) + session = await async_client.beta.realtime.sessions.create() assert_matches_type(SessionCreateResponse, session, path=["response"]) @parametrize async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: session = await async_client.beta.realtime.sessions.create( - model="gpt-4o-realtime-preview", input_audio_format="pcm16", input_audio_transcription={"model": "model"}, instructions="instructions", max_response_output_tokens=0, modalities=["text"], + model="gpt-4o-realtime-preview", output_audio_format="pcm16", temperature=0, tool_choice="tool_choice", @@ -123,9 +115,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> @parametrize async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: - response = await async_client.beta.realtime.sessions.with_raw_response.create( - model="gpt-4o-realtime-preview", - ) + response = await async_client.beta.realtime.sessions.with_raw_response.create() assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -134,9 +124,7 @@ async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: - async with async_client.beta.realtime.sessions.with_streaming_response.create( - model="gpt-4o-realtime-preview", - ) as response: + async with async_client.beta.realtime.sessions.with_streaming_response.create() as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index 393a790549..25c9a36164 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -72,7 +72,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: presence_penalty=-2, reasoning_effort="low", response_format={"type": "text"}, - seed=-9007199254740991, + seed=0, service_tier="auto", stop="string", store=True, @@ -187,7 +187,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: presence_penalty=-2, reasoning_effort="low", response_format={"type": "text"}, - seed=-9007199254740991, + seed=0, service_tier="auto", stop="string", store=True, @@ -321,7 +321,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn presence_penalty=-2, reasoning_effort="low", response_format={"type": "text"}, - seed=-9007199254740991, + seed=0, service_tier="auto", stop="string", store=True, @@ -436,7 +436,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn presence_penalty=-2, reasoning_effort="low", response_format={"type": "text"}, - seed=-9007199254740991, + seed=0, service_tier="auto", stop="string", store=True, diff --git a/tests/api_resources/test_completions.py b/tests/api_resources/test_completions.py index ad2679cabe..9ec503c1e3 100644 --- a/tests/api_resources/test_completions.py +++ b/tests/api_resources/test_completions.py @@ -38,7 +38,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: max_tokens=16, n=1, presence_penalty=-2, - seed=-9007199254740991, + seed=0, stop="\n", stream=False, stream_options={"include_usage": True}, @@ -98,7 +98,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: max_tokens=16, n=1, presence_penalty=-2, - seed=-9007199254740991, + seed=0, stop="\n", stream_options={"include_usage": True}, suffix="test.", @@ -160,7 +160,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn max_tokens=16, n=1, presence_penalty=-2, - seed=-9007199254740991, + seed=0, stop="\n", stream=False, stream_options={"include_usage": True}, @@ -220,7 +220,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn max_tokens=16, n=1, presence_penalty=-2, - seed=-9007199254740991, + seed=0, stop="\n", stream_options={"include_usage": True}, suffix="test.", From c111dab6af1bb40e1f8768c9941dc7c292293e59 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 22 Jan 2025 13:22:04 +0000 Subject: [PATCH 664/816] release: 1.60.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 18 ++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 21 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 32b4e18516..88c2f64985 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.59.9" + ".": "1.60.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 86951242c5..9f90d3dd22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,23 @@ # Changelog +## 1.60.0 (2025-01-22) + +Full Changelog: [v1.59.9...v1.60.0](https://github.com/openai/openai-python/compare/v1.59.9...v1.60.0) + +### Features + +* **api:** update enum values, comments, and examples ([#2045](https://github.com/openai/openai-python/issues/2045)) ([e8205fd](https://github.com/openai/openai-python/commit/e8205fd58f0d677f476c577a8d9afb90f5710506)) + + +### Chores + +* **internal:** minor style changes ([#2043](https://github.com/openai/openai-python/issues/2043)) ([89a9dd8](https://github.com/openai/openai-python/commit/89a9dd821eaf5300ad11b0270b61fdfa4fd6e9b6)) + + +### Documentation + +* **readme:** mention failed requests in request IDs ([5f7c30b](https://github.com/openai/openai-python/commit/5f7c30bc006ffb666c324011a68aae357cb33e35)) + ## 1.59.9 (2025-01-20) Full Changelog: [v1.59.8...v1.59.9](https://github.com/openai/openai-python/compare/v1.59.8...v1.59.9) diff --git a/pyproject.toml b/pyproject.toml index 0b142a6bd8..80c79ff585 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.59.9" +version = "1.60.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 7c92c3adf3..ef0ddcfc5c 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.59.9" # x-release-please-version +__version__ = "1.60.0" # x-release-please-version From abc5459c7504eec25a67b35104e2e09e7d8f232c Mon Sep 17 00:00:00 2001 From: Fernando de Oliveira <5161098+fedeoliv@users.noreply.github.com> Date: Wed, 22 Jan 2025 16:44:26 -0500 Subject: [PATCH 665/816] docs(examples/azure): add async snippet (#1787) --- examples/azure_ad.py | 79 ++++++++++++++++++++++++++++++++------------ 1 file changed, 58 insertions(+), 21 deletions(-) diff --git a/examples/azure_ad.py b/examples/azure_ad.py index 1b0d81863d..67e2f23713 100755 --- a/examples/azure_ad.py +++ b/examples/azure_ad.py @@ -1,30 +1,67 @@ -from azure.identity import DefaultAzureCredential, get_bearer_token_provider +import asyncio -from openai import AzureOpenAI +from openai.lib.azure import AzureOpenAI, AsyncAzureOpenAI, AzureADTokenProvider, AsyncAzureADTokenProvider -token_provider = get_bearer_token_provider(DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default") +scopes = "https://cognitiveservices.azure.com/.default" - -# may change in the future +# May change in the future # https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#rest-api-versioning api_version = "2023-07-01-preview" # https://learn.microsoft.com/en-us/azure/cognitive-services/openai/how-to/create-resource?pivots=web-portal#create-a-resource endpoint = "https://my-resource.openai.azure.com/" -client = AzureOpenAI( - api_version=api_version, - azure_endpoint=endpoint, - azure_ad_token_provider=token_provider, -) - -completion = client.chat.completions.create( - model="deployment-name", # e.g. gpt-35-instant - messages=[ - { - "role": "user", - "content": "How do I output all files in a directory using Python?", - }, - ], -) -print(completion.to_json()) +deployment_name = "deployment-name" # e.g. gpt-35-instant + + +def sync_main() -> None: + from azure.identity import DefaultAzureCredential, get_bearer_token_provider + + token_provider: AzureADTokenProvider = get_bearer_token_provider(DefaultAzureCredential(), scopes) + + client = AzureOpenAI( + api_version=api_version, + azure_endpoint=endpoint, + azure_ad_token_provider=token_provider, + ) + + completion = client.chat.completions.create( + model=deployment_name, + messages=[ + { + "role": "user", + "content": "How do I output all files in a directory using Python?", + } + ], + ) + + print(completion.to_json()) + + +async def async_main() -> None: + from azure.identity.aio import DefaultAzureCredential, get_bearer_token_provider + + token_provider: AsyncAzureADTokenProvider = get_bearer_token_provider(DefaultAzureCredential(), scopes) + + client = AsyncAzureOpenAI( + api_version=api_version, + azure_endpoint=endpoint, + azure_ad_token_provider=token_provider, + ) + + completion = await client.chat.completions.create( + model=deployment_name, + messages=[ + { + "role": "user", + "content": "How do I output all files in a directory using Python?", + } + ], + ) + + print(completion.to_json()) + + +sync_main() + +asyncio.run(async_main()) From 27d0e67b1d121ccc5b48c95e1f0bc3f6e93e9bd3 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 23 Jan 2025 12:39:04 +0000 Subject: [PATCH 666/816] chore(internal): minor formatting changes (#2050) --- .github/workflows/ci.yml | 1 + scripts/bootstrap | 2 +- scripts/lint | 1 - 3 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index de70348b9c..26f497db1f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,6 +29,7 @@ jobs: - name: Run lints run: ./scripts/lint + test: name: test runs-on: ubuntu-latest diff --git a/scripts/bootstrap b/scripts/bootstrap index 29df07e77b..9910ec05fc 100755 --- a/scripts/bootstrap +++ b/scripts/bootstrap @@ -4,7 +4,7 @@ set -e cd "$(dirname "$0")/.." -if [ -f "Brewfile" ] && [ "$(uname -s)" = "Darwin" ]; then +if ! command -v rye >/dev/null 2>&1 && [ -f "Brewfile" ] && [ "$(uname -s)" = "Darwin" ]; then brew bundle check >/dev/null 2>&1 || { echo "==> Installing Homebrew dependencies…" brew bundle diff --git a/scripts/lint b/scripts/lint index 64495ee345..55bc1dd711 100755 --- a/scripts/lint +++ b/scripts/lint @@ -9,4 +9,3 @@ rye run lint echo "==> Making sure it imports" rye run python -c 'import openai' - From b95be16e7c8a76c3d63335df13ab0d55ba3d5c35 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 24 Jan 2025 05:04:08 +0000 Subject: [PATCH 667/816] release: 1.60.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 88c2f64985..0b39405429 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.60.0" + ".": "1.60.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f90d3dd22..873a6a254d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.60.1 (2025-01-24) + +Full Changelog: [v1.60.0...v1.60.1](https://github.com/openai/openai-python/compare/v1.60.0...v1.60.1) + +### Chores + +* **internal:** minor formatting changes ([#2050](https://github.com/openai/openai-python/issues/2050)) ([9c44192](https://github.com/openai/openai-python/commit/9c44192be5776d9252d36dc027a33c60b33d81b2)) + + +### Documentation + +* **examples/azure:** add async snippet ([#1787](https://github.com/openai/openai-python/issues/1787)) ([f60eda1](https://github.com/openai/openai-python/commit/f60eda1c1e8caf0ec2274b18b3fb2252304196db)) + ## 1.60.0 (2025-01-22) Full Changelog: [v1.59.9...v1.60.0](https://github.com/openai/openai-python/compare/v1.59.9...v1.60.0) diff --git a/pyproject.toml b/pyproject.toml index 80c79ff585..fdfc9c73e3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.60.0" +version = "1.60.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index ef0ddcfc5c..b87aa8abd4 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.60.0" # x-release-please-version +__version__ = "1.60.1" # x-release-please-version From 257d79e8a00144a7317d511401da2432a4201c7b Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 27 Jan 2025 19:20:32 +0000 Subject: [PATCH 668/816] fix(parsing): don't validate input tools in the asynchronous `.parse()` method --- src/openai/resources/beta/chat/completions.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/openai/resources/beta/chat/completions.py b/src/openai/resources/beta/chat/completions.py index 48cb13f7a6..7771d2ff50 100644 --- a/src/openai/resources/beta/chat/completions.py +++ b/src/openai/resources/beta/chat/completions.py @@ -268,6 +268,8 @@ def stream( When the context manager exits, the response will be closed, however the `stream` instance is still available outside the context manager. """ + _validate_input_tools(tools) + extra_headers = { "X-Stainless-Helper-Method": "beta.chat.completions.stream", **(extra_headers or {}), From d16e6edde5a155626910b5758a0b939bfedb9ced Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 27 Jan 2025 19:26:48 +0000 Subject: [PATCH 669/816] release: 1.60.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 0b39405429..73f712c242 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.60.1" + ".": "1.60.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 873a6a254d..168d98e5cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.60.2 (2025-01-27) + +Full Changelog: [v1.60.1...v1.60.2](https://github.com/openai/openai-python/compare/v1.60.1...v1.60.2) + +### Bug Fixes + +* **parsing:** don't validate input tools in the asynchronous `.parse()` method ([6fcfe73](https://github.com/openai/openai-python/commit/6fcfe73cd335853c7dd2cd3151a0d5d1785cfc9c)) + ## 1.60.1 (2025-01-24) Full Changelog: [v1.60.0...v1.60.1](https://github.com/openai/openai-python/compare/v1.60.0...v1.60.1) diff --git a/pyproject.toml b/pyproject.toml index fdfc9c73e3..9657bdc0ce 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.60.1" +version = "1.60.2" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index b87aa8abd4..c8f825db34 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.60.1" # x-release-please-version +__version__ = "1.60.2" # x-release-please-version From 90e3d39655548c935002dee7ef6f617c846c123c Mon Sep 17 00:00:00 2001 From: Guspan Tanadi <36249910+guspan-tanadi@users.noreply.github.com> Date: Wed, 29 Jan 2025 04:58:34 +0700 Subject: [PATCH 670/816] docs(readme): current section links (#2055) chore(helpers): section links --- README.md | 4 ++-- helpers.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5f7d477cc8..3c103f036c 100644 --- a/README.md +++ b/README.md @@ -304,7 +304,7 @@ However the real magic of the Realtime API is handling audio inputs / outputs, s ### Realtime error handling -Whenever an error occurs, the Realtime API will send an [`error` event](https://platform.openai.com/docs/guides/realtime/realtime-api-beta#handling-errors) and the connection will stay open and remain usable. This means you need to handle it yourself, as *no errors are raised directly* by the SDK when an `error` event comes in. +Whenever an error occurs, the Realtime API will send an [`error` event](https://platform.openai.com/docs/guides/realtime-model-capabilities#error-handling) and the connection will stay open and remain usable. This means you need to handle it yourself, as *no errors are raised directly* by the SDK when an `error` event comes in. ```py client = AsyncOpenAI() @@ -547,7 +547,7 @@ client.with_options(max_retries=5).chat.completions.create( ### Timeouts By default requests time out after 10 minutes. You can configure this with a `timeout` option, -which accepts a float or an [`httpx.Timeout`](https://www.python-httpx.org/advanced/#fine-tuning-the-configuration) object: +which accepts a float or an [`httpx.Timeout`](https://www.python-httpx.org/advanced/timeouts/#fine-tuning-the-configuration) object: ```python from openai import OpenAI diff --git a/helpers.md b/helpers.md index 3f3fafa45c..77823fa750 100644 --- a/helpers.md +++ b/helpers.md @@ -134,7 +134,7 @@ OpenAI supports streaming responses when interacting with the [Chat Completion]( The SDK provides a `.beta.chat.completions.stream()` method that wraps the `.chat.completions.create(stream=True)` stream providing a more granular event API & automatic accumulation of each delta. -It also supports all aforementioned [parsing helpers](#parsing-helpers). +It also supports all aforementioned [parsing helpers](#structured-outputs-parsing-helpers). Unlike `.create(stream=True)`, the `.stream()` method requires usage within a context manager to prevent accidental leakage of the response: From d779e40bc960c1d5fcf1b23b804af9b9ccf43c58 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 10:09:46 +0000 Subject: [PATCH 671/816] chore: update api.md (#2063) --- api.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api.md b/api.md index 1edd3f6589..f1e0d023bd 100644 --- a/api.md +++ b/api.md @@ -99,7 +99,7 @@ Methods: - client.files.list(\*\*params) -> SyncCursorPage[FileObject] - client.files.delete(file_id) -> FileDeleted - client.files.content(file_id) -> HttpxBinaryResponseContent -- client.files.retrieve_content(file_id) -> str +- client.files.retrieve_content(file_id) -> str - client.files.wait_for_processing(\*args) -> FileObject # Images From a99096823a878f0725ef1433226b3bc725c4c618 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Fri, 31 Jan 2025 11:47:20 +0000 Subject: [PATCH 672/816] Revert "fix(parsing): don't validate input tools in the asynchronous `.parse()` method" This reverts commit 257d79e8a00144a7317d511401da2432a4201c7b. --- src/openai/resources/beta/chat/completions.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/openai/resources/beta/chat/completions.py b/src/openai/resources/beta/chat/completions.py index 7771d2ff50..48cb13f7a6 100644 --- a/src/openai/resources/beta/chat/completions.py +++ b/src/openai/resources/beta/chat/completions.py @@ -268,8 +268,6 @@ def stream( When the context manager exits, the response will be closed, however the `stream` instance is still available outside the context manager. """ - _validate_input_tools(tools) - extra_headers = { "X-Stainless-Helper-Method": "beta.chat.completions.stream", **(extra_headers or {}), From fdd52476b56cbd57d0cbc27d06f9d2907b537e82 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 19:09:53 +0000 Subject: [PATCH 673/816] feat(api): add o3-mini (#2067) fix(types): correct metadata type + other fixes --- .stats.yml | 2 +- api.md | 1 + src/openai/resources/audio/transcriptions.py | 8 +- src/openai/resources/batches.py | 26 ++-- src/openai/resources/beta/assistants.py | 41 +++--- .../resources/beta/realtime/sessions.py | 14 +- src/openai/resources/beta/threads/messages.py | 41 +++--- .../resources/beta/threads/runs/runs.py | 85 +++++++----- src/openai/resources/beta/threads/threads.py | 123 +++++++++++------- .../beta/vector_stores/vector_stores.py | 41 +++--- src/openai/resources/chat/completions.py | 89 ++++++++----- src/openai/types/__init__.py | 1 + .../audio/transcription_create_params.py | 4 +- src/openai/types/batch.py | 10 +- src/openai/types/batch_create_params.py | 15 ++- src/openai/types/beta/assistant.py | 9 +- .../types/beta/assistant_create_params.py | 21 +-- .../types/beta/assistant_update_params.py | 9 +- .../conversation_item_create_event.py | 12 +- .../conversation_item_create_event_param.py | 12 +- .../types/beta/realtime/realtime_response.py | 51 +++++++- .../beta/realtime/response_create_event.py | 9 +- .../realtime/response_create_event_param.py | 9 +- .../beta/realtime/session_create_params.py | 23 +++- .../beta/realtime/session_create_response.py | 6 +- .../beta/realtime/session_update_event.py | 23 +++- .../realtime/session_update_event_param.py | 23 +++- src/openai/types/beta/thread.py | 9 +- .../beta/thread_create_and_run_params.py | 43 +++--- src/openai/types/beta/thread_create_params.py | 29 +++-- src/openai/types/beta/thread_update_params.py | 10 +- src/openai/types/beta/threads/message.py | 9 +- .../beta/threads/message_create_params.py | 9 +- .../beta/threads/message_update_params.py | 10 +- src/openai/types/beta/threads/run.py | 9 +- .../types/beta/threads/run_create_params.py | 17 ++- .../types/beta/threads/run_update_params.py | 10 +- .../types/beta/threads/runs/run_step.py | 9 +- src/openai/types/beta/vector_store.py | 9 +- .../types/beta/vector_store_create_params.py | 9 +- .../types/beta/vector_store_update_params.py | 10 +- ...chat_completion_assistant_message_param.py | 4 +- .../types/chat/completion_create_params.py | 17 ++- src/openai/types/chat_model.py | 2 + src/openai/types/shared/__init__.py | 1 + src/openai/types/shared/metadata.py | 8 ++ src/openai/types/shared_params/__init__.py | 1 + src/openai/types/shared_params/metadata.py | 10 ++ src/openai/types/upload.py | 2 +- .../beta/realtime/test_sessions.py | 12 +- tests/api_resources/beta/test_assistants.py | 12 +- tests/api_resources/beta/test_threads.py | 52 ++++---- .../api_resources/beta/test_vector_stores.py | 16 +-- .../beta/threads/test_messages.py | 16 +-- tests/api_resources/beta/threads/test_runs.py | 28 ++-- 55 files changed, 710 insertions(+), 371 deletions(-) create mode 100644 src/openai/types/shared/metadata.py create mode 100644 src/openai/types/shared_params/metadata.py diff --git a/.stats.yml b/.stats.yml index d518bac586..e49b5c56e8 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 69 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-3904ef6b29a89c98f93a9b7da19879695f3c440564be6384db7af1b734611ede.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-6204952a29973265b9c0d66fc67ffaf53c6a90ae4d75cdacf9d147676f5274c9.yml diff --git a/api.md b/api.md index f1e0d023bd..c1262fd2c5 100644 --- a/api.md +++ b/api.md @@ -5,6 +5,7 @@ from openai.types import ( ErrorObject, FunctionDefinition, FunctionParameters, + Metadata, ResponseFormatJSONObject, ResponseFormatJSONSchema, ResponseFormatText, diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index 341446c43a..f338ad067d 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -138,8 +138,8 @@ def create( Whisper V2 model) is currently available. language: The language of the input audio. Supplying the input language in - [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format will - improve accuracy and latency. + [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) + format will improve accuracy and latency. prompt: An optional text to guide the model's style or continue a previous audio segment. The @@ -302,8 +302,8 @@ async def create( Whisper V2 model) is currently available. language: The language of the input audio. Supplying the input language in - [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format will - improve accuracy and latency. + [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) + format will improve accuracy and latency. prompt: An optional text to guide the model's style or continue a previous audio segment. The diff --git a/src/openai/resources/batches.py b/src/openai/resources/batches.py index 4a887642e9..7e7ec19ec2 100644 --- a/src/openai/resources/batches.py +++ b/src/openai/resources/batches.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Dict, Optional +from typing import Optional from typing_extensions import Literal import httpx @@ -19,10 +19,8 @@ from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ..pagination import SyncCursorPage, AsyncCursorPage from ..types.batch import Batch -from .._base_client import ( - AsyncPaginator, - make_request_options, -) +from .._base_client import AsyncPaginator, make_request_options +from ..types.shared_params.metadata import Metadata __all__ = ["Batches", "AsyncBatches"] @@ -53,7 +51,7 @@ def create( completion_window: Literal["24h"], endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"], input_file_id: str, - metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -83,7 +81,12 @@ def create( and must be uploaded with the purpose `batch`. The file can contain up to 50,000 requests, and can be up to 200 MB in size. - metadata: Optional custom metadata for the batch. + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. extra_headers: Send extra headers @@ -258,7 +261,7 @@ async def create( completion_window: Literal["24h"], endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"], input_file_id: str, - metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -288,7 +291,12 @@ async def create( and must be uploaded with the purpose `batch`. The file can contain up to 50,000 requests, and can be up to 200 MB in size. - metadata: Optional custom metadata for the batch. + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. extra_headers: Send extra headers diff --git a/src/openai/resources/beta/assistants.py b/src/openai/resources/beta/assistants.py index 2f2482b648..65b7c9cfc2 100644 --- a/src/openai/resources/beta/assistants.py +++ b/src/openai/resources/beta/assistants.py @@ -26,6 +26,7 @@ from ...types.chat_model import ChatModel from ...types.beta.assistant import Assistant from ...types.beta.assistant_deleted import AssistantDeleted +from ...types.shared_params.metadata import Metadata from ...types.beta.assistant_tool_param import AssistantToolParam from ...types.beta.assistant_response_format_option_param import AssistantResponseFormatOptionParam @@ -58,7 +59,7 @@ def create( model: Union[str, ChatModel], description: Optional[str] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -88,9 +89,11 @@ def create( characters. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. name: The name of the assistant. The maximum length is 256 characters. @@ -206,7 +209,7 @@ def update( *, description: Optional[str] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: str | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -232,9 +235,11 @@ def update( characters. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. model: ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to @@ -444,7 +449,7 @@ async def create( model: Union[str, ChatModel], description: Optional[str] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -474,9 +479,11 @@ async def create( characters. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. name: The name of the assistant. The maximum length is 256 characters. @@ -592,7 +599,7 @@ async def update( *, description: Optional[str] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: str | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -618,9 +625,11 @@ async def update( characters. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. model: ID of the model to use. You can use the [List models](https://platform.openai.com/docs/api-reference/models/list) API to diff --git a/src/openai/resources/beta/realtime/sessions.py b/src/openai/resources/beta/realtime/sessions.py index b920c89207..4b337b7c19 100644 --- a/src/openai/resources/beta/realtime/sessions.py +++ b/src/openai/resources/beta/realtime/sessions.py @@ -89,8 +89,11 @@ def create( input_audio_transcription: Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs - asynchronously through Whisper and should be treated as rough guidance rather - than the representation understood by the model. + asynchronously through + [OpenAI Whisper transcription](https://platform.openai.com/docs/api-reference/audio/createTranscription) + and should be treated as rough guidance rather than the representation + understood by the model. The client can optionally set the language and prompt + for transcription, these fields will be passed to the Whisper API. instructions: The default system instructions (i.e. system message) prepended to model calls. This field allows the client to guide the model on desired responses. The model @@ -232,8 +235,11 @@ async def create( input_audio_transcription: Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs - asynchronously through Whisper and should be treated as rough guidance rather - than the representation understood by the model. + asynchronously through + [OpenAI Whisper transcription](https://platform.openai.com/docs/api-reference/audio/createTranscription) + and should be treated as rough guidance rather than the representation + understood by the model. The client can optionally set the language and prompt + for transcription, these fields will be passed to the Whisper API. instructions: The default system instructions (i.e. system message) prepended to model calls. This field allows the client to guide the model on desired responses. The model diff --git a/src/openai/resources/beta/threads/messages.py b/src/openai/resources/beta/threads/messages.py index f780f6f558..e3374aba37 100644 --- a/src/openai/resources/beta/threads/messages.py +++ b/src/openai/resources/beta/threads/messages.py @@ -23,6 +23,7 @@ ) from ....types.beta.threads import message_list_params, message_create_params, message_update_params from ....types.beta.threads.message import Message +from ....types.shared_params.metadata import Metadata from ....types.beta.threads.message_deleted import MessageDeleted from ....types.beta.threads.message_content_part_param import MessageContentPartParam @@ -56,7 +57,7 @@ def create( content: Union[str, Iterable[MessageContentPartParam]], role: Literal["user", "assistant"], attachments: Optional[Iterable[message_create_params.Attachment]] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -81,9 +82,11 @@ def create( attachments: A list of files attached to the message, and the tools they should be added to. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. extra_headers: Send extra headers @@ -155,7 +158,7 @@ def update( message_id: str, *, thread_id: str, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -168,9 +171,11 @@ def update( Args: metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. extra_headers: Send extra headers @@ -330,7 +335,7 @@ async def create( content: Union[str, Iterable[MessageContentPartParam]], role: Literal["user", "assistant"], attachments: Optional[Iterable[message_create_params.Attachment]] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -355,9 +360,11 @@ async def create( attachments: A list of files attached to the message, and the tools they should be added to. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. extra_headers: Send extra headers @@ -429,7 +436,7 @@ async def update( message_id: str, *, thread_id: str, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -442,9 +449,11 @@ async def update( Args: metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. extra_headers: Send extra headers diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index f32a08f235..9cb202a1a2 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -47,6 +47,7 @@ run_submit_tool_outputs_params, ) from .....types.beta.threads.run import Run +from .....types.shared_params.metadata import Metadata from .....types.beta.assistant_tool_param import AssistantToolParam from .....types.beta.assistant_stream_event import AssistantStreamEvent from .....types.beta.threads.runs.run_step_include import RunStepInclude @@ -92,7 +93,7 @@ def create( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -148,9 +149,11 @@ def create( `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the @@ -233,7 +236,7 @@ def create( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -292,9 +295,11 @@ def create( `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the @@ -373,7 +378,7 @@ def create( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -432,9 +437,11 @@ def create( `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the @@ -512,7 +519,7 @@ def create( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -609,7 +616,7 @@ def update( run_id: str, *, thread_id: str, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -622,9 +629,11 @@ def update( Args: metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. extra_headers: Send extra headers @@ -1457,7 +1466,7 @@ async def create( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -1513,9 +1522,11 @@ async def create( `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the @@ -1598,7 +1609,7 @@ async def create( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -1657,9 +1668,11 @@ async def create( `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the @@ -1738,7 +1751,7 @@ async def create( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -1797,9 +1810,11 @@ async def create( `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the @@ -1877,7 +1892,7 @@ async def create( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -1974,7 +1989,7 @@ async def update( run_id: str, *, thread_id: str, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -1987,9 +2002,11 @@ async def update( Args: metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. extra_headers: Send extra headers diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 186b6f63e2..0ec59aca55 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -53,6 +53,7 @@ from ....types.beta.thread import Thread from ....types.beta.threads.run import Run from ....types.beta.thread_deleted import ThreadDeleted +from ....types.shared_params.metadata import Metadata from ....types.beta.assistant_stream_event import AssistantStreamEvent from ....types.beta.assistant_tool_choice_option_param import AssistantToolChoiceOptionParam from ....types.beta.assistant_response_format_option_param import AssistantResponseFormatOptionParam @@ -92,7 +93,7 @@ def create( self, *, messages: Iterable[thread_create_params.Message] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, tool_resources: Optional[thread_create_params.ToolResources] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -109,9 +110,11 @@ def create( start the thread with. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. tool_resources: A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the @@ -181,7 +184,7 @@ def update( self, thread_id: str, *, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, tool_resources: Optional[thread_update_params.ToolResources] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -195,9 +198,11 @@ def update( Args: metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. tool_resources: A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the @@ -272,7 +277,7 @@ def create_and_run( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -315,9 +320,11 @@ def create_and_run( `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the @@ -357,7 +364,8 @@ def create_and_run( make the output more random, while lower values like 0.2 will make it more focused and deterministic. - thread: If no thread is provided, an empty thread will be created. + thread: Options to create a new thread. If no thread is provided when running a request, + an empty thread will be created. tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value @@ -403,7 +411,7 @@ def create_and_run( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -449,9 +457,11 @@ def create_and_run( `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the @@ -487,7 +497,8 @@ def create_and_run( make the output more random, while lower values like 0.2 will make it more focused and deterministic. - thread: If no thread is provided, an empty thread will be created. + thread: Options to create a new thread. If no thread is provided when running a request, + an empty thread will be created. tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value @@ -533,7 +544,7 @@ def create_and_run( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -579,9 +590,11 @@ def create_and_run( `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the @@ -617,7 +630,8 @@ def create_and_run( make the output more random, while lower values like 0.2 will make it more focused and deterministic. - thread: If no thread is provided, an empty thread will be created. + thread: Options to create a new thread. If no thread is provided when running a request, + an empty thread will be created. tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value @@ -662,7 +676,7 @@ def create_and_run( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -926,7 +940,7 @@ async def create( self, *, messages: Iterable[thread_create_params.Message] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, tool_resources: Optional[thread_create_params.ToolResources] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -943,9 +957,11 @@ async def create( start the thread with. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. tool_resources: A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the @@ -1015,7 +1031,7 @@ async def update( self, thread_id: str, *, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, tool_resources: Optional[thread_update_params.ToolResources] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -1029,9 +1045,11 @@ async def update( Args: metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. tool_resources: A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the @@ -1106,7 +1124,7 @@ async def create_and_run( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -1149,9 +1167,11 @@ async def create_and_run( `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the @@ -1191,7 +1211,8 @@ async def create_and_run( make the output more random, while lower values like 0.2 will make it more focused and deterministic. - thread: If no thread is provided, an empty thread will be created. + thread: Options to create a new thread. If no thread is provided when running a request, + an empty thread will be created. tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value @@ -1237,7 +1258,7 @@ async def create_and_run( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -1283,9 +1304,11 @@ async def create_and_run( `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the @@ -1321,7 +1344,8 @@ async def create_and_run( make the output more random, while lower values like 0.2 will make it more focused and deterministic. - thread: If no thread is provided, an empty thread will be created. + thread: Options to create a new thread. If no thread is provided when running a request, + an empty thread will be created. tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value @@ -1367,7 +1391,7 @@ async def create_and_run( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -1413,9 +1437,11 @@ async def create_and_run( `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the @@ -1451,7 +1477,8 @@ async def create_and_run( make the output more random, while lower values like 0.2 will make it more focused and deterministic. - thread: If no thread is provided, an empty thread will be created. + thread: Options to create a new thread. If no thread is provided when running a request, + an empty thread will be created. tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value @@ -1496,7 +1523,7 @@ async def create_and_run( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, diff --git a/src/openai/resources/beta/vector_stores/vector_stores.py b/src/openai/resources/beta/vector_stores/vector_stores.py index 6b44c602f1..1da52fb3c7 100644 --- a/src/openai/resources/beta/vector_stores/vector_stores.py +++ b/src/openai/resources/beta/vector_stores/vector_stores.py @@ -41,6 +41,7 @@ ) from ...._base_client import AsyncPaginator, make_request_options from ....types.beta.vector_store import VectorStore +from ....types.shared_params.metadata import Metadata from ....types.beta.vector_store_deleted import VectorStoreDeleted from ....types.beta.file_chunking_strategy_param import FileChunkingStrategyParam @@ -81,7 +82,7 @@ def create( chunking_strategy: FileChunkingStrategyParam | NotGiven = NOT_GIVEN, expires_after: vector_store_create_params.ExpiresAfter | NotGiven = NOT_GIVEN, file_ids: List[str] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, name: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -104,9 +105,11 @@ def create( files. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. name: The name of the vector store. @@ -176,7 +179,7 @@ def update( vector_store_id: str, *, expires_after: Optional[vector_store_update_params.ExpiresAfter] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -192,9 +195,11 @@ def update( expires_after: The expiration policy for a vector store. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. name: The name of the vector store. @@ -359,7 +364,7 @@ async def create( chunking_strategy: FileChunkingStrategyParam | NotGiven = NOT_GIVEN, expires_after: vector_store_create_params.ExpiresAfter | NotGiven = NOT_GIVEN, file_ids: List[str] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, name: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -382,9 +387,11 @@ async def create( files. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. name: The name of the vector store. @@ -454,7 +461,7 @@ async def update( vector_store_id: str, *, expires_after: Optional[vector_store_update_params.ExpiresAfter] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -470,9 +477,11 @@ async def update( expires_after: The expiration policy for a vector store. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format. Keys - can be a maximum of 64 characters long and values can be a maximum of 512 - characters long. + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. name: The name of the vector store. diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index a9685c507a..34f6b50301 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -28,6 +28,7 @@ from ..._base_client import make_request_options from ...types.chat_model import ChatModel from ...types.chat.chat_completion import ChatCompletion +from ...types.shared_params.metadata import Metadata from ...types.chat.chat_completion_chunk import ChatCompletionChunk from ...types.chat.chat_completion_modality import ChatCompletionModality from ...types.chat.chat_completion_tool_param import ChatCompletionToolParam @@ -75,7 +76,7 @@ def create( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, @@ -179,8 +180,12 @@ def create( compatible with [o1 series models](https://platform.openai.com/docs/guides/reasoning). - metadata: Developer-defined tags and values used for filtering completions in the - [dashboard](https://platform.openai.com/chat-completions). + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. modalities: Output types that you would like the model to generate for this request. Most models are capable of generating text, which is the default: @@ -246,9 +251,9 @@ def create( utilize scale tier credits until they are exhausted. - If set to 'auto', and the Project is not Scale tier enabled, the request will be processed using the default service tier with a lower uptime SLA and no - latency guarentee. + latency guarantee. - If set to 'default', the request will be processed using the default service - tier with a lower uptime SLA and no latency guarentee. + tier with a lower uptime SLA and no latency guarantee. - When not set, the default behavior is 'auto'. stop: Up to 4 sequences where the API will stop generating further tokens. @@ -324,7 +329,7 @@ def create( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, @@ -434,8 +439,12 @@ def create( compatible with [o1 series models](https://platform.openai.com/docs/guides/reasoning). - metadata: Developer-defined tags and values used for filtering completions in the - [dashboard](https://platform.openai.com/chat-completions). + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. modalities: Output types that you would like the model to generate for this request. Most models are capable of generating text, which is the default: @@ -501,9 +510,9 @@ def create( utilize scale tier credits until they are exhausted. - If set to 'auto', and the Project is not Scale tier enabled, the request will be processed using the default service tier with a lower uptime SLA and no - latency guarentee. + latency guarantee. - If set to 'default', the request will be processed using the default service - tier with a lower uptime SLA and no latency guarentee. + tier with a lower uptime SLA and no latency guarantee. - When not set, the default behavior is 'auto'. stop: Up to 4 sequences where the API will stop generating further tokens. @@ -572,7 +581,7 @@ def create( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, @@ -682,8 +691,12 @@ def create( compatible with [o1 series models](https://platform.openai.com/docs/guides/reasoning). - metadata: Developer-defined tags and values used for filtering completions in the - [dashboard](https://platform.openai.com/chat-completions). + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. modalities: Output types that you would like the model to generate for this request. Most models are capable of generating text, which is the default: @@ -749,9 +762,9 @@ def create( utilize scale tier credits until they are exhausted. - If set to 'auto', and the Project is not Scale tier enabled, the request will be processed using the default service tier with a lower uptime SLA and no - latency guarentee. + latency guarantee. - If set to 'default', the request will be processed using the default service - tier with a lower uptime SLA and no latency guarentee. + tier with a lower uptime SLA and no latency guarantee. - When not set, the default behavior is 'auto'. stop: Up to 4 sequences where the API will stop generating further tokens. @@ -819,7 +832,7 @@ def create( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, @@ -927,7 +940,7 @@ async def create( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, @@ -1031,8 +1044,12 @@ async def create( compatible with [o1 series models](https://platform.openai.com/docs/guides/reasoning). - metadata: Developer-defined tags and values used for filtering completions in the - [dashboard](https://platform.openai.com/chat-completions). + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. modalities: Output types that you would like the model to generate for this request. Most models are capable of generating text, which is the default: @@ -1098,9 +1115,9 @@ async def create( utilize scale tier credits until they are exhausted. - If set to 'auto', and the Project is not Scale tier enabled, the request will be processed using the default service tier with a lower uptime SLA and no - latency guarentee. + latency guarantee. - If set to 'default', the request will be processed using the default service - tier with a lower uptime SLA and no latency guarentee. + tier with a lower uptime SLA and no latency guarantee. - When not set, the default behavior is 'auto'. stop: Up to 4 sequences where the API will stop generating further tokens. @@ -1176,7 +1193,7 @@ async def create( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, @@ -1286,8 +1303,12 @@ async def create( compatible with [o1 series models](https://platform.openai.com/docs/guides/reasoning). - metadata: Developer-defined tags and values used for filtering completions in the - [dashboard](https://platform.openai.com/chat-completions). + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. modalities: Output types that you would like the model to generate for this request. Most models are capable of generating text, which is the default: @@ -1353,9 +1374,9 @@ async def create( utilize scale tier credits until they are exhausted. - If set to 'auto', and the Project is not Scale tier enabled, the request will be processed using the default service tier with a lower uptime SLA and no - latency guarentee. + latency guarantee. - If set to 'default', the request will be processed using the default service - tier with a lower uptime SLA and no latency guarentee. + tier with a lower uptime SLA and no latency guarantee. - When not set, the default behavior is 'auto'. stop: Up to 4 sequences where the API will stop generating further tokens. @@ -1424,7 +1445,7 @@ async def create( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, @@ -1534,8 +1555,12 @@ async def create( compatible with [o1 series models](https://platform.openai.com/docs/guides/reasoning). - metadata: Developer-defined tags and values used for filtering completions in the - [dashboard](https://platform.openai.com/chat-completions). + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. modalities: Output types that you would like the model to generate for this request. Most models are capable of generating text, which is the default: @@ -1601,9 +1626,9 @@ async def create( utilize scale tier credits until they are exhausted. - If set to 'auto', and the Project is not Scale tier enabled, the request will be processed using the default service tier with a lower uptime SLA and no - latency guarentee. + latency guarantee. - If set to 'default', the request will be processed using the default service - tier with a lower uptime SLA and no latency guarentee. + tier with a lower uptime SLA and no latency guarantee. - When not set, the default behavior is 'auto'. stop: Up to 4 sequences where the API will stop generating further tokens. @@ -1671,7 +1696,7 @@ async def create( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index 72950f2491..7abb22f239 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -6,6 +6,7 @@ from .image import Image as Image from .model import Model as Model from .shared import ( + Metadata as Metadata, ErrorObject as ErrorObject, FunctionDefinition as FunctionDefinition, FunctionParameters as FunctionParameters, diff --git a/src/openai/types/audio/transcription_create_params.py b/src/openai/types/audio/transcription_create_params.py index 88805affbd..f1779c35e6 100644 --- a/src/openai/types/audio/transcription_create_params.py +++ b/src/openai/types/audio/transcription_create_params.py @@ -30,8 +30,8 @@ class TranscriptionCreateParams(TypedDict, total=False): """The language of the input audio. Supplying the input language in - [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format will - improve accuracy and latency. + [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) + format will improve accuracy and latency. """ prompt: str diff --git a/src/openai/types/batch.py b/src/openai/types/batch.py index ac3d7ea119..35de90ac85 100644 --- a/src/openai/types/batch.py +++ b/src/openai/types/batch.py @@ -1,11 +1,11 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -import builtins from typing import List, Optional from typing_extensions import Literal from .._models import BaseModel from .batch_error import BatchError +from .shared.metadata import Metadata from .batch_request_counts import BatchRequestCounts __all__ = ["Batch", "Errors"] @@ -70,12 +70,14 @@ class Batch(BaseModel): in_progress_at: Optional[int] = None """The Unix timestamp (in seconds) for when the batch started processing.""" - metadata: Optional[builtins.object] = None + metadata: Optional[Metadata] = None """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a - structured format. Keys can be a maximum of 64 characters long and values can be - a maximum of 512 characters long. + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ output_file_id: Optional[str] = None diff --git a/src/openai/types/batch_create_params.py b/src/openai/types/batch_create_params.py index b30c4d4658..e5be1d2bac 100644 --- a/src/openai/types/batch_create_params.py +++ b/src/openai/types/batch_create_params.py @@ -2,9 +2,11 @@ from __future__ import annotations -from typing import Dict, Optional +from typing import Optional from typing_extensions import Literal, Required, TypedDict +from .shared_params.metadata import Metadata + __all__ = ["BatchCreateParams"] @@ -35,5 +37,12 @@ class BatchCreateParams(TypedDict, total=False): requests, and can be up to 200 MB in size. """ - metadata: Optional[Dict[str, str]] - """Optional custom metadata for the batch.""" + metadata: Optional[Metadata] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + """ diff --git a/src/openai/types/beta/assistant.py b/src/openai/types/beta/assistant.py index 3c8b8e403b..58421e0f66 100644 --- a/src/openai/types/beta/assistant.py +++ b/src/openai/types/beta/assistant.py @@ -5,6 +5,7 @@ from ..._models import BaseModel from .assistant_tool import AssistantTool +from ..shared.metadata import Metadata from .assistant_response_format_option import AssistantResponseFormatOption __all__ = ["Assistant", "ToolResources", "ToolResourcesCodeInterpreter", "ToolResourcesFileSearch"] @@ -51,12 +52,14 @@ class Assistant(BaseModel): The maximum length is 256,000 characters. """ - metadata: Optional[object] = None + metadata: Optional[Metadata] = None """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a - structured format. Keys can be a maximum of 64 characters long and values can be - a maximum of 512 characters long. + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ model: str diff --git a/src/openai/types/beta/assistant_create_params.py b/src/openai/types/beta/assistant_create_params.py index 568b223ce7..e205856395 100644 --- a/src/openai/types/beta/assistant_create_params.py +++ b/src/openai/types/beta/assistant_create_params.py @@ -7,6 +7,7 @@ from ..chat_model import ChatModel from .assistant_tool_param import AssistantToolParam +from ..shared_params.metadata import Metadata from .file_chunking_strategy_param import FileChunkingStrategyParam from .assistant_response_format_option_param import AssistantResponseFormatOptionParam @@ -39,12 +40,14 @@ class AssistantCreateParams(TypedDict, total=False): The maximum length is 256,000 characters. """ - metadata: Optional[object] + metadata: Optional[Metadata] """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a - structured format. Keys can be a maximum of 64 characters long and values can be - a maximum of 512 characters long. + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ name: Optional[str] @@ -130,12 +133,14 @@ class ToolResourcesFileSearchVectorStore(TypedDict, total=False): store. """ - metadata: object - """Set of 16 key-value pairs that can be attached to a vector store. + metadata: Optional[Metadata] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. - This can be useful for storing additional information about the vector store in - a structured format. Keys can be a maximum of 64 characters long and values can - be a maximum of 512 characters long. + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ diff --git a/src/openai/types/beta/assistant_update_params.py b/src/openai/types/beta/assistant_update_params.py index 9a66e41ab3..35065ef61b 100644 --- a/src/openai/types/beta/assistant_update_params.py +++ b/src/openai/types/beta/assistant_update_params.py @@ -6,6 +6,7 @@ from typing_extensions import TypedDict from .assistant_tool_param import AssistantToolParam +from ..shared_params.metadata import Metadata from .assistant_response_format_option_param import AssistantResponseFormatOptionParam __all__ = ["AssistantUpdateParams", "ToolResources", "ToolResourcesCodeInterpreter", "ToolResourcesFileSearch"] @@ -21,12 +22,14 @@ class AssistantUpdateParams(TypedDict, total=False): The maximum length is 256,000 characters. """ - metadata: Optional[object] + metadata: Optional[Metadata] """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a - structured format. Keys can be a maximum of 64 characters long and values can be - a maximum of 512 characters long. + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ model: str diff --git a/src/openai/types/beta/realtime/conversation_item_create_event.py b/src/openai/types/beta/realtime/conversation_item_create_event.py index c4f72b9aff..f19d552a92 100644 --- a/src/openai/types/beta/realtime/conversation_item_create_event.py +++ b/src/openai/types/beta/realtime/conversation_item_create_event.py @@ -20,10 +20,10 @@ class ConversationItemCreateEvent(BaseModel): """Optional client-generated ID used to identify this event.""" previous_item_id: Optional[str] = None - """ - The ID of the preceding item after which the new item will be inserted. If not - set, the new item will be appended to the end of the conversation. If set to - `root`, the new item will be added to the beginning of the conversation. If set - to an existing ID, it allows an item to be inserted mid-conversation. If the ID - cannot be found, an error will be returned and the item will not be added. + """The ID of the preceding item after which the new item will be inserted. + + If not set, the new item will be appended to the end of the conversation. If set + to `root`, the new item will be added to the beginning of the conversation. If + set to an existing ID, it allows an item to be inserted mid-conversation. If the + ID cannot be found, an error will be returned and the item will not be added. """ diff --git a/src/openai/types/beta/realtime/conversation_item_create_event_param.py b/src/openai/types/beta/realtime/conversation_item_create_event_param.py index 6da5a63a9d..693d0fd54d 100644 --- a/src/openai/types/beta/realtime/conversation_item_create_event_param.py +++ b/src/openai/types/beta/realtime/conversation_item_create_event_param.py @@ -20,10 +20,10 @@ class ConversationItemCreateEventParam(TypedDict, total=False): """Optional client-generated ID used to identify this event.""" previous_item_id: str - """ - The ID of the preceding item after which the new item will be inserted. If not - set, the new item will be appended to the end of the conversation. If set to - `root`, the new item will be added to the beginning of the conversation. If set - to an existing ID, it allows an item to be inserted mid-conversation. If the ID - cannot be found, an error will be returned and the item will not be added. + """The ID of the preceding item after which the new item will be inserted. + + If not set, the new item will be appended to the end of the conversation. If set + to `root`, the new item will be added to the beginning of the conversation. If + set to an existing ID, it allows an item to be inserted mid-conversation. If the + ID cannot be found, an error will be returned and the item will not be added. """ diff --git a/src/openai/types/beta/realtime/realtime_response.py b/src/openai/types/beta/realtime/realtime_response.py index 3e1b1406c0..4c3c83d666 100644 --- a/src/openai/types/beta/realtime/realtime_response.py +++ b/src/openai/types/beta/realtime/realtime_response.py @@ -1,9 +1,10 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing import List, Optional +from typing import List, Union, Optional from typing_extensions import Literal from ...._models import BaseModel +from ...shared.metadata import Metadata from .conversation_item import ConversationItem from .realtime_response_usage import RealtimeResponseUsage from .realtime_response_status import RealtimeResponseStatus @@ -15,8 +16,40 @@ class RealtimeResponse(BaseModel): id: Optional[str] = None """The unique ID of the response.""" - metadata: Optional[object] = None - """Developer-provided string key-value pairs associated with this response.""" + conversation_id: Optional[str] = None + """ + Which conversation the response is added to, determined by the `conversation` + field in the `response.create` event. If `auto`, the response will be added to + the default conversation and the value of `conversation_id` will be an id like + `conv_1234`. If `none`, the response will not be added to any conversation and + the value of `conversation_id` will be `null`. If responses are being triggered + by server VAD, the response will be added to the default conversation, thus the + `conversation_id` will be an id like `conv_1234`. + """ + + max_output_tokens: Union[int, Literal["inf"], None] = None + """ + Maximum number of output tokens for a single assistant response, inclusive of + tool calls, that was used in this response. + """ + + metadata: Optional[Metadata] = None + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + """ + + modalities: Optional[List[Literal["text", "audio"]]] = None + """The set of modalities the model used to respond. + + If there are multiple modalities, the model will pick one, for example if + `modalities` is `["text", "audio"]`, the model could be responding in either + text or audio. + """ object: Optional[Literal["realtime.response"]] = None """The object type, must be `realtime.response`.""" @@ -24,6 +57,9 @@ class RealtimeResponse(BaseModel): output: Optional[List[ConversationItem]] = None """The list of output items generated by the response.""" + output_audio_format: Optional[Literal["pcm16", "g711_ulaw", "g711_alaw"]] = None + """The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.""" + status: Optional[Literal["completed", "cancelled", "failed", "incomplete"]] = None """ The final status of the response (`completed`, `cancelled`, `failed`, or @@ -33,6 +69,9 @@ class RealtimeResponse(BaseModel): status_details: Optional[RealtimeResponseStatus] = None """Additional details about the status.""" + temperature: Optional[float] = None + """Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.""" + usage: Optional[RealtimeResponseUsage] = None """Usage statistics for the Response, this will correspond to billing. @@ -40,3 +79,9 @@ class RealtimeResponse(BaseModel): to the Conversation, thus output from previous turns (text and audio tokens) will become the input for later turns. """ + + voice: Optional[Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"]] = None + """ + The voice the model used to respond. Current voice options are `alloy`, `ash`, + `ballad`, `coral`, `echo` `sage`, `shimmer` and `verse`. + """ diff --git a/src/openai/types/beta/realtime/response_create_event.py b/src/openai/types/beta/realtime/response_create_event.py index e4e5e7c68f..0801654bd8 100644 --- a/src/openai/types/beta/realtime/response_create_event.py +++ b/src/openai/types/beta/realtime/response_create_event.py @@ -4,6 +4,7 @@ from typing_extensions import Literal from ...._models import BaseModel +from ...shared.metadata import Metadata from .conversation_item import ConversationItem __all__ = ["ResponseCreateEvent", "Response", "ResponseTool"] @@ -66,12 +67,14 @@ class Response(BaseModel): `inf` for the maximum available tokens for a given model. Defaults to `inf`. """ - metadata: Optional[object] = None + metadata: Optional[Metadata] = None """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a - structured format. Keys can be a maximum of 64 characters long and values can be - a maximum of 512 characters long. + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ modalities: Optional[List[Literal["text", "audio"]]] = None diff --git a/src/openai/types/beta/realtime/response_create_event_param.py b/src/openai/types/beta/realtime/response_create_event_param.py index 7a4b5f086a..a87ef955e8 100644 --- a/src/openai/types/beta/realtime/response_create_event_param.py +++ b/src/openai/types/beta/realtime/response_create_event_param.py @@ -6,6 +6,7 @@ from typing_extensions import Literal, Required, TypedDict from .conversation_item_param import ConversationItemParam +from ...shared_params.metadata import Metadata __all__ = ["ResponseCreateEventParam", "Response", "ResponseTool"] @@ -67,12 +68,14 @@ class Response(TypedDict, total=False): `inf` for the maximum available tokens for a given model. Defaults to `inf`. """ - metadata: Optional[object] + metadata: Optional[Metadata] """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a - structured format. Keys can be a maximum of 64 characters long and values can be - a maximum of 512 characters long. + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ modalities: List[Literal["text", "audio"]] diff --git a/src/openai/types/beta/realtime/session_create_params.py b/src/openai/types/beta/realtime/session_create_params.py index 3708efeecd..1502d83d39 100644 --- a/src/openai/types/beta/realtime/session_create_params.py +++ b/src/openai/types/beta/realtime/session_create_params.py @@ -22,8 +22,11 @@ class SessionCreateParams(TypedDict, total=False): Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs - asynchronously through Whisper and should be treated as rough guidance rather - than the representation understood by the model. + asynchronously through + [OpenAI Whisper transcription](https://platform.openai.com/docs/api-reference/audio/createTranscription) + and should be treated as rough guidance rather than the representation + understood by the model. The client can optionally set the language and prompt + for transcription, these fields will be passed to the Whisper API. """ instructions: str @@ -101,12 +104,28 @@ class SessionCreateParams(TypedDict, total=False): class InputAudioTranscription(TypedDict, total=False): + language: str + """The language of the input audio. + + Supplying the input language in + [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) + format will improve accuracy and latency. + """ + model: str """ The model to use for transcription, `whisper-1` is the only currently supported model. """ + prompt: str + """An optional text to guide the model's style or continue a previous audio + segment. + + The [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) + should match the audio language. + """ + class Tool(TypedDict, total=False): description: str diff --git a/src/openai/types/beta/realtime/session_create_response.py b/src/openai/types/beta/realtime/session_create_response.py index 31f591b261..c26e62bef1 100644 --- a/src/openai/types/beta/realtime/session_create_response.py +++ b/src/openai/types/beta/realtime/session_create_response.py @@ -9,13 +9,13 @@ class ClientSecret(BaseModel): - expires_at: Optional[int] = None + expires_at: int """Timestamp for when the token expires. Currently, all tokens expire after one minute. """ - value: Optional[str] = None + value: str """ Ephemeral key usable in client environments to authenticate connections to the Realtime API. Use this in client-side environments rather than a standard API @@ -74,7 +74,7 @@ class TurnDetection(BaseModel): class SessionCreateResponse(BaseModel): - client_secret: Optional[ClientSecret] = None + client_secret: ClientSecret """Ephemeral key returned by the API.""" input_audio_format: Optional[str] = None diff --git a/src/openai/types/beta/realtime/session_update_event.py b/src/openai/types/beta/realtime/session_update_event.py index 322e588a4e..62fb0a3998 100644 --- a/src/openai/types/beta/realtime/session_update_event.py +++ b/src/openai/types/beta/realtime/session_update_event.py @@ -9,12 +9,28 @@ class SessionInputAudioTranscription(BaseModel): + language: Optional[str] = None + """The language of the input audio. + + Supplying the input language in + [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) + format will improve accuracy and latency. + """ + model: Optional[str] = None """ The model to use for transcription, `whisper-1` is the only currently supported model. """ + prompt: Optional[str] = None + """An optional text to guide the model's style or continue a previous audio + segment. + + The [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) + should match the audio language. + """ + class SessionTool(BaseModel): description: Optional[str] = None @@ -78,8 +94,11 @@ class Session(BaseModel): Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs - asynchronously through Whisper and should be treated as rough guidance rather - than the representation understood by the model. + asynchronously through + [OpenAI Whisper transcription](https://platform.openai.com/docs/api-reference/audio/createTranscription) + and should be treated as rough guidance rather than the representation + understood by the model. The client can optionally set the language and prompt + for transcription, these fields will be passed to the Whisper API. """ instructions: Optional[str] = None diff --git a/src/openai/types/beta/realtime/session_update_event_param.py b/src/openai/types/beta/realtime/session_update_event_param.py index c01d9b6887..133cdd91a1 100644 --- a/src/openai/types/beta/realtime/session_update_event_param.py +++ b/src/openai/types/beta/realtime/session_update_event_param.py @@ -15,12 +15,28 @@ class SessionInputAudioTranscription(TypedDict, total=False): + language: str + """The language of the input audio. + + Supplying the input language in + [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) + format will improve accuracy and latency. + """ + model: str """ The model to use for transcription, `whisper-1` is the only currently supported model. """ + prompt: str + """An optional text to guide the model's style or continue a previous audio + segment. + + The [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) + should match the audio language. + """ + class SessionTool(TypedDict, total=False): description: str @@ -84,8 +100,11 @@ class Session(TypedDict, total=False): Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs - asynchronously through Whisper and should be treated as rough guidance rather - than the representation understood by the model. + asynchronously through + [OpenAI Whisper transcription](https://platform.openai.com/docs/api-reference/audio/createTranscription) + and should be treated as rough guidance rather than the representation + understood by the model. The client can optionally set the language and prompt + for transcription, these fields will be passed to the Whisper API. """ instructions: str diff --git a/src/openai/types/beta/thread.py b/src/openai/types/beta/thread.py index 37d50ccb93..789f66e48b 100644 --- a/src/openai/types/beta/thread.py +++ b/src/openai/types/beta/thread.py @@ -4,6 +4,7 @@ from typing_extensions import Literal from ..._models import BaseModel +from ..shared.metadata import Metadata __all__ = ["Thread", "ToolResources", "ToolResourcesCodeInterpreter", "ToolResourcesFileSearch"] @@ -40,12 +41,14 @@ class Thread(BaseModel): created_at: int """The Unix timestamp (in seconds) for when the thread was created.""" - metadata: Optional[object] = None + metadata: Optional[Metadata] = None """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a - structured format. Keys can be a maximum of 64 characters long and values can be - a maximum of 512 characters long. + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ object: Literal["thread"] diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index 8310ba12f4..08f044c1be 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -8,6 +8,7 @@ from ..chat_model import ChatModel from .function_tool_param import FunctionToolParam from .file_search_tool_param import FileSearchToolParam +from ..shared_params.metadata import Metadata from .code_interpreter_tool_param import CodeInterpreterToolParam from .file_chunking_strategy_param import FileChunkingStrategyParam from .assistant_tool_choice_option_param import AssistantToolChoiceOptionParam @@ -67,12 +68,14 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): `incomplete_details` for more info. """ - metadata: Optional[object] + metadata: Optional[Metadata] """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a - structured format. Keys can be a maximum of 64 characters long and values can be - a maximum of 512 characters long. + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ model: Union[str, ChatModel, None] @@ -122,7 +125,11 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): """ thread: Thread - """If no thread is provided, an empty thread will be created.""" + """Options to create a new thread. + + If no thread is provided when running a request, an empty thread will be + created. + """ tool_choice: Optional[AssistantToolChoiceOptionParam] """ @@ -197,12 +204,14 @@ class ThreadMessage(TypedDict, total=False): attachments: Optional[Iterable[ThreadMessageAttachment]] """A list of files attached to the message, and the tools they should be added to.""" - metadata: Optional[object] + metadata: Optional[Metadata] """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a - structured format. Keys can be a maximum of 64 characters long and values can be - a maximum of 512 characters long. + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ @@ -230,12 +239,14 @@ class ThreadToolResourcesFileSearchVectorStore(TypedDict, total=False): store. """ - metadata: object - """Set of 16 key-value pairs that can be attached to a vector store. + metadata: Optional[Metadata] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. - This can be useful for storing additional information about the vector store in - a structured format. Keys can be a maximum of 64 characters long and values can - be a maximum of 512 characters long. + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ @@ -270,12 +281,14 @@ class Thread(TypedDict, total=False): start the thread with. """ - metadata: Optional[object] + metadata: Optional[Metadata] """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a - structured format. Keys can be a maximum of 64 characters long and values can be - a maximum of 512 characters long. + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ tool_resources: Optional[ThreadToolResources] diff --git a/src/openai/types/beta/thread_create_params.py b/src/openai/types/beta/thread_create_params.py index 3ac6c7d69b..127202753c 100644 --- a/src/openai/types/beta/thread_create_params.py +++ b/src/openai/types/beta/thread_create_params.py @@ -5,6 +5,7 @@ from typing import List, Union, Iterable, Optional from typing_extensions import Literal, Required, TypeAlias, TypedDict +from ..shared_params.metadata import Metadata from .code_interpreter_tool_param import CodeInterpreterToolParam from .file_chunking_strategy_param import FileChunkingStrategyParam from .threads.message_content_part_param import MessageContentPartParam @@ -29,12 +30,14 @@ class ThreadCreateParams(TypedDict, total=False): start the thread with. """ - metadata: Optional[object] + metadata: Optional[Metadata] """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a - structured format. Keys can be a maximum of 64 characters long and values can be - a maximum of 512 characters long. + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ tool_resources: Optional[ToolResources] @@ -78,12 +81,14 @@ class Message(TypedDict, total=False): attachments: Optional[Iterable[MessageAttachment]] """A list of files attached to the message, and the tools they should be added to.""" - metadata: Optional[object] + metadata: Optional[Metadata] """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a - structured format. Keys can be a maximum of 64 characters long and values can be - a maximum of 512 characters long. + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ @@ -111,12 +116,14 @@ class ToolResourcesFileSearchVectorStore(TypedDict, total=False): store. """ - metadata: object - """Set of 16 key-value pairs that can be attached to a vector store. + metadata: Optional[Metadata] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. - This can be useful for storing additional information about the vector store in - a structured format. Keys can be a maximum of 64 characters long and values can - be a maximum of 512 characters long. + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ diff --git a/src/openai/types/beta/thread_update_params.py b/src/openai/types/beta/thread_update_params.py index 78c5ec4f2e..b47ea8f3b0 100644 --- a/src/openai/types/beta/thread_update_params.py +++ b/src/openai/types/beta/thread_update_params.py @@ -5,16 +5,20 @@ from typing import List, Optional from typing_extensions import TypedDict +from ..shared_params.metadata import Metadata + __all__ = ["ThreadUpdateParams", "ToolResources", "ToolResourcesCodeInterpreter", "ToolResourcesFileSearch"] class ThreadUpdateParams(TypedDict, total=False): - metadata: Optional[object] + metadata: Optional[Metadata] """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a - structured format. Keys can be a maximum of 64 characters long and values can be - a maximum of 512 characters long. + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ tool_resources: Optional[ToolResources] diff --git a/src/openai/types/beta/threads/message.py b/src/openai/types/beta/threads/message.py index 63c5c4800a..4a05a128eb 100644 --- a/src/openai/types/beta/threads/message.py +++ b/src/openai/types/beta/threads/message.py @@ -5,6 +5,7 @@ from ...._models import BaseModel from .message_content import MessageContent +from ...shared.metadata import Metadata from ..code_interpreter_tool import CodeInterpreterTool __all__ = [ @@ -66,12 +67,14 @@ class Message(BaseModel): incomplete_details: Optional[IncompleteDetails] = None """On an incomplete message, details about why the message is incomplete.""" - metadata: Optional[object] = None + metadata: Optional[Metadata] = None """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a - structured format. Keys can be a maximum of 64 characters long and values can be - a maximum of 512 characters long. + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ object: Literal["thread.message"] diff --git a/src/openai/types/beta/threads/message_create_params.py b/src/openai/types/beta/threads/message_create_params.py index 2c4edfdf71..b52386824a 100644 --- a/src/openai/types/beta/threads/message_create_params.py +++ b/src/openai/types/beta/threads/message_create_params.py @@ -5,6 +5,7 @@ from typing import Union, Iterable, Optional from typing_extensions import Literal, Required, TypeAlias, TypedDict +from ...shared_params.metadata import Metadata from .message_content_part_param import MessageContentPartParam from ..code_interpreter_tool_param import CodeInterpreterToolParam @@ -27,12 +28,14 @@ class MessageCreateParams(TypedDict, total=False): attachments: Optional[Iterable[Attachment]] """A list of files attached to the message, and the tools they should be added to.""" - metadata: Optional[object] + metadata: Optional[Metadata] """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a - structured format. Keys can be a maximum of 64 characters long and values can be - a maximum of 512 characters long. + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ diff --git a/src/openai/types/beta/threads/message_update_params.py b/src/openai/types/beta/threads/message_update_params.py index e8f8cc910c..bb078281e6 100644 --- a/src/openai/types/beta/threads/message_update_params.py +++ b/src/openai/types/beta/threads/message_update_params.py @@ -5,16 +5,20 @@ from typing import Optional from typing_extensions import Required, TypedDict +from ...shared_params.metadata import Metadata + __all__ = ["MessageUpdateParams"] class MessageUpdateParams(TypedDict, total=False): thread_id: Required[str] - metadata: Optional[object] + metadata: Optional[Metadata] """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a - structured format. Keys can be a maximum of 64 characters long and values can be - a maximum of 512 characters long. + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ diff --git a/src/openai/types/beta/threads/run.py b/src/openai/types/beta/threads/run.py index ad32135b7d..da9418d6f9 100644 --- a/src/openai/types/beta/threads/run.py +++ b/src/openai/types/beta/threads/run.py @@ -6,6 +6,7 @@ from ...._models import BaseModel from .run_status import RunStatus from ..assistant_tool import AssistantTool +from ...shared.metadata import Metadata from ..assistant_tool_choice_option import AssistantToolChoiceOption from ..assistant_response_format_option import AssistantResponseFormatOption from .required_action_function_tool_call import RequiredActionFunctionToolCall @@ -133,12 +134,14 @@ class Run(BaseModel): of the run. """ - metadata: Optional[object] = None + metadata: Optional[Metadata] = None """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a - structured format. Keys can be a maximum of 64 characters long and values can be - a maximum of 512 characters long. + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ model: str diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index 88dc39645e..091dd3da66 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -8,6 +8,7 @@ from ...chat_model import ChatModel from ..assistant_tool_param import AssistantToolParam from .runs.run_step_include import RunStepInclude +from ...shared_params.metadata import Metadata from .message_content_part_param import MessageContentPartParam from ..code_interpreter_tool_param import CodeInterpreterToolParam from ..assistant_tool_choice_option_param import AssistantToolChoiceOptionParam @@ -80,12 +81,14 @@ class RunCreateParamsBase(TypedDict, total=False): `incomplete_details` for more info. """ - metadata: Optional[object] + metadata: Optional[Metadata] """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a - structured format. Keys can be a maximum of 64 characters long and values can be - a maximum of 512 characters long. + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ model: Union[str, ChatModel, None] @@ -199,12 +202,14 @@ class AdditionalMessage(TypedDict, total=False): attachments: Optional[Iterable[AdditionalMessageAttachment]] """A list of files attached to the message, and the tools they should be added to.""" - metadata: Optional[object] + metadata: Optional[Metadata] """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a - structured format. Keys can be a maximum of 64 characters long and values can be - a maximum of 512 characters long. + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ diff --git a/src/openai/types/beta/threads/run_update_params.py b/src/openai/types/beta/threads/run_update_params.py index cb4f053645..fbcbd3fb14 100644 --- a/src/openai/types/beta/threads/run_update_params.py +++ b/src/openai/types/beta/threads/run_update_params.py @@ -5,16 +5,20 @@ from typing import Optional from typing_extensions import Required, TypedDict +from ...shared_params.metadata import Metadata + __all__ = ["RunUpdateParams"] class RunUpdateParams(TypedDict, total=False): thread_id: Required[str] - metadata: Optional[object] + metadata: Optional[Metadata] """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a - structured format. Keys can be a maximum of 64 characters long and values can be - a maximum of 512 characters long. + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ diff --git a/src/openai/types/beta/threads/runs/run_step.py b/src/openai/types/beta/threads/runs/run_step.py index 0445ae360d..b5f380c7b1 100644 --- a/src/openai/types/beta/threads/runs/run_step.py +++ b/src/openai/types/beta/threads/runs/run_step.py @@ -5,6 +5,7 @@ from ....._utils import PropertyInfo from ....._models import BaseModel +from ....shared.metadata import Metadata from .tool_calls_step_details import ToolCallsStepDetails from .message_creation_step_details import MessageCreationStepDetails @@ -70,12 +71,14 @@ class RunStep(BaseModel): Will be `null` if there are no errors. """ - metadata: Optional[object] = None + metadata: Optional[Metadata] = None """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a - structured format. Keys can be a maximum of 64 characters long and values can be - a maximum of 512 characters long. + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ object: Literal["thread.run.step"] diff --git a/src/openai/types/beta/vector_store.py b/src/openai/types/beta/vector_store.py index 2d3ceea80c..b947dfb79d 100644 --- a/src/openai/types/beta/vector_store.py +++ b/src/openai/types/beta/vector_store.py @@ -4,6 +4,7 @@ from typing_extensions import Literal from ..._models import BaseModel +from ..shared.metadata import Metadata __all__ = ["VectorStore", "FileCounts", "ExpiresAfter"] @@ -48,12 +49,14 @@ class VectorStore(BaseModel): last_active_at: Optional[int] = None """The Unix timestamp (in seconds) for when the vector store was last active.""" - metadata: Optional[object] = None + metadata: Optional[Metadata] = None """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a - structured format. Keys can be a maximum of 64 characters long and values can be - a maximum of 512 characters long. + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ name: str diff --git a/src/openai/types/beta/vector_store_create_params.py b/src/openai/types/beta/vector_store_create_params.py index 4fc7c38927..faca6d9000 100644 --- a/src/openai/types/beta/vector_store_create_params.py +++ b/src/openai/types/beta/vector_store_create_params.py @@ -5,6 +5,7 @@ from typing import List, Optional from typing_extensions import Literal, Required, TypedDict +from ..shared_params.metadata import Metadata from .file_chunking_strategy_param import FileChunkingStrategyParam __all__ = ["VectorStoreCreateParams", "ExpiresAfter"] @@ -28,12 +29,14 @@ class VectorStoreCreateParams(TypedDict, total=False): files. """ - metadata: Optional[object] + metadata: Optional[Metadata] """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a - structured format. Keys can be a maximum of 64 characters long and values can be - a maximum of 512 characters long. + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ name: str diff --git a/src/openai/types/beta/vector_store_update_params.py b/src/openai/types/beta/vector_store_update_params.py index ff6c068efb..e91b3ba5ad 100644 --- a/src/openai/types/beta/vector_store_update_params.py +++ b/src/openai/types/beta/vector_store_update_params.py @@ -5,6 +5,8 @@ from typing import Optional from typing_extensions import Literal, Required, TypedDict +from ..shared_params.metadata import Metadata + __all__ = ["VectorStoreUpdateParams", "ExpiresAfter"] @@ -12,12 +14,14 @@ class VectorStoreUpdateParams(TypedDict, total=False): expires_after: Optional[ExpiresAfter] """The expiration policy for a vector store.""" - metadata: Optional[object] + metadata: Optional[Metadata] """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a - structured format. Keys can be a maximum of 64 characters long and values can be - a maximum of 512 characters long. + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ name: Optional[str] diff --git a/src/openai/types/chat/chat_completion_assistant_message_param.py b/src/openai/types/chat/chat_completion_assistant_message_param.py index 229fb822f4..35e3a3d784 100644 --- a/src/openai/types/chat/chat_completion_assistant_message_param.py +++ b/src/openai/types/chat/chat_completion_assistant_message_param.py @@ -38,8 +38,8 @@ class ChatCompletionAssistantMessageParam(TypedDict, total=False): """The role of the messages author, in this case `assistant`.""" audio: Optional[Audio] - """ - Data about a previous audio response from the model. + """Data about a previous audio response from the model. + [Learn more](https://platform.openai.com/docs/guides/audio). """ diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 30d930b120..ec88ea1fb0 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -6,6 +6,7 @@ from typing_extensions import Literal, Required, TypeAlias, TypedDict from ..chat_model import ChatModel +from ..shared_params.metadata import Metadata from .chat_completion_modality import ChatCompletionModality from .chat_completion_tool_param import ChatCompletionToolParam from .chat_completion_audio_param import ChatCompletionAudioParam @@ -122,10 +123,14 @@ class CompletionCreateParamsBase(TypedDict, total=False): [o1 series models](https://platform.openai.com/docs/guides/reasoning). """ - metadata: Optional[Dict[str, str]] - """ - Developer-defined tags and values used for filtering completions in the - [dashboard](https://platform.openai.com/chat-completions). + metadata: Optional[Metadata] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. """ modalities: Optional[List[ChatCompletionModality]] @@ -216,9 +221,9 @@ class CompletionCreateParamsBase(TypedDict, total=False): utilize scale tier credits until they are exhausted. - If set to 'auto', and the Project is not Scale tier enabled, the request will be processed using the default service tier with a lower uptime SLA and no - latency guarentee. + latency guarantee. - If set to 'default', the request will be processed using the default service - tier with a lower uptime SLA and no latency guarentee. + tier with a lower uptime SLA and no latency guarantee. - When not set, the default behavior is 'auto'. """ diff --git a/src/openai/types/chat_model.py b/src/openai/types/chat_model.py index e1ac464320..c191cb9734 100644 --- a/src/openai/types/chat_model.py +++ b/src/openai/types/chat_model.py @@ -5,6 +5,8 @@ __all__ = ["ChatModel"] ChatModel: TypeAlias = Literal[ + "o3-mini", + "o3-mini-2025-01-31", "o1", "o1-2024-12-17", "o1-preview", diff --git a/src/openai/types/shared/__init__.py b/src/openai/types/shared/__init__.py index c8776bca0e..74bf304904 100644 --- a/src/openai/types/shared/__init__.py +++ b/src/openai/types/shared/__init__.py @@ -1,5 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +from .metadata import Metadata as Metadata from .error_object import ErrorObject as ErrorObject from .function_definition import FunctionDefinition as FunctionDefinition from .function_parameters import FunctionParameters as FunctionParameters diff --git a/src/openai/types/shared/metadata.py b/src/openai/types/shared/metadata.py new file mode 100644 index 0000000000..0da88c679c --- /dev/null +++ b/src/openai/types/shared/metadata.py @@ -0,0 +1,8 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict +from typing_extensions import TypeAlias + +__all__ = ["Metadata"] + +Metadata: TypeAlias = Dict[str, str] diff --git a/src/openai/types/shared_params/__init__.py b/src/openai/types/shared_params/__init__.py index ab4057d59f..68a8db75fe 100644 --- a/src/openai/types/shared_params/__init__.py +++ b/src/openai/types/shared_params/__init__.py @@ -1,5 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +from .metadata import Metadata as Metadata from .function_definition import FunctionDefinition as FunctionDefinition from .function_parameters import FunctionParameters as FunctionParameters from .response_format_text import ResponseFormatText as ResponseFormatText diff --git a/src/openai/types/shared_params/metadata.py b/src/openai/types/shared_params/metadata.py new file mode 100644 index 0000000000..821650b48b --- /dev/null +++ b/src/openai/types/shared_params/metadata.py @@ -0,0 +1,10 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict +from typing_extensions import TypeAlias + +__all__ = ["Metadata"] + +Metadata: TypeAlias = Dict[str, str] diff --git a/src/openai/types/upload.py b/src/openai/types/upload.py index 1cf8ee97f8..d8108c62f9 100644 --- a/src/openai/types/upload.py +++ b/src/openai/types/upload.py @@ -39,4 +39,4 @@ class Upload(BaseModel): """The status of the Upload.""" file: Optional[FileObject] = None - """The ready File object after the Upload is completed.""" + """The `File` object represents a document that has been uploaded to OpenAI.""" diff --git a/tests/api_resources/beta/realtime/test_sessions.py b/tests/api_resources/beta/realtime/test_sessions.py index 908aa983be..5a17088ce6 100644 --- a/tests/api_resources/beta/realtime/test_sessions.py +++ b/tests/api_resources/beta/realtime/test_sessions.py @@ -26,7 +26,11 @@ def test_method_create(self, client: OpenAI) -> None: def test_method_create_with_all_params(self, client: OpenAI) -> None: session = client.beta.realtime.sessions.create( input_audio_format="pcm16", - input_audio_transcription={"model": "model"}, + input_audio_transcription={ + "language": "language", + "model": "model", + "prompt": "prompt", + }, instructions="instructions", max_response_output_tokens=0, modalities=["text"], @@ -86,7 +90,11 @@ async def test_method_create(self, async_client: AsyncOpenAI) -> None: async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: session = await async_client.beta.realtime.sessions.create( input_audio_format="pcm16", - input_audio_transcription={"model": "model"}, + input_audio_transcription={ + "language": "language", + "model": "model", + "prompt": "prompt", + }, instructions="instructions", max_response_output_tokens=0, modalities=["text"], diff --git a/tests/api_resources/beta/test_assistants.py b/tests/api_resources/beta/test_assistants.py index d9944448b7..458e3f5e90 100644 --- a/tests/api_resources/beta/test_assistants.py +++ b/tests/api_resources/beta/test_assistants.py @@ -34,7 +34,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: model="gpt-4o", description="description", instructions="instructions", - metadata={}, + metadata={"foo": "string"}, name="name", response_format="auto", temperature=1, @@ -46,7 +46,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: { "chunking_strategy": {"type": "auto"}, "file_ids": ["string"], - "metadata": {}, + "metadata": {"foo": "string"}, } ], }, @@ -131,7 +131,7 @@ def test_method_update_with_all_params(self, client: OpenAI) -> None: assistant_id="assistant_id", description="description", instructions="instructions", - metadata={}, + metadata={"foo": "string"}, model="model", name="name", response_format="auto", @@ -266,7 +266,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> model="gpt-4o", description="description", instructions="instructions", - metadata={}, + metadata={"foo": "string"}, name="name", response_format="auto", temperature=1, @@ -278,7 +278,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> { "chunking_strategy": {"type": "auto"}, "file_ids": ["string"], - "metadata": {}, + "metadata": {"foo": "string"}, } ], }, @@ -363,7 +363,7 @@ async def test_method_update_with_all_params(self, async_client: AsyncOpenAI) -> assistant_id="assistant_id", description="description", instructions="instructions", - metadata={}, + metadata={"foo": "string"}, model="model", name="name", response_format="auto", diff --git a/tests/api_resources/beta/test_threads.py b/tests/api_resources/beta/test_threads.py index 789f870d6a..ecf5b11102 100644 --- a/tests/api_resources/beta/test_threads.py +++ b/tests/api_resources/beta/test_threads.py @@ -39,10 +39,10 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "tools": [{"type": "code_interpreter"}], } ], - "metadata": {}, + "metadata": {"foo": "string"}, } ], - metadata={}, + metadata={"foo": "string"}, tool_resources={ "code_interpreter": {"file_ids": ["string"]}, "file_search": { @@ -51,7 +51,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: { "chunking_strategy": {"type": "auto"}, "file_ids": ["string"], - "metadata": {}, + "metadata": {"foo": "string"}, } ], }, @@ -127,8 +127,8 @@ def test_method_update(self, client: OpenAI) -> None: @parametrize def test_method_update_with_all_params(self, client: OpenAI) -> None: thread = client.beta.threads.update( - "string", - metadata={}, + thread_id="thread_id", + metadata={"foo": "string"}, tool_resources={ "code_interpreter": {"file_ids": ["string"]}, "file_search": {"vector_store_ids": ["string"]}, @@ -219,7 +219,7 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) instructions="string", max_completion_tokens=256, max_prompt_tokens=256, - metadata={}, + metadata={"foo": "string"}, model="gpt-4o", parallel_tool_calls=True, response_format="auto", @@ -236,10 +236,10 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) "tools": [{"type": "code_interpreter"}], } ], - "metadata": {}, + "metadata": {"foo": "string"}, } ], - "metadata": {}, + "metadata": {"foo": "string"}, "tool_resources": { "code_interpreter": {"file_ids": ["string"]}, "file_search": { @@ -248,7 +248,7 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) { "chunking_strategy": {"type": "auto"}, "file_ids": ["string"], - "metadata": {}, + "metadata": {"foo": "string"}, } ], }, @@ -308,7 +308,7 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) instructions="string", max_completion_tokens=256, max_prompt_tokens=256, - metadata={}, + metadata={"foo": "string"}, model="gpt-4o", parallel_tool_calls=True, response_format="auto", @@ -324,10 +324,10 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) "tools": [{"type": "code_interpreter"}], } ], - "metadata": {}, + "metadata": {"foo": "string"}, } ], - "metadata": {}, + "metadata": {"foo": "string"}, "tool_resources": { "code_interpreter": {"file_ids": ["string"]}, "file_search": { @@ -336,7 +336,7 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) { "chunking_strategy": {"type": "auto"}, "file_ids": ["string"], - "metadata": {}, + "metadata": {"foo": "string"}, } ], }, @@ -403,10 +403,10 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "tools": [{"type": "code_interpreter"}], } ], - "metadata": {}, + "metadata": {"foo": "string"}, } ], - metadata={}, + metadata={"foo": "string"}, tool_resources={ "code_interpreter": {"file_ids": ["string"]}, "file_search": { @@ -415,7 +415,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> { "chunking_strategy": {"type": "auto"}, "file_ids": ["string"], - "metadata": {}, + "metadata": {"foo": "string"}, } ], }, @@ -491,8 +491,8 @@ async def test_method_update(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_method_update_with_all_params(self, async_client: AsyncOpenAI) -> None: thread = await async_client.beta.threads.update( - "string", - metadata={}, + thread_id="thread_id", + metadata={"foo": "string"}, tool_resources={ "code_interpreter": {"file_ids": ["string"]}, "file_search": {"vector_store_ids": ["string"]}, @@ -583,7 +583,7 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie instructions="string", max_completion_tokens=256, max_prompt_tokens=256, - metadata={}, + metadata={"foo": "string"}, model="gpt-4o", parallel_tool_calls=True, response_format="auto", @@ -600,10 +600,10 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie "tools": [{"type": "code_interpreter"}], } ], - "metadata": {}, + "metadata": {"foo": "string"}, } ], - "metadata": {}, + "metadata": {"foo": "string"}, "tool_resources": { "code_interpreter": {"file_ids": ["string"]}, "file_search": { @@ -612,7 +612,7 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie { "chunking_strategy": {"type": "auto"}, "file_ids": ["string"], - "metadata": {}, + "metadata": {"foo": "string"}, } ], }, @@ -672,7 +672,7 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie instructions="string", max_completion_tokens=256, max_prompt_tokens=256, - metadata={}, + metadata={"foo": "string"}, model="gpt-4o", parallel_tool_calls=True, response_format="auto", @@ -688,10 +688,10 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie "tools": [{"type": "code_interpreter"}], } ], - "metadata": {}, + "metadata": {"foo": "string"}, } ], - "metadata": {}, + "metadata": {"foo": "string"}, "tool_resources": { "code_interpreter": {"file_ids": ["string"]}, "file_search": { @@ -700,7 +700,7 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie { "chunking_strategy": {"type": "auto"}, "file_ids": ["string"], - "metadata": {}, + "metadata": {"foo": "string"}, } ], }, diff --git a/tests/api_resources/beta/test_vector_stores.py b/tests/api_resources/beta/test_vector_stores.py index 99e1970c33..e13b8c7613 100644 --- a/tests/api_resources/beta/test_vector_stores.py +++ b/tests/api_resources/beta/test_vector_stores.py @@ -35,8 +35,8 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "days": 1, }, file_ids=["string"], - metadata={}, - name="string", + metadata={"foo": "string"}, + name="name", ) assert_matches_type(VectorStore, vector_store, path=["response"]) @@ -113,8 +113,8 @@ def test_method_update_with_all_params(self, client: OpenAI) -> None: "anchor": "last_active_at", "days": 1, }, - metadata={}, - name="string", + metadata={"foo": "string"}, + name="name", ) assert_matches_type(VectorStore, vector_store, path=["response"]) @@ -240,8 +240,8 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "days": 1, }, file_ids=["string"], - metadata={}, - name="string", + metadata={"foo": "string"}, + name="name", ) assert_matches_type(VectorStore, vector_store, path=["response"]) @@ -318,8 +318,8 @@ async def test_method_update_with_all_params(self, async_client: AsyncOpenAI) -> "anchor": "last_active_at", "days": 1, }, - metadata={}, - name="string", + metadata={"foo": "string"}, + name="name", ) assert_matches_type(VectorStore, vector_store, path=["response"]) diff --git a/tests/api_resources/beta/threads/test_messages.py b/tests/api_resources/beta/threads/test_messages.py index 06c37e608a..9189a2f29e 100644 --- a/tests/api_resources/beta/threads/test_messages.py +++ b/tests/api_resources/beta/threads/test_messages.py @@ -42,7 +42,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "tools": [{"type": "code_interpreter"}], } ], - metadata={}, + metadata={"foo": "string"}, ) assert_matches_type(Message, message, path=["response"]) @@ -142,9 +142,9 @@ def test_method_update(self, client: OpenAI) -> None: @parametrize def test_method_update_with_all_params(self, client: OpenAI) -> None: message = client.beta.threads.messages.update( - "string", - thread_id="string", - metadata={}, + message_id="message_id", + thread_id="thread_id", + metadata={"foo": "string"}, ) assert_matches_type(Message, message, path=["response"]) @@ -311,7 +311,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "tools": [{"type": "code_interpreter"}], } ], - metadata={}, + metadata={"foo": "string"}, ) assert_matches_type(Message, message, path=["response"]) @@ -411,9 +411,9 @@ async def test_method_update(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_method_update_with_all_params(self, async_client: AsyncOpenAI) -> None: message = await async_client.beta.threads.messages.update( - "string", - thread_id="string", - metadata={}, + message_id="message_id", + thread_id="thread_id", + metadata={"foo": "string"}, ) assert_matches_type(Message, message, path=["response"]) diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index c48cc6de43..48b39cfe5b 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -47,13 +47,13 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: "tools": [{"type": "code_interpreter"}], } ], - "metadata": {}, + "metadata": {"foo": "string"}, } ], instructions="string", max_completion_tokens=256, max_prompt_tokens=256, - metadata={}, + metadata={"foo": "string"}, model="gpt-4o", parallel_tool_calls=True, response_format="auto", @@ -130,13 +130,13 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: "tools": [{"type": "code_interpreter"}], } ], - "metadata": {}, + "metadata": {"foo": "string"}, } ], instructions="string", max_completion_tokens=256, max_prompt_tokens=256, - metadata={}, + metadata={"foo": "string"}, model="gpt-4o", parallel_tool_calls=True, response_format="auto", @@ -246,9 +246,9 @@ def test_method_update(self, client: OpenAI) -> None: @parametrize def test_method_update_with_all_params(self, client: OpenAI) -> None: run = client.beta.threads.runs.update( - "string", - thread_id="string", - metadata={}, + run_id="run_id", + thread_id="thread_id", + metadata={"foo": "string"}, ) assert_matches_type(Run, run, path=["response"]) @@ -543,13 +543,13 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn "tools": [{"type": "code_interpreter"}], } ], - "metadata": {}, + "metadata": {"foo": "string"}, } ], instructions="string", max_completion_tokens=256, max_prompt_tokens=256, - metadata={}, + metadata={"foo": "string"}, model="gpt-4o", parallel_tool_calls=True, response_format="auto", @@ -626,13 +626,13 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn "tools": [{"type": "code_interpreter"}], } ], - "metadata": {}, + "metadata": {"foo": "string"}, } ], instructions="string", max_completion_tokens=256, max_prompt_tokens=256, - metadata={}, + metadata={"foo": "string"}, model="gpt-4o", parallel_tool_calls=True, response_format="auto", @@ -742,9 +742,9 @@ async def test_method_update(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_method_update_with_all_params(self, async_client: AsyncOpenAI) -> None: run = await async_client.beta.threads.runs.update( - "string", - thread_id="string", - metadata={}, + run_id="run_id", + thread_id="thread_id", + metadata={"foo": "string"}, ) assert_matches_type(Run, run, path=["response"]) From b56b357e60b9bccdb1ad5ab56a86614cfd4d402d Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Fri, 31 Jan 2025 19:14:32 +0000 Subject: [PATCH 674/816] chore(types): fix Metadata types --- src/openai/resources/beta/chat/completions.py | 9 +++--- .../resources/beta/threads/runs/runs.py | 28 +++++++++---------- src/openai/resources/beta/threads/threads.py | 16 +++++------ 3 files changed, 27 insertions(+), 26 deletions(-) diff --git a/src/openai/resources/beta/chat/completions.py b/src/openai/resources/beta/chat/completions.py index 48cb13f7a6..8a3a20d9e0 100644 --- a/src/openai/resources/beta/chat/completions.py +++ b/src/openai/resources/beta/chat/completions.py @@ -28,6 +28,7 @@ ) from ....types.chat_model import ChatModel from ....lib.streaming.chat import ChatCompletionStreamManager, AsyncChatCompletionStreamManager +from ....types.shared_params import Metadata from ....types.chat.chat_completion import ChatCompletion from ....types.chat.chat_completion_chunk import ChatCompletionChunk from ....types.chat.parsed_chat_completion import ParsedChatCompletion @@ -76,7 +77,7 @@ def parse( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, @@ -221,7 +222,7 @@ def stream( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, @@ -351,7 +352,7 @@ async def parse( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, @@ -496,7 +497,7 @@ def stream( logprobs: Optional[bool] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 9cb202a1a2..13301ad507 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -771,7 +771,7 @@ def create_and_poll( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -840,7 +840,7 @@ def create_and_stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -871,7 +871,7 @@ def create_and_stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -902,7 +902,7 @@ def create_and_stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -1019,7 +1019,7 @@ def stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -1050,7 +1050,7 @@ def stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -1081,7 +1081,7 @@ def stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -2144,7 +2144,7 @@ async def create_and_poll( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -2213,7 +2213,7 @@ def create_and_stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -2244,7 +2244,7 @@ def create_and_stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -2275,7 +2275,7 @@ def create_and_stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -2393,7 +2393,7 @@ def stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -2424,7 +2424,7 @@ def stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -2455,7 +2455,7 @@ def stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 0ec59aca55..6ff8539501 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -734,7 +734,7 @@ def create_and_run_poll( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -790,7 +790,7 @@ def create_and_run_stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -819,7 +819,7 @@ def create_and_run_stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -848,7 +848,7 @@ def create_and_run_stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -1581,7 +1581,7 @@ async def create_and_run_poll( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -1639,7 +1639,7 @@ def create_and_run_stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -1668,7 +1668,7 @@ def create_and_run_stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, @@ -1697,7 +1697,7 @@ def create_and_run_stream( instructions: Optional[str] | NotGiven = NOT_GIVEN, max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_prompt_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[object] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, From 7a6517d81e4ae9e9e9527cd401bb76937983dfef Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 31 Jan 2025 19:18:58 +0000 Subject: [PATCH 675/816] release: 1.61.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 25 +++++++++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 28 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 73f712c242..68804e4da0 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.60.2" + ".": "1.61.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 168d98e5cd..dcd1c06333 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,30 @@ # Changelog +## 1.61.0 (2025-01-31) + +Full Changelog: [v1.60.2...v1.61.0](https://github.com/openai/openai-python/compare/v1.60.2...v1.61.0) + +### Features + +* **api:** add o3-mini ([#2067](https://github.com/openai/openai-python/issues/2067)) ([12b87a4](https://github.com/openai/openai-python/commit/12b87a4a1e6cb071a6b063d089585dec56a5d534)) + + +### Bug Fixes + +* **types:** correct metadata type + other fixes ([12b87a4](https://github.com/openai/openai-python/commit/12b87a4a1e6cb071a6b063d089585dec56a5d534)) + + +### Chores + +* **helpers:** section links ([ef8d3cc](https://github.com/openai/openai-python/commit/ef8d3cce40022d3482d341455be604e5f1afbd70)) +* **types:** fix Metadata types ([82d3156](https://github.com/openai/openai-python/commit/82d3156e74ed2f95edd10cd7ebea53d2b5562794)) +* update api.md ([#2063](https://github.com/openai/openai-python/issues/2063)) ([21964f0](https://github.com/openai/openai-python/commit/21964f00fb104011c4c357544114702052b74548)) + + +### Documentation + +* **readme:** current section links ([#2055](https://github.com/openai/openai-python/issues/2055)) ([ef8d3cc](https://github.com/openai/openai-python/commit/ef8d3cce40022d3482d341455be604e5f1afbd70)) + ## 1.60.2 (2025-01-27) Full Changelog: [v1.60.1...v1.60.2](https://github.com/openai/openai-python/compare/v1.60.1...v1.60.2) diff --git a/pyproject.toml b/pyproject.toml index 9657bdc0ce..07913fcbd2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.60.2" +version = "1.61.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index c8f825db34..e9ab8be65e 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.60.2" # x-release-please-version +__version__ = "1.61.0" # x-release-please-version From c27e8cc997212b895743941966530980cd56d9da Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 3 Feb 2025 11:54:55 +0000 Subject: [PATCH 676/816] fix(cli/chat): only send params when set (#2077) --- src/openai/cli/_api/chat/completions.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/openai/cli/_api/chat/completions.py b/src/openai/cli/_api/chat/completions.py index c299741fe0..feedb5ccab 100644 --- a/src/openai/cli/_api/chat/completions.py +++ b/src/openai/cli/_api/chat/completions.py @@ -100,13 +100,17 @@ def create(args: CLIChatCompletionCreateArgs) -> None: "messages": [ {"role": cast(Literal["user"], message.role), "content": message.content} for message in args.message ], - "n": args.n, - "temperature": args.temperature, - "top_p": args.top_p, - "stop": args.stop, # type checkers are not good at inferring union types so we have to set stream afterwards "stream": False, } + if args.temperature is not None: + params['temperature'] = args.temperature + if args.stop is not None: + params['stop'] = args.stop + if args.top_p is not None: + params['top_p'] = args.top_p + if args.n is not None: + params['n'] = args.n if args.stream: params["stream"] = args.stream # type: ignore if args.max_tokens is not None: From 5a1a412b77c4233ca3b147738f63956f09a65fb1 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 3 Feb 2025 14:43:52 +0000 Subject: [PATCH 677/816] chore(internal): change default timeout to an int (#2079) --- src/openai/_constants.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/openai/_constants.py b/src/openai/_constants.py index 3f82bed037..7029dc72b0 100644 --- a/src/openai/_constants.py +++ b/src/openai/_constants.py @@ -6,7 +6,7 @@ OVERRIDE_CAST_TO_HEADER = "____stainless_override_cast_to" # default timeout is 10 minutes -DEFAULT_TIMEOUT = httpx.Timeout(timeout=600.0, connect=5.0) +DEFAULT_TIMEOUT = httpx.Timeout(timeout=600, connect=5.0) DEFAULT_MAX_RETRIES = 2 DEFAULT_CONNECTION_LIMITS = httpx.Limits(max_connections=1000, max_keepalive_connections=100) From 6afde0dc8512a16ff2eca781fee0395cab254f8c Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 3 Feb 2025 15:27:06 +0000 Subject: [PATCH 678/816] chore(internal): bummp ruff dependency (#2080) --- pyproject.toml | 2 +- requirements-dev.lock | 2 +- scripts/utils/ruffen-docs.py | 4 ++-- src/openai/_models.py | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 07913fcbd2..dc78d95d3f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -194,7 +194,7 @@ select = [ "T201", "T203", # misuse of typing.TYPE_CHECKING - "TCH004", + "TC004", # import rules "TID251", ] diff --git a/requirements-dev.lock b/requirements-dev.lock index 38cc6e1cf2..5599057b66 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -140,7 +140,7 @@ requests==2.31.0 respx==0.22.0 rich==13.7.1 # via inline-snapshot -ruff==0.6.9 +ruff==0.9.4 setuptools==68.2.2 # via nodeenv six==1.16.0 diff --git a/scripts/utils/ruffen-docs.py b/scripts/utils/ruffen-docs.py index 37b3d94f0f..0cf2bd2fd9 100644 --- a/scripts/utils/ruffen-docs.py +++ b/scripts/utils/ruffen-docs.py @@ -47,7 +47,7 @@ def _md_match(match: Match[str]) -> str: with _collect_error(match): code = format_code_block(code) code = textwrap.indent(code, match["indent"]) - return f'{match["before"]}{code}{match["after"]}' + return f"{match['before']}{code}{match['after']}" def _pycon_match(match: Match[str]) -> str: code = "" @@ -97,7 +97,7 @@ def finish_fragment() -> None: def _md_pycon_match(match: Match[str]) -> str: code = _pycon_match(match) code = textwrap.indent(code, match["indent"]) - return f'{match["before"]}{code}{match["after"]}' + return f"{match['before']}{code}{match['after']}" src = MD_RE.sub(_md_match, src) src = MD_PYCON_RE.sub(_md_pycon_match, src) diff --git a/src/openai/_models.py b/src/openai/_models.py index 23456d9f80..c6e1305087 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -197,7 +197,7 @@ def to_json( @override def __str__(self) -> str: # mypy complains about an invalid self arg - return f'{self.__repr_name__()}({self.__repr_str__(", ")})' # type: ignore[misc] + return f"{self.__repr_name__()}({self.__repr_str__(', ')})" # type: ignore[misc] # Override the 'construct' method in a way that supports recursive parsing without validation. # Based on https://github.com/samuelcolvin/pydantic/issues/1168#issuecomment-817742836. From f344db250ac3a1f5cb1bb36b6719a2bf4e002d87 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 5 Feb 2025 11:26:48 +0000 Subject: [PATCH 679/816] fix(api/types): correct audio duration & role types (#2091) --- .stats.yml | 2 +- api.md | 1 + .../types/audio/transcription_verbose.py | 2 +- src/openai/types/audio/translation_verbose.py | 2 +- src/openai/types/beta/realtime/__init__.py | 4 ++ .../conversation_item_with_reference.py | 67 ++++++++++++++++++ .../conversation_item_with_reference_param.py | 68 +++++++++++++++++++ .../beta/realtime/response_create_event.py | 10 +-- .../realtime/response_create_event_param.py | 10 +-- .../types/chat/chat_completion_chunk.py | 2 +- src/openai/types/chat/chat_completion_role.py | 2 +- 11 files changed, 157 insertions(+), 13 deletions(-) create mode 100644 src/openai/types/beta/realtime/conversation_item_with_reference.py create mode 100644 src/openai/types/beta/realtime/conversation_item_with_reference_param.py diff --git a/.stats.yml b/.stats.yml index e49b5c56e8..df7877dfd0 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 69 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-6204952a29973265b9c0d66fc67ffaf53c6a90ae4d75cdacf9d147676f5274c9.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-fc5dbc19505b0035f9e7f88868619f4fb519b048bde011f6154f3132d4be71fb.yml diff --git a/api.md b/api.md index c1262fd2c5..efbfeaa68f 100644 --- a/api.md +++ b/api.md @@ -255,6 +255,7 @@ from openai.types.beta.realtime import ( ConversationItemInputAudioTranscriptionFailedEvent, ConversationItemTruncateEvent, ConversationItemTruncatedEvent, + ConversationItemWithReference, ErrorEvent, InputAudioBufferAppendEvent, InputAudioBufferClearEvent, diff --git a/src/openai/types/audio/transcription_verbose.py b/src/openai/types/audio/transcription_verbose.py index 3b18fa4871..2a670189e0 100644 --- a/src/openai/types/audio/transcription_verbose.py +++ b/src/openai/types/audio/transcription_verbose.py @@ -10,7 +10,7 @@ class TranscriptionVerbose(BaseModel): - duration: str + duration: float """The duration of the input audio.""" language: str diff --git a/src/openai/types/audio/translation_verbose.py b/src/openai/types/audio/translation_verbose.py index 5901ae7535..27cb02d64f 100644 --- a/src/openai/types/audio/translation_verbose.py +++ b/src/openai/types/audio/translation_verbose.py @@ -9,7 +9,7 @@ class TranslationVerbose(BaseModel): - duration: str + duration: float """The duration of the input audio.""" language: str diff --git a/src/openai/types/beta/realtime/__init__.py b/src/openai/types/beta/realtime/__init__.py index 372d4ec19d..cd0616dcfa 100644 --- a/src/openai/types/beta/realtime/__init__.py +++ b/src/openai/types/beta/realtime/__init__.py @@ -42,6 +42,7 @@ from .input_audio_buffer_commit_event import InputAudioBufferCommitEvent as InputAudioBufferCommitEvent from .response_output_item_done_event import ResponseOutputItemDoneEvent as ResponseOutputItemDoneEvent from .conversation_item_truncate_event import ConversationItemTruncateEvent as ConversationItemTruncateEvent +from .conversation_item_with_reference import ConversationItemWithReference as ConversationItemWithReference from .input_audio_buffer_cleared_event import InputAudioBufferClearedEvent as InputAudioBufferClearedEvent from .response_content_part_done_event import ResponseContentPartDoneEvent as ResponseContentPartDoneEvent from .response_output_item_added_event import ResponseOutputItemAddedEvent as ResponseOutputItemAddedEvent @@ -60,6 +61,9 @@ from .conversation_item_truncate_event_param import ( ConversationItemTruncateEventParam as ConversationItemTruncateEventParam, ) +from .conversation_item_with_reference_param import ( + ConversationItemWithReferenceParam as ConversationItemWithReferenceParam, +) from .input_audio_buffer_speech_started_event import ( InputAudioBufferSpeechStartedEvent as InputAudioBufferSpeechStartedEvent, ) diff --git a/src/openai/types/beta/realtime/conversation_item_with_reference.py b/src/openai/types/beta/realtime/conversation_item_with_reference.py new file mode 100644 index 0000000000..31806afc33 --- /dev/null +++ b/src/openai/types/beta/realtime/conversation_item_with_reference.py @@ -0,0 +1,67 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from ...._models import BaseModel +from .conversation_item_content import ConversationItemContent + +__all__ = ["ConversationItemWithReference"] + + +class ConversationItemWithReference(BaseModel): + id: Optional[str] = None + """ + For an item of type (`message` | `function_call` | `function_call_output`) this + field allows the client to assign the unique ID of the item. It is not required + because the server will generate one if not provided. + + For an item of type `item_reference`, this field is required and is a reference + to any item that has previously existed in the conversation. + """ + + arguments: Optional[str] = None + """The arguments of the function call (for `function_call` items).""" + + call_id: Optional[str] = None + """ + The ID of the function call (for `function_call` and `function_call_output` + items). If passed on a `function_call_output` item, the server will check that a + `function_call` item with the same ID exists in the conversation history. + """ + + content: Optional[List[ConversationItemContent]] = None + """The content of the message, applicable for `message` items. + + - Message items of role `system` support only `input_text` content + - Message items of role `user` support `input_text` and `input_audio` content + - Message items of role `assistant` support `text` content. + """ + + name: Optional[str] = None + """The name of the function being called (for `function_call` items).""" + + object: Optional[Literal["realtime.item"]] = None + """Identifier for the API object being returned - always `realtime.item`.""" + + output: Optional[str] = None + """The output of the function call (for `function_call_output` items).""" + + role: Optional[Literal["user", "assistant", "system"]] = None + """ + The role of the message sender (`user`, `assistant`, `system`), only applicable + for `message` items. + """ + + status: Optional[Literal["completed", "incomplete"]] = None + """The status of the item (`completed`, `incomplete`). + + These have no effect on the conversation, but are accepted for consistency with + the `conversation.item.created` event. + """ + + type: Optional[Literal["message", "function_call", "function_call_output", "item_reference"]] = None + """ + The type of the item (`message`, `function_call`, `function_call_output`, + `item_reference`). + """ diff --git a/src/openai/types/beta/realtime/conversation_item_with_reference_param.py b/src/openai/types/beta/realtime/conversation_item_with_reference_param.py new file mode 100644 index 0000000000..e266cdce32 --- /dev/null +++ b/src/openai/types/beta/realtime/conversation_item_with_reference_param.py @@ -0,0 +1,68 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Literal, TypedDict + +from .conversation_item_content_param import ConversationItemContentParam + +__all__ = ["ConversationItemWithReferenceParam"] + + +class ConversationItemWithReferenceParam(TypedDict, total=False): + id: str + """ + For an item of type (`message` | `function_call` | `function_call_output`) this + field allows the client to assign the unique ID of the item. It is not required + because the server will generate one if not provided. + + For an item of type `item_reference`, this field is required and is a reference + to any item that has previously existed in the conversation. + """ + + arguments: str + """The arguments of the function call (for `function_call` items).""" + + call_id: str + """ + The ID of the function call (for `function_call` and `function_call_output` + items). If passed on a `function_call_output` item, the server will check that a + `function_call` item with the same ID exists in the conversation history. + """ + + content: Iterable[ConversationItemContentParam] + """The content of the message, applicable for `message` items. + + - Message items of role `system` support only `input_text` content + - Message items of role `user` support `input_text` and `input_audio` content + - Message items of role `assistant` support `text` content. + """ + + name: str + """The name of the function being called (for `function_call` items).""" + + object: Literal["realtime.item"] + """Identifier for the API object being returned - always `realtime.item`.""" + + output: str + """The output of the function call (for `function_call_output` items).""" + + role: Literal["user", "assistant", "system"] + """ + The role of the message sender (`user`, `assistant`, `system`), only applicable + for `message` items. + """ + + status: Literal["completed", "incomplete"] + """The status of the item (`completed`, `incomplete`). + + These have no effect on the conversation, but are accepted for consistency with + the `conversation.item.created` event. + """ + + type: Literal["message", "function_call", "function_call_output", "item_reference"] + """ + The type of the item (`message`, `function_call`, `function_call_output`, + `item_reference`). + """ diff --git a/src/openai/types/beta/realtime/response_create_event.py b/src/openai/types/beta/realtime/response_create_event.py index 0801654bd8..d6c5fda926 100644 --- a/src/openai/types/beta/realtime/response_create_event.py +++ b/src/openai/types/beta/realtime/response_create_event.py @@ -5,7 +5,7 @@ from ...._models import BaseModel from ...shared.metadata import Metadata -from .conversation_item import ConversationItem +from .conversation_item_with_reference import ConversationItemWithReference __all__ = ["ResponseCreateEvent", "Response", "ResponseTool"] @@ -37,11 +37,13 @@ class Response(BaseModel): will not add items to default conversation. """ - input: Optional[List[ConversationItem]] = None + input: Optional[List[ConversationItemWithReference]] = None """Input items to include in the prompt for the model. - Creates a new context for this response, without including the default - conversation. Can include references to items from the default conversation. + Using this field creates a new context for this Response instead of using the + default conversation. An empty array `[]` will clear the context for this + Response. Note that this can include references to items from the default + conversation. """ instructions: Optional[str] = None diff --git a/src/openai/types/beta/realtime/response_create_event_param.py b/src/openai/types/beta/realtime/response_create_event_param.py index a87ef955e8..c02fe1b34e 100644 --- a/src/openai/types/beta/realtime/response_create_event_param.py +++ b/src/openai/types/beta/realtime/response_create_event_param.py @@ -5,8 +5,8 @@ from typing import List, Union, Iterable, Optional from typing_extensions import Literal, Required, TypedDict -from .conversation_item_param import ConversationItemParam from ...shared_params.metadata import Metadata +from .conversation_item_with_reference_param import ConversationItemWithReferenceParam __all__ = ["ResponseCreateEventParam", "Response", "ResponseTool"] @@ -38,11 +38,13 @@ class Response(TypedDict, total=False): will not add items to default conversation. """ - input: Iterable[ConversationItemParam] + input: Iterable[ConversationItemWithReferenceParam] """Input items to include in the prompt for the model. - Creates a new context for this response, without including the default - conversation. Can include references to items from the default conversation. + Using this field creates a new context for this Response instead of using the + default conversation. An empty array `[]` will clear the context for this + Response. Note that this can include references to items from the default + conversation. """ instructions: str diff --git a/src/openai/types/chat/chat_completion_chunk.py b/src/openai/types/chat/chat_completion_chunk.py index 7b0ae2e121..dede513f1e 100644 --- a/src/openai/types/chat/chat_completion_chunk.py +++ b/src/openai/types/chat/chat_completion_chunk.py @@ -70,7 +70,7 @@ class ChoiceDelta(BaseModel): refusal: Optional[str] = None """The refusal message generated by the model.""" - role: Optional[Literal["system", "user", "assistant", "tool"]] = None + role: Optional[Literal["developer", "system", "user", "assistant", "tool"]] = None """The role of the author of this message.""" tool_calls: Optional[List[ChoiceDeltaToolCall]] = None diff --git a/src/openai/types/chat/chat_completion_role.py b/src/openai/types/chat/chat_completion_role.py index c2ebef74c8..3ec5e9ad87 100644 --- a/src/openai/types/chat/chat_completion_role.py +++ b/src/openai/types/chat/chat_completion_role.py @@ -4,4 +4,4 @@ __all__ = ["ChatCompletionRole"] -ChatCompletionRole: TypeAlias = Literal["system", "user", "assistant", "tool", "function"] +ChatCompletionRole: TypeAlias = Literal["developer", "system", "user", "assistant", "tool", "function"] From 7193688e364bd726594fe369032e813ced1bdfe2 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 5 Feb 2025 11:27:26 +0000 Subject: [PATCH 680/816] release: 1.61.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 15 +++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 18 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 68804e4da0..285741ee32 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.61.0" + ".": "1.61.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index dcd1c06333..101e7480b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## 1.61.1 (2025-02-05) + +Full Changelog: [v1.61.0...v1.61.1](https://github.com/openai/openai-python/compare/v1.61.0...v1.61.1) + +### Bug Fixes + +* **api/types:** correct audio duration & role types ([#2091](https://github.com/openai/openai-python/issues/2091)) ([afcea48](https://github.com/openai/openai-python/commit/afcea4891ff85de165ccc2b5497ccf9a90520e9e)) +* **cli/chat:** only send params when set ([#2077](https://github.com/openai/openai-python/issues/2077)) ([688b223](https://github.com/openai/openai-python/commit/688b223d9a733d241d50e5d7df62f346592c537c)) + + +### Chores + +* **internal:** bummp ruff dependency ([#2080](https://github.com/openai/openai-python/issues/2080)) ([b7a80b1](https://github.com/openai/openai-python/commit/b7a80b1994ab86e81485b88531e4aea63b3da594)) +* **internal:** change default timeout to an int ([#2079](https://github.com/openai/openai-python/issues/2079)) ([d3df1c6](https://github.com/openai/openai-python/commit/d3df1c6ca090598701e38fd376a9796aadba88f1)) + ## 1.61.0 (2025-01-31) Full Changelog: [v1.60.2...v1.61.0](https://github.com/openai/openai-python/compare/v1.60.2...v1.61.0) diff --git a/pyproject.toml b/pyproject.toml index dc78d95d3f..6f1a6eb28a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.61.0" +version = "1.61.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index e9ab8be65e..7ffe16b95d 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.61.0" # x-release-please-version +__version__ = "1.61.1" # x-release-please-version From b99c35c62f3773980ee77179cdad9d8afd46f13b Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 5 Feb 2025 17:15:22 +0000 Subject: [PATCH 681/816] feat(client): send `X-Stainless-Read-Timeout` header (#2094) --- src/openai/_base_client.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 1fa039c0b1..8a408d8e58 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -420,10 +420,17 @@ def _build_headers(self, options: FinalRequestOptions, *, retries_taken: int = 0 if idempotency_header and options.method.lower() != "get" and idempotency_header not in headers: headers[idempotency_header] = options.idempotency_key or self._idempotency_key() - # Don't set the retry count header if it was already set or removed by the caller. We check + # Don't set these headers if they were already set or removed by the caller. We check # `custom_headers`, which can contain `Omit()`, instead of `headers` to account for the removal case. - if "x-stainless-retry-count" not in (header.lower() for header in custom_headers): + lower_custom_headers = [header.lower() for header in custom_headers] + if "x-stainless-retry-count" not in lower_custom_headers: headers["x-stainless-retry-count"] = str(retries_taken) + if "x-stainless-read-timeout" not in lower_custom_headers: + timeout = self.timeout if isinstance(options.timeout, NotGiven) else options.timeout + if isinstance(timeout, Timeout): + timeout = timeout.read + if timeout is not None: + headers["x-stainless-read-timeout"] = str(timeout) return headers From 8640fd837f371e6c6e235bbdc3a6ff395ba632b7 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 5 Feb 2025 21:25:56 +0000 Subject: [PATCH 682/816] fix(api): add missing reasoning effort + model enums (#2096) --- .stats.yml | 2 +- src/openai/resources/beta/assistants.py | 106 +++++++++++++++++- src/openai/resources/beta/chat/completions.py | 8 +- .../resources/beta/threads/runs/runs.py | 68 +++++++++++ src/openai/resources/chat/completions.py | 28 ++--- .../types/beta/assistant_create_params.py | 11 +- .../types/beta/assistant_update_params.py | 47 +++++++- .../types/beta/threads/run_create_params.py | 9 ++ .../chat/chat_completion_reasoning_effort.py | 3 +- .../types/chat/completion_create_params.py | 4 +- tests/api_resources/beta/test_assistants.py | 8 +- tests/api_resources/beta/threads/test_runs.py | 4 + 12 files changed, 268 insertions(+), 30 deletions(-) diff --git a/.stats.yml b/.stats.yml index df7877dfd0..8a5d2c06b2 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 69 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-fc5dbc19505b0035f9e7f88868619f4fb519b048bde011f6154f3132d4be71fb.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-7c699d4503077d06a4a44f52c0c1f902d19a87c766b8be75b97c8dfd484ad4aa.yml diff --git a/src/openai/resources/beta/assistants.py b/src/openai/resources/beta/assistants.py index 65b7c9cfc2..462086f74b 100644 --- a/src/openai/resources/beta/assistants.py +++ b/src/openai/resources/beta/assistants.py @@ -61,6 +61,7 @@ def create( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_resources: Optional[assistant_create_params.ToolResources] | NotGiven = NOT_GIVEN, @@ -97,6 +98,13 @@ def create( name: The name of the assistant. The maximum length is 256 characters. + reasoning_effort: **o1 and o3-mini models only** + + Constrains effort on reasoning for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + supported values are `low`, `medium`, and `high`. Reducing reasoning effort can + result in faster responses and fewer tokens used on reasoning in a response. + response_format: Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), @@ -155,6 +163,7 @@ def create( "instructions": instructions, "metadata": metadata, "name": name, + "reasoning_effort": reasoning_effort, "response_format": response_format, "temperature": temperature, "tool_resources": tool_resources, @@ -210,8 +219,42 @@ def update( description: Optional[str] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - model: str | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "o3-mini", + "o3-mini-2025-01-31", + "o1", + "o1-2024-12-17", + "gpt-4o", + "gpt-4o-2024-11-20", + "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + ] + | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_resources: Optional[assistant_update_params.ToolResources] | NotGiven = NOT_GIVEN, @@ -249,6 +292,13 @@ def update( name: The name of the assistant. The maximum length is 256 characters. + reasoning_effort: **o1 and o3-mini models only** + + Constrains effort on reasoning for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + supported values are `low`, `medium`, and `high`. Reducing reasoning effort can + result in faster responses and fewer tokens used on reasoning in a response. + response_format: Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), @@ -309,6 +359,7 @@ def update( "metadata": metadata, "model": model, "name": name, + "reasoning_effort": reasoning_effort, "response_format": response_format, "temperature": temperature, "tool_resources": tool_resources, @@ -451,6 +502,7 @@ async def create( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_resources: Optional[assistant_create_params.ToolResources] | NotGiven = NOT_GIVEN, @@ -487,6 +539,13 @@ async def create( name: The name of the assistant. The maximum length is 256 characters. + reasoning_effort: **o1 and o3-mini models only** + + Constrains effort on reasoning for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + supported values are `low`, `medium`, and `high`. Reducing reasoning effort can + result in faster responses and fewer tokens used on reasoning in a response. + response_format: Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), @@ -545,6 +604,7 @@ async def create( "instructions": instructions, "metadata": metadata, "name": name, + "reasoning_effort": reasoning_effort, "response_format": response_format, "temperature": temperature, "tool_resources": tool_resources, @@ -600,8 +660,42 @@ async def update( description: Optional[str] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - model: str | NotGiven = NOT_GIVEN, + model: Union[ + str, + Literal[ + "o3-mini", + "o3-mini-2025-01-31", + "o1", + "o1-2024-12-17", + "gpt-4o", + "gpt-4o-2024-11-20", + "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + ] + | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_resources: Optional[assistant_update_params.ToolResources] | NotGiven = NOT_GIVEN, @@ -639,6 +733,13 @@ async def update( name: The name of the assistant. The maximum length is 256 characters. + reasoning_effort: **o1 and o3-mini models only** + + Constrains effort on reasoning for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + supported values are `low`, `medium`, and `high`. Reducing reasoning effort can + result in faster responses and fewer tokens used on reasoning in a response. + response_format: Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), @@ -699,6 +800,7 @@ async def update( "metadata": metadata, "model": model, "name": name, + "reasoning_effort": reasoning_effort, "response_format": response_format, "temperature": temperature, "tool_resources": tool_resources, diff --git a/src/openai/resources/beta/chat/completions.py b/src/openai/resources/beta/chat/completions.py index 8a3a20d9e0..0c631b9821 100644 --- a/src/openai/resources/beta/chat/completions.py +++ b/src/openai/resources/beta/chat/completions.py @@ -83,7 +83,7 @@ def parse( parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, - reasoning_effort: ChatCompletionReasoningEffort | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ChatCompletionReasoningEffort] | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, @@ -228,7 +228,7 @@ def stream( parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, - reasoning_effort: ChatCompletionReasoningEffort | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ChatCompletionReasoningEffort] | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, @@ -358,7 +358,7 @@ async def parse( parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, - reasoning_effort: ChatCompletionReasoningEffort | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ChatCompletionReasoningEffort] | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, @@ -503,7 +503,7 @@ def stream( parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, - reasoning_effort: ChatCompletionReasoningEffort | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ChatCompletionReasoningEffort] | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 13301ad507..dc364b4e31 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -96,6 +96,7 @@ def create( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -164,6 +165,13 @@ def create( [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. + reasoning_effort: **o1 and o3-mini models only** + + Constrains effort on reasoning for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + supported values are `low`, `medium`, and `high`. Reducing reasoning effort can + result in faster responses and fewer tokens used on reasoning in a response. + response_format: Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), @@ -239,6 +247,7 @@ def create( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -310,6 +319,13 @@ def create( [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. + reasoning_effort: **o1 and o3-mini models only** + + Constrains effort on reasoning for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + supported values are `low`, `medium`, and `high`. Reducing reasoning effort can + result in faster responses and fewer tokens used on reasoning in a response. + response_format: Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), @@ -381,6 +397,7 @@ def create( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -452,6 +469,13 @@ def create( [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. + reasoning_effort: **o1 and o3-mini models only** + + Constrains effort on reasoning for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + supported values are `low`, `medium`, and `high`. Reducing reasoning effort can + result in faster responses and fewer tokens used on reasoning in a response. + response_format: Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), @@ -522,6 +546,7 @@ def create( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -552,6 +577,7 @@ def create( "metadata": metadata, "model": model, "parallel_tool_calls": parallel_tool_calls, + "reasoning_effort": reasoning_effort, "response_format": response_format, "stream": stream, "temperature": temperature, @@ -774,6 +800,7 @@ def create_and_poll( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -809,6 +836,7 @@ def create_and_poll( temperature=temperature, tool_choice=tool_choice, parallel_tool_calls=parallel_tool_calls, + reasoning_effort=reasoning_effort, # We assume we are not streaming when polling stream=False, tools=tools, @@ -843,6 +871,7 @@ def create_and_stream( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -874,6 +903,7 @@ def create_and_stream( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -905,6 +935,7 @@ def create_and_stream( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -950,6 +981,7 @@ def create_and_stream( "tools": tools, "truncation_strategy": truncation_strategy, "parallel_tool_calls": parallel_tool_calls, + "reasoning_effort": reasoning_effort, "top_p": top_p, }, run_create_params.RunCreateParams, @@ -1022,6 +1054,7 @@ def stream( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -1053,6 +1086,7 @@ def stream( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -1084,6 +1118,7 @@ def stream( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -1128,6 +1163,7 @@ def stream( "stream": True, "tools": tools, "parallel_tool_calls": parallel_tool_calls, + "reasoning_effort": reasoning_effort, "truncation_strategy": truncation_strategy, "top_p": top_p, }, @@ -1469,6 +1505,7 @@ async def create( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -1537,6 +1574,13 @@ async def create( [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. + reasoning_effort: **o1 and o3-mini models only** + + Constrains effort on reasoning for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + supported values are `low`, `medium`, and `high`. Reducing reasoning effort can + result in faster responses and fewer tokens used on reasoning in a response. + response_format: Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), @@ -1612,6 +1656,7 @@ async def create( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -1683,6 +1728,13 @@ async def create( [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. + reasoning_effort: **o1 and o3-mini models only** + + Constrains effort on reasoning for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + supported values are `low`, `medium`, and `high`. Reducing reasoning effort can + result in faster responses and fewer tokens used on reasoning in a response. + response_format: Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), @@ -1754,6 +1806,7 @@ async def create( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -1825,6 +1878,13 @@ async def create( [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. + reasoning_effort: **o1 and o3-mini models only** + + Constrains effort on reasoning for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + supported values are `low`, `medium`, and `high`. Reducing reasoning effort can + result in faster responses and fewer tokens used on reasoning in a response. + response_format: Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), @@ -1895,6 +1955,7 @@ async def create( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -1925,6 +1986,7 @@ async def create( "metadata": metadata, "model": model, "parallel_tool_calls": parallel_tool_calls, + "reasoning_effort": reasoning_effort, "response_format": response_format, "stream": stream, "temperature": temperature, @@ -2147,6 +2209,7 @@ async def create_and_poll( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -2182,6 +2245,7 @@ async def create_and_poll( temperature=temperature, tool_choice=tool_choice, parallel_tool_calls=parallel_tool_calls, + reasoning_effort=reasoning_effort, # We assume we are not streaming when polling stream=False, tools=tools, @@ -2396,6 +2460,7 @@ def stream( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -2427,6 +2492,7 @@ def stream( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -2458,6 +2524,7 @@ def stream( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -2504,6 +2571,7 @@ def stream( "stream": True, "tools": tools, "parallel_tool_calls": parallel_tool_calls, + "reasoning_effort": reasoning_effort, "truncation_strategy": truncation_strategy, "top_p": top_p, }, diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index 34f6b50301..cc839103a0 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -82,7 +82,7 @@ def create( parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, - reasoning_effort: ChatCompletionReasoningEffort | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ChatCompletionReasoningEffort] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, @@ -213,7 +213,7 @@ def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - reasoning_effort: **o1 models only** + reasoning_effort: **o1 and o3-mini models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently @@ -335,7 +335,7 @@ def create( parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, - reasoning_effort: ChatCompletionReasoningEffort | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ChatCompletionReasoningEffort] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, @@ -472,7 +472,7 @@ def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - reasoning_effort: **o1 models only** + reasoning_effort: **o1 and o3-mini models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently @@ -587,7 +587,7 @@ def create( parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, - reasoning_effort: ChatCompletionReasoningEffort | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ChatCompletionReasoningEffort] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, @@ -724,7 +724,7 @@ def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - reasoning_effort: **o1 models only** + reasoning_effort: **o1 and o3-mini models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently @@ -838,7 +838,7 @@ def create( parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, - reasoning_effort: ChatCompletionReasoningEffort | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ChatCompletionReasoningEffort] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, @@ -946,7 +946,7 @@ async def create( parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, - reasoning_effort: ChatCompletionReasoningEffort | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ChatCompletionReasoningEffort] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, @@ -1077,7 +1077,7 @@ async def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - reasoning_effort: **o1 models only** + reasoning_effort: **o1 and o3-mini models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently @@ -1199,7 +1199,7 @@ async def create( parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, - reasoning_effort: ChatCompletionReasoningEffort | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ChatCompletionReasoningEffort] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, @@ -1336,7 +1336,7 @@ async def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - reasoning_effort: **o1 models only** + reasoning_effort: **o1 and o3-mini models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently @@ -1451,7 +1451,7 @@ async def create( parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, - reasoning_effort: ChatCompletionReasoningEffort | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ChatCompletionReasoningEffort] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, @@ -1588,7 +1588,7 @@ async def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - reasoning_effort: **o1 models only** + reasoning_effort: **o1 and o3-mini models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently @@ -1702,7 +1702,7 @@ async def create( parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, - reasoning_effort: ChatCompletionReasoningEffort | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ChatCompletionReasoningEffort] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, diff --git a/src/openai/types/beta/assistant_create_params.py b/src/openai/types/beta/assistant_create_params.py index e205856395..66bef02ced 100644 --- a/src/openai/types/beta/assistant_create_params.py +++ b/src/openai/types/beta/assistant_create_params.py @@ -3,7 +3,7 @@ from __future__ import annotations from typing import List, Union, Iterable, Optional -from typing_extensions import Required, TypedDict +from typing_extensions import Literal, Required, TypedDict from ..chat_model import ChatModel from .assistant_tool_param import AssistantToolParam @@ -53,6 +53,15 @@ class AssistantCreateParams(TypedDict, total=False): name: Optional[str] """The name of the assistant. The maximum length is 256 characters.""" + reasoning_effort: Optional[Literal["low", "medium", "high"]] + """**o1 and o3-mini models only** + + Constrains effort on reasoning for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + supported values are `low`, `medium`, and `high`. Reducing reasoning effort can + result in faster responses and fewer tokens used on reasoning in a response. + """ + response_format: Optional[AssistantResponseFormatOptionParam] """Specifies the format that the model must output. diff --git a/src/openai/types/beta/assistant_update_params.py b/src/openai/types/beta/assistant_update_params.py index 35065ef61b..80fec110cd 100644 --- a/src/openai/types/beta/assistant_update_params.py +++ b/src/openai/types/beta/assistant_update_params.py @@ -2,8 +2,8 @@ from __future__ import annotations -from typing import List, Iterable, Optional -from typing_extensions import TypedDict +from typing import List, Union, Iterable, Optional +from typing_extensions import Literal, TypedDict from .assistant_tool_param import AssistantToolParam from ..shared_params.metadata import Metadata @@ -32,7 +32,39 @@ class AssistantUpdateParams(TypedDict, total=False): a maximum length of 512 characters. """ - model: str + model: Union[ + str, + Literal[ + "o3-mini", + "o3-mini-2025-01-31", + "o1", + "o1-2024-12-17", + "gpt-4o", + "gpt-4o-2024-11-20", + "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", + ], + ] """ID of the model to use. You can use the @@ -45,6 +77,15 @@ class AssistantUpdateParams(TypedDict, total=False): name: Optional[str] """The name of the assistant. The maximum length is 256 characters.""" + reasoning_effort: Optional[Literal["low", "medium", "high"]] + """**o1 and o3-mini models only** + + Constrains effort on reasoning for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + supported values are `low`, `medium`, and `high`. Reducing reasoning effort can + result in faster responses and fewer tokens used on reasoning in a response. + """ + response_format: Optional[AssistantResponseFormatOptionParam] """Specifies the format that the model must output. diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index 091dd3da66..093b4ce321 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -106,6 +106,15 @@ class RunCreateParamsBase(TypedDict, total=False): during tool use. """ + reasoning_effort: Optional[Literal["low", "medium", "high"]] + """**o1 and o3-mini models only** + + Constrains effort on reasoning for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + supported values are `low`, `medium`, and `high`. Reducing reasoning effort can + result in faster responses and fewer tokens used on reasoning in a response. + """ + response_format: Optional[AssistantResponseFormatOptionParam] """Specifies the format that the model must output. diff --git a/src/openai/types/chat/chat_completion_reasoning_effort.py b/src/openai/types/chat/chat_completion_reasoning_effort.py index 9e7946974a..85249c53b1 100644 --- a/src/openai/types/chat/chat_completion_reasoning_effort.py +++ b/src/openai/types/chat/chat_completion_reasoning_effort.py @@ -1,7 +1,8 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +from typing import Optional from typing_extensions import Literal, TypeAlias __all__ = ["ChatCompletionReasoningEffort"] -ChatCompletionReasoningEffort: TypeAlias = Literal["low", "medium", "high"] +ChatCompletionReasoningEffort: TypeAlias = Optional[Literal["low", "medium", "high"]] diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index ec88ea1fb0..c761cbe07b 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -174,8 +174,8 @@ class CompletionCreateParamsBase(TypedDict, total=False): far, increasing the model's likelihood to talk about new topics. """ - reasoning_effort: ChatCompletionReasoningEffort - """**o1 models only** + reasoning_effort: Optional[ChatCompletionReasoningEffort] + """**o1 and o3-mini models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently diff --git a/tests/api_resources/beta/test_assistants.py b/tests/api_resources/beta/test_assistants.py index 458e3f5e90..82aaf87b1c 100644 --- a/tests/api_resources/beta/test_assistants.py +++ b/tests/api_resources/beta/test_assistants.py @@ -36,6 +36,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: instructions="instructions", metadata={"foo": "string"}, name="name", + reasoning_effort="low", response_format="auto", temperature=1, tool_resources={ @@ -132,8 +133,9 @@ def test_method_update_with_all_params(self, client: OpenAI) -> None: description="description", instructions="instructions", metadata={"foo": "string"}, - model="model", + model="string", name="name", + reasoning_effort="low", response_format="auto", temperature=1, tool_resources={ @@ -268,6 +270,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> instructions="instructions", metadata={"foo": "string"}, name="name", + reasoning_effort="low", response_format="auto", temperature=1, tool_resources={ @@ -364,8 +367,9 @@ async def test_method_update_with_all_params(self, async_client: AsyncOpenAI) -> description="description", instructions="instructions", metadata={"foo": "string"}, - model="model", + model="string", name="name", + reasoning_effort="low", response_format="auto", temperature=1, tool_resources={ diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index 48b39cfe5b..d05ee96144 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -56,6 +56,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: metadata={"foo": "string"}, model="gpt-4o", parallel_tool_calls=True, + reasoning_effort="low", response_format="auto", stream=False, temperature=1, @@ -139,6 +140,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: metadata={"foo": "string"}, model="gpt-4o", parallel_tool_calls=True, + reasoning_effort="low", response_format="auto", temperature=1, tool_choice="none", @@ -552,6 +554,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn metadata={"foo": "string"}, model="gpt-4o", parallel_tool_calls=True, + reasoning_effort="low", response_format="auto", stream=False, temperature=1, @@ -635,6 +638,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn metadata={"foo": "string"}, model="gpt-4o", parallel_tool_calls=True, + reasoning_effort="low", response_format="auto", temperature=1, tool_choice="none", From 2c20ea7af7bcd531d04122624789402778370c52 Mon Sep 17 00:00:00 2001 From: Anthony Shaw Date: Thu, 6 Feb 2025 21:15:14 +1100 Subject: [PATCH 683/816] feat(embeddings): use stdlib array type for improved performance (#2060) --- src/openai/resources/embeddings.py | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/src/openai/resources/embeddings.py b/src/openai/resources/embeddings.py index 382a42340e..a392d5eb17 100644 --- a/src/openai/resources/embeddings.py +++ b/src/openai/resources/embeddings.py @@ -2,6 +2,7 @@ from __future__ import annotations +import array import base64 from typing import List, Union, Iterable, cast from typing_extensions import Literal @@ -102,7 +103,7 @@ def create( "dimensions": dimensions, "encoding_format": encoding_format, } - if not is_given(encoding_format) and has_numpy(): + if not is_given(encoding_format): params["encoding_format"] = "base64" def parser(obj: CreateEmbeddingResponse) -> CreateEmbeddingResponse: @@ -113,12 +114,14 @@ def parser(obj: CreateEmbeddingResponse) -> CreateEmbeddingResponse: for embedding in obj.data: data = cast(object, embedding.embedding) if not isinstance(data, str): - # numpy is not installed / base64 optimisation isn't enabled for this model yet continue - - embedding.embedding = np.frombuffer( # type: ignore[no-untyped-call] - base64.b64decode(data), dtype="float32" - ).tolist() + if not has_numpy(): + # use array for base64 optimisation + embedding.embedding = array.array("f", base64.b64decode(data)).tolist() + else: + embedding.embedding = np.frombuffer( # type: ignore[no-untyped-call] + base64.b64decode(data), dtype="float32" + ).tolist() return obj @@ -215,7 +218,7 @@ async def create( "dimensions": dimensions, "encoding_format": encoding_format, } - if not is_given(encoding_format) and has_numpy(): + if not is_given(encoding_format): params["encoding_format"] = "base64" def parser(obj: CreateEmbeddingResponse) -> CreateEmbeddingResponse: @@ -226,12 +229,14 @@ def parser(obj: CreateEmbeddingResponse) -> CreateEmbeddingResponse: for embedding in obj.data: data = cast(object, embedding.embedding) if not isinstance(data, str): - # numpy is not installed / base64 optimisation isn't enabled for this model yet continue - - embedding.embedding = np.frombuffer( # type: ignore[no-untyped-call] - base64.b64decode(data), dtype="float32" - ).tolist() + if not has_numpy(): + # use array for base64 optimisation + embedding.embedding = array.array("f", base64.b64decode(data)).tolist() + else: + embedding.embedding = np.frombuffer( # type: ignore[no-untyped-call] + base64.b64decode(data), dtype="float32" + ).tolist() return obj From af6a9437128fc64643178a12d3e700a962f08977 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 6 Feb 2025 13:00:22 +0000 Subject: [PATCH 684/816] chore(internal): fix type traversing dictionary params (#2097) --- src/openai/_utils/_transform.py | 12 +++++++++++- tests/test_transform.py | 11 ++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/openai/_utils/_transform.py b/src/openai/_utils/_transform.py index a6b62cad0c..18afd9d8bd 100644 --- a/src/openai/_utils/_transform.py +++ b/src/openai/_utils/_transform.py @@ -25,7 +25,7 @@ is_annotated_type, strip_annotated_type, ) -from .._compat import model_dump, is_typeddict +from .._compat import get_origin, model_dump, is_typeddict _T = TypeVar("_T") @@ -164,9 +164,14 @@ def _transform_recursive( inner_type = annotation stripped_type = strip_annotated_type(inner_type) + origin = get_origin(stripped_type) or stripped_type if is_typeddict(stripped_type) and is_mapping(data): return _transform_typeddict(data, stripped_type) + if origin == dict and is_mapping(data): + items_type = get_args(stripped_type)[1] + return {key: _transform_recursive(value, annotation=items_type) for key, value in data.items()} + if ( # List[T] (is_list_type(stripped_type) and is_list(data)) @@ -307,9 +312,14 @@ async def _async_transform_recursive( inner_type = annotation stripped_type = strip_annotated_type(inner_type) + origin = get_origin(stripped_type) or stripped_type if is_typeddict(stripped_type) and is_mapping(data): return await _async_transform_typeddict(data, stripped_type) + if origin == dict and is_mapping(data): + items_type = get_args(stripped_type)[1] + return {key: _transform_recursive(value, annotation=items_type) for key, value in data.items()} + if ( # List[T] (is_list_type(stripped_type) and is_list(data)) diff --git a/tests/test_transform.py b/tests/test_transform.py index 8c6aba6448..385fbe2b2c 100644 --- a/tests/test_transform.py +++ b/tests/test_transform.py @@ -2,7 +2,7 @@ import io import pathlib -from typing import Any, List, Union, TypeVar, Iterable, Optional, cast +from typing import Any, Dict, List, Union, TypeVar, Iterable, Optional, cast from datetime import date, datetime from typing_extensions import Required, Annotated, TypedDict @@ -388,6 +388,15 @@ def my_iter() -> Iterable[Baz8]: } +@parametrize +@pytest.mark.asyncio +async def test_dictionary_items(use_async: bool) -> None: + class DictItems(TypedDict): + foo_baz: Annotated[str, PropertyInfo(alias="fooBaz")] + + assert await transform({"foo": {"foo_baz": "bar"}}, Dict[str, DictItems], use_async) == {"foo": {"fooBaz": "bar"}} + + class TypedDictIterableUnionStr(TypedDict): foo: Annotated[Union[str, Iterable[Baz8]], PropertyInfo(alias="FOO")] From e2f2db8a1c237997a699a28b4192a054a040fc61 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 6 Feb 2025 15:16:44 +0000 Subject: [PATCH 685/816] feat(pagination): avoid fetching when has_more: false (#2098) --- .stats.yml | 2 +- src/openai/pagination.py | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index 8a5d2c06b2..d59a86d22e 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 69 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-7c699d4503077d06a4a44f52c0c1f902d19a87c766b8be75b97c8dfd484ad4aa.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-dfb00c627f58e5180af7a9b29ed2f2aa0764a3b9daa6a32a1cc45bc8e48dfe15.yml diff --git a/src/openai/pagination.py b/src/openai/pagination.py index 8293638269..a59cced854 100644 --- a/src/openai/pagination.py +++ b/src/openai/pagination.py @@ -61,6 +61,7 @@ def next_page_info(self) -> None: class SyncCursorPage(BaseSyncPage[_T], BasePage[_T], Generic[_T]): data: List[_T] + has_more: Optional[bool] = None @override def _get_page_items(self) -> List[_T]: @@ -69,6 +70,14 @@ def _get_page_items(self) -> List[_T]: return [] return data + @override + def has_next_page(self) -> bool: + has_more = self.has_more + if has_more is not None and has_more is False: + return False + + return super().has_next_page() + @override def next_page_info(self) -> Optional[PageInfo]: data = self.data @@ -85,6 +94,7 @@ def next_page_info(self) -> Optional[PageInfo]: class AsyncCursorPage(BaseAsyncPage[_T], BasePage[_T], Generic[_T]): data: List[_T] + has_more: Optional[bool] = None @override def _get_page_items(self) -> List[_T]: @@ -93,6 +103,14 @@ def _get_page_items(self) -> List[_T]: return [] return data + @override + def has_next_page(self) -> bool: + has_more = self.has_more + if has_more is not None and has_more is False: + return False + + return super().has_next_page() + @override def next_page_info(self) -> Optional[PageInfo]: data = self.data From b5f6dc78feafbd3e34457dbf11b00978502823c0 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 6 Feb 2025 16:22:46 +0000 Subject: [PATCH 686/816] chore(internal): minor type handling changes (#2099) --- src/openai/_models.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/openai/_models.py b/src/openai/_models.py index c6e1305087..92986bfdf5 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -451,10 +451,16 @@ def construct_type(*, value: object, type_: object) -> object: If the given value does not match the expected type then it is returned as-is. """ + + # store a reference to the original type we were given before we extract any inner + # types so that we can properly resolve forward references in `TypeAliasType` annotations + original_type = None + # we allow `object` as the input type because otherwise, passing things like # `Literal['value']` will be reported as a type error by type checkers type_ = cast("type[object]", type_) if is_type_alias_type(type_): + original_type = type_ # type: ignore[unreachable] type_ = type_.__value__ # type: ignore[unreachable] # unwrap `Annotated[T, ...]` -> `T` @@ -471,7 +477,7 @@ def construct_type(*, value: object, type_: object) -> object: if is_union(origin): try: - return validate_type(type_=cast("type[object]", type_), value=value) + return validate_type(type_=cast("type[object]", original_type or type_), value=value) except Exception: pass From b45168e26f9fbbfcd7c1d1bd28f46a267ffcd3f9 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 10 Feb 2025 18:08:55 +0000 Subject: [PATCH 687/816] fix(parsing): don't default to an empty array (#2106) --- src/openai/lib/_parsing/_completions.py | 2 +- tests/lib/chat/test_completions.py | 22 ++++++++++---------- tests/lib/chat/test_completions_streaming.py | 20 +++++++++--------- 3 files changed, 22 insertions(+), 22 deletions(-) diff --git a/src/openai/lib/_parsing/_completions.py b/src/openai/lib/_parsing/_completions.py index 33c4ccb946..14b1745d3d 100644 --- a/src/openai/lib/_parsing/_completions.py +++ b/src/openai/lib/_parsing/_completions.py @@ -111,7 +111,7 @@ def parse_chat_completion( response_format=response_format, message=message, ), - "tool_calls": tool_calls, + "tool_calls": tool_calls if tool_calls else None, }, }, ) diff --git a/tests/lib/chat/test_completions.py b/tests/lib/chat/test_completions.py index 48f41eb221..74cee27b93 100644 --- a/tests/lib/chat/test_completions.py +++ b/tests/lib/chat/test_completions.py @@ -65,7 +65,7 @@ def test_parse_nothing(client: OpenAI, respx_mock: MockRouter, monkeypatch: pyte parsed=None, refusal=None, role='assistant', - tool_calls=[] + tool_calls=None ) ) ], @@ -132,7 +132,7 @@ class Location(BaseModel): parsed=Location(city='San Francisco', temperature=65.0, units='f'), refusal=None, role='assistant', - tool_calls=[] + tool_calls=None ) ) ], @@ -201,7 +201,7 @@ class Location(BaseModel): parsed=Location(city='San Francisco', temperature=65.0, units='f'), refusal=None, role='assistant', - tool_calls=[] + tool_calls=None ) ) ], @@ -272,7 +272,7 @@ class ColorDetection(BaseModel): parsed=ColorDetection(color=, hex_color_code='#FF0000'), refusal=None, role='assistant', - tool_calls=[] + tool_calls=None ) ) """ @@ -321,7 +321,7 @@ class Location(BaseModel): parsed=Location(city='San Francisco', temperature=64.0, units='f'), refusal=None, role='assistant', - tool_calls=[] + tool_calls=None ) ), ParsedChoice[Location]( @@ -335,7 +335,7 @@ class Location(BaseModel): parsed=Location(city='San Francisco', temperature=65.0, units='f'), refusal=None, role='assistant', - tool_calls=[] + tool_calls=None ) ), ParsedChoice[Location]( @@ -349,7 +349,7 @@ class Location(BaseModel): parsed=Location(city='San Francisco', temperature=63.0, units='f'), refusal=None, role='assistant', - tool_calls=[] + tool_calls=None ) ) ] @@ -399,7 +399,7 @@ class CalendarEvent: parsed=CalendarEvent(name='Science Fair', date='Friday', participants=['Alice', 'Bob']), refusal=None, role='assistant', - tool_calls=[] + tool_calls=None ) ) ], @@ -571,7 +571,7 @@ class Location(BaseModel): parsed=None, refusal="I'm very sorry, but I can't assist with that.", role='assistant', - tool_calls=[] + tool_calls=None ) ) ] @@ -855,7 +855,7 @@ class Location(BaseModel): parsed=Location(city='San Francisco', temperature=58.0, units='f'), refusal=None, role='assistant', - tool_calls=[] + tool_calls=None ) ) ], @@ -930,7 +930,7 @@ class Location(BaseModel): parsed=Location(city='San Francisco', temperature=65.0, units='f'), refusal=None, role='assistant', - tool_calls=[] + tool_calls=None ) ) ], diff --git a/tests/lib/chat/test_completions_streaming.py b/tests/lib/chat/test_completions_streaming.py index 1eed031af7..71b4173738 100644 --- a/tests/lib/chat/test_completions_streaming.py +++ b/tests/lib/chat/test_completions_streaming.py @@ -70,7 +70,7 @@ def test_parse_nothing(client: OpenAI, respx_mock: MockRouter, monkeypatch: pyte parsed=None, refusal=None, role='assistant', - tool_calls=[] + tool_calls=None ) ) ] @@ -147,7 +147,7 @@ def on_event(stream: ChatCompletionStream[Location], event: ChatCompletionStream parsed=Location(city='San Francisco', temperature=61.0, units='f'), refusal=None, role='assistant', - tool_calls=[] + tool_calls=None ) ) ], @@ -324,7 +324,7 @@ class Location(BaseModel): parsed=Location(city='San Francisco', temperature=65.0, units='f'), refusal=None, role='assistant', - tool_calls=[] + tool_calls=None ) ), ParsedChoice[Location]( @@ -338,7 +338,7 @@ class Location(BaseModel): parsed=Location(city='San Francisco', temperature=61.0, units='f'), refusal=None, role='assistant', - tool_calls=[] + tool_calls=None ) ), ParsedChoice[Location]( @@ -352,7 +352,7 @@ class Location(BaseModel): parsed=Location(city='San Francisco', temperature=59.0, units='f'), refusal=None, role='assistant', - tool_calls=[] + tool_calls=None ) ) ] @@ -427,7 +427,7 @@ class Location(BaseModel): parsed=None, refusal="I'm sorry, I can't assist with that request.", role='assistant', - tool_calls=[] + tool_calls=None ) ) ] @@ -501,7 +501,7 @@ def test_content_logprobs_events(client: OpenAI, respx_mock: MockRouter, monkeyp parsed=None, refusal=None, role='assistant', - tool_calls=[] + tool_calls=None ) ) ] @@ -612,7 +612,7 @@ class Location(BaseModel): parsed=None, refusal="I'm very sorry, but I can't assist with that.", role='assistant', - tool_calls=[] + tool_calls=None ) ) ] @@ -925,7 +925,7 @@ def test_non_pydantic_response_format(client: OpenAI, respx_mock: MockRouter, mo parsed=None, refusal=None, role='assistant', - tool_calls=[] + tool_calls=None ) ) ] @@ -1040,7 +1040,7 @@ def streamer(client: OpenAI) -> Iterator[ChatCompletionChunk]: parsed=None, refusal=None, role='assistant', - tool_calls=[] + tool_calls=None ) ) ] From 3f8d8205ae41c389541e125336b0ae0c5e437661 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 12 Feb 2025 05:04:25 +0000 Subject: [PATCH 688/816] release: 1.62.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 22 ++++++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 25 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 285741ee32..ccd8ea8be5 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.61.1" + ".": "1.62.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 101e7480b7..583fbd9add 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,27 @@ # Changelog +## 1.62.0 (2025-02-12) + +Full Changelog: [v1.61.1...v1.62.0](https://github.com/openai/openai-python/compare/v1.61.1...v1.62.0) + +### Features + +* **client:** send `X-Stainless-Read-Timeout` header ([#2094](https://github.com/openai/openai-python/issues/2094)) ([0288213](https://github.com/openai/openai-python/commit/0288213fbfa935c9bf9d56416619ea929ae1cf63)) +* **embeddings:** use stdlib array type for improved performance ([#2060](https://github.com/openai/openai-python/issues/2060)) ([9a95db9](https://github.com/openai/openai-python/commit/9a95db9154ac98678970e7f1652a7cacfd2f7fdb)) +* **pagination:** avoid fetching when has_more: false ([#2098](https://github.com/openai/openai-python/issues/2098)) ([1882483](https://github.com/openai/openai-python/commit/18824832d3a676ae49206cd2b5e09d4796fdf033)) + + +### Bug Fixes + +* **api:** add missing reasoning effort + model enums ([#2096](https://github.com/openai/openai-python/issues/2096)) ([e0ca9f0](https://github.com/openai/openai-python/commit/e0ca9f0f6fae40230f8cab97573914ed632920b6)) +* **parsing:** don't default to an empty array ([#2106](https://github.com/openai/openai-python/issues/2106)) ([8e748bb](https://github.com/openai/openai-python/commit/8e748bb08d9c0d1f7e8a1af31452e25eb7154f55)) + + +### Chores + +* **internal:** fix type traversing dictionary params ([#2097](https://github.com/openai/openai-python/issues/2097)) ([4e5b368](https://github.com/openai/openai-python/commit/4e5b368bf576f38d0f125778edde74ed6d101d7d)) +* **internal:** minor type handling changes ([#2099](https://github.com/openai/openai-python/issues/2099)) ([a2c6da0](https://github.com/openai/openai-python/commit/a2c6da0fbc610ee80a2e044a0b20fc1cc2376962)) + ## 1.61.1 (2025-02-05) Full Changelog: [v1.61.0...v1.61.1](https://github.com/openai/openai-python/compare/v1.61.0...v1.61.1) diff --git a/pyproject.toml b/pyproject.toml index 6f1a6eb28a..85cb145673 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.61.1" +version = "1.62.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 7ffe16b95d..7dd5163b53 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.61.1" # x-release-please-version +__version__ = "1.62.0" # x-release-please-version From 300f58bbbde749e023dd1cf39de8f5339780a33d Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 13 Feb 2025 19:45:16 +0000 Subject: [PATCH 689/816] feat(api): add support for storing chat completions (#2117) --- .stats.yml | 4 +- api.md | 14 +- src/openai/_utils/_sync.py | 20 +- src/openai/cli/_api/chat/completions.py | 8 +- src/openai/lib/_parsing/_completions.py | 4 +- src/openai/resources/chat/chat.py | 2 +- .../resources/chat/completions/__init__.py | 33 ++ .../chat/{ => completions}/completions.py | 486 +++++++++++++++++- .../resources/chat/completions/messages.py | 212 ++++++++ src/openai/types/chat/__init__.py | 4 + .../types/chat/chat_completion_deleted.py | 18 + .../chat/chat_completion_store_message.py | 11 + .../types/chat/completion_list_params.py | 33 ++ .../types/chat/completion_update_params.py | 22 + src/openai/types/chat/completions/__init__.py | 5 + .../chat/completions/message_list_params.py | 21 + src/openai/types/moderation.py | 6 +- .../chat/completions/__init__.py | 1 + .../chat/completions/test_messages.py | 119 +++++ tests/api_resources/chat/test_completions.py | 310 +++++++++++ tests/lib/test_azure.py | 24 +- tests/test_client.py | 78 +-- 22 files changed, 1350 insertions(+), 85 deletions(-) create mode 100644 src/openai/resources/chat/completions/__init__.py rename src/openai/resources/chat/{ => completions}/completions.py (83%) create mode 100644 src/openai/resources/chat/completions/messages.py create mode 100644 src/openai/types/chat/chat_completion_deleted.py create mode 100644 src/openai/types/chat/chat_completion_store_message.py create mode 100644 src/openai/types/chat/completion_list_params.py create mode 100644 src/openai/types/chat/completion_update_params.py create mode 100644 src/openai/types/chat/completions/__init__.py create mode 100644 src/openai/types/chat/completions/message_list_params.py create mode 100644 tests/api_resources/chat/completions/__init__.py create mode 100644 tests/api_resources/chat/completions/test_messages.py diff --git a/.stats.yml b/.stats.yml index d59a86d22e..658877d3b0 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ -configured_endpoints: 69 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-dfb00c627f58e5180af7a9b29ed2f2aa0764a3b9daa6a32a1cc45bc8e48dfe15.yml +configured_endpoints: 74 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-4aa6ee65ba9efc789e05e6a5ef0883b2cadf06def8efd863dbf75e9e233067e1.yml diff --git a/api.md b/api.md index efbfeaa68f..2db9d1157e 100644 --- a/api.md +++ b/api.md @@ -48,6 +48,7 @@ from openai.types.chat import ( ChatCompletionContentPartInputAudio, ChatCompletionContentPartRefusal, ChatCompletionContentPartText, + ChatCompletionDeleted, ChatCompletionDeveloperMessageParam, ChatCompletionFunctionCallOption, ChatCompletionFunctionMessageParam, @@ -59,6 +60,7 @@ from openai.types.chat import ( ChatCompletionPredictionContent, ChatCompletionReasoningEffort, ChatCompletionRole, + ChatCompletionStoreMessage, ChatCompletionStreamOptions, ChatCompletionSystemMessageParam, ChatCompletionTokenLogprob, @@ -71,7 +73,17 @@ from openai.types.chat import ( Methods: -- client.chat.completions.create(\*\*params) -> ChatCompletion +- client.chat.completions.create(\*\*params) -> ChatCompletion +- client.chat.completions.retrieve(completion_id) -> ChatCompletion +- client.chat.completions.update(completion_id, \*\*params) -> ChatCompletion +- client.chat.completions.list(\*\*params) -> SyncCursorPage[ChatCompletion] +- client.chat.completions.delete(completion_id) -> ChatCompletionDeleted + +### Messages + +Methods: + +- client.chat.completions.messages.list(completion_id, \*\*params) -> SyncCursorPage[ChatCompletionStoreMessage] # Embeddings diff --git a/src/openai/_utils/_sync.py b/src/openai/_utils/_sync.py index 5d9e2c2ac9..ad7ec71b76 100644 --- a/src/openai/_utils/_sync.py +++ b/src/openai/_utils/_sync.py @@ -7,16 +7,20 @@ from typing import Any, TypeVar, Callable, Awaitable from typing_extensions import ParamSpec +import anyio +import sniffio +import anyio.to_thread + T_Retval = TypeVar("T_Retval") T_ParamSpec = ParamSpec("T_ParamSpec") if sys.version_info >= (3, 9): - to_thread = asyncio.to_thread + _asyncio_to_thread = asyncio.to_thread else: # backport of https://docs.python.org/3/library/asyncio-task.html#asyncio.to_thread # for Python 3.8 support - async def to_thread( + async def _asyncio_to_thread( func: Callable[T_ParamSpec, T_Retval], /, *args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs ) -> Any: """Asynchronously run function *func* in a separate thread. @@ -34,6 +38,17 @@ async def to_thread( return await loop.run_in_executor(None, func_call) +async def to_thread( + func: Callable[T_ParamSpec, T_Retval], /, *args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs +) -> T_Retval: + if sniffio.current_async_library() == "asyncio": + return await _asyncio_to_thread(func, *args, **kwargs) + + return await anyio.to_thread.run_sync( + functools.partial(func, *args, **kwargs), + ) + + # inspired by `asyncer`, https://github.com/tiangolo/asyncer def asyncify(function: Callable[T_ParamSpec, T_Retval]) -> Callable[T_ParamSpec, Awaitable[T_Retval]]: """ @@ -50,6 +65,7 @@ def blocking_func(arg1, arg2, kwarg1=None): # blocking code return result + result = asyncify(blocking_function)(arg1, arg2, kwarg1=value1) ``` diff --git a/src/openai/cli/_api/chat/completions.py b/src/openai/cli/_api/chat/completions.py index feedb5ccab..344eeff37c 100644 --- a/src/openai/cli/_api/chat/completions.py +++ b/src/openai/cli/_api/chat/completions.py @@ -104,13 +104,13 @@ def create(args: CLIChatCompletionCreateArgs) -> None: "stream": False, } if args.temperature is not None: - params['temperature'] = args.temperature + params["temperature"] = args.temperature if args.stop is not None: - params['stop'] = args.stop + params["stop"] = args.stop if args.top_p is not None: - params['top_p'] = args.top_p + params["top_p"] = args.top_p if args.n is not None: - params['n'] = args.n + params["n"] = args.n if args.stream: params["stream"] = args.stream # type: ignore if args.max_tokens is not None: diff --git a/src/openai/lib/_parsing/_completions.py b/src/openai/lib/_parsing/_completions.py index 14b1745d3d..c160070b66 100644 --- a/src/openai/lib/_parsing/_completions.py +++ b/src/openai/lib/_parsing/_completions.py @@ -45,13 +45,13 @@ def validate_input_tools( for tool in tools: if tool["type"] != "function": raise ValueError( - f'Currently only `function` tool types support auto-parsing; Received `{tool["type"]}`', + f"Currently only `function` tool types support auto-parsing; Received `{tool['type']}`", ) strict = tool["function"].get("strict") if strict is not True: raise ValueError( - f'`{tool["function"]["name"]}` is not strict. Only `strict` function tools can be auto-parsed' + f"`{tool['function']['name']}` is not strict. Only `strict` function tools can be auto-parsed" ) diff --git a/src/openai/resources/chat/chat.py b/src/openai/resources/chat/chat.py index 9c4aacc953..14f9224b41 100644 --- a/src/openai/resources/chat/chat.py +++ b/src/openai/resources/chat/chat.py @@ -4,7 +4,7 @@ from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource -from .completions import ( +from .completions.completions import ( Completions, AsyncCompletions, CompletionsWithRawResponse, diff --git a/src/openai/resources/chat/completions/__init__.py b/src/openai/resources/chat/completions/__init__.py new file mode 100644 index 0000000000..12d3b3aa28 --- /dev/null +++ b/src/openai/resources/chat/completions/__init__.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .messages import ( + Messages, + AsyncMessages, + MessagesWithRawResponse, + AsyncMessagesWithRawResponse, + MessagesWithStreamingResponse, + AsyncMessagesWithStreamingResponse, +) +from .completions import ( + Completions, + AsyncCompletions, + CompletionsWithRawResponse, + AsyncCompletionsWithRawResponse, + CompletionsWithStreamingResponse, + AsyncCompletionsWithStreamingResponse, +) + +__all__ = [ + "Messages", + "AsyncMessages", + "MessagesWithRawResponse", + "AsyncMessagesWithRawResponse", + "MessagesWithStreamingResponse", + "AsyncMessagesWithStreamingResponse", + "Completions", + "AsyncCompletions", + "CompletionsWithRawResponse", + "AsyncCompletionsWithRawResponse", + "CompletionsWithStreamingResponse", + "AsyncCompletionsWithStreamingResponse", +] diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions/completions.py similarity index 83% rename from src/openai/resources/chat/completions.py rename to src/openai/resources/chat/completions/completions.py index cc839103a0..1753f6c990 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions/completions.py @@ -9,40 +9,56 @@ import httpx import pydantic -from ... import _legacy_response -from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ..._utils import ( +from .... import _legacy_response +from .messages import ( + Messages, + AsyncMessages, + MessagesWithRawResponse, + AsyncMessagesWithRawResponse, + MessagesWithStreamingResponse, + AsyncMessagesWithStreamingResponse, +) +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ...._utils import ( required_args, maybe_transform, async_maybe_transform, ) -from ..._compat import cached_property -from ..._resource import SyncAPIResource, AsyncAPIResource -from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper -from ..._streaming import Stream, AsyncStream -from ...types.chat import ( +from ...._compat import cached_property +from ...._resource import SyncAPIResource, AsyncAPIResource +from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ...._streaming import Stream, AsyncStream +from ....pagination import SyncCursorPage, AsyncCursorPage +from ....types.chat import ( ChatCompletionAudioParam, ChatCompletionReasoningEffort, + completion_list_params, completion_create_params, + completion_update_params, ) -from ..._base_client import make_request_options -from ...types.chat_model import ChatModel -from ...types.chat.chat_completion import ChatCompletion -from ...types.shared_params.metadata import Metadata -from ...types.chat.chat_completion_chunk import ChatCompletionChunk -from ...types.chat.chat_completion_modality import ChatCompletionModality -from ...types.chat.chat_completion_tool_param import ChatCompletionToolParam -from ...types.chat.chat_completion_audio_param import ChatCompletionAudioParam -from ...types.chat.chat_completion_message_param import ChatCompletionMessageParam -from ...types.chat.chat_completion_reasoning_effort import ChatCompletionReasoningEffort -from ...types.chat.chat_completion_stream_options_param import ChatCompletionStreamOptionsParam -from ...types.chat.chat_completion_prediction_content_param import ChatCompletionPredictionContentParam -from ...types.chat.chat_completion_tool_choice_option_param import ChatCompletionToolChoiceOptionParam +from ...._base_client import AsyncPaginator, make_request_options +from ....types.chat_model import ChatModel +from ....types.chat.chat_completion import ChatCompletion +from ....types.shared_params.metadata import Metadata +from ....types.chat.chat_completion_chunk import ChatCompletionChunk +from ....types.chat.chat_completion_deleted import ChatCompletionDeleted +from ....types.chat.chat_completion_modality import ChatCompletionModality +from ....types.chat.chat_completion_tool_param import ChatCompletionToolParam +from ....types.chat.chat_completion_audio_param import ChatCompletionAudioParam +from ....types.chat.chat_completion_message_param import ChatCompletionMessageParam +from ....types.chat.chat_completion_reasoning_effort import ChatCompletionReasoningEffort +from ....types.chat.chat_completion_stream_options_param import ChatCompletionStreamOptionsParam +from ....types.chat.chat_completion_prediction_content_param import ChatCompletionPredictionContentParam +from ....types.chat.chat_completion_tool_choice_option_param import ChatCompletionToolChoiceOptionParam __all__ = ["Completions", "AsyncCompletions"] class Completions(SyncAPIResource): + @cached_property + def messages(self) -> Messages: + return Messages(self._client) + @cached_property def with_raw_response(self) -> CompletionsWithRawResponse: """ @@ -905,8 +921,192 @@ def create( stream_cls=Stream[ChatCompletionChunk], ) + def retrieve( + self, + completion_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> ChatCompletion: + """Get a stored chat completion. + + Only chat completions that have been created with + the `store` parameter set to `true` will be returned. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not completion_id: + raise ValueError(f"Expected a non-empty value for `completion_id` but received {completion_id!r}") + return self._get( + f"/chat/completions/{completion_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ChatCompletion, + ) + + def update( + self, + completion_id: str, + *, + metadata: Optional[Metadata], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> ChatCompletion: + """Modify a stored chat completion. + + Only chat completions that have been created + with the `store` parameter set to `true` can be modified. Currently, the only + supported modification is to update the `metadata` field. + + Args: + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not completion_id: + raise ValueError(f"Expected a non-empty value for `completion_id` but received {completion_id!r}") + return self._post( + f"/chat/completions/{completion_id}", + body=maybe_transform({"metadata": metadata}, completion_update_params.CompletionUpdateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ChatCompletion, + ) + + def list( + self, + *, + after: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + model: str | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> SyncCursorPage[ChatCompletion]: + """List stored chat completions. + + Only chat completions that have been stored with + the `store` parameter set to `true` will be returned. + + Args: + after: Identifier for the last chat completion from the previous pagination request. + + limit: Number of chat completions to retrieve. + + metadata: + A list of metadata keys to filter the chat completions by. Example: + + `metadata[key1]=value1&metadata[key2]=value2` + + model: The model used to generate the chat completions. + + order: Sort order for chat completions by timestamp. Use `asc` for ascending order or + `desc` for descending order. Defaults to `asc`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get_api_list( + "/chat/completions", + page=SyncCursorPage[ChatCompletion], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "limit": limit, + "metadata": metadata, + "model": model, + "order": order, + }, + completion_list_params.CompletionListParams, + ), + ), + model=ChatCompletion, + ) + + def delete( + self, + completion_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> ChatCompletionDeleted: + """Delete a stored chat completion. + + Only chat completions that have been created + with the `store` parameter set to `true` can be deleted. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not completion_id: + raise ValueError(f"Expected a non-empty value for `completion_id` but received {completion_id!r}") + return self._delete( + f"/chat/completions/{completion_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ChatCompletionDeleted, + ) + class AsyncCompletions(AsyncAPIResource): + @cached_property + def messages(self) -> AsyncMessages: + return AsyncMessages(self._client) + @cached_property def with_raw_response(self) -> AsyncCompletionsWithRawResponse: """ @@ -1769,6 +1969,186 @@ async def create( stream_cls=AsyncStream[ChatCompletionChunk], ) + async def retrieve( + self, + completion_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> ChatCompletion: + """Get a stored chat completion. + + Only chat completions that have been created with + the `store` parameter set to `true` will be returned. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not completion_id: + raise ValueError(f"Expected a non-empty value for `completion_id` but received {completion_id!r}") + return await self._get( + f"/chat/completions/{completion_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ChatCompletion, + ) + + async def update( + self, + completion_id: str, + *, + metadata: Optional[Metadata], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> ChatCompletion: + """Modify a stored chat completion. + + Only chat completions that have been created + with the `store` parameter set to `true` can be modified. Currently, the only + supported modification is to update the `metadata` field. + + Args: + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not completion_id: + raise ValueError(f"Expected a non-empty value for `completion_id` but received {completion_id!r}") + return await self._post( + f"/chat/completions/{completion_id}", + body=await async_maybe_transform({"metadata": metadata}, completion_update_params.CompletionUpdateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ChatCompletion, + ) + + def list( + self, + *, + after: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + model: str | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncPaginator[ChatCompletion, AsyncCursorPage[ChatCompletion]]: + """List stored chat completions. + + Only chat completions that have been stored with + the `store` parameter set to `true` will be returned. + + Args: + after: Identifier for the last chat completion from the previous pagination request. + + limit: Number of chat completions to retrieve. + + metadata: + A list of metadata keys to filter the chat completions by. Example: + + `metadata[key1]=value1&metadata[key2]=value2` + + model: The model used to generate the chat completions. + + order: Sort order for chat completions by timestamp. Use `asc` for ascending order or + `desc` for descending order. Defaults to `asc`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get_api_list( + "/chat/completions", + page=AsyncCursorPage[ChatCompletion], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "limit": limit, + "metadata": metadata, + "model": model, + "order": order, + }, + completion_list_params.CompletionListParams, + ), + ), + model=ChatCompletion, + ) + + async def delete( + self, + completion_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> ChatCompletionDeleted: + """Delete a stored chat completion. + + Only chat completions that have been created + with the `store` parameter set to `true` can be deleted. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not completion_id: + raise ValueError(f"Expected a non-empty value for `completion_id` but received {completion_id!r}") + return await self._delete( + f"/chat/completions/{completion_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=ChatCompletionDeleted, + ) + class CompletionsWithRawResponse: def __init__(self, completions: Completions) -> None: @@ -1777,6 +2157,22 @@ def __init__(self, completions: Completions) -> None: self.create = _legacy_response.to_raw_response_wrapper( completions.create, ) + self.retrieve = _legacy_response.to_raw_response_wrapper( + completions.retrieve, + ) + self.update = _legacy_response.to_raw_response_wrapper( + completions.update, + ) + self.list = _legacy_response.to_raw_response_wrapper( + completions.list, + ) + self.delete = _legacy_response.to_raw_response_wrapper( + completions.delete, + ) + + @cached_property + def messages(self) -> MessagesWithRawResponse: + return MessagesWithRawResponse(self._completions.messages) class AsyncCompletionsWithRawResponse: @@ -1786,6 +2182,22 @@ def __init__(self, completions: AsyncCompletions) -> None: self.create = _legacy_response.async_to_raw_response_wrapper( completions.create, ) + self.retrieve = _legacy_response.async_to_raw_response_wrapper( + completions.retrieve, + ) + self.update = _legacy_response.async_to_raw_response_wrapper( + completions.update, + ) + self.list = _legacy_response.async_to_raw_response_wrapper( + completions.list, + ) + self.delete = _legacy_response.async_to_raw_response_wrapper( + completions.delete, + ) + + @cached_property + def messages(self) -> AsyncMessagesWithRawResponse: + return AsyncMessagesWithRawResponse(self._completions.messages) class CompletionsWithStreamingResponse: @@ -1795,6 +2207,22 @@ def __init__(self, completions: Completions) -> None: self.create = to_streamed_response_wrapper( completions.create, ) + self.retrieve = to_streamed_response_wrapper( + completions.retrieve, + ) + self.update = to_streamed_response_wrapper( + completions.update, + ) + self.list = to_streamed_response_wrapper( + completions.list, + ) + self.delete = to_streamed_response_wrapper( + completions.delete, + ) + + @cached_property + def messages(self) -> MessagesWithStreamingResponse: + return MessagesWithStreamingResponse(self._completions.messages) class AsyncCompletionsWithStreamingResponse: @@ -1804,6 +2232,22 @@ def __init__(self, completions: AsyncCompletions) -> None: self.create = async_to_streamed_response_wrapper( completions.create, ) + self.retrieve = async_to_streamed_response_wrapper( + completions.retrieve, + ) + self.update = async_to_streamed_response_wrapper( + completions.update, + ) + self.list = async_to_streamed_response_wrapper( + completions.list, + ) + self.delete = async_to_streamed_response_wrapper( + completions.delete, + ) + + @cached_property + def messages(self) -> AsyncMessagesWithStreamingResponse: + return AsyncMessagesWithStreamingResponse(self._completions.messages) def validate_response_format(response_format: object) -> None: diff --git a/src/openai/resources/chat/completions/messages.py b/src/openai/resources/chat/completions/messages.py new file mode 100644 index 0000000000..b71d670927 --- /dev/null +++ b/src/openai/resources/chat/completions/messages.py @@ -0,0 +1,212 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal + +import httpx + +from .... import _legacy_response +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ...._utils import maybe_transform +from ...._compat import cached_property +from ...._resource import SyncAPIResource, AsyncAPIResource +from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ....pagination import SyncCursorPage, AsyncCursorPage +from ...._base_client import AsyncPaginator, make_request_options +from ....types.chat.completions import message_list_params +from ....types.chat.chat_completion_store_message import ChatCompletionStoreMessage + +__all__ = ["Messages", "AsyncMessages"] + + +class Messages(SyncAPIResource): + @cached_property + def with_raw_response(self) -> MessagesWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return MessagesWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> MessagesWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return MessagesWithStreamingResponse(self) + + def list( + self, + completion_id: str, + *, + after: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> SyncCursorPage[ChatCompletionStoreMessage]: + """Get the messages in a stored chat completion. + + Only chat completions that have + been created with the `store` parameter set to `true` will be returned. + + Args: + after: Identifier for the last message from the previous pagination request. + + limit: Number of messages to retrieve. + + order: Sort order for messages by timestamp. Use `asc` for ascending order or `desc` + for descending order. Defaults to `asc`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not completion_id: + raise ValueError(f"Expected a non-empty value for `completion_id` but received {completion_id!r}") + return self._get_api_list( + f"/chat/completions/{completion_id}/messages", + page=SyncCursorPage[ChatCompletionStoreMessage], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "limit": limit, + "order": order, + }, + message_list_params.MessageListParams, + ), + ), + model=ChatCompletionStoreMessage, + ) + + +class AsyncMessages(AsyncAPIResource): + @cached_property + def with_raw_response(self) -> AsyncMessagesWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return AsyncMessagesWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncMessagesWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return AsyncMessagesWithStreamingResponse(self) + + def list( + self, + completion_id: str, + *, + after: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncPaginator[ChatCompletionStoreMessage, AsyncCursorPage[ChatCompletionStoreMessage]]: + """Get the messages in a stored chat completion. + + Only chat completions that have + been created with the `store` parameter set to `true` will be returned. + + Args: + after: Identifier for the last message from the previous pagination request. + + limit: Number of messages to retrieve. + + order: Sort order for messages by timestamp. Use `asc` for ascending order or `desc` + for descending order. Defaults to `asc`. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not completion_id: + raise ValueError(f"Expected a non-empty value for `completion_id` but received {completion_id!r}") + return self._get_api_list( + f"/chat/completions/{completion_id}/messages", + page=AsyncCursorPage[ChatCompletionStoreMessage], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "limit": limit, + "order": order, + }, + message_list_params.MessageListParams, + ), + ), + model=ChatCompletionStoreMessage, + ) + + +class MessagesWithRawResponse: + def __init__(self, messages: Messages) -> None: + self._messages = messages + + self.list = _legacy_response.to_raw_response_wrapper( + messages.list, + ) + + +class AsyncMessagesWithRawResponse: + def __init__(self, messages: AsyncMessages) -> None: + self._messages = messages + + self.list = _legacy_response.async_to_raw_response_wrapper( + messages.list, + ) + + +class MessagesWithStreamingResponse: + def __init__(self, messages: Messages) -> None: + self._messages = messages + + self.list = to_streamed_response_wrapper( + messages.list, + ) + + +class AsyncMessagesWithStreamingResponse: + def __init__(self, messages: AsyncMessages) -> None: + self._messages = messages + + self.list = async_to_streamed_response_wrapper( + messages.list, + ) diff --git a/src/openai/types/chat/__init__.py b/src/openai/types/chat/__init__.py index c623a982af..b4f43b298f 100644 --- a/src/openai/types/chat/__init__.py +++ b/src/openai/types/chat/__init__.py @@ -6,14 +6,17 @@ from .chat_completion_role import ChatCompletionRole as ChatCompletionRole from .chat_completion_audio import ChatCompletionAudio as ChatCompletionAudio from .chat_completion_chunk import ChatCompletionChunk as ChatCompletionChunk +from .completion_list_params import CompletionListParams as CompletionListParams from .parsed_chat_completion import ( ParsedChoice as ParsedChoice, ParsedChatCompletion as ParsedChatCompletion, ParsedChatCompletionMessage as ParsedChatCompletionMessage, ) +from .chat_completion_deleted import ChatCompletionDeleted as ChatCompletionDeleted from .chat_completion_message import ChatCompletionMessage as ChatCompletionMessage from .chat_completion_modality import ChatCompletionModality as ChatCompletionModality from .completion_create_params import CompletionCreateParams as CompletionCreateParams +from .completion_update_params import CompletionUpdateParams as CompletionUpdateParams from .parsed_function_tool_call import ( ParsedFunction as ParsedFunction, ParsedFunctionToolCall as ParsedFunctionToolCall, @@ -21,6 +24,7 @@ from .chat_completion_tool_param import ChatCompletionToolParam as ChatCompletionToolParam from .chat_completion_audio_param import ChatCompletionAudioParam as ChatCompletionAudioParam from .chat_completion_message_param import ChatCompletionMessageParam as ChatCompletionMessageParam +from .chat_completion_store_message import ChatCompletionStoreMessage as ChatCompletionStoreMessage from .chat_completion_token_logprob import ChatCompletionTokenLogprob as ChatCompletionTokenLogprob from .chat_completion_reasoning_effort import ChatCompletionReasoningEffort as ChatCompletionReasoningEffort from .chat_completion_message_tool_call import ChatCompletionMessageToolCall as ChatCompletionMessageToolCall diff --git a/src/openai/types/chat/chat_completion_deleted.py b/src/openai/types/chat/chat_completion_deleted.py new file mode 100644 index 0000000000..0a541cb23d --- /dev/null +++ b/src/openai/types/chat/chat_completion_deleted.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ChatCompletionDeleted"] + + +class ChatCompletionDeleted(BaseModel): + id: str + """The ID of the chat completion that was deleted.""" + + deleted: bool + """Whether the chat completion was deleted.""" + + object: Literal["chat.completion.deleted"] + """The type of object being deleted.""" diff --git a/src/openai/types/chat/chat_completion_store_message.py b/src/openai/types/chat/chat_completion_store_message.py new file mode 100644 index 0000000000..95adc08af8 --- /dev/null +++ b/src/openai/types/chat/chat_completion_store_message.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +from .chat_completion_message import ChatCompletionMessage + +__all__ = ["ChatCompletionStoreMessage"] + + +class ChatCompletionStoreMessage(ChatCompletionMessage): + id: str + """The identifier of the chat message.""" diff --git a/src/openai/types/chat/completion_list_params.py b/src/openai/types/chat/completion_list_params.py new file mode 100644 index 0000000000..a8fce900ce --- /dev/null +++ b/src/openai/types/chat/completion_list_params.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, TypedDict + +from ..shared_params.metadata import Metadata + +__all__ = ["CompletionListParams"] + + +class CompletionListParams(TypedDict, total=False): + after: str + """Identifier for the last chat completion from the previous pagination request.""" + + limit: int + """Number of chat completions to retrieve.""" + + metadata: Optional[Metadata] + """A list of metadata keys to filter the chat completions by. Example: + + `metadata[key1]=value1&metadata[key2]=value2` + """ + + model: str + """The model used to generate the chat completions.""" + + order: Literal["asc", "desc"] + """Sort order for chat completions by timestamp. + + Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`. + """ diff --git a/src/openai/types/chat/completion_update_params.py b/src/openai/types/chat/completion_update_params.py new file mode 100644 index 0000000000..fc71733f07 --- /dev/null +++ b/src/openai/types/chat/completion_update_params.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Required, TypedDict + +from ..shared_params.metadata import Metadata + +__all__ = ["CompletionUpdateParams"] + + +class CompletionUpdateParams(TypedDict, total=False): + metadata: Required[Optional[Metadata]] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + """ diff --git a/src/openai/types/chat/completions/__init__.py b/src/openai/types/chat/completions/__init__.py new file mode 100644 index 0000000000..b8e62d6a64 --- /dev/null +++ b/src/openai/types/chat/completions/__init__.py @@ -0,0 +1,5 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .message_list_params import MessageListParams as MessageListParams diff --git a/src/openai/types/chat/completions/message_list_params.py b/src/openai/types/chat/completions/message_list_params.py new file mode 100644 index 0000000000..4e694e83ea --- /dev/null +++ b/src/openai/types/chat/completions/message_list_params.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, TypedDict + +__all__ = ["MessageListParams"] + + +class MessageListParams(TypedDict, total=False): + after: str + """Identifier for the last message from the previous pagination request.""" + + limit: int + """Number of messages to retrieve.""" + + order: Literal["asc", "desc"] + """Sort order for messages by timestamp. + + Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`. + """ diff --git a/src/openai/types/moderation.py b/src/openai/types/moderation.py index e4ec182ce2..608f562218 100644 --- a/src/openai/types/moderation.py +++ b/src/openai/types/moderation.py @@ -1,6 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing import List +from typing import List, Optional from typing_extensions import Literal from pydantic import Field as FieldInfo @@ -38,14 +38,14 @@ class Categories(BaseModel): orientation, disability status, or caste. """ - illicit: bool + illicit: Optional[bool] = None """ Content that includes instructions or advice that facilitate the planning or execution of wrongdoing, or that gives advice or instruction on how to commit illicit acts. For example, "how to shoplift" would fit this category. """ - illicit_violent: bool = FieldInfo(alias="illicit/violent") + illicit_violent: Optional[bool] = FieldInfo(alias="illicit/violent", default=None) """ Content that includes instructions or advice that facilitate the planning or execution of wrongdoing that also includes violence, or that gives advice or diff --git a/tests/api_resources/chat/completions/__init__.py b/tests/api_resources/chat/completions/__init__.py new file mode 100644 index 0000000000..fd8019a9a1 --- /dev/null +++ b/tests/api_resources/chat/completions/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/chat/completions/test_messages.py b/tests/api_resources/chat/completions/test_messages.py new file mode 100644 index 0000000000..5caac9ec6c --- /dev/null +++ b/tests/api_resources/chat/completions/test_messages.py @@ -0,0 +1,119 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai.pagination import SyncCursorPage, AsyncCursorPage +from openai.types.chat import ChatCompletionStoreMessage + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") + + +class TestMessages: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + def test_method_list(self, client: OpenAI) -> None: + message = client.chat.completions.messages.list( + completion_id="completion_id", + ) + assert_matches_type(SyncCursorPage[ChatCompletionStoreMessage], message, path=["response"]) + + @parametrize + def test_method_list_with_all_params(self, client: OpenAI) -> None: + message = client.chat.completions.messages.list( + completion_id="completion_id", + after="after", + limit=0, + order="asc", + ) + assert_matches_type(SyncCursorPage[ChatCompletionStoreMessage], message, path=["response"]) + + @parametrize + def test_raw_response_list(self, client: OpenAI) -> None: + response = client.chat.completions.messages.with_raw_response.list( + completion_id="completion_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + message = response.parse() + assert_matches_type(SyncCursorPage[ChatCompletionStoreMessage], message, path=["response"]) + + @parametrize + def test_streaming_response_list(self, client: OpenAI) -> None: + with client.chat.completions.messages.with_streaming_response.list( + completion_id="completion_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + message = response.parse() + assert_matches_type(SyncCursorPage[ChatCompletionStoreMessage], message, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_list(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `completion_id` but received ''"): + client.chat.completions.messages.with_raw_response.list( + completion_id="", + ) + + +class TestAsyncMessages: + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + async def test_method_list(self, async_client: AsyncOpenAI) -> None: + message = await async_client.chat.completions.messages.list( + completion_id="completion_id", + ) + assert_matches_type(AsyncCursorPage[ChatCompletionStoreMessage], message, path=["response"]) + + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: + message = await async_client.chat.completions.messages.list( + completion_id="completion_id", + after="after", + limit=0, + order="asc", + ) + assert_matches_type(AsyncCursorPage[ChatCompletionStoreMessage], message, path=["response"]) + + @parametrize + async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: + response = await async_client.chat.completions.messages.with_raw_response.list( + completion_id="completion_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + message = response.parse() + assert_matches_type(AsyncCursorPage[ChatCompletionStoreMessage], message, path=["response"]) + + @parametrize + async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: + async with async_client.chat.completions.messages.with_streaming_response.list( + completion_id="completion_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + message = await response.parse() + assert_matches_type(AsyncCursorPage[ChatCompletionStoreMessage], message, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_list(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `completion_id` but received ''"): + await async_client.chat.completions.messages.with_raw_response.list( + completion_id="", + ) diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index 25c9a36164..48b687a70e 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -10,8 +10,10 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type +from openai.pagination import SyncCursorPage, AsyncCursorPage from openai.types.chat import ( ChatCompletion, + ChatCompletionDeleted, ) base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") @@ -248,6 +250,160 @@ def test_streaming_response_create_overload_2(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_method_retrieve(self, client: OpenAI) -> None: + completion = client.chat.completions.retrieve( + "completion_id", + ) + assert_matches_type(ChatCompletion, completion, path=["response"]) + + @parametrize + def test_raw_response_retrieve(self, client: OpenAI) -> None: + response = client.chat.completions.with_raw_response.retrieve( + "completion_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + completion = response.parse() + assert_matches_type(ChatCompletion, completion, path=["response"]) + + @parametrize + def test_streaming_response_retrieve(self, client: OpenAI) -> None: + with client.chat.completions.with_streaming_response.retrieve( + "completion_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + completion = response.parse() + assert_matches_type(ChatCompletion, completion, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_retrieve(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `completion_id` but received ''"): + client.chat.completions.with_raw_response.retrieve( + "", + ) + + @parametrize + def test_method_update(self, client: OpenAI) -> None: + completion = client.chat.completions.update( + completion_id="completion_id", + metadata={"foo": "string"}, + ) + assert_matches_type(ChatCompletion, completion, path=["response"]) + + @parametrize + def test_raw_response_update(self, client: OpenAI) -> None: + response = client.chat.completions.with_raw_response.update( + completion_id="completion_id", + metadata={"foo": "string"}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + completion = response.parse() + assert_matches_type(ChatCompletion, completion, path=["response"]) + + @parametrize + def test_streaming_response_update(self, client: OpenAI) -> None: + with client.chat.completions.with_streaming_response.update( + completion_id="completion_id", + metadata={"foo": "string"}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + completion = response.parse() + assert_matches_type(ChatCompletion, completion, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_update(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `completion_id` but received ''"): + client.chat.completions.with_raw_response.update( + completion_id="", + metadata={"foo": "string"}, + ) + + @parametrize + def test_method_list(self, client: OpenAI) -> None: + completion = client.chat.completions.list() + assert_matches_type(SyncCursorPage[ChatCompletion], completion, path=["response"]) + + @parametrize + def test_method_list_with_all_params(self, client: OpenAI) -> None: + completion = client.chat.completions.list( + after="after", + limit=0, + metadata={"foo": "string"}, + model="model", + order="asc", + ) + assert_matches_type(SyncCursorPage[ChatCompletion], completion, path=["response"]) + + @parametrize + def test_raw_response_list(self, client: OpenAI) -> None: + response = client.chat.completions.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + completion = response.parse() + assert_matches_type(SyncCursorPage[ChatCompletion], completion, path=["response"]) + + @parametrize + def test_streaming_response_list(self, client: OpenAI) -> None: + with client.chat.completions.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + completion = response.parse() + assert_matches_type(SyncCursorPage[ChatCompletion], completion, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_method_delete(self, client: OpenAI) -> None: + completion = client.chat.completions.delete( + "completion_id", + ) + assert_matches_type(ChatCompletionDeleted, completion, path=["response"]) + + @parametrize + def test_raw_response_delete(self, client: OpenAI) -> None: + response = client.chat.completions.with_raw_response.delete( + "completion_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + completion = response.parse() + assert_matches_type(ChatCompletionDeleted, completion, path=["response"]) + + @parametrize + def test_streaming_response_delete(self, client: OpenAI) -> None: + with client.chat.completions.with_streaming_response.delete( + "completion_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + completion = response.parse() + assert_matches_type(ChatCompletionDeleted, completion, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_delete(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `completion_id` but received ''"): + client.chat.completions.with_raw_response.delete( + "", + ) + @parametrize def test_method_create_disallows_pydantic(self, client: OpenAI) -> None: class MyModel(pydantic.BaseModel): @@ -497,6 +653,160 @@ async def test_streaming_response_create_overload_2(self, async_client: AsyncOpe assert cast(Any, response.is_closed) is True + @parametrize + async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: + completion = await async_client.chat.completions.retrieve( + "completion_id", + ) + assert_matches_type(ChatCompletion, completion, path=["response"]) + + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: + response = await async_client.chat.completions.with_raw_response.retrieve( + "completion_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + completion = response.parse() + assert_matches_type(ChatCompletion, completion, path=["response"]) + + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: + async with async_client.chat.completions.with_streaming_response.retrieve( + "completion_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + completion = await response.parse() + assert_matches_type(ChatCompletion, completion, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `completion_id` but received ''"): + await async_client.chat.completions.with_raw_response.retrieve( + "", + ) + + @parametrize + async def test_method_update(self, async_client: AsyncOpenAI) -> None: + completion = await async_client.chat.completions.update( + completion_id="completion_id", + metadata={"foo": "string"}, + ) + assert_matches_type(ChatCompletion, completion, path=["response"]) + + @parametrize + async def test_raw_response_update(self, async_client: AsyncOpenAI) -> None: + response = await async_client.chat.completions.with_raw_response.update( + completion_id="completion_id", + metadata={"foo": "string"}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + completion = response.parse() + assert_matches_type(ChatCompletion, completion, path=["response"]) + + @parametrize + async def test_streaming_response_update(self, async_client: AsyncOpenAI) -> None: + async with async_client.chat.completions.with_streaming_response.update( + completion_id="completion_id", + metadata={"foo": "string"}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + completion = await response.parse() + assert_matches_type(ChatCompletion, completion, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_update(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `completion_id` but received ''"): + await async_client.chat.completions.with_raw_response.update( + completion_id="", + metadata={"foo": "string"}, + ) + + @parametrize + async def test_method_list(self, async_client: AsyncOpenAI) -> None: + completion = await async_client.chat.completions.list() + assert_matches_type(AsyncCursorPage[ChatCompletion], completion, path=["response"]) + + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: + completion = await async_client.chat.completions.list( + after="after", + limit=0, + metadata={"foo": "string"}, + model="model", + order="asc", + ) + assert_matches_type(AsyncCursorPage[ChatCompletion], completion, path=["response"]) + + @parametrize + async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: + response = await async_client.chat.completions.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + completion = response.parse() + assert_matches_type(AsyncCursorPage[ChatCompletion], completion, path=["response"]) + + @parametrize + async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: + async with async_client.chat.completions.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + completion = await response.parse() + assert_matches_type(AsyncCursorPage[ChatCompletion], completion, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_method_delete(self, async_client: AsyncOpenAI) -> None: + completion = await async_client.chat.completions.delete( + "completion_id", + ) + assert_matches_type(ChatCompletionDeleted, completion, path=["response"]) + + @parametrize + async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None: + response = await async_client.chat.completions.with_raw_response.delete( + "completion_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + completion = response.parse() + assert_matches_type(ChatCompletionDeleted, completion, path=["response"]) + + @parametrize + async def test_streaming_response_delete(self, async_client: AsyncOpenAI) -> None: + async with async_client.chat.completions.with_streaming_response.delete( + "completion_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + completion = await response.parse() + assert_matches_type(ChatCompletionDeleted, completion, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_delete(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `completion_id` but received ''"): + await async_client.chat.completions.with_raw_response.delete( + "", + ) + @parametrize async def test_method_create_disallows_pydantic(self, async_client: AsyncOpenAI) -> None: class MyModel(pydantic.BaseModel): diff --git a/tests/lib/test_azure.py b/tests/lib/test_azure.py index 626d7df311..a28aa8c2f6 100644 --- a/tests/lib/test_azure.py +++ b/tests/lib/test_azure.py @@ -153,7 +153,6 @@ def token_provider() -> str: class TestAzureLogging: - @pytest.fixture(autouse=True) def logger_with_filter(self) -> logging.Logger: logger = logging.getLogger("openai") @@ -165,9 +164,7 @@ def logger_with_filter(self) -> logging.Logger: def test_azure_api_key_redacted(self, respx_mock: MockRouter, caplog: pytest.LogCaptureFixture) -> None: respx_mock.post( "https://example-resource.azure.openai.com/openai/deployments/gpt-4/chat/completions?api-version=2024-06-01" - ).mock( - return_value=httpx.Response(200, json={"model": "gpt-4"}) - ) + ).mock(return_value=httpx.Response(200, json={"model": "gpt-4"})) client = AzureOpenAI( api_version="2024-06-01", @@ -182,14 +179,11 @@ def test_azure_api_key_redacted(self, respx_mock: MockRouter, caplog: pytest.Log if is_dict(record.args) and record.args.get("headers") and is_dict(record.args["headers"]): assert record.args["headers"]["api-key"] == "" - @pytest.mark.respx() def test_azure_bearer_token_redacted(self, respx_mock: MockRouter, caplog: pytest.LogCaptureFixture) -> None: respx_mock.post( "https://example-resource.azure.openai.com/openai/deployments/gpt-4/chat/completions?api-version=2024-06-01" - ).mock( - return_value=httpx.Response(200, json={"model": "gpt-4"}) - ) + ).mock(return_value=httpx.Response(200, json={"model": "gpt-4"})) client = AzureOpenAI( api_version="2024-06-01", @@ -204,15 +198,12 @@ def test_azure_bearer_token_redacted(self, respx_mock: MockRouter, caplog: pytes if is_dict(record.args) and record.args.get("headers") and is_dict(record.args["headers"]): assert record.args["headers"]["Authorization"] == "" - @pytest.mark.asyncio @pytest.mark.respx() async def test_azure_api_key_redacted_async(self, respx_mock: MockRouter, caplog: pytest.LogCaptureFixture) -> None: respx_mock.post( "https://example-resource.azure.openai.com/openai/deployments/gpt-4/chat/completions?api-version=2024-06-01" - ).mock( - return_value=httpx.Response(200, json={"model": "gpt-4"}) - ) + ).mock(return_value=httpx.Response(200, json={"model": "gpt-4"})) client = AsyncAzureOpenAI( api_version="2024-06-01", @@ -227,15 +218,14 @@ async def test_azure_api_key_redacted_async(self, respx_mock: MockRouter, caplog if is_dict(record.args) and record.args.get("headers") and is_dict(record.args["headers"]): assert record.args["headers"]["api-key"] == "" - @pytest.mark.asyncio @pytest.mark.respx() - async def test_azure_bearer_token_redacted_async(self, respx_mock: MockRouter, caplog: pytest.LogCaptureFixture) -> None: + async def test_azure_bearer_token_redacted_async( + self, respx_mock: MockRouter, caplog: pytest.LogCaptureFixture + ) -> None: respx_mock.post( "https://example-resource.azure.openai.com/openai/deployments/gpt-4/chat/completions?api-version=2024-06-01" - ).mock( - return_value=httpx.Response(200, json={"model": "gpt-4"}) - ) + ).mock(return_value=httpx.Response(200, json={"model": "gpt-4"})) client = AsyncAzureOpenAI( api_version="2024-06-01", diff --git a/tests/test_client.py b/tests/test_client.py index 41da2d5d04..62654afe1e 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -23,11 +23,13 @@ from openai import OpenAI, AsyncOpenAI, APIResponseValidationError from openai._types import Omit +from openai._utils import maybe_transform from openai._models import BaseModel, FinalRequestOptions from openai._constants import RAW_RESPONSE_HEADER from openai._streaming import Stream, AsyncStream from openai._exceptions import OpenAIError, APIStatusError, APITimeoutError, APIResponseValidationError from openai._base_client import DEFAULT_TIMEOUT, HTTPX_DEFAULT_TIMEOUT, BaseClient, make_request_options +from openai.types.chat.completion_create_params import CompletionCreateParamsNonStreaming from .utils import update_env @@ -724,14 +726,17 @@ def test_retrying_timeout_errors_doesnt_leak(self, respx_mock: MockRouter) -> No "/chat/completions", body=cast( object, - dict( - messages=[ - { - "role": "user", - "content": "Say this is a test", - } - ], - model="gpt-4o", + maybe_transform( + dict( + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-4o", + ), + CompletionCreateParamsNonStreaming, ), ), cast_to=httpx.Response, @@ -750,14 +755,17 @@ def test_retrying_status_errors_doesnt_leak(self, respx_mock: MockRouter) -> Non "/chat/completions", body=cast( object, - dict( - messages=[ - { - "role": "user", - "content": "Say this is a test", - } - ], - model="gpt-4o", + maybe_transform( + dict( + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-4o", + ), + CompletionCreateParamsNonStreaming, ), ), cast_to=httpx.Response, @@ -1591,14 +1599,17 @@ async def test_retrying_timeout_errors_doesnt_leak(self, respx_mock: MockRouter) "/chat/completions", body=cast( object, - dict( - messages=[ - { - "role": "user", - "content": "Say this is a test", - } - ], - model="gpt-4o", + maybe_transform( + dict( + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-4o", + ), + CompletionCreateParamsNonStreaming, ), ), cast_to=httpx.Response, @@ -1617,14 +1628,17 @@ async def test_retrying_status_errors_doesnt_leak(self, respx_mock: MockRouter) "/chat/completions", body=cast( object, - dict( - messages=[ - { - "role": "user", - "content": "Say this is a test", - } - ], - model="gpt-4o", + maybe_transform( + dict( + messages=[ + { + "role": "user", + "content": "Say this is a test", + } + ], + model="gpt-4o", + ), + CompletionCreateParamsNonStreaming, ), ), cast_to=httpx.Response, From 720ae54414f392202289578c9cc3b84cccc7432c Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 13 Feb 2025 19:45:55 +0000 Subject: [PATCH 690/816] release: 1.63.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index ccd8ea8be5..7b243c5918 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.62.0" + ".": "1.63.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 583fbd9add..361effb558 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.63.0 (2025-02-13) + +Full Changelog: [v1.62.0...v1.63.0](https://github.com/openai/openai-python/compare/v1.62.0...v1.63.0) + +### Features + +* **api:** add support for storing chat completions ([#2117](https://github.com/openai/openai-python/issues/2117)) ([2357a8f](https://github.com/openai/openai-python/commit/2357a8f97246a3fe17c6ac1fb0d7a67d6f1ffc1d)) + ## 1.62.0 (2025-02-12) Full Changelog: [v1.61.1...v1.62.0](https://github.com/openai/openai-python/compare/v1.61.1...v1.62.0) diff --git a/pyproject.toml b/pyproject.toml index 85cb145673..fed9f20ab3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.62.0" +version = "1.63.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 7dd5163b53..f58a5a5da8 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.62.0" # x-release-please-version +__version__ = "1.63.0" # x-release-please-version From a942394481e58a6f8b4a21f1b75af1ca6fcfd809 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 14 Feb 2025 11:11:51 +0000 Subject: [PATCH 691/816] chore(internal): temporary commit (#2121) --- .github/ISSUE_TEMPLATE/bug_report.yml | 64 ---------------------- .github/ISSUE_TEMPLATE/config.yml | 7 --- .github/ISSUE_TEMPLATE/feature_request.yml | 28 ---------- .github/pull_request_template.md | 10 ---- 4 files changed, 109 deletions(-) delete mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml delete mode 100644 .github/ISSUE_TEMPLATE/config.yml delete mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml delete mode 100644 .github/pull_request_template.md diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml deleted file mode 100644 index fa09dbe5b0..0000000000 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ /dev/null @@ -1,64 +0,0 @@ -name: Bug report -description: Report an issue or bug with this library -labels: ['bug'] -body: - - type: markdown - attributes: - value: | - Thanks for taking the time to fill out this bug report! - - type: checkboxes - id: non_api - attributes: - label: Confirm this is an issue with the Python library and not an underlying OpenAI API - description: Issues with the underlying OpenAI API should be reported on our [Developer Community](https://community.openai.com/c/api/7) - options: - - label: This is an issue with the Python library - required: true - - type: textarea - id: what-happened - attributes: - label: Describe the bug - description: A clear and concise description of what the bug is, and any additional context. - placeholder: Tell us what you see! - validations: - required: true - - type: textarea - id: repro-steps - attributes: - label: To Reproduce - description: Steps to reproduce the behavior. - placeholder: | - 1. Fetch a '...' - 2. Update the '....' - 3. See error - validations: - required: true - - type: textarea - id: code-snippets - attributes: - label: Code snippets - description: If applicable, add code snippets to help explain your problem. - render: Python - validations: - required: false - - type: input - id: os - attributes: - label: OS - placeholder: macOS - validations: - required: true - - type: input - id: language-version - attributes: - label: Python version - placeholder: Python v3.11.4 - validations: - required: true - - type: input - id: lib-version - attributes: - label: Library version - placeholder: openai v1.0.1 - validations: - required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml deleted file mode 100644 index 0498cf7f6f..0000000000 --- a/.github/ISSUE_TEMPLATE/config.yml +++ /dev/null @@ -1,7 +0,0 @@ -blank_issues_enabled: false -contact_links: - - name: OpenAI support - url: https://help.openai.com/ - about: | - Please only file issues here that you believe represent actual bugs or feature requests for the OpenAI Python library. - If you're having general trouble with the OpenAI API, please visit our help center to get support. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml deleted file mode 100644 index b529547d08..0000000000 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ /dev/null @@ -1,28 +0,0 @@ -name: Feature request -description: Suggest an idea for this library -labels: ['feature-request'] -body: - - type: markdown - attributes: - value: | - Thanks for taking the time to fill out this feature request! - - type: checkboxes - id: non_api - attributes: - label: Confirm this is a feature request for the Python library and not the underlying OpenAI API. - description: Feature requests for the underlying OpenAI API should be reported on our [Developer Community](https://community.openai.com/c/api/7) - options: - - label: This is a feature request for the Python library - required: true - - type: textarea - id: feature - attributes: - label: Describe the feature or improvement you're requesting - description: A clear and concise description of what you want to happen. - validations: - required: true - - type: textarea - id: context - attributes: - label: Additional context - description: Add any other context about the feature request here. diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md deleted file mode 100644 index 4416b1e547..0000000000 --- a/.github/pull_request_template.md +++ /dev/null @@ -1,10 +0,0 @@ - - - - - -- [ ] I understand that this repository is auto-generated and my pull request may not be merged - -## Changes being requested - -## Additional context & links From fea5e6b0dbc4353fcd35d5fcf11273347c4ee110 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 17 Feb 2025 05:04:23 +0000 Subject: [PATCH 692/816] release: 1.63.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 7b243c5918..d9c83dfafb 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.63.0" + ".": "1.63.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 361effb558..1bcb96c22c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.63.1 (2025-02-17) + +Full Changelog: [v1.63.0...v1.63.1](https://github.com/openai/openai-python/compare/v1.63.0...v1.63.1) + +### Chores + +* **internal:** temporary commit ([#2121](https://github.com/openai/openai-python/issues/2121)) ([f7f8361](https://github.com/openai/openai-python/commit/f7f83614c8da84c6725d60936f08f9f1a65f0a9e)) + ## 1.63.0 (2025-02-13) Full Changelog: [v1.62.0...v1.63.0](https://github.com/openai/openai-python/compare/v1.62.0...v1.63.0) diff --git a/pyproject.toml b/pyproject.toml index fed9f20ab3..0e90c2cad7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.63.0" +version = "1.63.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index f58a5a5da8..1d08feda0d 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.63.0" # x-release-please-version +__version__ = "1.63.1" # x-release-please-version From 7319e6e3f139d68173e03033f077732c4c4bdfa5 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Mon, 17 Feb 2025 13:08:59 +0000 Subject: [PATCH 693/816] chore(internal): revert temporary commit (#2121) --- .github/ISSUE_TEMPLATE/bug_report.yml | 64 ++++++++++++++++++++++ .github/ISSUE_TEMPLATE/config.yml | 7 +++ .github/ISSUE_TEMPLATE/feature_request.yml | 28 ++++++++++ .github/pull_request_template.md | 10 ++++ 4 files changed, 109 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml create mode 100644 .github/pull_request_template.md diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000000..fa09dbe5b0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,64 @@ +name: Bug report +description: Report an issue or bug with this library +labels: ['bug'] +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to fill out this bug report! + - type: checkboxes + id: non_api + attributes: + label: Confirm this is an issue with the Python library and not an underlying OpenAI API + description: Issues with the underlying OpenAI API should be reported on our [Developer Community](https://community.openai.com/c/api/7) + options: + - label: This is an issue with the Python library + required: true + - type: textarea + id: what-happened + attributes: + label: Describe the bug + description: A clear and concise description of what the bug is, and any additional context. + placeholder: Tell us what you see! + validations: + required: true + - type: textarea + id: repro-steps + attributes: + label: To Reproduce + description: Steps to reproduce the behavior. + placeholder: | + 1. Fetch a '...' + 2. Update the '....' + 3. See error + validations: + required: true + - type: textarea + id: code-snippets + attributes: + label: Code snippets + description: If applicable, add code snippets to help explain your problem. + render: Python + validations: + required: false + - type: input + id: os + attributes: + label: OS + placeholder: macOS + validations: + required: true + - type: input + id: language-version + attributes: + label: Python version + placeholder: Python v3.11.4 + validations: + required: true + - type: input + id: lib-version + attributes: + label: Library version + placeholder: openai v1.0.1 + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000..0498cf7f6f --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,7 @@ +blank_issues_enabled: false +contact_links: + - name: OpenAI support + url: https://help.openai.com/ + about: | + Please only file issues here that you believe represent actual bugs or feature requests for the OpenAI Python library. + If you're having general trouble with the OpenAI API, please visit our help center to get support. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000000..b529547d08 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,28 @@ +name: Feature request +description: Suggest an idea for this library +labels: ['feature-request'] +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to fill out this feature request! + - type: checkboxes + id: non_api + attributes: + label: Confirm this is a feature request for the Python library and not the underlying OpenAI API. + description: Feature requests for the underlying OpenAI API should be reported on our [Developer Community](https://community.openai.com/c/api/7) + options: + - label: This is a feature request for the Python library + required: true + - type: textarea + id: feature + attributes: + label: Describe the feature or improvement you're requesting + description: A clear and concise description of what you want to happen. + validations: + required: true + - type: textarea + id: context + attributes: + label: Additional context + description: Add any other context about the feature request here. diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000000..4416b1e547 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,10 @@ + + + + + +- [ ] I understand that this repository is auto-generated and my pull request may not be merged + +## Changes being requested + +## Additional context & links From 2e56c8da6f163db00a4ca362020148bb391edca9 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 17 Feb 2025 13:09:50 +0000 Subject: [PATCH 694/816] release: 1.63.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index d9c83dfafb..a9866d99a2 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.63.1" + ".": "1.63.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 1bcb96c22c..7ed87c5875 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.63.2 (2025-02-17) + +Full Changelog: [v1.63.1...v1.63.2](https://github.com/openai/openai-python/compare/v1.63.1...v1.63.2) + +### Chores + +* **internal:** revert temporary commit ([#2121](https://github.com/openai/openai-python/issues/2121)) ([72458ab](https://github.com/openai/openai-python/commit/72458abeed3dd95db8aabed94a33bb12a916f8b7)) + ## 1.63.1 (2025-02-17) Full Changelog: [v1.63.0...v1.63.1](https://github.com/openai/openai-python/compare/v1.63.0...v1.63.1) diff --git a/pyproject.toml b/pyproject.toml index 0e90c2cad7..453b3cea33 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.63.1" +version = "1.63.2" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 1d08feda0d..1f57a6db7e 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.63.1" # x-release-please-version +__version__ = "1.63.2" # x-release-please-version From 7cc9c9e95511e9d94f3e5ba913bf79623477e10d Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 20 Feb 2025 22:37:49 +0000 Subject: [PATCH 695/816] feat(client): allow passing `NotGiven` for body (#2135) fix(client): mark some request bodies as optional --- src/openai/_base_client.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 8a408d8e58..94a5edd010 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -520,7 +520,7 @@ def _build_request( # so that passing a `TypedDict` doesn't cause an error. # https://github.com/microsoft/pyright/issues/3526#event-6715453066 params=self.qs.stringify(cast(Mapping[str, Any], params)) if params else None, - json=json_data, + json=json_data if is_given(json_data) else None, files=files, **kwargs, ) From fe9eb8d1d4c2232aab342e7ae068319e255bf685 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 21 Feb 2025 15:08:25 +0000 Subject: [PATCH 696/816] chore(internal): fix devcontainers setup (#2137) --- .devcontainer/Dockerfile | 2 +- .devcontainer/devcontainer.json | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index ac9a2e7521..55d20255c9 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -6,4 +6,4 @@ USER vscode RUN curl -sSf https://rye.astral.sh/get | RYE_VERSION="0.35.0" RYE_INSTALL_OPTION="--yes" bash ENV PATH=/home/vscode/.rye/shims:$PATH -RUN echo "[[ -d .venv ]] && source .venv/bin/activate" >> /home/vscode/.bashrc +RUN echo "[[ -d .venv ]] && source .venv/bin/activate || export PATH=\$PATH" >> /home/vscode/.bashrc diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index bbeb30b148..c17fdc169f 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -24,6 +24,9 @@ } } } + }, + "features": { + "ghcr.io/devcontainers/features/node:1": {} } // Features to add to the dev container. More info: https://containers.dev/features. From 3e69750d47df4f0759d4a28ddc68e4b38756d9ca Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Sat, 22 Feb 2025 05:03:56 +0000 Subject: [PATCH 697/816] release: 1.64.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 18 ++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 21 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index a9866d99a2..7ef7bb772e 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.63.2" + ".": "1.64.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ed87c5875..1aa32a14bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,23 @@ # Changelog +## 1.64.0 (2025-02-22) + +Full Changelog: [v1.63.2...v1.64.0](https://github.com/openai/openai-python/compare/v1.63.2...v1.64.0) + +### Features + +* **client:** allow passing `NotGiven` for body ([#2135](https://github.com/openai/openai-python/issues/2135)) ([4451f56](https://github.com/openai/openai-python/commit/4451f5677f9eaad9b8fee74f71c2e5fe6785c420)) + + +### Bug Fixes + +* **client:** mark some request bodies as optional ([4451f56](https://github.com/openai/openai-python/commit/4451f5677f9eaad9b8fee74f71c2e5fe6785c420)) + + +### Chores + +* **internal:** fix devcontainers setup ([#2137](https://github.com/openai/openai-python/issues/2137)) ([4d88402](https://github.com/openai/openai-python/commit/4d884020cbeb1ca6093dd5317e3e5812551f7a46)) + ## 1.63.2 (2025-02-17) Full Changelog: [v1.63.1...v1.63.2](https://github.com/openai/openai-python/compare/v1.63.1...v1.63.2) diff --git a/pyproject.toml b/pyproject.toml index 453b3cea33..7cd583da3f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.63.2" +version = "1.64.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 1f57a6db7e..0a898ceeb8 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.63.2" # x-release-please-version +__version__ = "1.64.0" # x-release-please-version From 5bde5722f18e778abb896f9434fd52f0c4284e0a Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 25 Feb 2025 11:04:28 +0000 Subject: [PATCH 698/816] chore(internal): properly set __pydantic_private__ (#2144) --- src/openai/_base_client.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 94a5edd010..43dc9ab2a4 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -63,7 +63,7 @@ ModelBuilderProtocol, ) from ._utils import SensitiveHeadersFilter, is_dict, is_list, asyncify, is_given, lru_cache, is_mapping -from ._compat import model_copy, model_dump +from ._compat import PYDANTIC_V2, model_copy, model_dump from ._models import GenericModel, FinalRequestOptions, validate_type, construct_type from ._response import ( APIResponse, @@ -209,6 +209,9 @@ def _set_private_attributes( model: Type[_T], options: FinalRequestOptions, ) -> None: + if PYDANTIC_V2 and getattr(self, "__pydantic_private__", None) is None: + self.__pydantic_private__ = {} + self._model = model self._client = client self._options = options @@ -294,6 +297,9 @@ def _set_private_attributes( client: AsyncAPIClient, options: FinalRequestOptions, ) -> None: + if PYDANTIC_V2 and getattr(self, "__pydantic_private__", None) is None: + self.__pydantic_private__ = {} + self._model = model self._client = client self._options = options From 0c62bebe59c93921035459c77719d3d8ae23d0f5 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 27 Feb 2025 20:05:36 +0000 Subject: [PATCH 699/816] feat(api): add gpt-4.5-preview (#2149) --- .stats.yml | 2 +- src/openai/resources/beta/assistants.py | 4 +++ .../resources/beta/realtime/realtime.py | 36 +++++++++++-------- .../types/beta/assistant_update_params.py | 2 ++ src/openai/types/beta/realtime/session.py | 14 ++++++++ .../beta/realtime/session_create_params.py | 10 +++++- .../beta/realtime/session_update_event.py | 10 +++++- .../realtime/session_update_event_param.py | 10 +++++- src/openai/types/chat_model.py | 2 ++ src/openai/types/file_object.py | 3 ++ src/openai/types/upload.py | 2 +- .../beta/realtime/test_sessions.py | 2 ++ 12 files changed, 77 insertions(+), 20 deletions(-) diff --git a/.stats.yml b/.stats.yml index 658877d3b0..163146e38d 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 74 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-4aa6ee65ba9efc789e05e6a5ef0883b2cadf06def8efd863dbf75e9e233067e1.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-5d30684c3118d049682ea30cdb4dbef39b97d51667da484689193dc40162af32.yml diff --git a/src/openai/resources/beta/assistants.py b/src/openai/resources/beta/assistants.py index 462086f74b..d2bb8d7b92 100644 --- a/src/openai/resources/beta/assistants.py +++ b/src/openai/resources/beta/assistants.py @@ -232,6 +232,8 @@ def update( "gpt-4o-2024-05-13", "gpt-4o-mini", "gpt-4o-mini-2024-07-18", + "gpt-4.5-preview", + "gpt-4.5-preview-2025-02-27", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", @@ -673,6 +675,8 @@ async def update( "gpt-4o-2024-05-13", "gpt-4o-mini", "gpt-4o-mini-2024-07-18", + "gpt-4.5-preview", + "gpt-4.5-preview-2025-02-27", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", diff --git a/src/openai/resources/beta/realtime/realtime.py b/src/openai/resources/beta/realtime/realtime.py index 235790a9f5..0cf7c85799 100644 --- a/src/openai/resources/beta/realtime/realtime.py +++ b/src/openai/resources/beta/realtime/realtime.py @@ -561,14 +561,17 @@ def __init__(self, connection: RealtimeConnection) -> None: class RealtimeSessionResource(BaseRealtimeConnectionResource): def update(self, *, session: session_update_event_param.Session, event_id: str | NotGiven = NOT_GIVEN) -> None: - """Send this event to update the session’s default configuration. + """ + Send this event to update the session’s default configuration. + The client may send this event at any time to update any field, + except for `voice`. However, note that once a session has been + initialized with a particular `model`, it can’t be changed to + another model using `session.update`. - The client may - send this event at any time to update the session configuration, and any - field may be updated at any time, except for "voice". The server will respond - with a `session.updated` event that shows the full effective configuration. - Only fields that are present are updated, thus the correct way to clear a - field like "instructions" is to pass an empty string. + When the server receives a `session.update`, it will respond + with a `session.updated` event showing the full, effective configuration. + Only the fields that are present are updated. To clear a field like + `instructions`, pass an empty string. """ self._connection.send( cast( @@ -768,14 +771,17 @@ class AsyncRealtimeSessionResource(BaseAsyncRealtimeConnectionResource): async def update( self, *, session: session_update_event_param.Session, event_id: str | NotGiven = NOT_GIVEN ) -> None: - """Send this event to update the session’s default configuration. - - The client may - send this event at any time to update the session configuration, and any - field may be updated at any time, except for "voice". The server will respond - with a `session.updated` event that shows the full effective configuration. - Only fields that are present are updated, thus the correct way to clear a - field like "instructions" is to pass an empty string. + """ + Send this event to update the session’s default configuration. + The client may send this event at any time to update any field, + except for `voice`. However, note that once a session has been + initialized with a particular `model`, it can’t be changed to + another model using `session.update`. + + When the server receives a `session.update`, it will respond + with a `session.updated` event showing the full, effective configuration. + Only the fields that are present are updated. To clear a field like + `instructions`, pass an empty string. """ await self._connection.send( cast( diff --git a/src/openai/types/beta/assistant_update_params.py b/src/openai/types/beta/assistant_update_params.py index 80fec110cd..12a57a4063 100644 --- a/src/openai/types/beta/assistant_update_params.py +++ b/src/openai/types/beta/assistant_update_params.py @@ -45,6 +45,8 @@ class AssistantUpdateParams(TypedDict, total=False): "gpt-4o-2024-05-13", "gpt-4o-mini", "gpt-4o-mini-2024-07-18", + "gpt-4.5-preview", + "gpt-4.5-preview-2025-02-27", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-0125-preview", diff --git a/src/openai/types/beta/realtime/session.py b/src/openai/types/beta/realtime/session.py index 2d028f817c..aee20fa906 100644 --- a/src/openai/types/beta/realtime/session.py +++ b/src/openai/types/beta/realtime/session.py @@ -34,6 +34,20 @@ class Tool(BaseModel): class TurnDetection(BaseModel): + create_response: Optional[bool] = None + """Whether or not to automatically generate a response when a VAD stop event + occurs. + + `true` by default. + """ + + interrupt_response: Optional[bool] = None + """ + Whether or not to automatically interrupt any ongoing response with output to + the default conversation (i.e. `conversation` of `auto`) when a VAD start event + occurs. `true` by default. + """ + prefix_padding_ms: Optional[int] = None """Amount of audio to include before the VAD detected speech (in milliseconds). diff --git a/src/openai/types/beta/realtime/session_create_params.py b/src/openai/types/beta/realtime/session_create_params.py index 1502d83d39..bbc86d7c7d 100644 --- a/src/openai/types/beta/realtime/session_create_params.py +++ b/src/openai/types/beta/realtime/session_create_params.py @@ -146,11 +146,19 @@ class Tool(TypedDict, total=False): class TurnDetection(TypedDict, total=False): create_response: bool - """Whether or not to automatically generate a response when VAD is enabled. + """Whether or not to automatically generate a response when a VAD stop event + occurs. `true` by default. """ + interrupt_response: bool + """ + Whether or not to automatically interrupt any ongoing response with output to + the default conversation (i.e. `conversation` of `auto`) when a VAD start event + occurs. `true` by default. + """ + prefix_padding_ms: int """Amount of audio to include before the VAD detected speech (in milliseconds). diff --git a/src/openai/types/beta/realtime/session_update_event.py b/src/openai/types/beta/realtime/session_update_event.py index 62fb0a3998..999cd8d660 100644 --- a/src/openai/types/beta/realtime/session_update_event.py +++ b/src/openai/types/beta/realtime/session_update_event.py @@ -51,11 +51,19 @@ class SessionTool(BaseModel): class SessionTurnDetection(BaseModel): create_response: Optional[bool] = None - """Whether or not to automatically generate a response when VAD is enabled. + """Whether or not to automatically generate a response when a VAD stop event + occurs. `true` by default. """ + interrupt_response: Optional[bool] = None + """ + Whether or not to automatically interrupt any ongoing response with output to + the default conversation (i.e. `conversation` of `auto`) when a VAD start event + occurs. `true` by default. + """ + prefix_padding_ms: Optional[int] = None """Amount of audio to include before the VAD detected speech (in milliseconds). diff --git a/src/openai/types/beta/realtime/session_update_event_param.py b/src/openai/types/beta/realtime/session_update_event_param.py index 133cdd91a1..07fdba9d85 100644 --- a/src/openai/types/beta/realtime/session_update_event_param.py +++ b/src/openai/types/beta/realtime/session_update_event_param.py @@ -57,11 +57,19 @@ class SessionTool(TypedDict, total=False): class SessionTurnDetection(TypedDict, total=False): create_response: bool - """Whether or not to automatically generate a response when VAD is enabled. + """Whether or not to automatically generate a response when a VAD stop event + occurs. `true` by default. """ + interrupt_response: bool + """ + Whether or not to automatically interrupt any ongoing response with output to + the default conversation (i.e. `conversation` of `auto`) when a VAD start event + occurs. `true` by default. + """ + prefix_padding_ms: int """Amount of audio to include before the VAD detected speech (in milliseconds). diff --git a/src/openai/types/chat_model.py b/src/openai/types/chat_model.py index c191cb9734..6fe705a0b4 100644 --- a/src/openai/types/chat_model.py +++ b/src/openai/types/chat_model.py @@ -13,6 +13,8 @@ "o1-preview-2024-09-12", "o1-mini", "o1-mini-2024-09-12", + "gpt-4.5-preview", + "gpt-4.5-preview-2025-02-27", "gpt-4o", "gpt-4o-2024-11-20", "gpt-4o-2024-08-06", diff --git a/src/openai/types/file_object.py b/src/openai/types/file_object.py index 6e2bf310a4..1d65e6987d 100644 --- a/src/openai/types/file_object.py +++ b/src/openai/types/file_object.py @@ -40,6 +40,9 @@ class FileObject(BaseModel): `error`. """ + expires_at: Optional[int] = None + """The Unix timestamp (in seconds) for when the file will expire.""" + status_details: Optional[str] = None """Deprecated. diff --git a/src/openai/types/upload.py b/src/openai/types/upload.py index d8108c62f9..914b69a863 100644 --- a/src/openai/types/upload.py +++ b/src/openai/types/upload.py @@ -20,7 +20,7 @@ class Upload(BaseModel): """The Unix timestamp (in seconds) for when the Upload was created.""" expires_at: int - """The Unix timestamp (in seconds) for when the Upload was created.""" + """The Unix timestamp (in seconds) for when the Upload will expire.""" filename: str """The name of the file to be uploaded.""" diff --git a/tests/api_resources/beta/realtime/test_sessions.py b/tests/api_resources/beta/realtime/test_sessions.py index 5a17088ce6..5ea308ca0d 100644 --- a/tests/api_resources/beta/realtime/test_sessions.py +++ b/tests/api_resources/beta/realtime/test_sessions.py @@ -48,6 +48,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: ], turn_detection={ "create_response": True, + "interrupt_response": True, "prefix_padding_ms": 0, "silence_duration_ms": 0, "threshold": 0, @@ -112,6 +113,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> ], turn_detection={ "create_response": True, + "interrupt_response": True, "prefix_padding_ms": 0, "silence_duration_ms": 0, "threshold": 0, From 939c861263b2b6ed2d086b794261766ddf5b5f65 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 27 Feb 2025 20:07:02 +0000 Subject: [PATCH 700/816] release: 1.65.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 7ef7bb772e..045e3819b6 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.64.0" + ".": "1.65.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 1aa32a14bd..f6190ab04e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.65.0 (2025-02-27) + +Full Changelog: [v1.64.0...v1.65.0](https://github.com/openai/openai-python/compare/v1.64.0...v1.65.0) + +### Features + +* **api:** add gpt-4.5-preview ([#2149](https://github.com/openai/openai-python/issues/2149)) ([4cee52e](https://github.com/openai/openai-python/commit/4cee52e8d191b0532f28d86446da79b43a58b907)) + + +### Chores + +* **internal:** properly set __pydantic_private__ ([#2144](https://github.com/openai/openai-python/issues/2144)) ([2b1bd16](https://github.com/openai/openai-python/commit/2b1bd1604a038ded67367742a0b1c9d92e29dfc8)) + ## 1.64.0 (2025-02-22) Full Changelog: [v1.63.2...v1.64.0](https://github.com/openai/openai-python/compare/v1.63.2...v1.64.0) diff --git a/pyproject.toml b/pyproject.toml index 7cd583da3f..511da522a7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.64.0" +version = "1.65.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 0a898ceeb8..31af749758 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.64.0" # x-release-please-version +__version__ = "1.65.0" # x-release-please-version From 06d79fd2cc1edea9af81c8ba4304eefdd1195fc7 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 27 Feb 2025 22:01:07 +0000 Subject: [PATCH 701/816] docs: update URLs from stainlessapi.com to stainless.com (#2150) More details at https://www.stainless.com/changelog/stainless-com --- SECURITY.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index c54acaf331..3b3bd8a662 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,9 +2,9 @@ ## Reporting Security Issues -This SDK is generated by [Stainless Software Inc](http://stainlessapi.com). Stainless takes security seriously, and encourages you to report any security vulnerability promptly so that appropriate action can be taken. +This SDK is generated by [Stainless Software Inc](http://stainless.com). Stainless takes security seriously, and encourages you to report any security vulnerability promptly so that appropriate action can be taken. -To report a security issue, please contact the Stainless team at security@stainlessapi.com. +To report a security issue, please contact the Stainless team at security@stainless.com. ## Responsible Disclosure From 724f56c56487578692bec45fca79474e57516308 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 27 Feb 2025 22:01:57 +0000 Subject: [PATCH 702/816] release: 1.65.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 045e3819b6..57b589ea9e 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.65.0" + ".": "1.65.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index f6190ab04e..ac6f54aa21 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.65.1 (2025-02-27) + +Full Changelog: [v1.65.0...v1.65.1](https://github.com/openai/openai-python/compare/v1.65.0...v1.65.1) + +### Documentation + +* update URLs from stainlessapi.com to stainless.com ([#2150](https://github.com/openai/openai-python/issues/2150)) ([dee4298](https://github.com/openai/openai-python/commit/dee42986eff46dd23ba25b3e2a5bb7357aca39d9)) + ## 1.65.0 (2025-02-27) Full Changelog: [v1.64.0...v1.65.0](https://github.com/openai/openai-python/compare/v1.64.0...v1.65.0) diff --git a/pyproject.toml b/pyproject.toml index 511da522a7..13bd84e4f4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.65.0" +version = "1.65.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 31af749758..422c9a283d 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.65.0" # x-release-please-version +__version__ = "1.65.1" # x-release-please-version From ba2a8a0953c41dc1364221a2009f2a942e4d6f35 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 27 Feb 2025 22:51:14 +0000 Subject: [PATCH 703/816] chore(docs): update client docstring (#2152) --- src/openai/_client.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/openai/_client.py b/src/openai/_client.py index c784694f20..2464c6504c 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -97,7 +97,7 @@ def __init__( # part of our public interface in the future. _strict_response_validation: bool = False, ) -> None: - """Construct a new synchronous openai client instance. + """Construct a new synchronous OpenAI client instance. This automatically infers the following arguments from their corresponding environment variables if they are not provided: - `api_key` from `OPENAI_API_KEY` @@ -324,7 +324,7 @@ def __init__( # part of our public interface in the future. _strict_response_validation: bool = False, ) -> None: - """Construct a new async openai client instance. + """Construct a new async AsyncOpenAI client instance. This automatically infers the following arguments from their corresponding environment variables if they are not provided: - `api_key` from `OPENAI_API_KEY` From c98d7400785011e0f5de2e33c9bf4dec95332847 Mon Sep 17 00:00:00 2001 From: Krista Pratico Date: Fri, 28 Feb 2025 06:36:08 -0800 Subject: [PATCH 704/816] fix(azure): azure_deployment use with realtime + non-deployment-based APIs (#2154) * support realtime with azure_deployment * lint * use rsplit * switch approach: save copy of the original url * save azure_endpoint as it was given * docstring * format * remove unnecessary check + add test * fix for websocket_base_url * add another test --- src/openai/lib/azure.py | 67 ++- .../resources/beta/realtime/realtime.py | 36 +- tests/lib/test_azure.py | 563 ++++++++++++++++++ 3 files changed, 637 insertions(+), 29 deletions(-) diff --git a/src/openai/lib/azure.py b/src/openai/lib/azure.py index f857d76e51..ea7bd20d99 100644 --- a/src/openai/lib/azure.py +++ b/src/openai/lib/azure.py @@ -49,6 +49,9 @@ def __init__(self) -> None: class BaseAzureClient(BaseClient[_HttpxClientT, _DefaultStreamT]): + _azure_endpoint: httpx.URL | None + _azure_deployment: str | None + @override def _build_request( self, @@ -58,11 +61,29 @@ def _build_request( ) -> httpx.Request: if options.url in _deployments_endpoints and is_mapping(options.json_data): model = options.json_data.get("model") - if model is not None and not "/deployments" in str(self.base_url): + if model is not None and "/deployments" not in str(self.base_url.path): options.url = f"/deployments/{model}{options.url}" return super()._build_request(options, retries_taken=retries_taken) + @override + def _prepare_url(http://github.com/self,%20url:%20str) -> httpx.URL: + """Adjust the URL if the client was configured with an Azure endpoint + deployment + and the API feature being called is **not** a deployments-based endpoint + (i.e. requires /deployments/deployment-name in the URL path). + """ + if self._azure_deployment and self._azure_endpoint and url not in _deployments_endpoints: + merge_url = httpx.URL(url) + if merge_url.is_relative_url: + merge_raw_path = ( + self._azure_endpoint.raw_path.rstrip(b"/") + b"/openai/" + merge_url.raw_path.lstrip(b"/") + ) + return self._azure_endpoint.copy_with(raw_path=merge_raw_path) + + return merge_url + + return super()._prepare_http://github.com/url(url) + class AzureOpenAI(BaseAzureClient[httpx.Client, Stream[Any]], OpenAI): @overload @@ -160,8 +181,8 @@ def __init__( azure_ad_token_provider: A function that returns an Azure Active Directory token, will be invoked on every request. - azure_deployment: A model deployment, if given sets the base client URL to include `/deployments/{azure_deployment}`. - Note: this means you won't be able to use non-deployment endpoints. Not supported with Assistants APIs. + azure_deployment: A model deployment, if given with `azure_endpoint`, sets the base client URL to include `/deployments/{azure_deployment}`. + Not supported with Assistants APIs. """ if api_key is None: api_key = os.environ.get("AZURE_OPENAI_API_KEY") @@ -224,6 +245,8 @@ def __init__( self._api_version = api_version self._azure_ad_token = azure_ad_token self._azure_ad_token_provider = azure_ad_token_provider + self._azure_deployment = azure_deployment if azure_endpoint else None + self._azure_endpoint = httpx.URL(azure_endpoint) if azure_endpoint else None @override def copy( @@ -307,12 +330,12 @@ def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions: return options - def _configure_realtime(self, model: str, extra_query: Query) -> tuple[Query, dict[str, str]]: + def _configure_realtime(self, model: str, extra_query: Query) -> tuple[httpx.URL, dict[str, str]]: auth_headers = {} query = { **extra_query, "api-version": self._api_version, - "deployment": model, + "deployment": self._azure_deployment or model, } if self.api_key != "": auth_headers = {"api-key": self.api_key} @@ -320,7 +343,17 @@ def _configure_realtime(self, model: str, extra_query: Query) -> tuple[Query, di token = self._get_azure_ad_token() if token: auth_headers = {"Authorization": f"Bearer {token}"} - return query, auth_headers + + if self.websocket_base_url is not None: + base_url = httpx.URL(self.websocket_base_url) + merge_raw_path = base_url.raw_path.rstrip(b"/") + b"/realtime" + realtime_url = base_url.copy_with(raw_path=merge_raw_path) + else: + base_url = self._prepare_url("http://github.com/realtime") + realtime_url = base_url.copy_with(scheme="wss") + + url = realtime_url.copy_with(params={**query}) + return url, auth_headers class AsyncAzureOpenAI(BaseAzureClient[httpx.AsyncClient, AsyncStream[Any]], AsyncOpenAI): @@ -422,8 +455,8 @@ def __init__( azure_ad_token_provider: A function that returns an Azure Active Directory token, will be invoked on every request. - azure_deployment: A model deployment, if given sets the base client URL to include `/deployments/{azure_deployment}`. - Note: this means you won't be able to use non-deployment endpoints. Not supported with Assistants APIs. + azure_deployment: A model deployment, if given with `azure_endpoint`, sets the base client URL to include `/deployments/{azure_deployment}`. + Not supported with Assistants APIs. """ if api_key is None: api_key = os.environ.get("AZURE_OPENAI_API_KEY") @@ -486,6 +519,8 @@ def __init__( self._api_version = api_version self._azure_ad_token = azure_ad_token self._azure_ad_token_provider = azure_ad_token_provider + self._azure_deployment = azure_deployment if azure_endpoint else None + self._azure_endpoint = httpx.URL(azure_endpoint) if azure_endpoint else None @override def copy( @@ -571,12 +606,12 @@ async def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOp return options - async def _configure_realtime(self, model: str, extra_query: Query) -> tuple[Query, dict[str, str]]: + async def _configure_realtime(self, model: str, extra_query: Query) -> tuple[httpx.URL, dict[str, str]]: auth_headers = {} query = { **extra_query, "api-version": self._api_version, - "deployment": model, + "deployment": self._azure_deployment or model, } if self.api_key != "": auth_headers = {"api-key": self.api_key} @@ -584,4 +619,14 @@ async def _configure_realtime(self, model: str, extra_query: Query) -> tuple[Que token = await self._get_azure_ad_token() if token: auth_headers = {"Authorization": f"Bearer {token}"} - return query, auth_headers + + if self.websocket_base_url is not None: + base_url = httpx.URL(self.websocket_base_url) + merge_raw_path = base_url.raw_path.rstrip(b"/") + b"/realtime" + realtime_url = base_url.copy_with(raw_path=merge_raw_path) + else: + base_url = self._prepare_url("http://github.com/realtime") + realtime_url = base_url.copy_with(scheme="wss") + + url = realtime_url.copy_with(params={**query}) + return url, auth_headers diff --git a/src/openai/resources/beta/realtime/realtime.py b/src/openai/resources/beta/realtime/realtime.py index 0cf7c85799..cd610d9089 100644 --- a/src/openai/resources/beta/realtime/realtime.py +++ b/src/openai/resources/beta/realtime/realtime.py @@ -324,15 +324,15 @@ async def __aenter__(self) -> AsyncRealtimeConnection: extra_query = self.__extra_query auth_headers = self.__client.auth_headers if is_async_azure_client(self.__client): - extra_query, auth_headers = await self.__client._configure_realtime(self.__model, extra_query) - - url = self._prepare_url().copy_with( - params={ - **self.__client.base_url.params, - "model": self.__model, - **extra_query, - }, - ) + url, auth_headers = await self.__client._configure_realtime(self.__model, extra_query) + else: + url = self._prepare_url().copy_with( + params={ + **self.__client.base_url.params, + "model": self.__model, + **extra_query, + }, + ) log.debug("Connecting to %s", url) if self.__websocket_connection_options: log.debug("Connection options: %s", self.__websocket_connection_options) @@ -506,15 +506,15 @@ def __enter__(self) -> RealtimeConnection: extra_query = self.__extra_query auth_headers = self.__client.auth_headers if is_azure_client(self.__client): - extra_query, auth_headers = self.__client._configure_realtime(self.__model, extra_query) - - url = self._prepare_url().copy_with( - params={ - **self.__client.base_url.params, - "model": self.__model, - **extra_query, - }, - ) + url, auth_headers = self.__client._configure_realtime(self.__model, extra_query) + else: + url = self._prepare_url().copy_with( + params={ + **self.__client.base_url.params, + "model": self.__model, + **extra_query, + }, + ) log.debug("Connecting to %s", url) if self.__websocket_connection_options: log.debug("Connection options: %s", self.__websocket_connection_options) diff --git a/tests/lib/test_azure.py b/tests/lib/test_azure.py index a28aa8c2f6..52c24eba27 100644 --- a/tests/lib/test_azure.py +++ b/tests/lib/test_azure.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import logging from typing import Union, cast from typing_extensions import Literal, Protocol @@ -239,3 +241,564 @@ async def test_azure_bearer_token_redacted_async( for record in caplog.records: if is_dict(record.args) and record.args.get("headers") and is_dict(record.args["headers"]): assert record.args["headers"]["Authorization"] == "" + + +@pytest.mark.parametrize( + "client,base_url,api,json_data,expected", + [ + # Deployment-based endpoints + # AzureOpenAI: No deployment specified + ( + AzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", + ), + "https://example-resource.azure.openai.com/openai/", + "/chat/completions", + {"model": "deployment-body"}, + "https://example-resource.azure.openai.com/openai/deployments/deployment-body/chat/completions?api-version=2024-02-01", + ), + # AzureOpenAI: Deployment specified + ( + AzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", + azure_deployment="deployment-client", + ), + "https://example-resource.azure.openai.com/openai/deployments/deployment-client/", + "/chat/completions", + {"model": "deployment-body"}, + "https://example-resource.azure.openai.com/openai/deployments/deployment-client/chat/completions?api-version=2024-02-01", + ), + # AzureOpenAI: "deployments" in the DNS name + ( + AzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://deployments.example-resource.azure.openai.com/", + ), + "https://deployments.example-resource.azure.openai.com/openai/", + "/chat/completions", + {"model": "deployment-body"}, + "https://deployments.example-resource.azure.openai.com/openai/deployments/deployment-body/chat/completions?api-version=2024-02-01", + ), + # AzureOpenAI: Deployment called deployments + ( + AzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", + azure_deployment="deployments", + ), + "https://example-resource.azure.openai.com/openai/deployments/deployments/", + "/chat/completions", + {"model": "deployment-body"}, + "https://example-resource.azure.openai.com/openai/deployments/deployments/chat/completions?api-version=2024-02-01", + ), + # AzureOpenAI: base_url and azure_deployment specified; ignored b/c not supported + ( + AzureOpenAI( # type: ignore + api_version="2024-02-01", + api_key="example API key", + base_url="https://example.azure-api.net/PTU/", + azure_deployment="deployment-client", + ), + "https://example.azure-api.net/PTU/", + "/chat/completions", + {"model": "deployment-body"}, + "https://example.azure-api.net/PTU/deployments/deployment-body/chat/completions?api-version=2024-02-01", + ), + # AsyncAzureOpenAI: No deployment specified + ( + AsyncAzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", + ), + "https://example-resource.azure.openai.com/openai/", + "/chat/completions", + {"model": "deployment-body"}, + "https://example-resource.azure.openai.com/openai/deployments/deployment-body/chat/completions?api-version=2024-02-01", + ), + # AsyncAzureOpenAI: Deployment specified + ( + AsyncAzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", + azure_deployment="deployment-client", + ), + "https://example-resource.azure.openai.com/openai/deployments/deployment-client/", + "/chat/completions", + {"model": "deployment-body"}, + "https://example-resource.azure.openai.com/openai/deployments/deployment-client/chat/completions?api-version=2024-02-01", + ), + # AsyncAzureOpenAI: "deployments" in the DNS name + ( + AsyncAzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://deployments.example-resource.azure.openai.com/", + ), + "https://deployments.example-resource.azure.openai.com/openai/", + "/chat/completions", + {"model": "deployment-body"}, + "https://deployments.example-resource.azure.openai.com/openai/deployments/deployment-body/chat/completions?api-version=2024-02-01", + ), + # AsyncAzureOpenAI: Deployment called deployments + ( + AsyncAzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", + azure_deployment="deployments", + ), + "https://example-resource.azure.openai.com/openai/deployments/deployments/", + "/chat/completions", + {"model": "deployment-body"}, + "https://example-resource.azure.openai.com/openai/deployments/deployments/chat/completions?api-version=2024-02-01", + ), + # AsyncAzureOpenAI: base_url and azure_deployment specified; azure_deployment ignored b/c not supported + ( + AsyncAzureOpenAI( # type: ignore + api_version="2024-02-01", + api_key="example API key", + base_url="https://example.azure-api.net/PTU/", + azure_deployment="deployment-client", + ), + "https://example.azure-api.net/PTU/", + "/chat/completions", + {"model": "deployment-body"}, + "https://example.azure-api.net/PTU/deployments/deployment-body/chat/completions?api-version=2024-02-01", + ), + ], +) +def test_prepare_url_deployment_endpoint( + client: Client, base_url: str, api: str, json_data: dict[str, str], expected: str +) -> None: + req = client._build_request( + FinalRequestOptions.construct( + method="post", + url=api, + json_data=json_data, + ) + ) + assert req.url == expected + assert client.base_url == base_url + + +@pytest.mark.parametrize( + "client,base_url,api,json_data,expected", + [ + # Non-deployment endpoints + # AzureOpenAI: No deployment specified + ( + AzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", + ), + "https://example-resource.azure.openai.com/openai/", + "/models", + {}, + "https://example-resource.azure.openai.com/openai/models?api-version=2024-02-01", + ), + # AzureOpenAI: No deployment specified + ( + AzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", + ), + "https://example-resource.azure.openai.com/openai/", + "/assistants", + {"model": "deployment-body"}, + "https://example-resource.azure.openai.com/openai/assistants?api-version=2024-02-01", + ), + # AzureOpenAI: Deployment specified + ( + AzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", + azure_deployment="deployment-client", + ), + "https://example-resource.azure.openai.com/openai/deployments/deployment-client/", + "/models", + {}, + "https://example-resource.azure.openai.com/openai/models?api-version=2024-02-01", + ), + # AzureOpenAI: Deployment specified + ( + AzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", + azure_deployment="deployment-client", + ), + "https://example-resource.azure.openai.com/openai/deployments/deployment-client/", + "/assistants", + {"model": "deployment-body"}, + "https://example-resource.azure.openai.com/openai/assistants?api-version=2024-02-01", + ), + # AzureOpenAI: "deployments" in the DNS name + ( + AzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://deployments.example-resource.azure.openai.com/", + ), + "https://deployments.example-resource.azure.openai.com/openai/", + "/models", + {}, + "https://deployments.example-resource.azure.openai.com/openai/models?api-version=2024-02-01", + ), + # AzureOpenAI: Deployment called "deployments" + ( + AzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", + azure_deployment="deployments", + ), + "https://example-resource.azure.openai.com/openai/deployments/deployments/", + "/models", + {}, + "https://example-resource.azure.openai.com/openai/models?api-version=2024-02-01", + ), + # AzureOpenAI: base_url and azure_deployment specified; azure_deployment ignored b/c not supported + ( + AzureOpenAI( # type: ignore + api_version="2024-02-01", + api_key="example API key", + base_url="https://example.azure-api.net/PTU/", + azure_deployment="deployment-client", + ), + "https://example.azure-api.net/PTU/", + "/models", + {}, + "https://example.azure-api.net/PTU/models?api-version=2024-02-01", + ), + # AsyncAzureOpenAI: No deployment specified + ( + AsyncAzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", + ), + "https://example-resource.azure.openai.com/openai/", + "/models", + {}, + "https://example-resource.azure.openai.com/openai/models?api-version=2024-02-01", + ), + # AsyncAzureOpenAI: No deployment specified + ( + AsyncAzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", + ), + "https://example-resource.azure.openai.com/openai/", + "/assistants", + {"model": "deployment-body"}, + "https://example-resource.azure.openai.com/openai/assistants?api-version=2024-02-01", + ), + # AsyncAzureOpenAI: Deployment specified + ( + AsyncAzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", + azure_deployment="deployment-client", + ), + "https://example-resource.azure.openai.com/openai/deployments/deployment-client/", + "/models", + {}, + "https://example-resource.azure.openai.com/openai/models?api-version=2024-02-01", + ), + # AsyncAzureOpenAI: Deployment specified + ( + AsyncAzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", + azure_deployment="deployment-client", + ), + "https://example-resource.azure.openai.com/openai/deployments/deployment-client/", + "/assistants", + {"model": "deployment-body"}, + "https://example-resource.azure.openai.com/openai/assistants?api-version=2024-02-01", + ), + # AsyncAzureOpenAI: "deployments" in the DNS name + ( + AsyncAzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://deployments.example-resource.azure.openai.com/", + ), + "https://deployments.example-resource.azure.openai.com/openai/", + "/models", + {}, + "https://deployments.example-resource.azure.openai.com/openai/models?api-version=2024-02-01", + ), + # AsyncAzureOpenAI: Deployment called "deployments" + ( + AsyncAzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", + azure_deployment="deployments", + ), + "https://example-resource.azure.openai.com/openai/deployments/deployments/", + "/models", + {}, + "https://example-resource.azure.openai.com/openai/models?api-version=2024-02-01", + ), + # AsyncAzureOpenAI: base_url and azure_deployment specified; azure_deployment ignored b/c not supported + ( + AsyncAzureOpenAI( # type: ignore + api_version="2024-02-01", + api_key="example API key", + base_url="https://example.azure-api.net/PTU/", + azure_deployment="deployment-client", + ), + "https://example.azure-api.net/PTU/", + "/models", + {}, + "https://example.azure-api.net/PTU/models?api-version=2024-02-01", + ), + ], +) +def test_prepare_url_nondeployment_endpoint( + client: Client, base_url: str, api: str, json_data: dict[str, str], expected: str +) -> None: + req = client._build_request( + FinalRequestOptions.construct( + method="post", + url=api, + json_data=json_data, + ) + ) + assert req.url == expected + assert client.base_url == base_url + + +@pytest.mark.parametrize( + "client,base_url,json_data,expected", + [ + # Realtime endpoint + # AzureOpenAI: No deployment specified + ( + AzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", + ), + "https://example-resource.azure.openai.com/openai/", + {"model": "deployment-body"}, + "wss://example-resource.azure.openai.com/openai/realtime?api-version=2024-02-01&deployment=deployment-body", + ), + # AzureOpenAI: Deployment specified + ( + AzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", + azure_deployment="deployment-client", + ), + "https://example-resource.azure.openai.com/openai/deployments/deployment-client/", + {"model": "deployment-body"}, + "wss://example-resource.azure.openai.com/openai/realtime?api-version=2024-02-01&deployment=deployment-client", + ), + # AzureOpenAI: "deployments" in the DNS name + ( + AzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://deployments.azure.openai.com/", + ), + "https://deployments.azure.openai.com/openai/", + {"model": "deployment-body"}, + "wss://deployments.azure.openai.com/openai/realtime?api-version=2024-02-01&deployment=deployment-body", + ), + # AzureOpenAI: Deployment called "deployments" + ( + AzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", + azure_deployment="deployments", + ), + "https://example-resource.azure.openai.com/openai/deployments/deployments/", + {"model": "deployment-body"}, + "wss://example-resource.azure.openai.com/openai/realtime?api-version=2024-02-01&deployment=deployments", + ), + # AzureOpenAI: base_url and azure_deployment specified; azure_deployment ignored b/c not supported + ( + AzureOpenAI( # type: ignore + api_version="2024-02-01", + api_key="example API key", + base_url="https://example.azure-api.net/PTU/", + azure_deployment="my-deployment", + ), + "https://example.azure-api.net/PTU/", + {"model": "deployment-body"}, + "wss://example.azure-api.net/PTU/realtime?api-version=2024-02-01&deployment=deployment-body", + ), + # AzureOpenAI: websocket_base_url specified + ( + AzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", + websocket_base_url="wss://example-resource.azure.openai.com/base", + ), + "https://example-resource.azure.openai.com/openai/", + {"model": "deployment-body"}, + "wss://example-resource.azure.openai.com/base/realtime?api-version=2024-02-01&deployment=deployment-body", + ), + ], +) +def test_prepare_url_realtime(client: AzureOpenAI, base_url: str, json_data: dict[str, str], expected: str) -> None: + url, _ = client._configure_realtime(json_data["model"], {}) + assert str(url) == expected + assert client.base_url == base_url + + +@pytest.mark.parametrize( + "client,base_url,json_data,expected", + [ + # AsyncAzureOpenAI: No deployment specified + ( + AsyncAzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", + ), + "https://example-resource.azure.openai.com/openai/", + {"model": "deployment-body"}, + "wss://example-resource.azure.openai.com/openai/realtime?api-version=2024-02-01&deployment=deployment-body", + ), + # AsyncAzureOpenAI: Deployment specified + ( + AsyncAzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", + azure_deployment="deployment-client", + ), + "https://example-resource.azure.openai.com/openai/deployments/deployment-client/", + {"model": "deployment-body"}, + "wss://example-resource.azure.openai.com/openai/realtime?api-version=2024-02-01&deployment=deployment-client", + ), + # AsyncAzureOpenAI: "deployments" in the DNS name + ( + AsyncAzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://deployments.azure.openai.com/", + ), + "https://deployments.azure.openai.com/openai/", + {"model": "deployment-body"}, + "wss://deployments.azure.openai.com/openai/realtime?api-version=2024-02-01&deployment=deployment-body", + ), + # AsyncAzureOpenAI: Deployment called "deployments" + ( + AsyncAzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", + azure_deployment="deployments", + ), + "https://example-resource.azure.openai.com/openai/deployments/deployments/", + {"model": "deployment-body"}, + "wss://example-resource.azure.openai.com/openai/realtime?api-version=2024-02-01&deployment=deployments", + ), + # AsyncAzureOpenAI: base_url and azure_deployment specified; azure_deployment ignored b/c not supported + ( + AsyncAzureOpenAI( # type: ignore + api_version="2024-02-01", + api_key="example API key", + base_url="https://example.azure-api.net/PTU/", + azure_deployment="deployment-client", + ), + "https://example.azure-api.net/PTU/", + {"model": "deployment-body"}, + "wss://example.azure-api.net/PTU/realtime?api-version=2024-02-01&deployment=deployment-body", + ), + # AsyncAzureOpenAI: websocket_base_url specified + ( + AsyncAzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", + websocket_base_url="wss://example-resource.azure.openai.com/base", + ), + "https://example-resource.azure.openai.com/openai/", + {"model": "deployment-body"}, + "wss://example-resource.azure.openai.com/base/realtime?api-version=2024-02-01&deployment=deployment-body", + ), + ], +) +async def test_prepare_url_realtime_async( + client: AsyncAzureOpenAI, base_url: str, json_data: dict[str, str], expected: str +) -> None: + url, _ = await client._configure_realtime(json_data["model"], {}) + assert str(url) == expected + assert client.base_url == base_url + + +def test_client_sets_base_url(/service/client: Client) -> None: + client = AzureOpenAI( + api_version="2024-02-01", + api_key="example API key", + azure_endpoint="https://example-resource.azure.openai.com/", + azure_deployment="my-deployment", + ) + assert client.base_url == "https://example-resource.azure.openai.com/openai/deployments/my-deployment/" + + # (not recommended) user sets base_url to target different deployment + client.base_url = "https://example-resource.azure.openai.com/openai/deployments/different-deployment/" + req = client._build_request( + FinalRequestOptions.construct( + method="post", + url="/chat/completions", + json_data={"model": "placeholder"}, + ) + ) + assert ( + req.url + == "https://example-resource.azure.openai.com/openai/deployments/different-deployment/chat/completions?api-version=2024-02-01" + ) + req = client._build_request( + FinalRequestOptions.construct( + method="post", + url="/models", + json_data={}, + ) + ) + assert req.url == "https://example-resource.azure.openai.com/openai/models?api-version=2024-02-01" + + # (not recommended) user sets base_url to remove deployment + client.base_url = "https://example-resource.azure.openai.com/openai/" + req = client._build_request( + FinalRequestOptions.construct( + method="post", + url="/chat/completions", + json_data={"model": "deployment"}, + ) + ) + assert ( + req.url + == "https://example-resource.azure.openai.com/openai/deployments/deployment/chat/completions?api-version=2024-02-01" + ) + req = client._build_request( + FinalRequestOptions.construct( + method="post", + url="/models", + json_data={}, + ) + ) + assert req.url == "https://example-resource.azure.openai.com/openai/models?api-version=2024-02-01" From 64af9e8f06be4bfe02e0e5e9cb0aa7889a5db6d7 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Sat, 1 Mar 2025 05:04:12 +0000 Subject: [PATCH 705/816] release: 1.65.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 57b589ea9e..ae5a2791b1 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.65.1" + ".": "1.65.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index ac6f54aa21..8f7edb2cae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.65.2 (2025-03-01) + +Full Changelog: [v1.65.1...v1.65.2](https://github.com/openai/openai-python/compare/v1.65.1...v1.65.2) + +### Bug Fixes + +* **azure:** azure_deployment use with realtime + non-deployment-based APIs ([#2154](https://github.com/openai/openai-python/issues/2154)) ([5846b55](https://github.com/openai/openai-python/commit/5846b552877f3d278689c521f9a26ce31167e1ea)) + + +### Chores + +* **docs:** update client docstring ([#2152](https://github.com/openai/openai-python/issues/2152)) ([0518c34](https://github.com/openai/openai-python/commit/0518c341ee0e19941c6b1d9d60e2552e1aa17f26)) + ## 1.65.1 (2025-02-27) Full Changelog: [v1.65.0...v1.65.1](https://github.com/openai/openai-python/compare/v1.65.0...v1.65.1) diff --git a/pyproject.toml b/pyproject.toml index 13bd84e4f4..d9a2417194 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.65.1" +version = "1.65.2" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 422c9a283d..d48f48f4e1 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.65.1" # x-release-please-version +__version__ = "1.65.2" # x-release-please-version From 65f2c5cee943d5c2a57f087c7bcc8204449cec51 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 3 Mar 2025 20:43:26 +0000 Subject: [PATCH 706/816] chore(internal): remove unused http client options forwarding (#2158) --- src/openai/_base_client.py | 97 +------------------------------------- 1 file changed, 1 insertion(+), 96 deletions(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 43dc9ab2a4..f31e5af54b 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -9,7 +9,6 @@ import inspect import logging import platform -import warnings import email.utils from types import TracebackType from random import random @@ -36,7 +35,7 @@ import httpx import distro import pydantic -from httpx import URL, Limits +from httpx import URL from pydantic import PrivateAttr from . import _exceptions @@ -51,13 +50,10 @@ Timeout, NotGiven, ResponseT, - Transport, AnyMapping, PostParser, - ProxiesTypes, RequestFiles, HttpxSendArgs, - AsyncTransport, RequestOptions, HttpxRequestFiles, ModelBuilderProtocol, @@ -339,9 +335,6 @@ class BaseClient(Generic[_HttpxClientT, _DefaultStreamT]): _base_url: URL max_retries: int timeout: Union[float, Timeout, None] - _limits: httpx.Limits - _proxies: ProxiesTypes | None - _transport: Transport | AsyncTransport | None _strict_response_validation: bool _idempotency_header: str | None _default_stream_cls: type[_DefaultStreamT] | None = None @@ -354,9 +347,6 @@ def __init__( _strict_response_validation: bool, max_retries: int = DEFAULT_MAX_RETRIES, timeout: float | Timeout | None = DEFAULT_TIMEOUT, - limits: httpx.Limits, - transport: Transport | AsyncTransport | None, - proxies: ProxiesTypes | None, custom_headers: Mapping[str, str] | None = None, custom_query: Mapping[str, object] | None = None, ) -> None: @@ -364,9 +354,6 @@ def __init__( self._base_url = self._enforce_trailing_slash(URL(base_url)) self.max_retries = max_retries self.timeout = timeout - self._limits = limits - self._proxies = proxies - self._transport = transport self._custom_headers = custom_headers or {} self._custom_query = custom_query or {} self._strict_response_validation = _strict_response_validation @@ -802,46 +789,11 @@ def __init__( base_url: str | URL, max_retries: int = DEFAULT_MAX_RETRIES, timeout: float | Timeout | None | NotGiven = NOT_GIVEN, - transport: Transport | None = None, - proxies: ProxiesTypes | None = None, - limits: Limits | None = None, http_client: httpx.Client | None = None, custom_headers: Mapping[str, str] | None = None, custom_query: Mapping[str, object] | None = None, _strict_response_validation: bool, ) -> None: - kwargs: dict[str, Any] = {} - if limits is not None: - warnings.warn( - "The `connection_pool_limits` argument is deprecated. The `http_client` argument should be passed instead", - category=DeprecationWarning, - stacklevel=3, - ) - if http_client is not None: - raise ValueError("The `http_client` argument is mutually exclusive with `connection_pool_limits`") - else: - limits = DEFAULT_CONNECTION_LIMITS - - if transport is not None: - kwargs["transport"] = transport - warnings.warn( - "The `transport` argument is deprecated. The `http_client` argument should be passed instead", - category=DeprecationWarning, - stacklevel=3, - ) - if http_client is not None: - raise ValueError("The `http_client` argument is mutually exclusive with `transport`") - - if proxies is not None: - kwargs["proxies"] = proxies - warnings.warn( - "The `proxies` argument is deprecated. The `http_client` argument should be passed instead", - category=DeprecationWarning, - stacklevel=3, - ) - if http_client is not None: - raise ValueError("The `http_client` argument is mutually exclusive with `proxies`") - if not is_given(timeout): # if the user passed in a custom http client with a non-default # timeout set then we use that timeout. @@ -862,12 +814,9 @@ def __init__( super().__init__( version=version, - limits=limits, # cast to a valid type because mypy doesn't understand our type narrowing timeout=cast(Timeout, timeout), - proxies=proxies, base_url=base_url, - transport=transport, max_retries=max_retries, custom_query=custom_query, custom_headers=custom_headers, @@ -877,9 +826,6 @@ def __init__( base_url=base_url, # cast to a valid type because mypy doesn't understand our type narrowing timeout=cast(Timeout, timeout), - limits=limits, - follow_redirects=True, - **kwargs, # type: ignore ) def is_closed(self) -> bool: @@ -1389,45 +1335,10 @@ def __init__( _strict_response_validation: bool, max_retries: int = DEFAULT_MAX_RETRIES, timeout: float | Timeout | None | NotGiven = NOT_GIVEN, - transport: AsyncTransport | None = None, - proxies: ProxiesTypes | None = None, - limits: Limits | None = None, http_client: httpx.AsyncClient | None = None, custom_headers: Mapping[str, str] | None = None, custom_query: Mapping[str, object] | None = None, ) -> None: - kwargs: dict[str, Any] = {} - if limits is not None: - warnings.warn( - "The `connection_pool_limits` argument is deprecated. The `http_client` argument should be passed instead", - category=DeprecationWarning, - stacklevel=3, - ) - if http_client is not None: - raise ValueError("The `http_client` argument is mutually exclusive with `connection_pool_limits`") - else: - limits = DEFAULT_CONNECTION_LIMITS - - if transport is not None: - kwargs["transport"] = transport - warnings.warn( - "The `transport` argument is deprecated. The `http_client` argument should be passed instead", - category=DeprecationWarning, - stacklevel=3, - ) - if http_client is not None: - raise ValueError("The `http_client` argument is mutually exclusive with `transport`") - - if proxies is not None: - kwargs["proxies"] = proxies - warnings.warn( - "The `proxies` argument is deprecated. The `http_client` argument should be passed instead", - category=DeprecationWarning, - stacklevel=3, - ) - if http_client is not None: - raise ValueError("The `http_client` argument is mutually exclusive with `proxies`") - if not is_given(timeout): # if the user passed in a custom http client with a non-default # timeout set then we use that timeout. @@ -1449,11 +1360,8 @@ def __init__( super().__init__( version=version, base_url=base_url, - limits=limits, # cast to a valid type because mypy doesn't understand our type narrowing timeout=cast(Timeout, timeout), - proxies=proxies, - transport=transport, max_retries=max_retries, custom_query=custom_query, custom_headers=custom_headers, @@ -1463,9 +1371,6 @@ def __init__( base_url=base_url, # cast to a valid type because mypy doesn't understand our type narrowing timeout=cast(Timeout, timeout), - limits=limits, - follow_redirects=True, - **kwargs, # type: ignore ) def is_closed(self) -> bool: From b31f4d4c61cbeecf44b7ea6e0773eeec0748d91f Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 4 Mar 2025 21:09:25 +0000 Subject: [PATCH 707/816] chore(internal): run example files in CI (#2160) --- .github/workflows/ci.yml | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 26f497db1f..d0e0ffe2f3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -51,3 +51,30 @@ jobs: - name: Run tests run: ./scripts/test + + examples: + name: examples + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: Install Rye + run: | + curl -sSf https://rye.astral.sh/get | bash + echo "$HOME/.rye/shims" >> $GITHUB_PATH + env: + RYE_VERSION: '0.35.0' + RYE_INSTALL_OPTION: '--yes' + - name: Install dependencies + run: | + rye sync --all-features + + - env: + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + run: | + rye run python examples/demo.py + - env: + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + run: | + rye run python examples/async_demo.py From d6bb8c14e66605ad2b7ed7bd62951014cd21b576 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 4 Mar 2025 21:10:03 +0000 Subject: [PATCH 708/816] release: 1.65.3 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 9 +++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index ae5a2791b1..352e389697 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.65.2" + ".": "1.65.3" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f7edb2cae..95093fb510 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 1.65.3 (2025-03-04) + +Full Changelog: [v1.65.2...v1.65.3](https://github.com/openai/openai-python/compare/v1.65.2...v1.65.3) + +### Chores + +* **internal:** remove unused http client options forwarding ([#2158](https://github.com/openai/openai-python/issues/2158)) ([76ec464](https://github.com/openai/openai-python/commit/76ec464cfe3db3fa59a766259d6d6ee5bb889f86)) +* **internal:** run example files in CI ([#2160](https://github.com/openai/openai-python/issues/2160)) ([9979345](https://github.com/openai/openai-python/commit/9979345038594440eec2f500c0c7cc5417cc7c08)) + ## 1.65.2 (2025-03-01) Full Changelog: [v1.65.1...v1.65.2](https://github.com/openai/openai-python/compare/v1.65.1...v1.65.2) diff --git a/pyproject.toml b/pyproject.toml index d9a2417194..c9e2afbf0c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.65.2" +version = "1.65.3" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index d48f48f4e1..5e54102501 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.65.2" # x-release-please-version +__version__ = "1.65.3" # x-release-please-version From 5608d64bb832dc7f8305a4dfb6b8e76f7087c944 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 5 Mar 2025 21:22:02 +0000 Subject: [PATCH 709/816] fix(api): add missing file rank enum + more metadata (#2164) --- .stats.yml | 2 +- src/openai/resources/fine_tuning/jobs/jobs.py | 31 ++++++++++++++++++- .../threads/runs/file_search_tool_call.py | 7 +++-- .../types/fine_tuning/fine_tuning_job.py | 11 +++++++ .../types/fine_tuning/job_create_params.py | 12 +++++++ .../types/fine_tuning/job_list_params.py | 8 +++++ tests/api_resources/fine_tuning/test_jobs.py | 4 +++ 7 files changed, 71 insertions(+), 4 deletions(-) diff --git a/.stats.yml b/.stats.yml index 163146e38d..0d7e83be4f 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 74 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-5d30684c3118d049682ea30cdb4dbef39b97d51667da484689193dc40162af32.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-b524aed1c2c5c928aa4e2c546f5dbb364e7b4d5027daf05e42e210b05a97c3c6.yml diff --git a/src/openai/resources/fine_tuning/jobs/jobs.py b/src/openai/resources/fine_tuning/jobs/jobs.py index e023d28fea..bbeff60bc6 100644 --- a/src/openai/resources/fine_tuning/jobs/jobs.py +++ b/src/openai/resources/fine_tuning/jobs/jobs.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Union, Iterable, Optional +from typing import Dict, Union, Iterable, Optional from typing_extensions import Literal import httpx @@ -30,6 +30,7 @@ make_request_options, ) from ....types.fine_tuning import job_list_params, job_create_params, job_list_events_params +from ....types.shared_params.metadata import Metadata from ....types.fine_tuning.fine_tuning_job import FineTuningJob from ....types.fine_tuning.fine_tuning_job_event import FineTuningJobEvent @@ -67,6 +68,7 @@ def create( training_file: str, hyperparameters: job_create_params.Hyperparameters | NotGiven = NOT_GIVEN, integrations: Optional[Iterable[job_create_params.Integration]] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, method: job_create_params.Method | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, suffix: Optional[str] | NotGiven = NOT_GIVEN, @@ -114,6 +116,13 @@ def create( integrations: A list of integrations to enable for your fine-tuning job. + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + method: The method used for fine-tuning. seed: The seed controls the reproducibility of the job. Passing in the same seed and @@ -155,6 +164,7 @@ def create( "training_file": training_file, "hyperparameters": hyperparameters, "integrations": integrations, + "metadata": metadata, "method": method, "seed": seed, "suffix": suffix, @@ -208,6 +218,7 @@ def list( *, after: str | NotGiven = NOT_GIVEN, limit: int | NotGiven = NOT_GIVEN, + metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -223,6 +234,9 @@ def list( limit: Number of fine-tuning jobs to retrieve. + metadata: Optional metadata filter. To filter, use the syntax `metadata[k]=v`. + Alternatively, set `metadata=null` to indicate no metadata. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -243,6 +257,7 @@ def list( { "after": after, "limit": limit, + "metadata": metadata, }, job_list_params.JobListParams, ), @@ -365,6 +380,7 @@ async def create( training_file: str, hyperparameters: job_create_params.Hyperparameters | NotGiven = NOT_GIVEN, integrations: Optional[Iterable[job_create_params.Integration]] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, method: job_create_params.Method | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, suffix: Optional[str] | NotGiven = NOT_GIVEN, @@ -412,6 +428,13 @@ async def create( integrations: A list of integrations to enable for your fine-tuning job. + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + method: The method used for fine-tuning. seed: The seed controls the reproducibility of the job. Passing in the same seed and @@ -453,6 +476,7 @@ async def create( "training_file": training_file, "hyperparameters": hyperparameters, "integrations": integrations, + "metadata": metadata, "method": method, "seed": seed, "suffix": suffix, @@ -506,6 +530,7 @@ def list( *, after: str | NotGiven = NOT_GIVEN, limit: int | NotGiven = NOT_GIVEN, + metadata: Optional[Dict[str, str]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -521,6 +546,9 @@ def list( limit: Number of fine-tuning jobs to retrieve. + metadata: Optional metadata filter. To filter, use the syntax `metadata[k]=v`. + Alternatively, set `metadata=null` to indicate no metadata. + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -541,6 +569,7 @@ def list( { "after": after, "limit": limit, + "metadata": metadata, }, job_list_params.JobListParams, ), diff --git a/src/openai/types/beta/threads/runs/file_search_tool_call.py b/src/openai/types/beta/threads/runs/file_search_tool_call.py index da4d58dc37..a2068daad1 100644 --- a/src/openai/types/beta/threads/runs/file_search_tool_call.py +++ b/src/openai/types/beta/threads/runs/file_search_tool_call.py @@ -15,8 +15,11 @@ class FileSearchRankingOptions(BaseModel): - ranker: Literal["default_2024_08_21"] - """The ranker used for the file search.""" + ranker: Literal["auto", "default_2024_08_21"] + """The ranker to use for the file search. + + If not specified will use the `auto` ranker. + """ score_threshold: float """The score threshold for the file search. diff --git a/src/openai/types/fine_tuning/fine_tuning_job.py b/src/openai/types/fine_tuning/fine_tuning_job.py index f5a11c2107..c7fff2b7b1 100644 --- a/src/openai/types/fine_tuning/fine_tuning_job.py +++ b/src/openai/types/fine_tuning/fine_tuning_job.py @@ -4,6 +4,7 @@ from typing_extensions import Literal from ..._models import BaseModel +from ..shared.metadata import Metadata from .fine_tuning_job_wandb_integration_object import FineTuningJobWandbIntegrationObject __all__ = [ @@ -208,5 +209,15 @@ class FineTuningJob(BaseModel): integrations: Optional[List[FineTuningJobWandbIntegrationObject]] = None """A list of integrations to enable for this fine-tuning job.""" + metadata: Optional[Metadata] = None + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + """ + method: Optional[Method] = None """The method used for fine-tuning.""" diff --git a/src/openai/types/fine_tuning/job_create_params.py b/src/openai/types/fine_tuning/job_create_params.py index 09c3f8571c..f4cf980b08 100644 --- a/src/openai/types/fine_tuning/job_create_params.py +++ b/src/openai/types/fine_tuning/job_create_params.py @@ -5,6 +5,8 @@ from typing import List, Union, Iterable, Optional from typing_extensions import Literal, Required, TypedDict +from ..shared_params.metadata import Metadata + __all__ = [ "JobCreateParams", "Hyperparameters", @@ -55,6 +57,16 @@ class JobCreateParams(TypedDict, total=False): integrations: Optional[Iterable[Integration]] """A list of integrations to enable for your fine-tuning job.""" + metadata: Optional[Metadata] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + """ + method: Method """The method used for fine-tuning.""" diff --git a/src/openai/types/fine_tuning/job_list_params.py b/src/openai/types/fine_tuning/job_list_params.py index 5c075ca33f..b79f3ce86a 100644 --- a/src/openai/types/fine_tuning/job_list_params.py +++ b/src/openai/types/fine_tuning/job_list_params.py @@ -2,6 +2,7 @@ from __future__ import annotations +from typing import Dict, Optional from typing_extensions import TypedDict __all__ = ["JobListParams"] @@ -13,3 +14,10 @@ class JobListParams(TypedDict, total=False): limit: int """Number of fine-tuning jobs to retrieve.""" + + metadata: Optional[Dict[str, str]] + """Optional metadata filter. + + To filter, use the syntax `metadata[k]=v`. Alternatively, set `metadata=null` to + indicate no metadata. + """ diff --git a/tests/api_resources/fine_tuning/test_jobs.py b/tests/api_resources/fine_tuning/test_jobs.py index 1e421c30c0..75f72f9d09 100644 --- a/tests/api_resources/fine_tuning/test_jobs.py +++ b/tests/api_resources/fine_tuning/test_jobs.py @@ -50,6 +50,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: }, } ], + metadata={"foo": "string"}, method={ "dpo": { "hyperparameters": { @@ -148,6 +149,7 @@ def test_method_list_with_all_params(self, client: OpenAI) -> None: job = client.fine_tuning.jobs.list( after="string", limit=0, + metadata={"foo": "string"}, ) assert_matches_type(SyncCursorPage[FineTuningJob], job, path=["response"]) @@ -289,6 +291,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> }, } ], + metadata={"foo": "string"}, method={ "dpo": { "hyperparameters": { @@ -387,6 +390,7 @@ async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> N job = await async_client.fine_tuning.jobs.list( after="string", limit=0, + metadata={"foo": "string"}, ) assert_matches_type(AsyncCursorPage[FineTuningJob], job, path=["response"]) From dfc4cfabfab3db89c0668c9bfd5f3f6f49093935 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 5 Mar 2025 21:22:42 +0000 Subject: [PATCH 710/816] release: 1.65.4 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 352e389697..b31d1b2102 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.65.3" + ".": "1.65.4" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 95093fb510..759edd60a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.65.4 (2025-03-05) + +Full Changelog: [v1.65.3...v1.65.4](https://github.com/openai/openai-python/compare/v1.65.3...v1.65.4) + +### Bug Fixes + +* **api:** add missing file rank enum + more metadata ([#2164](https://github.com/openai/openai-python/issues/2164)) ([0387e48](https://github.com/openai/openai-python/commit/0387e48e0880e496eb74b60eec9ed76a3171f14d)) + ## 1.65.3 (2025-03-04) Full Changelog: [v1.65.2...v1.65.3](https://github.com/openai/openai-python/compare/v1.65.2...v1.65.3) diff --git a/pyproject.toml b/pyproject.toml index c9e2afbf0c..a44991907d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.65.3" +version = "1.65.4" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 5e54102501..13991c8059 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.65.3" # x-release-please-version +__version__ = "1.65.4" # x-release-please-version From 530f9b80c7c21b1290a6749f6c2c82d72c047585 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 6 Mar 2025 20:10:48 +0000 Subject: [PATCH 711/816] chore: move ChatModel type to shared (#2167) --- api.md | 3 +- src/openai/resources/beta/assistants.py | 2 +- .../resources/beta/threads/runs/runs.py | 2 +- src/openai/resources/beta/threads/threads.py | 2 +- .../resources/chat/completions/completions.py | 2 +- src/openai/types/__init__.py | 2 +- .../types/beta/assistant_create_params.py | 2 +- .../beta/thread_create_and_run_params.py | 2 +- .../types/beta/threads/run_create_params.py | 2 +- .../types/chat/completion_create_params.py | 2 +- src/openai/types/chat_model.py | 47 ++--------------- src/openai/types/shared/__init__.py | 1 + src/openai/types/shared/chat_model.py | 49 ++++++++++++++++++ src/openai/types/shared_params/__init__.py | 1 + src/openai/types/shared_params/chat_model.py | 51 +++++++++++++++++++ 15 files changed, 116 insertions(+), 54 deletions(-) create mode 100644 src/openai/types/shared/chat_model.py create mode 100644 src/openai/types/shared_params/chat_model.py diff --git a/api.md b/api.md index 2db9d1157e..20e776289e 100644 --- a/api.md +++ b/api.md @@ -2,6 +2,7 @@ ```python from openai.types import ( + ChatModel, ErrorObject, FunctionDefinition, FunctionParameters, @@ -222,9 +223,9 @@ Types: from openai.types.fine_tuning import ( FineTuningJob, FineTuningJobEvent, - FineTuningJobIntegration, FineTuningJobWandbIntegration, FineTuningJobWandbIntegrationObject, + FineTuningJobIntegration, ) ``` diff --git a/src/openai/resources/beta/assistants.py b/src/openai/resources/beta/assistants.py index d2bb8d7b92..ffecd8f9e9 100644 --- a/src/openai/resources/beta/assistants.py +++ b/src/openai/resources/beta/assistants.py @@ -23,8 +23,8 @@ assistant_update_params, ) from ..._base_client import AsyncPaginator, make_request_options -from ...types.chat_model import ChatModel from ...types.beta.assistant import Assistant +from ...types.shared.chat_model import ChatModel from ...types.beta.assistant_deleted import AssistantDeleted from ...types.shared_params.metadata import Metadata from ...types.beta.assistant_tool_param import AssistantToolParam diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index dc364b4e31..b819678be6 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -39,7 +39,6 @@ AsyncAssistantEventHandlerT, AsyncAssistantStreamManager, ) -from .....types.chat_model import ChatModel from .....types.beta.threads import ( run_list_params, run_create_params, @@ -47,6 +46,7 @@ run_submit_tool_outputs_params, ) from .....types.beta.threads.run import Run +from .....types.shared.chat_model import ChatModel from .....types.shared_params.metadata import Metadata from .....types.beta.assistant_tool_param import AssistantToolParam from .....types.beta.assistant_stream_event import AssistantStreamEvent diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 6ff8539501..d88559bdeb 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -49,9 +49,9 @@ AsyncAssistantEventHandlerT, AsyncAssistantStreamManager, ) -from ....types.chat_model import ChatModel from ....types.beta.thread import Thread from ....types.beta.threads.run import Run +from ....types.shared.chat_model import ChatModel from ....types.beta.thread_deleted import ThreadDeleted from ....types.shared_params.metadata import Metadata from ....types.beta.assistant_stream_event import AssistantStreamEvent diff --git a/src/openai/resources/chat/completions/completions.py b/src/openai/resources/chat/completions/completions.py index 1753f6c990..708b1ff166 100644 --- a/src/openai/resources/chat/completions/completions.py +++ b/src/openai/resources/chat/completions/completions.py @@ -37,7 +37,7 @@ completion_update_params, ) from ...._base_client import AsyncPaginator, make_request_options -from ....types.chat_model import ChatModel +from ....types.shared.chat_model import ChatModel from ....types.chat.chat_completion import ChatCompletion from ....types.shared_params.metadata import Metadata from ....types.chat.chat_completion_chunk import ChatCompletionChunk diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index 7abb22f239..5785877c8a 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -7,6 +7,7 @@ from .model import Model as Model from .shared import ( Metadata as Metadata, + ChatModel as ChatModel, ErrorObject as ErrorObject, FunctionDefinition as FunctionDefinition, FunctionParameters as FunctionParameters, @@ -16,7 +17,6 @@ ) from .upload import Upload as Upload from .embedding import Embedding as Embedding -from .chat_model import ChatModel as ChatModel from .completion import Completion as Completion from .moderation import Moderation as Moderation from .audio_model import AudioModel as AudioModel diff --git a/src/openai/types/beta/assistant_create_params.py b/src/openai/types/beta/assistant_create_params.py index 66bef02ced..e90aabfd3f 100644 --- a/src/openai/types/beta/assistant_create_params.py +++ b/src/openai/types/beta/assistant_create_params.py @@ -5,7 +5,7 @@ from typing import List, Union, Iterable, Optional from typing_extensions import Literal, Required, TypedDict -from ..chat_model import ChatModel +from ..shared.chat_model import ChatModel from .assistant_tool_param import AssistantToolParam from ..shared_params.metadata import Metadata from .file_chunking_strategy_param import FileChunkingStrategyParam diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index 08f044c1be..d888fb3eee 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -5,7 +5,7 @@ from typing import List, Union, Iterable, Optional from typing_extensions import Literal, Required, TypeAlias, TypedDict -from ..chat_model import ChatModel +from ..shared.chat_model import ChatModel from .function_tool_param import FunctionToolParam from .file_search_tool_param import FileSearchToolParam from ..shared_params.metadata import Metadata diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index 093b4ce321..098e50a1d9 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -5,7 +5,7 @@ from typing import List, Union, Iterable, Optional from typing_extensions import Literal, Required, TypeAlias, TypedDict -from ...chat_model import ChatModel +from ...shared.chat_model import ChatModel from ..assistant_tool_param import AssistantToolParam from .runs.run_step_include import RunStepInclude from ...shared_params.metadata import Metadata diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index c761cbe07b..4dd2812aba 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -5,7 +5,7 @@ from typing import Dict, List, Union, Iterable, Optional from typing_extensions import Literal, Required, TypeAlias, TypedDict -from ..chat_model import ChatModel +from ..shared.chat_model import ChatModel from ..shared_params.metadata import Metadata from .chat_completion_modality import ChatCompletionModality from .chat_completion_tool_param import ChatCompletionToolParam diff --git a/src/openai/types/chat_model.py b/src/openai/types/chat_model.py index 6fe705a0b4..9304d195d6 100644 --- a/src/openai/types/chat_model.py +++ b/src/openai/types/chat_model.py @@ -1,49 +1,8 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing_extensions import Literal, TypeAlias + +from .shared import chat_model __all__ = ["ChatModel"] -ChatModel: TypeAlias = Literal[ - "o3-mini", - "o3-mini-2025-01-31", - "o1", - "o1-2024-12-17", - "o1-preview", - "o1-preview-2024-09-12", - "o1-mini", - "o1-mini-2024-09-12", - "gpt-4.5-preview", - "gpt-4.5-preview-2025-02-27", - "gpt-4o", - "gpt-4o-2024-11-20", - "gpt-4o-2024-08-06", - "gpt-4o-2024-05-13", - "gpt-4o-audio-preview", - "gpt-4o-audio-preview-2024-10-01", - "gpt-4o-audio-preview-2024-12-17", - "gpt-4o-mini-audio-preview", - "gpt-4o-mini-audio-preview-2024-12-17", - "chatgpt-4o-latest", - "gpt-4o-mini", - "gpt-4o-mini-2024-07-18", - "gpt-4-turbo", - "gpt-4-turbo-2024-04-09", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "gpt-4-1106-preview", - "gpt-4-vision-preview", - "gpt-4", - "gpt-4-0314", - "gpt-4-0613", - "gpt-4-32k", - "gpt-4-32k-0314", - "gpt-4-32k-0613", - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-3.5-turbo-0301", - "gpt-3.5-turbo-0613", - "gpt-3.5-turbo-1106", - "gpt-3.5-turbo-0125", - "gpt-3.5-turbo-16k-0613", -] +ChatModel = chat_model.ChatModel diff --git a/src/openai/types/shared/__init__.py b/src/openai/types/shared/__init__.py index 74bf304904..4cf367b1cc 100644 --- a/src/openai/types/shared/__init__.py +++ b/src/openai/types/shared/__init__.py @@ -1,6 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from .metadata import Metadata as Metadata +from .chat_model import ChatModel as ChatModel from .error_object import ErrorObject as ErrorObject from .function_definition import FunctionDefinition as FunctionDefinition from .function_parameters import FunctionParameters as FunctionParameters diff --git a/src/openai/types/shared/chat_model.py b/src/openai/types/shared/chat_model.py new file mode 100644 index 0000000000..6fe705a0b4 --- /dev/null +++ b/src/openai/types/shared/chat_model.py @@ -0,0 +1,49 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["ChatModel"] + +ChatModel: TypeAlias = Literal[ + "o3-mini", + "o3-mini-2025-01-31", + "o1", + "o1-2024-12-17", + "o1-preview", + "o1-preview-2024-09-12", + "o1-mini", + "o1-mini-2024-09-12", + "gpt-4.5-preview", + "gpt-4.5-preview-2025-02-27", + "gpt-4o", + "gpt-4o-2024-11-20", + "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "gpt-4o-audio-preview", + "gpt-4o-audio-preview-2024-10-01", + "gpt-4o-audio-preview-2024-12-17", + "gpt-4o-mini-audio-preview", + "gpt-4o-mini-audio-preview-2024-12-17", + "chatgpt-4o-latest", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0301", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", +] diff --git a/src/openai/types/shared_params/__init__.py b/src/openai/types/shared_params/__init__.py index 68a8db75fe..47a747b2d4 100644 --- a/src/openai/types/shared_params/__init__.py +++ b/src/openai/types/shared_params/__init__.py @@ -1,6 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from .metadata import Metadata as Metadata +from .chat_model import ChatModel as ChatModel from .function_definition import FunctionDefinition as FunctionDefinition from .function_parameters import FunctionParameters as FunctionParameters from .response_format_text import ResponseFormatText as ResponseFormatText diff --git a/src/openai/types/shared_params/chat_model.py b/src/openai/types/shared_params/chat_model.py new file mode 100644 index 0000000000..0ac3f31611 --- /dev/null +++ b/src/openai/types/shared_params/chat_model.py @@ -0,0 +1,51 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, TypeAlias + +__all__ = ["ChatModel"] + +ChatModel: TypeAlias = Literal[ + "o3-mini", + "o3-mini-2025-01-31", + "o1", + "o1-2024-12-17", + "o1-preview", + "o1-preview-2024-09-12", + "o1-mini", + "o1-mini-2024-09-12", + "gpt-4.5-preview", + "gpt-4.5-preview-2025-02-27", + "gpt-4o", + "gpt-4o-2024-11-20", + "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "gpt-4o-audio-preview", + "gpt-4o-audio-preview-2024-10-01", + "gpt-4o-audio-preview-2024-12-17", + "gpt-4o-mini-audio-preview", + "gpt-4o-mini-audio-preview-2024-12-17", + "chatgpt-4o-latest", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0301", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613", +] From a6b493071b843bec3db807637e441c1768b695f8 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Sun, 9 Mar 2025 05:03:47 +0000 Subject: [PATCH 712/816] release: 1.65.5 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index b31d1b2102..b8446e8608 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.65.4" + ".": "1.65.5" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 759edd60a8..e2bf62a4df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.65.5 (2025-03-09) + +Full Changelog: [v1.65.4...v1.65.5](https://github.com/openai/openai-python/compare/v1.65.4...v1.65.5) + +### Chores + +* move ChatModel type to shared ([#2167](https://github.com/openai/openai-python/issues/2167)) ([104f02a](https://github.com/openai/openai-python/commit/104f02af371076d5d2498e48ae14d2eacc7df8bd)) + ## 1.65.4 (2025-03-05) Full Changelog: [v1.65.3...v1.65.4](https://github.com/openai/openai-python/compare/v1.65.3...v1.65.4) diff --git a/pyproject.toml b/pyproject.toml index a44991907d..09e79f5592 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.65.4" +version = "1.65.5" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 13991c8059..859b56580d 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.65.4" # x-release-please-version +__version__ = "1.65.5" # x-release-please-version From bf4a7e67d71a10a2644f18aeb110fda1dcba0023 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 11 Mar 2025 01:09:36 +0000 Subject: [PATCH 713/816] test: add DEFER_PYDANTIC_BUILD=false flag to tests (#2174) --- scripts/test | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripts/test b/scripts/test index 4fa5698b8f..2b87845670 100755 --- a/scripts/test +++ b/scripts/test @@ -52,6 +52,8 @@ else echo fi +export DEFER_PYDANTIC_BUILD=false + echo "==> Running tests" rye run pytest "$@" From 71f73540d4f0cb21887bedf2cc43516a0ebbe7c9 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 11 Mar 2025 13:17:10 +0000 Subject: [PATCH 714/816] chore: export more types (#2176) --- src/openai/types/__init__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index 5785877c8a..eb71ac6ccc 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -17,6 +17,7 @@ ) from .upload import Upload as Upload from .embedding import Embedding as Embedding +from .chat_model import ChatModel as ChatModel from .completion import Completion as Completion from .moderation import Moderation as Moderation from .audio_model import AudioModel as AudioModel From 2954945ecc185259cfd7cd33c8cbc818a88e4e1b Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Tue, 11 Mar 2025 12:22:03 -0400 Subject: [PATCH 715/816] feat(api): add /v1/responses and built-in tools [platform.openai.com/docs/changelog](http://platform.openai.com/docs/changelog) --- .stats.yml | 4 +- README.md | 229 +-- api.md | 232 ++- examples/responses/__init__.py | 0 examples/responses/streaming.py | 30 + examples/responses/streaming_tools.py | 68 + examples/responses/structured_outputs.py | 55 + .../responses/structured_outputs_tools.py | 73 + src/openai/_client.py | 18 + src/openai/_streaming.py | 4 +- src/openai/lib/_parsing/_responses.py | 168 ++ src/openai/lib/_tools.py | 12 + .../lib/streaming/responses/__init__.py | 13 + src/openai/lib/streaming/responses/_events.py | 106 + .../lib/streaming/responses/_responses.py | 354 ++++ src/openai/lib/streaming/responses/_types.py | 10 + src/openai/resources/__init__.py | 28 + src/openai/resources/beta/__init__.py | 14 - src/openai/resources/beta/assistants.py | 17 +- src/openai/resources/beta/beta.py | 32 - src/openai/resources/beta/chat/completions.py | 40 +- .../resources/beta/threads/runs/runs.py | 51 +- .../resources/chat/completions/completions.py | 496 +++-- .../resources/chat/completions/messages.py | 4 +- src/openai/resources/files.py | 24 +- src/openai/resources/responses/__init__.py | 33 + src/openai/resources/responses/input_items.py | 223 ++ src/openai/resources/responses/responses.py | 1790 +++++++++++++++++ src/openai/resources/uploads/uploads.py | 14 +- .../{beta => }/vector_stores/__init__.py | 0 .../{beta => }/vector_stores/file_batches.py | 48 +- .../{beta => }/vector_stores/files.py | 235 ++- .../{beta => }/vector_stores/vector_stores.py | 178 +- src/openai/types/__init__.py | 21 + .../auto_file_chunking_strategy_param.py | 0 src/openai/types/beta/__init__.py | 15 - .../types/beta/assistant_create_params.py | 49 +- .../types/beta/assistant_update_params.py | 5 +- .../beta/thread_create_and_run_params.py | 43 +- src/openai/types/beta/thread_create_params.py | 42 +- .../types/beta/threads/run_create_params.py | 5 +- .../types/chat/chat_completion_audio_param.py | 5 +- .../chat_completion_content_part_param.py | 31 +- .../types/chat/chat_completion_message.py | 30 +- .../chat/chat_completion_reasoning_effort.py | 6 +- .../types/chat/completion_create_params.py | 132 +- .../types/chat/completion_list_params.py | 8 +- .../{beta => }/file_chunking_strategy.py | 2 +- .../file_chunking_strategy_param.py | 0 src/openai/types/file_create_params.py | 10 +- src/openai/types/file_purpose.py | 2 +- .../other_file_chunking_strategy_object.py | 2 +- src/openai/types/responses/__init__.py | 138 ++ src/openai/types/responses/computer_tool.py | 21 + .../types/responses/computer_tool_param.py | 21 + .../responses/easy_input_message_param.py | 27 + .../types/responses/file_search_tool.py | 44 + .../types/responses/file_search_tool_param.py | 45 + src/openai/types/responses/function_tool.py | 28 + .../types/responses/function_tool_param.py | 28 + .../types/responses/input_item_list_params.py | 28 + src/openai/types/responses/parsed_response.py | 77 + src/openai/types/responses/response.py | 204 ++ .../responses/response_audio_delta_event.py | 15 + .../responses/response_audio_done_event.py | 12 + .../response_audio_transcript_delta_event.py | 15 + .../response_audio_transcript_done_event.py | 12 + ..._code_interpreter_call_code_delta_event.py | 18 + ...e_code_interpreter_call_code_done_event.py | 18 + ...e_code_interpreter_call_completed_event.py | 19 + ...code_interpreter_call_in_progress_event.py | 19 + ...ode_interpreter_call_interpreting_event.py | 19 + .../response_code_interpreter_tool_call.py | 52 + .../responses/response_completed_event.py | 16 + .../responses/response_computer_tool_call.py | 212 ++ .../response_computer_tool_call_param.py | 208 ++ .../response_content_part_added_event.py | 30 + .../response_content_part_done_event.py | 30 + .../types/responses/response_create_params.py | 204 ++ .../types/responses/response_created_event.py | 16 + src/openai/types/responses/response_error.py | 34 + .../types/responses/response_error_event.py | 22 + .../types/responses/response_failed_event.py | 16 + ...sponse_file_search_call_completed_event.py | 18 + ...onse_file_search_call_in_progress_event.py | 18 + ...sponse_file_search_call_searching_event.py | 18 + .../response_file_search_tool_call.py | 51 + .../response_file_search_tool_call_param.py | 51 + .../responses/response_format_text_config.py | 16 + .../response_format_text_config_param.py | 16 + ...response_format_text_json_schema_config.py | 43 + ...se_format_text_json_schema_config_param.py | 41 + ...nse_function_call_arguments_delta_event.py | 23 + ...onse_function_call_arguments_done_event.py | 20 + .../responses/response_function_tool_call.py | 32 + .../response_function_tool_call_param.py | 31 + .../responses/response_function_web_search.py | 18 + .../response_function_web_search_param.py | 18 + .../responses/response_in_progress_event.py | 16 + .../types/responses/response_includable.py | 9 + .../responses/response_incomplete_event.py | 16 + .../types/responses/response_input_content.py | 15 + .../responses/response_input_content_param.py | 14 + .../types/responses/response_input_file.py | 22 + .../responses/response_input_file_param.py | 21 + .../types/responses/response_input_image.py | 28 + .../responses/response_input_image_param.py | 28 + .../responses/response_input_item_param.py | 174 ++ .../response_input_message_content_list.py | 10 + ...sponse_input_message_content_list_param.py | 16 + .../types/responses/response_input_param.py | 177 ++ .../types/responses/response_input_text.py | 15 + .../responses/response_input_text_param.py | 15 + .../types/responses/response_item_list.py | 152 ++ .../types/responses/response_output_item.py | 55 + .../response_output_item_added_event.py | 19 + .../response_output_item_done_event.py | 19 + .../responses/response_output_message.py | 34 + .../response_output_message_param.py | 34 + .../responses/response_output_refusal.py | 15 + .../response_output_refusal_param.py | 15 + .../types/responses/response_output_text.py | 64 + .../responses/response_output_text_param.py | 67 + .../responses/response_refusal_delta_event.py | 24 + .../responses/response_refusal_done_event.py | 24 + .../responses/response_retrieve_params.py | 18 + src/openai/types/responses/response_status.py | 7 + .../types/responses/response_stream_event.py | 78 + .../response_text_annotation_delta_event.py | 79 + .../types/responses/response_text_config.py | 26 + .../responses/response_text_config_param.py | 27 + .../responses/response_text_delta_event.py | 24 + .../responses/response_text_done_event.py | 24 + src/openai/types/responses/response_usage.py | 25 + ...esponse_web_search_call_completed_event.py | 18 + ...ponse_web_search_call_in_progress_event.py | 18 + ...esponse_web_search_call_searching_event.py | 18 + src/openai/types/responses/tool.py | 16 + .../types/responses/tool_choice_function.py | 15 + .../responses/tool_choice_function_param.py | 15 + .../types/responses/tool_choice_options.py | 7 + .../types/responses/tool_choice_types.py | 22 + .../responses/tool_choice_types_param.py | 24 + src/openai/types/responses/tool_param.py | 18 + src/openai/types/responses/web_search_tool.py | 48 + .../types/responses/web_search_tool_param.py | 48 + src/openai/types/shared/__init__.py | 4 + src/openai/types/shared/chat_model.py | 3 + src/openai/types/shared/comparison_filter.py | 30 + src/openai/types/shared/compound_filter.py | 22 + src/openai/types/shared/reasoning.py | 28 + src/openai/types/shared/reasoning_effort.py | 8 + .../shared/response_format_json_object.py | 2 +- .../shared/response_format_json_schema.py | 18 +- .../types/shared/response_format_text.py | 2 +- src/openai/types/shared_params/__init__.py | 4 + src/openai/types/shared_params/chat_model.py | 3 + .../types/shared_params/comparison_filter.py | 30 + .../types/shared_params/compound_filter.py | 23 + src/openai/types/shared_params/reasoning.py | 29 + .../types/shared_params/reasoning_effort.py | 10 + .../response_format_json_object.py | 2 +- .../response_format_json_schema.py | 18 +- .../shared_params/response_format_text.py | 2 +- .../static_file_chunking_strategy.py | 2 +- .../static_file_chunking_strategy_object.py | 2 +- ...tic_file_chunking_strategy_object_param.py | 0 .../static_file_chunking_strategy_param.py | 0 src/openai/types/{beta => }/vector_store.py | 4 +- .../{beta => }/vector_store_create_params.py | 2 +- .../types/{beta => }/vector_store_deleted.py | 2 +- .../{beta => }/vector_store_list_params.py | 0 .../types/vector_store_search_params.py | 40 + .../types/vector_store_search_response.py | 39 + .../{beta => }/vector_store_update_params.py | 2 +- .../{beta => }/vector_stores/__init__.py | 2 + .../vector_stores/file_batch_create_params.py | 11 +- .../file_batch_list_files_params.py | 0 .../vector_stores/file_content_response.py | 15 + .../vector_stores/file_create_params.py | 10 + .../vector_stores/file_list_params.py | 0 .../types/vector_stores/file_update_params.py | 21 + .../vector_stores/vector_store_file.py | 13 +- .../vector_stores/vector_store_file_batch.py | 2 +- .../vector_store_file_deleted.py | 2 +- .../beta/vector_stores/test_files.py | 420 ---- tests/api_resources/chat/test_completions.py | 64 +- .../vector_stores => responses}/__init__.py | 0 .../responses/test_input_items.py | 121 ++ tests/api_resources/test_responses.py | 498 +++++ .../{beta => }/test_vector_stores.py | 263 ++- tests/api_resources/vector_stores/__init__.py | 1 + .../vector_stores/test_file_batches.py | 216 +- .../api_resources/vector_stores/test_files.py | 625 ++++++ tests/lib/chat/test_completions.py | 15 + tests/lib/chat/test_completions_streaming.py | 15 + 196 files changed, 10058 insertions(+), 1333 deletions(-) create mode 100644 examples/responses/__init__.py create mode 100644 examples/responses/streaming.py create mode 100644 examples/responses/streaming_tools.py create mode 100644 examples/responses/structured_outputs.py create mode 100644 examples/responses/structured_outputs_tools.py create mode 100644 src/openai/lib/_parsing/_responses.py create mode 100644 src/openai/lib/streaming/responses/__init__.py create mode 100644 src/openai/lib/streaming/responses/_events.py create mode 100644 src/openai/lib/streaming/responses/_responses.py create mode 100644 src/openai/lib/streaming/responses/_types.py create mode 100644 src/openai/resources/responses/__init__.py create mode 100644 src/openai/resources/responses/input_items.py create mode 100644 src/openai/resources/responses/responses.py rename src/openai/resources/{beta => }/vector_stores/__init__.py (100%) rename src/openai/resources/{beta => }/vector_stores/file_batches.py (93%) rename src/openai/resources/{beta => }/vector_stores/files.py (73%) rename src/openai/resources/{beta => }/vector_stores/vector_stores.py (80%) rename src/openai/types/{beta => }/auto_file_chunking_strategy_param.py (100%) rename src/openai/types/{beta => }/file_chunking_strategy.py (93%) rename src/openai/types/{beta => }/file_chunking_strategy_param.py (100%) rename src/openai/types/{beta => }/other_file_chunking_strategy_object.py (89%) create mode 100644 src/openai/types/responses/__init__.py create mode 100644 src/openai/types/responses/computer_tool.py create mode 100644 src/openai/types/responses/computer_tool_param.py create mode 100644 src/openai/types/responses/easy_input_message_param.py create mode 100644 src/openai/types/responses/file_search_tool.py create mode 100644 src/openai/types/responses/file_search_tool_param.py create mode 100644 src/openai/types/responses/function_tool.py create mode 100644 src/openai/types/responses/function_tool_param.py create mode 100644 src/openai/types/responses/input_item_list_params.py create mode 100644 src/openai/types/responses/parsed_response.py create mode 100644 src/openai/types/responses/response.py create mode 100644 src/openai/types/responses/response_audio_delta_event.py create mode 100644 src/openai/types/responses/response_audio_done_event.py create mode 100644 src/openai/types/responses/response_audio_transcript_delta_event.py create mode 100644 src/openai/types/responses/response_audio_transcript_done_event.py create mode 100644 src/openai/types/responses/response_code_interpreter_call_code_delta_event.py create mode 100644 src/openai/types/responses/response_code_interpreter_call_code_done_event.py create mode 100644 src/openai/types/responses/response_code_interpreter_call_completed_event.py create mode 100644 src/openai/types/responses/response_code_interpreter_call_in_progress_event.py create mode 100644 src/openai/types/responses/response_code_interpreter_call_interpreting_event.py create mode 100644 src/openai/types/responses/response_code_interpreter_tool_call.py create mode 100644 src/openai/types/responses/response_completed_event.py create mode 100644 src/openai/types/responses/response_computer_tool_call.py create mode 100644 src/openai/types/responses/response_computer_tool_call_param.py create mode 100644 src/openai/types/responses/response_content_part_added_event.py create mode 100644 src/openai/types/responses/response_content_part_done_event.py create mode 100644 src/openai/types/responses/response_create_params.py create mode 100644 src/openai/types/responses/response_created_event.py create mode 100644 src/openai/types/responses/response_error.py create mode 100644 src/openai/types/responses/response_error_event.py create mode 100644 src/openai/types/responses/response_failed_event.py create mode 100644 src/openai/types/responses/response_file_search_call_completed_event.py create mode 100644 src/openai/types/responses/response_file_search_call_in_progress_event.py create mode 100644 src/openai/types/responses/response_file_search_call_searching_event.py create mode 100644 src/openai/types/responses/response_file_search_tool_call.py create mode 100644 src/openai/types/responses/response_file_search_tool_call_param.py create mode 100644 src/openai/types/responses/response_format_text_config.py create mode 100644 src/openai/types/responses/response_format_text_config_param.py create mode 100644 src/openai/types/responses/response_format_text_json_schema_config.py create mode 100644 src/openai/types/responses/response_format_text_json_schema_config_param.py create mode 100644 src/openai/types/responses/response_function_call_arguments_delta_event.py create mode 100644 src/openai/types/responses/response_function_call_arguments_done_event.py create mode 100644 src/openai/types/responses/response_function_tool_call.py create mode 100644 src/openai/types/responses/response_function_tool_call_param.py create mode 100644 src/openai/types/responses/response_function_web_search.py create mode 100644 src/openai/types/responses/response_function_web_search_param.py create mode 100644 src/openai/types/responses/response_in_progress_event.py create mode 100644 src/openai/types/responses/response_includable.py create mode 100644 src/openai/types/responses/response_incomplete_event.py create mode 100644 src/openai/types/responses/response_input_content.py create mode 100644 src/openai/types/responses/response_input_content_param.py create mode 100644 src/openai/types/responses/response_input_file.py create mode 100644 src/openai/types/responses/response_input_file_param.py create mode 100644 src/openai/types/responses/response_input_image.py create mode 100644 src/openai/types/responses/response_input_image_param.py create mode 100644 src/openai/types/responses/response_input_item_param.py create mode 100644 src/openai/types/responses/response_input_message_content_list.py create mode 100644 src/openai/types/responses/response_input_message_content_list_param.py create mode 100644 src/openai/types/responses/response_input_param.py create mode 100644 src/openai/types/responses/response_input_text.py create mode 100644 src/openai/types/responses/response_input_text_param.py create mode 100644 src/openai/types/responses/response_item_list.py create mode 100644 src/openai/types/responses/response_output_item.py create mode 100644 src/openai/types/responses/response_output_item_added_event.py create mode 100644 src/openai/types/responses/response_output_item_done_event.py create mode 100644 src/openai/types/responses/response_output_message.py create mode 100644 src/openai/types/responses/response_output_message_param.py create mode 100644 src/openai/types/responses/response_output_refusal.py create mode 100644 src/openai/types/responses/response_output_refusal_param.py create mode 100644 src/openai/types/responses/response_output_text.py create mode 100644 src/openai/types/responses/response_output_text_param.py create mode 100644 src/openai/types/responses/response_refusal_delta_event.py create mode 100644 src/openai/types/responses/response_refusal_done_event.py create mode 100644 src/openai/types/responses/response_retrieve_params.py create mode 100644 src/openai/types/responses/response_status.py create mode 100644 src/openai/types/responses/response_stream_event.py create mode 100644 src/openai/types/responses/response_text_annotation_delta_event.py create mode 100644 src/openai/types/responses/response_text_config.py create mode 100644 src/openai/types/responses/response_text_config_param.py create mode 100644 src/openai/types/responses/response_text_delta_event.py create mode 100644 src/openai/types/responses/response_text_done_event.py create mode 100644 src/openai/types/responses/response_usage.py create mode 100644 src/openai/types/responses/response_web_search_call_completed_event.py create mode 100644 src/openai/types/responses/response_web_search_call_in_progress_event.py create mode 100644 src/openai/types/responses/response_web_search_call_searching_event.py create mode 100644 src/openai/types/responses/tool.py create mode 100644 src/openai/types/responses/tool_choice_function.py create mode 100644 src/openai/types/responses/tool_choice_function_param.py create mode 100644 src/openai/types/responses/tool_choice_options.py create mode 100644 src/openai/types/responses/tool_choice_types.py create mode 100644 src/openai/types/responses/tool_choice_types_param.py create mode 100644 src/openai/types/responses/tool_param.py create mode 100644 src/openai/types/responses/web_search_tool.py create mode 100644 src/openai/types/responses/web_search_tool_param.py create mode 100644 src/openai/types/shared/comparison_filter.py create mode 100644 src/openai/types/shared/compound_filter.py create mode 100644 src/openai/types/shared/reasoning.py create mode 100644 src/openai/types/shared/reasoning_effort.py create mode 100644 src/openai/types/shared_params/comparison_filter.py create mode 100644 src/openai/types/shared_params/compound_filter.py create mode 100644 src/openai/types/shared_params/reasoning.py create mode 100644 src/openai/types/shared_params/reasoning_effort.py rename src/openai/types/{beta => }/static_file_chunking_strategy.py (94%) rename src/openai/types/{beta => }/static_file_chunking_strategy_object.py (92%) rename src/openai/types/{beta => }/static_file_chunking_strategy_object_param.py (100%) rename src/openai/types/{beta => }/static_file_chunking_strategy_param.py (100%) rename src/openai/types/{beta => }/vector_store.py (97%) rename src/openai/types/{beta => }/vector_store_create_params.py (97%) rename src/openai/types/{beta => }/vector_store_deleted.py (89%) rename src/openai/types/{beta => }/vector_store_list_params.py (100%) create mode 100644 src/openai/types/vector_store_search_params.py create mode 100644 src/openai/types/vector_store_search_response.py rename src/openai/types/{beta => }/vector_store_update_params.py (96%) rename src/openai/types/{beta => }/vector_stores/__init__.py (82%) rename src/openai/types/{beta => }/vector_stores/file_batch_create_params.py (61%) rename src/openai/types/{beta => }/vector_stores/file_batch_list_files_params.py (100%) create mode 100644 src/openai/types/vector_stores/file_content_response.py rename src/openai/types/{beta => }/vector_stores/file_create_params.py (60%) rename src/openai/types/{beta => }/vector_stores/file_list_params.py (100%) create mode 100644 src/openai/types/vector_stores/file_update_params.py rename src/openai/types/{beta => }/vector_stores/vector_store_file.py (76%) rename src/openai/types/{beta => }/vector_stores/vector_store_file_batch.py (97%) rename src/openai/types/{beta => }/vector_stores/vector_store_file_deleted.py (89%) delete mode 100644 tests/api_resources/beta/vector_stores/test_files.py rename tests/api_resources/{beta/vector_stores => responses}/__init__.py (100%) create mode 100644 tests/api_resources/responses/test_input_items.py create mode 100644 tests/api_resources/test_responses.py rename tests/api_resources/{beta => }/test_vector_stores.py (60%) create mode 100644 tests/api_resources/vector_stores/__init__.py rename tests/api_resources/{beta => }/vector_stores/test_file_batches.py (68%) create mode 100644 tests/api_resources/vector_stores/test_files.py diff --git a/.stats.yml b/.stats.yml index 0d7e83be4f..455874212c 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ -configured_endpoints: 74 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-b524aed1c2c5c928aa4e2c546f5dbb364e7b4d5027daf05e42e210b05a97c3c6.yml +configured_endpoints: 81 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-be834d63e326a82494e819085137f5eb15866f3fc787db1f3afe7168d419e18a.yml diff --git a/README.md b/README.md index 3c103f036c..c52bffbb5f 100644 --- a/README.md +++ b/README.md @@ -10,13 +10,10 @@ It is generated from our [OpenAPI specification](https://github.com/openai/opena ## Documentation -The REST API documentation can be found on [platform.openai.com](https://platform.openai.com/docs). The full API of this library can be found in [api.md](api.md). +The REST API documentation can be found on [platform.openai.com](https://platform.openai.com/docs/api-reference). The full API of this library can be found in [api.md](api.md). ## Installation -> [!IMPORTANT] -> The SDK was rewritten in v1, which was released November 6th 2023. See the [v1 migration guide](https://github.com/openai/openai-python/discussions/742), which includes scripts to automatically update your code. - ```sh # install from PyPI pip install openai @@ -26,46 +23,69 @@ pip install openai The full API of this library can be found in [api.md](api.md). +The primary API for interacting with OpenAI models is the [Responses API](https://platform.openai.com/docs/api-reference/responses). You can generate text from the model with the code below. + ```python import os from openai import OpenAI client = OpenAI( - api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + # This is the default and can be omitted + api_key=os.environ.get("OPENAI_API_KEY"), +) + +response = client.responses.create( + model="gpt-4o", + instructions="You are a coding assistant that talks like a pirate.", + input="How do I check if a Python object is an instance of a class?", ) -chat_completion = client.chat.completions.create( +print(response.output_text) +``` + +The previous standard (supported indefinitely) for generating text is the [Chat Completions API](https://platform.openai.com/docs/api-reference/chat). You can use that API to generate text from the model with the code below. + +```python +from openai import OpenAI + +client = OpenAI() + +completion = client.chat.completions.create( + model="gpt-4o", messages=[ + {"role": "developer", "content": "Talk like a pirate."}, { "role": "user", - "content": "Say this is a test", - } + "content": "How do I check if a Python object is an instance of a class?", + }, ], - model="gpt-4o", ) + +print(completion.choices[0].message.content) ``` While you can provide an `api_key` keyword argument, we recommend using [python-dotenv](https://pypi.org/project/python-dotenv/) to add `OPENAI_API_KEY="My API Key"` to your `.env` file -so that your API Key is not stored in source control. +so that your API key is not stored in source control. +[Get an API key here](https://platform.openai.com/settings/organization/api-keys). ### Vision -With a hosted image: +With an image URL: ```python -response = client.chat.completions.create( +prompt = "What is in this image?" +img_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/2023_06_08_Raccoon1.jpg/1599px-2023_06_08_Raccoon1.jpg" + +response = client.responses.create( model="gpt-4o-mini", - messages=[ + input=[ { "role": "user", "content": [ - {"type": "text", "text": prompt}, - { - "type": "image_url", - "image_url": {"url": f"{img_url}"}, - }, + {"type": "input_text", "text": prompt}, + {"type": "input_image", "image_url": f"{img_url}"}, ], } ], @@ -75,73 +95,29 @@ response = client.chat.completions.create( With the image as a base64 encoded string: ```python -response = client.chat.completions.create( +import base64 +from openai import OpenAI + +client = OpenAI() + +prompt = "What is in this image?" +with open("path/to/image.png", "rb") as image_file: + b64_image = base64.b64encode(image_file.read()).decode("utf-8") + +response = client.responses.create( model="gpt-4o-mini", - messages=[ + input=[ { "role": "user", "content": [ - {"type": "text", "text": prompt}, - { - "type": "image_url", - "image_url": {"url": f"data:{img_type};base64,{img_b64_str}"}, - }, + {"type": "input_text", "text": prompt}, + {"type": "input_image", "image_url": f"data:image/png;base64,{b64_image}"}, ], } ], ) ``` -### Polling Helpers - -When interacting with the API some actions such as starting a Run and adding files to vector stores are asynchronous and take time to complete. The SDK includes -helper functions which will poll the status until it reaches a terminal state and then return the resulting object. -If an API method results in an action that could benefit from polling there will be a corresponding version of the -method ending in '\_and_poll'. - -For instance to create a Run and poll until it reaches a terminal state you can run: - -```python -run = client.beta.threads.runs.create_and_poll( - thread_id=thread.id, - assistant_id=assistant.id, -) -``` - -More information on the lifecycle of a Run can be found in the [Run Lifecycle Documentation](https://platform.openai.com/docs/assistants/how-it-works/run-lifecycle) - -### Bulk Upload Helpers - -When creating and interacting with vector stores, you can use polling helpers to monitor the status of operations. -For convenience, we also provide a bulk upload helper to allow you to simultaneously upload several files at once. - -```python -sample_files = [Path("sample-paper.pdf"), ...] - -batch = await client.vector_stores.file_batches.upload_and_poll( - store.id, - files=sample_files, -) -``` - -### Streaming Helpers - -The SDK also includes helpers to process streams and handle incoming events. - -```python -with client.beta.threads.runs.stream( - thread_id=thread.id, - assistant_id=assistant.id, - instructions="Please address the user as Jane Doe. The user has a premium account.", -) as stream: - for event in stream: - # Print the text from text delta events - if event.type == "thread.message.delta" and event.data.delta.content: - print(event.data.delta.content[0].text) -``` - -More information on streaming helpers can be found in the dedicated documentation: [helpers.md](helpers.md) - ## Async usage Simply import `AsyncOpenAI` instead of `OpenAI` and use `await` with each API call: @@ -152,20 +128,16 @@ import asyncio from openai import AsyncOpenAI client = AsyncOpenAI( - api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + # This is the default and can be omitted + api_key=os.environ.get("OPENAI_API_KEY"), ) async def main() -> None: - chat_completion = await client.chat.completions.create( - messages=[ - { - "role": "user", - "content": "Say this is a test", - } - ], - model="gpt-4o", + response = await client.responses.create( + model="gpt-4o", input="Explain disestablishmentarianism to a smart five year old." ) + print(response.output_text) asyncio.run(main()) @@ -182,18 +154,14 @@ from openai import OpenAI client = OpenAI() -stream = client.chat.completions.create( - messages=[ - { - "role": "user", - "content": "Say this is a test", - } - ], +stream = client.responses.create( model="gpt-4o", + input="Write a one-sentence bedtime story about a unicorn.", stream=True, ) -for chunk in stream: - print(chunk.choices[0].delta.content or "", end="") + +for event in stream: + print(event) ``` The async client uses the exact same interface. @@ -206,58 +174,19 @@ client = AsyncOpenAI() async def main(): - stream = await client.chat.completions.create( - model="gpt-4", - messages=[{"role": "user", "content": "Say this is a test"}], + stream = client.responses.create( + model="gpt-4o", + input="Write a one-sentence bedtime story about a unicorn.", stream=True, ) - async for chunk in stream: - print(chunk.choices[0].delta.content or "", end="") - - -asyncio.run(main()) -``` - -## Module-level client - -> [!IMPORTANT] -> We highly recommend instantiating client instances instead of relying on the global client. -We also expose a global client instance that is accessible in a similar fashion to versions prior to v1. - -```py -import openai - -# optional; defaults to `os.environ['OPENAI_API_KEY']` -openai.api_key = '...' + for event in stream: + print(event) -# all client options can be configured just like the `OpenAI` instantiation counterpart -openai.base_url = "https://.../" -openai.default_headers = {"x-foo": "true"} -completion = openai.chat.completions.create( - model="gpt-4o", - messages=[ - { - "role": "user", - "content": "How do I output all files in a directory using Python?", - }, - ], -) -print(completion.choices[0].message.content) +asyncio.run(main()) ``` -The API is the exact same as the standard client instance-based API. - -This is intended to be used within REPLs or notebooks for faster iteration, **not** in application code. - -We recommend that you always instantiate a client (e.g., with `client = OpenAI()`) in application code because: - -- It can be difficult to reason about where client options are configured -- It's not possible to change certain client options without potentially causing race conditions -- It's harder to mock for testing purposes -- It's not possible to control cleanup of network connections - ## Realtime API beta The Realtime API enables you to build low-latency, multi-modal conversational experiences. It currently supports text and audio as both input and output, as well as [function calling](https://platform.openai.com/docs/guides/function-calling) through a WebSocket connection. @@ -304,7 +233,7 @@ However the real magic of the Realtime API is handling audio inputs / outputs, s ### Realtime error handling -Whenever an error occurs, the Realtime API will send an [`error` event](https://platform.openai.com/docs/guides/realtime-model-capabilities#error-handling) and the connection will stay open and remain usable. This means you need to handle it yourself, as *no errors are raised directly* by the SDK when an `error` event comes in. +Whenever an error occurs, the Realtime API will send an [`error` event](https://platform.openai.com/docs/guides/realtime-model-capabilities#error-handling) and the connection will stay open and remain usable. This means you need to handle it yourself, as _no errors are raised directly_ by the SDK when an `error` event comes in. ```py client = AsyncOpenAI() @@ -408,11 +337,11 @@ from openai import OpenAI client = OpenAI() -completion = client.chat.completions.create( - messages=[ +response = client.chat.responses.create( + input=[ { "role": "user", - "content": "Can you generate an example json object describing a fruit?", + "content": "How much ?", } ], model="gpt-4o", @@ -489,15 +418,16 @@ Error codes are as follows: All object responses in the SDK provide a `_request_id` property which is added from the `x-request-id` response header so that you can quickly log failing requests and report them back to OpenAI. ```python -completion = await client.chat.completions.create( - messages=[{"role": "user", "content": "Say this is a test"}], model="gpt-4" +response = await client.responses.create( + model="gpt-4o-mini", + input="Say 'this is a test'.", ) -print(completion._request_id) # req_123 +print(response._request_id) # req_123 ``` Note that unlike other properties that use an `_` prefix, the `_request_id` property -*is* public. Unless documented otherwise, *all* other `_` prefix properties, -methods and modules are *private*. +_is_ public. Unless documented otherwise, _all_ other `_` prefix properties, +methods and modules are _private_. > [!IMPORTANT] > If you need to access request IDs for failed requests you must catch the `APIStatusError` exception @@ -514,8 +444,7 @@ except openai.APIStatusError as exc: raise exc ``` - -### Retries +## Retries Certain errors are automatically retried 2 times by default, with a short exponential backoff. Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, @@ -544,7 +473,7 @@ client.with_options(max_retries=5).chat.completions.create( ) ``` -### Timeouts +## Timeouts By default requests time out after 10 minutes. You can configure this with a `timeout` option, which accepts a float or an [`httpx.Timeout`](https://www.python-httpx.org/advanced/timeouts/#fine-tuning-the-configuration) object: diff --git a/api.md b/api.md index 20e776289e..6827b88f0b 100644 --- a/api.md +++ b/api.md @@ -3,10 +3,14 @@ ```python from openai.types import ( ChatModel, + ComparisonFilter, + CompoundFilter, ErrorObject, FunctionDefinition, FunctionParameters, Metadata, + Reasoning, + ReasoningEffort, ResponseFormatJSONObject, ResponseFormatJSONSchema, ResponseFormatText, @@ -59,7 +63,6 @@ from openai.types.chat import ( ChatCompletionModality, ChatCompletionNamedToolChoice, ChatCompletionPredictionContent, - ChatCompletionReasoningEffort, ChatCompletionRole, ChatCompletionStoreMessage, ChatCompletionStreamOptions, @@ -69,6 +72,7 @@ from openai.types.chat import ( ChatCompletionToolChoiceOption, ChatCompletionToolMessageParam, ChatCompletionUserMessageParam, + ChatCompletionReasoningEffort, ) ``` @@ -249,6 +253,73 @@ Methods: - client.fine_tuning.jobs.checkpoints.list(fine_tuning_job_id, \*\*params) -> SyncCursorPage[FineTuningJobCheckpoint] +# VectorStores + +Types: + +```python +from openai.types import ( + AutoFileChunkingStrategyParam, + FileChunkingStrategy, + FileChunkingStrategyParam, + OtherFileChunkingStrategyObject, + StaticFileChunkingStrategy, + StaticFileChunkingStrategyObject, + StaticFileChunkingStrategyObjectParam, + VectorStore, + VectorStoreDeleted, + VectorStoreSearchResponse, +) +``` + +Methods: + +- client.vector_stores.create(\*\*params) -> VectorStore +- client.vector_stores.retrieve(vector_store_id) -> VectorStore +- client.vector_stores.update(vector_store_id, \*\*params) -> VectorStore +- client.vector_stores.list(\*\*params) -> SyncCursorPage[VectorStore] +- client.vector_stores.delete(vector_store_id) -> VectorStoreDeleted +- client.vector_stores.search(vector_store_id, \*\*params) -> SyncPage[VectorStoreSearchResponse] + +## Files + +Types: + +```python +from openai.types.vector_stores import VectorStoreFile, VectorStoreFileDeleted, FileContentResponse +``` + +Methods: + +- client.vector_stores.files.create(vector_store_id, \*\*params) -> VectorStoreFile +- client.vector_stores.files.retrieve(file_id, \*, vector_store_id) -> VectorStoreFile +- client.vector_stores.files.update(file_id, \*, vector_store_id, \*\*params) -> VectorStoreFile +- client.vector_stores.files.list(vector_store_id, \*\*params) -> SyncCursorPage[VectorStoreFile] +- client.vector_stores.files.delete(file_id, \*, vector_store_id) -> VectorStoreFileDeleted +- client.vector_stores.files.content(file_id, \*, vector_store_id) -> SyncPage[FileContentResponse] +- client.vector_stores.files.create_and_poll(\*args) -> VectorStoreFile +- client.vector_stores.files.poll(\*args) -> VectorStoreFile +- client.vector_stores.files.upload(\*args) -> VectorStoreFile +- client.vector_stores.files.upload_and_poll(\*args) -> VectorStoreFile + +## FileBatches + +Types: + +```python +from openai.types.vector_stores import VectorStoreFileBatch +``` + +Methods: + +- client.vector_stores.file_batches.create(vector_store_id, \*\*params) -> VectorStoreFileBatch +- client.vector_stores.file_batches.retrieve(batch_id, \*, vector_store_id) -> VectorStoreFileBatch +- client.vector_stores.file_batches.cancel(batch_id, \*, vector_store_id) -> VectorStoreFileBatch +- client.vector_stores.file_batches.list_files(batch_id, \*, vector_store_id, \*\*params) -> SyncCursorPage[VectorStoreFile] +- client.vector_stores.file_batches.create_and_poll(\*args) -> VectorStoreFileBatch +- client.vector_stores.file_batches.poll(\*args) -> VectorStoreFileBatch +- client.vector_stores.file_batches.upload_and_poll(\*args) -> VectorStoreFileBatch + # Beta ## Realtime @@ -317,69 +388,6 @@ Methods: - client.beta.realtime.sessions.create(\*\*params) -> SessionCreateResponse -## VectorStores - -Types: - -```python -from openai.types.beta import ( - AutoFileChunkingStrategyParam, - FileChunkingStrategy, - FileChunkingStrategyParam, - OtherFileChunkingStrategyObject, - StaticFileChunkingStrategy, - StaticFileChunkingStrategyObject, - StaticFileChunkingStrategyObjectParam, - VectorStore, - VectorStoreDeleted, -) -``` - -Methods: - -- client.beta.vector_stores.create(\*\*params) -> VectorStore -- client.beta.vector_stores.retrieve(vector_store_id) -> VectorStore -- client.beta.vector_stores.update(vector_store_id, \*\*params) -> VectorStore -- client.beta.vector_stores.list(\*\*params) -> SyncCursorPage[VectorStore] -- client.beta.vector_stores.delete(vector_store_id) -> VectorStoreDeleted - -### Files - -Types: - -```python -from openai.types.beta.vector_stores import VectorStoreFile, VectorStoreFileDeleted -``` - -Methods: - -- client.beta.vector_stores.files.create(vector_store_id, \*\*params) -> VectorStoreFile -- client.beta.vector_stores.files.retrieve(file_id, \*, vector_store_id) -> VectorStoreFile -- client.beta.vector_stores.files.list(vector_store_id, \*\*params) -> SyncCursorPage[VectorStoreFile] -- client.beta.vector_stores.files.delete(file_id, \*, vector_store_id) -> VectorStoreFileDeleted -- client.beta.vector_stores.files.create_and_poll(\*args) -> VectorStoreFile -- client.beta.vector_stores.files.poll(\*args) -> VectorStoreFile -- client.beta.vector_stores.files.upload(\*args) -> VectorStoreFile -- client.beta.vector_stores.files.upload_and_poll(\*args) -> VectorStoreFile - -### FileBatches - -Types: - -```python -from openai.types.beta.vector_stores import VectorStoreFileBatch -``` - -Methods: - -- client.beta.vector_stores.file_batches.create(vector_store_id, \*\*params) -> VectorStoreFileBatch -- client.beta.vector_stores.file_batches.retrieve(batch_id, \*, vector_store_id) -> VectorStoreFileBatch -- client.beta.vector_stores.file_batches.cancel(batch_id, \*, vector_store_id) -> VectorStoreFileBatch -- client.beta.vector_stores.file_batches.list_files(batch_id, \*, vector_store_id, \*\*params) -> SyncCursorPage[VectorStoreFile] -- client.beta.vector_stores.file_batches.create_and_poll(\*args) -> VectorStoreFileBatch -- client.beta.vector_stores.file_batches.poll(\*args) -> VectorStoreFileBatch -- client.beta.vector_stores.file_batches.upload_and_poll(\*args) -> VectorStoreFileBatch - ## Assistants Types: @@ -573,3 +581,99 @@ from openai.types.uploads import UploadPart Methods: - client.uploads.parts.create(upload_id, \*\*params) -> UploadPart + +# Responses + +Types: + +```python +from openai.types.responses import ( + ComputerTool, + EasyInputMessage, + FileSearchTool, + FunctionTool, + Response, + ResponseAudioDeltaEvent, + ResponseAudioDoneEvent, + ResponseAudioTranscriptDeltaEvent, + ResponseAudioTranscriptDoneEvent, + ResponseCodeInterpreterCallCodeDeltaEvent, + ResponseCodeInterpreterCallCodeDoneEvent, + ResponseCodeInterpreterCallCompletedEvent, + ResponseCodeInterpreterCallInProgressEvent, + ResponseCodeInterpreterCallInterpretingEvent, + ResponseCodeInterpreterToolCall, + ResponseCompletedEvent, + ResponseComputerToolCall, + ResponseContent, + ResponseContentPartAddedEvent, + ResponseContentPartDoneEvent, + ResponseCreatedEvent, + ResponseError, + ResponseErrorEvent, + ResponseFailedEvent, + ResponseFileSearchCallCompletedEvent, + ResponseFileSearchCallInProgressEvent, + ResponseFileSearchCallSearchingEvent, + ResponseFileSearchToolCall, + ResponseFormatTextConfig, + ResponseFormatTextJSONSchemaConfig, + ResponseFunctionCallArgumentsDeltaEvent, + ResponseFunctionCallArgumentsDoneEvent, + ResponseFunctionToolCall, + ResponseFunctionWebSearch, + ResponseInProgressEvent, + ResponseIncludable, + ResponseIncompleteEvent, + ResponseInput, + ResponseInputAudio, + ResponseInputContent, + ResponseInputFile, + ResponseInputImage, + ResponseInputItem, + ResponseInputMessageContentList, + ResponseInputText, + ResponseOutputAudio, + ResponseOutputItem, + ResponseOutputItemAddedEvent, + ResponseOutputItemDoneEvent, + ResponseOutputMessage, + ResponseOutputRefusal, + ResponseOutputText, + ResponseRefusalDeltaEvent, + ResponseRefusalDoneEvent, + ResponseStatus, + ResponseStreamEvent, + ResponseTextAnnotationDeltaEvent, + ResponseTextConfig, + ResponseTextDeltaEvent, + ResponseTextDoneEvent, + ResponseUsage, + ResponseWebSearchCallCompletedEvent, + ResponseWebSearchCallInProgressEvent, + ResponseWebSearchCallSearchingEvent, + Tool, + ToolChoiceFunction, + ToolChoiceOptions, + ToolChoiceTypes, + WebSearchTool, +) +``` + +Methods: + +- client.responses.create(\*\*params) -> Response +- client.responses.retrieve(response_id, \*\*params) -> Response +- client.responses.delete(response_id) -> None + +## InputItems + +Types: + +```python +from openai.types.responses import ResponseItemList +``` + +Methods: + +- client.responses.input_items.list(response_id, \*\*params) -> SyncCursorPage[Data] diff --git a/examples/responses/__init__.py b/examples/responses/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/examples/responses/streaming.py b/examples/responses/streaming.py new file mode 100644 index 0000000000..39787968d6 --- /dev/null +++ b/examples/responses/streaming.py @@ -0,0 +1,30 @@ +from typing import List + +import rich +from pydantic import BaseModel + +from openai import OpenAI + + +class Step(BaseModel): + explanation: str + output: str + + +class MathResponse(BaseModel): + steps: List[Step] + final_answer: str + + +client = OpenAI() + +with client.responses.stream( + input="solve 8x + 31 = 2", + model="gpt-4o-2024-08-06", + text_format=MathResponse, +) as stream: + for event in stream: + if "output_text" in event.type: + rich.print(event) + +rich.print(stream.get_final_response()) diff --git a/examples/responses/streaming_tools.py b/examples/responses/streaming_tools.py new file mode 100644 index 0000000000..f40cd9356d --- /dev/null +++ b/examples/responses/streaming_tools.py @@ -0,0 +1,68 @@ +from enum import Enum +from typing import List, Union + +import rich +from pydantic import BaseModel + +import openai +from openai import OpenAI + + +class Table(str, Enum): + orders = "orders" + customers = "customers" + products = "products" + + +class Column(str, Enum): + id = "id" + status = "status" + expected_delivery_date = "expected_delivery_date" + delivered_at = "delivered_at" + shipped_at = "shipped_at" + ordered_at = "ordered_at" + canceled_at = "canceled_at" + + +class Operator(str, Enum): + eq = "=" + gt = ">" + lt = "<" + le = "<=" + ge = ">=" + ne = "!=" + + +class OrderBy(str, Enum): + asc = "asc" + desc = "desc" + + +class DynamicValue(BaseModel): + column_name: str + + +class Condition(BaseModel): + column: str + operator: Operator + value: Union[str, int, DynamicValue] + + +class Query(BaseModel): + table_name: Table + columns: List[Column] + conditions: List[Condition] + order_by: OrderBy + + +client = OpenAI() + +with client.responses.stream( + model="gpt-4o-2024-08-06", + input="look up all my orders in november of last year that were fulfilled but not delivered on time", + tools=[ + openai.pydantic_function_tool(Query), + ], +) as stream: + for event in stream: + rich.print(event) diff --git a/examples/responses/structured_outputs.py b/examples/responses/structured_outputs.py new file mode 100644 index 0000000000..0b146bc0bc --- /dev/null +++ b/examples/responses/structured_outputs.py @@ -0,0 +1,55 @@ +from typing import List + +import rich +from pydantic import BaseModel + +from openai import OpenAI + + +class Step(BaseModel): + explanation: str + output: str + + +class MathResponse(BaseModel): + steps: List[Step] + final_answer: str + + +client = OpenAI() + +rsp = client.responses.parse( + input="solve 8x + 31 = 2", + model="gpt-4o-2024-08-06", + text_format=MathResponse, +) + +for output in rsp.output: + if output.type != "message": + raise Exception("Unexpected non message") + + for item in output.content: + if item.type != "output_text": + raise Exception("unexpected output type") + + if not item.parsed: + raise Exception("Could not parse response") + + rich.print(item.parsed) + + print("answer: ", item.parsed.final_answer) + +# or + +message = rsp.output[0] +assert message.type == "message" + +text = message.content[0] +assert text.type == "output_text" + +if not text.parsed: + raise Exception("Could not parse response") + +rich.print(text.parsed) + +print("answer: ", text.parsed.final_answer) diff --git a/examples/responses/structured_outputs_tools.py b/examples/responses/structured_outputs_tools.py new file mode 100644 index 0000000000..918348207d --- /dev/null +++ b/examples/responses/structured_outputs_tools.py @@ -0,0 +1,73 @@ +from enum import Enum +from typing import List, Union + +import rich +from pydantic import BaseModel + +import openai +from openai import OpenAI + + +class Table(str, Enum): + orders = "orders" + customers = "customers" + products = "products" + + +class Column(str, Enum): + id = "id" + status = "status" + expected_delivery_date = "expected_delivery_date" + delivered_at = "delivered_at" + shipped_at = "shipped_at" + ordered_at = "ordered_at" + canceled_at = "canceled_at" + + +class Operator(str, Enum): + eq = "=" + gt = ">" + lt = "<" + le = "<=" + ge = ">=" + ne = "!=" + + +class OrderBy(str, Enum): + asc = "asc" + desc = "desc" + + +class DynamicValue(BaseModel): + column_name: str + + +class Condition(BaseModel): + column: str + operator: Operator + value: Union[str, int, DynamicValue] + + +class Query(BaseModel): + table_name: Table + columns: List[Column] + conditions: List[Condition] + order_by: OrderBy + + +client = OpenAI() + +response = client.responses.parse( + model="gpt-4o-2024-08-06", + input="look up all my orders in november of last year that were fulfilled but not delivered on time", + tools=[ + openai.pydantic_function_tool(Query), + ], +) + +rich.print(response) + +function_call = response.output[0] +assert function_call.type == "function_call" +assert isinstance(function_call.parsed_arguments, Query) +print("table name:", function_call.parsed_arguments.table_name) diff --git a/src/openai/_client.py b/src/openai/_client.py index 2464c6504c..18d96da9a3 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -37,7 +37,9 @@ from .resources.chat import chat from .resources.audio import audio from .resources.uploads import uploads +from .resources.responses import responses from .resources.fine_tuning import fine_tuning +from .resources.vector_stores import vector_stores __all__ = ["Timeout", "Transport", "ProxiesTypes", "RequestOptions", "OpenAI", "AsyncOpenAI", "Client", "AsyncClient"] @@ -52,9 +54,11 @@ class OpenAI(SyncAPIClient): moderations: moderations.Moderations models: models.Models fine_tuning: fine_tuning.FineTuning + vector_stores: vector_stores.VectorStores beta: beta.Beta batches: batches.Batches uploads: uploads.Uploads + responses: responses.Responses with_raw_response: OpenAIWithRawResponse with_streaming_response: OpenAIWithStreamedResponse @@ -149,9 +153,11 @@ def __init__( self.moderations = moderations.Moderations(self) self.models = models.Models(self) self.fine_tuning = fine_tuning.FineTuning(self) + self.vector_stores = vector_stores.VectorStores(self) self.beta = beta.Beta(self) self.batches = batches.Batches(self) self.uploads = uploads.Uploads(self) + self.responses = responses.Responses(self) self.with_raw_response = OpenAIWithRawResponse(self) self.with_streaming_response = OpenAIWithStreamedResponse(self) @@ -279,9 +285,11 @@ class AsyncOpenAI(AsyncAPIClient): moderations: moderations.AsyncModerations models: models.AsyncModels fine_tuning: fine_tuning.AsyncFineTuning + vector_stores: vector_stores.AsyncVectorStores beta: beta.AsyncBeta batches: batches.AsyncBatches uploads: uploads.AsyncUploads + responses: responses.AsyncResponses with_raw_response: AsyncOpenAIWithRawResponse with_streaming_response: AsyncOpenAIWithStreamedResponse @@ -376,9 +384,11 @@ def __init__( self.moderations = moderations.AsyncModerations(self) self.models = models.AsyncModels(self) self.fine_tuning = fine_tuning.AsyncFineTuning(self) + self.vector_stores = vector_stores.AsyncVectorStores(self) self.beta = beta.AsyncBeta(self) self.batches = batches.AsyncBatches(self) self.uploads = uploads.AsyncUploads(self) + self.responses = responses.AsyncResponses(self) self.with_raw_response = AsyncOpenAIWithRawResponse(self) self.with_streaming_response = AsyncOpenAIWithStreamedResponse(self) @@ -507,9 +517,11 @@ def __init__(self, client: OpenAI) -> None: self.moderations = moderations.ModerationsWithRawResponse(client.moderations) self.models = models.ModelsWithRawResponse(client.models) self.fine_tuning = fine_tuning.FineTuningWithRawResponse(client.fine_tuning) + self.vector_stores = vector_stores.VectorStoresWithRawResponse(client.vector_stores) self.beta = beta.BetaWithRawResponse(client.beta) self.batches = batches.BatchesWithRawResponse(client.batches) self.uploads = uploads.UploadsWithRawResponse(client.uploads) + self.responses = responses.ResponsesWithRawResponse(client.responses) class AsyncOpenAIWithRawResponse: @@ -523,9 +535,11 @@ def __init__(self, client: AsyncOpenAI) -> None: self.moderations = moderations.AsyncModerationsWithRawResponse(client.moderations) self.models = models.AsyncModelsWithRawResponse(client.models) self.fine_tuning = fine_tuning.AsyncFineTuningWithRawResponse(client.fine_tuning) + self.vector_stores = vector_stores.AsyncVectorStoresWithRawResponse(client.vector_stores) self.beta = beta.AsyncBetaWithRawResponse(client.beta) self.batches = batches.AsyncBatchesWithRawResponse(client.batches) self.uploads = uploads.AsyncUploadsWithRawResponse(client.uploads) + self.responses = responses.AsyncResponsesWithRawResponse(client.responses) class OpenAIWithStreamedResponse: @@ -539,9 +553,11 @@ def __init__(self, client: OpenAI) -> None: self.moderations = moderations.ModerationsWithStreamingResponse(client.moderations) self.models = models.ModelsWithStreamingResponse(client.models) self.fine_tuning = fine_tuning.FineTuningWithStreamingResponse(client.fine_tuning) + self.vector_stores = vector_stores.VectorStoresWithStreamingResponse(client.vector_stores) self.beta = beta.BetaWithStreamingResponse(client.beta) self.batches = batches.BatchesWithStreamingResponse(client.batches) self.uploads = uploads.UploadsWithStreamingResponse(client.uploads) + self.responses = responses.ResponsesWithStreamingResponse(client.responses) class AsyncOpenAIWithStreamedResponse: @@ -555,9 +571,11 @@ def __init__(self, client: AsyncOpenAI) -> None: self.moderations = moderations.AsyncModerationsWithStreamingResponse(client.moderations) self.models = models.AsyncModelsWithStreamingResponse(client.models) self.fine_tuning = fine_tuning.AsyncFineTuningWithStreamingResponse(client.fine_tuning) + self.vector_stores = vector_stores.AsyncVectorStoresWithStreamingResponse(client.vector_stores) self.beta = beta.AsyncBetaWithStreamingResponse(client.beta) self.batches = batches.AsyncBatchesWithStreamingResponse(client.batches) self.uploads = uploads.AsyncUploadsWithStreamingResponse(client.uploads) + self.responses = responses.AsyncResponsesWithStreamingResponse(client.responses) Client = OpenAI diff --git a/src/openai/_streaming.py b/src/openai/_streaming.py index 0fda992cff..9cb72ffe17 100644 --- a/src/openai/_streaming.py +++ b/src/openai/_streaming.py @@ -59,7 +59,7 @@ def __stream__(self) -> Iterator[_T]: if sse.data.startswith("[DONE]"): break - if sse.event is None: + if sse.event is None or sse.event.startswith("response."): data = sse.json() if is_mapping(data) and data.get("error"): message = None @@ -161,7 +161,7 @@ async def __stream__(self) -> AsyncIterator[_T]: if sse.data.startswith("[DONE]"): break - if sse.event is None: + if sse.event is None or sse.event.startswith("response."): data = sse.json() if is_mapping(data) and data.get("error"): message = None diff --git a/src/openai/lib/_parsing/_responses.py b/src/openai/lib/_parsing/_responses.py new file mode 100644 index 0000000000..a189dcf937 --- /dev/null +++ b/src/openai/lib/_parsing/_responses.py @@ -0,0 +1,168 @@ +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, Any, List, Iterable, cast +from typing_extensions import TypeVar, assert_never + +import pydantic + +from .._tools import ResponsesPydanticFunctionTool +from ..._types import NotGiven +from ..._utils import is_given +from ..._compat import PYDANTIC_V2, model_parse_json +from ..._models import construct_type_unchecked +from .._pydantic import is_basemodel_type, is_dataclass_like_type +from ._completions import solve_response_format_t, type_to_response_format_param +from ...types.responses import ( + Response, + ToolParam, + ParsedContent, + ParsedResponse, + FunctionToolParam, + ParsedResponseOutputItem, + ParsedResponseOutputText, + ResponseFunctionToolCall, + ParsedResponseOutputMessage, + ResponseFormatTextConfigParam, + ParsedResponseFunctionToolCall, +) +from ...types.chat.completion_create_params import ResponseFormat + +TextFormatT = TypeVar( + "TextFormatT", + # if it isn't given then we don't do any parsing + default=None, +) + + +def type_to_text_format_param(type_: type) -> ResponseFormatTextConfigParam: + response_format_dict = type_to_response_format_param(type_) + assert is_given(response_format_dict) + response_format_dict = cast(ResponseFormat, response_format_dict) # pyright: ignore[reportUnnecessaryCast] + assert response_format_dict["type"] == "json_schema" + assert "schema" in response_format_dict["json_schema"] + + return { + "type": "json_schema", + "strict": True, + "name": response_format_dict["json_schema"]["name"], + "schema": response_format_dict["json_schema"]["schema"], + } + + +def parse_response( + *, + text_format: type[TextFormatT] | NotGiven, + input_tools: Iterable[ToolParam] | NotGiven | None, + response: Response | ParsedResponse[object], +) -> ParsedResponse[TextFormatT]: + solved_t = solve_response_format_t(text_format) + output_list: List[ParsedResponseOutputItem[TextFormatT]] = [] + + for output in response.output: + if output.type == "message": + content_list: List[ParsedContent[TextFormatT]] = [] + for item in output.content: + if item.type != "output_text": + content_list.append(item) + continue + + content_list.append( + construct_type_unchecked( + type_=cast(Any, ParsedResponseOutputText)[solved_t], + value={ + **item.to_dict(), + "parsed": parse_text(item.text, text_format=text_format), + }, + ) + ) + + output_list.append( + construct_type_unchecked( + type_=cast(Any, ParsedResponseOutputMessage)[solved_t], + value={ + **output.to_dict(), + "content": content_list, + }, + ) + ) + elif output.type == "function_call": + output_list.append( + construct_type_unchecked( + type_=ParsedResponseFunctionToolCall, + value={ + **output.to_dict(), + "parsed_arguments": parse_function_tool_arguments( + input_tools=input_tools, function_call=output + ), + }, + ) + ) + elif ( + output.type == "computer_call" + or output.type == "file_search_call" + or output.type == "web_search_call" + or output.type == "reasoning" + ): + output_list.append(output) + elif TYPE_CHECKING: # type: ignore + assert_never(output) + else: + output_list.append(output) + + return cast( + ParsedResponse[TextFormatT], + construct_type_unchecked( + type_=cast(Any, ParsedResponse)[solved_t], + value={ + **response.to_dict(), + "output": output_list, + }, + ), + ) + + +def parse_text(text: str, text_format: type[TextFormatT] | NotGiven) -> TextFormatT | None: + if not is_given(text_format): + return None + + if is_basemodel_type(text_format): + return cast(TextFormatT, model_parse_json(text_format, text)) + + if is_dataclass_like_type(text_format): + if not PYDANTIC_V2: + raise TypeError(f"Non BaseModel types are only supported with Pydantic v2 - {text_format}") + + return pydantic.TypeAdapter(text_format).validate_json(text) + + raise TypeError(f"Unable to automatically parse response format type {text_format}") + + +def get_input_tool_by_name(*, input_tools: Iterable[ToolParam], name: str) -> FunctionToolParam | None: + for tool in input_tools: + if tool["type"] == "function" and tool.get("name") == name: + return tool + + return None + + +def parse_function_tool_arguments( + *, + input_tools: Iterable[ToolParam] | NotGiven | None, + function_call: ParsedResponseFunctionToolCall | ResponseFunctionToolCall, +) -> object: + if input_tools is None or not is_given(input_tools): + return None + + input_tool = get_input_tool_by_name(input_tools=input_tools, name=function_call.name) + if not input_tool: + return None + + tool = cast(object, input_tool) + if isinstance(tool, ResponsesPydanticFunctionTool): + return model_parse_json(tool.model, function_call.arguments) + + if not input_tool.get("strict"): + return None + + return json.loads(function_call.arguments) diff --git a/src/openai/lib/_tools.py b/src/openai/lib/_tools.py index 8478ed676c..415d750074 100644 --- a/src/openai/lib/_tools.py +++ b/src/openai/lib/_tools.py @@ -7,6 +7,7 @@ from ._pydantic import to_strict_json_schema from ..types.chat import ChatCompletionToolParam from ..types.shared_params import FunctionDefinition +from ..types.responses.function_tool_param import FunctionToolParam as ResponsesFunctionToolParam class PydanticFunctionTool(Dict[str, Any]): @@ -25,6 +26,17 @@ def cast(self) -> FunctionDefinition: return cast(FunctionDefinition, self) +class ResponsesPydanticFunctionTool(Dict[str, Any]): + model: type[pydantic.BaseModel] + + def __init__(self, tool: ResponsesFunctionToolParam, model: type[pydantic.BaseModel]) -> None: + super().__init__(tool) + self.model = model + + def cast(self) -> ResponsesFunctionToolParam: + return cast(ResponsesFunctionToolParam, self) + + def pydantic_function_tool( model: type[pydantic.BaseModel], *, diff --git a/src/openai/lib/streaming/responses/__init__.py b/src/openai/lib/streaming/responses/__init__.py new file mode 100644 index 0000000000..ff073633bf --- /dev/null +++ b/src/openai/lib/streaming/responses/__init__.py @@ -0,0 +1,13 @@ +from ._events import ( + ResponseTextDoneEvent as ResponseTextDoneEvent, + ResponseTextDeltaEvent as ResponseTextDeltaEvent, + ResponseFunctionCallArgumentsDeltaEvent as ResponseFunctionCallArgumentsDeltaEvent, +) +from ._responses import ( + ResponseStream as ResponseStream, + AsyncResponseStream as AsyncResponseStream, + ResponseStreamEvent as ResponseStreamEvent, + ResponseStreamState as ResponseStreamState, + ResponseStreamManager as ResponseStreamManager, + AsyncResponseStreamManager as AsyncResponseStreamManager, +) diff --git a/src/openai/lib/streaming/responses/_events.py b/src/openai/lib/streaming/responses/_events.py new file mode 100644 index 0000000000..fe17edf649 --- /dev/null +++ b/src/openai/lib/streaming/responses/_events.py @@ -0,0 +1,106 @@ +from __future__ import annotations + +from typing import Optional +from typing_extensions import Union, Generic, TypeVar, Annotated, TypeAlias + +from ...._utils import PropertyInfo +from ...._compat import GenericModel +from ....types.responses import ( + ParsedResponse, + ResponseErrorEvent, + ResponseFailedEvent, + ResponseCreatedEvent, + ResponseTextDoneEvent as RawResponseTextDoneEvent, + ResponseAudioDoneEvent, + ResponseCompletedEvent as RawResponseCompletedEvent, + ResponseTextDeltaEvent as RawResponseTextDeltaEvent, + ResponseAudioDeltaEvent, + ResponseIncompleteEvent, + ResponseInProgressEvent, + ResponseRefusalDoneEvent, + ResponseRefusalDeltaEvent, + ResponseOutputItemDoneEvent, + ResponseContentPartDoneEvent, + ResponseOutputItemAddedEvent, + ResponseContentPartAddedEvent, + ResponseAudioTranscriptDoneEvent, + ResponseTextAnnotationDeltaEvent, + ResponseAudioTranscriptDeltaEvent, + ResponseWebSearchCallCompletedEvent, + ResponseWebSearchCallSearchingEvent, + ResponseFileSearchCallCompletedEvent, + ResponseFileSearchCallSearchingEvent, + ResponseWebSearchCallInProgressEvent, + ResponseFileSearchCallInProgressEvent, + ResponseFunctionCallArgumentsDoneEvent, + ResponseFunctionCallArgumentsDeltaEvent as RawResponseFunctionCallArgumentsDeltaEvent, + ResponseCodeInterpreterCallCodeDoneEvent, + ResponseCodeInterpreterCallCodeDeltaEvent, + ResponseCodeInterpreterCallCompletedEvent, + ResponseCodeInterpreterCallInProgressEvent, + ResponseCodeInterpreterCallInterpretingEvent, +) + +TextFormatT = TypeVar( + "TextFormatT", + # if it isn't given then we don't do any parsing + default=None, +) + + +class ResponseTextDeltaEvent(RawResponseTextDeltaEvent): + snapshot: str + + +class ResponseTextDoneEvent(RawResponseTextDoneEvent, GenericModel, Generic[TextFormatT]): + parsed: Optional[TextFormatT] = None + + +class ResponseFunctionCallArgumentsDeltaEvent(RawResponseFunctionCallArgumentsDeltaEvent): + snapshot: str + + +class ResponseCompletedEvent(RawResponseCompletedEvent, GenericModel, Generic[TextFormatT]): + response: ParsedResponse[TextFormatT] # type: ignore[assignment] + + +ResponseStreamEvent: TypeAlias = Annotated[ + Union[ + # wrappers with snapshots added on + ResponseTextDeltaEvent, + ResponseTextDoneEvent[TextFormatT], + ResponseFunctionCallArgumentsDeltaEvent, + ResponseCompletedEvent[TextFormatT], + # the same as the non-accumulated API + ResponseAudioDeltaEvent, + ResponseAudioDoneEvent, + ResponseAudioTranscriptDeltaEvent, + ResponseAudioTranscriptDoneEvent, + ResponseCodeInterpreterCallCodeDeltaEvent, + ResponseCodeInterpreterCallCodeDoneEvent, + ResponseCodeInterpreterCallCompletedEvent, + ResponseCodeInterpreterCallInProgressEvent, + ResponseCodeInterpreterCallInterpretingEvent, + ResponseContentPartAddedEvent, + ResponseContentPartDoneEvent, + ResponseCreatedEvent, + ResponseErrorEvent, + ResponseFileSearchCallCompletedEvent, + ResponseFileSearchCallInProgressEvent, + ResponseFileSearchCallSearchingEvent, + ResponseFunctionCallArgumentsDoneEvent, + ResponseInProgressEvent, + ResponseFailedEvent, + ResponseIncompleteEvent, + ResponseOutputItemAddedEvent, + ResponseOutputItemDoneEvent, + ResponseRefusalDeltaEvent, + ResponseRefusalDoneEvent, + ResponseTextAnnotationDeltaEvent, + ResponseTextDoneEvent, + ResponseWebSearchCallCompletedEvent, + ResponseWebSearchCallInProgressEvent, + ResponseWebSearchCallSearchingEvent, + ], + PropertyInfo(discriminator="type"), +] diff --git a/src/openai/lib/streaming/responses/_responses.py b/src/openai/lib/streaming/responses/_responses.py new file mode 100644 index 0000000000..f8f4b64174 --- /dev/null +++ b/src/openai/lib/streaming/responses/_responses.py @@ -0,0 +1,354 @@ +from __future__ import annotations + +import inspect +from types import TracebackType +from typing import Any, List, Generic, Iterable, Awaitable, cast +from typing_extensions import Self, Callable, Iterator, AsyncIterator + +from ._types import ParsedResponseSnapshot +from ._events import ( + ResponseStreamEvent, + ResponseTextDoneEvent, + ResponseCompletedEvent, + ResponseTextDeltaEvent, + ResponseFunctionCallArgumentsDeltaEvent, +) +from ...._types import NOT_GIVEN, NotGiven +from ...._utils import is_given, consume_sync_iterator, consume_async_iterator +from ...._models import build, construct_type_unchecked +from ...._streaming import Stream, AsyncStream +from ....types.responses import ParsedResponse, ResponseStreamEvent as RawResponseStreamEvent +from ..._parsing._responses import TextFormatT, parse_text, parse_response +from ....types.responses.tool_param import ToolParam +from ....types.responses.parsed_response import ( + ParsedContent, + ParsedResponseOutputMessage, + ParsedResponseFunctionToolCall, +) + + +class ResponseStream(Generic[TextFormatT]): + def __init__( + self, + *, + raw_stream: Stream[RawResponseStreamEvent], + text_format: type[TextFormatT] | NotGiven, + input_tools: Iterable[ToolParam] | NotGiven, + ) -> None: + self._raw_stream = raw_stream + self._response = raw_stream.response + self._iterator = self.__stream__() + self._state = ResponseStreamState(text_format=text_format, input_tools=input_tools) + + def __next__(self) -> ResponseStreamEvent[TextFormatT]: + return self._iterator.__next__() + + def __iter__(self) -> Iterator[ResponseStreamEvent[TextFormatT]]: + for item in self._iterator: + yield item + + def __enter__(self) -> Self: + return self + + def __stream__(self) -> Iterator[ResponseStreamEvent[TextFormatT]]: + for sse_event in self._raw_stream: + events_to_fire = self._state.handle_event(sse_event) + for event in events_to_fire: + yield event + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + self.close() + + def close(self) -> None: + """ + Close the response and release the connection. + + Automatically called if the response body is read to completion. + """ + self._response.close() + + def get_final_response(self) -> ParsedResponse[TextFormatT]: + """Waits until the stream has been read to completion and returns + the accumulated `ParsedResponse` object. + """ + self.until_done() + response = self._state._completed_response + if not response: + raise RuntimeError("Didn't receive a `response.completed` event.") + + return response + + def until_done(self) -> Self: + """Blocks until the stream has been consumed.""" + consume_sync_iterator(self) + return self + + +class ResponseStreamManager(Generic[TextFormatT]): + def __init__( + self, + api_request: Callable[[], Stream[RawResponseStreamEvent]], + *, + text_format: type[TextFormatT] | NotGiven, + input_tools: Iterable[ToolParam] | NotGiven, + ) -> None: + self.__stream: ResponseStream[TextFormatT] | None = None + self.__api_request = api_request + self.__text_format = text_format + self.__input_tools = input_tools + + def __enter__(self) -> ResponseStream[TextFormatT]: + raw_stream = self.__api_request() + + self.__stream = ResponseStream( + raw_stream=raw_stream, + text_format=self.__text_format, + input_tools=self.__input_tools, + ) + + return self.__stream + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self.__stream is not None: + self.__stream.close() + + +class AsyncResponseStream(Generic[TextFormatT]): + def __init__( + self, + *, + raw_stream: AsyncStream[RawResponseStreamEvent], + text_format: type[TextFormatT] | NotGiven, + input_tools: Iterable[ToolParam] | NotGiven, + ) -> None: + self._raw_stream = raw_stream + self._response = raw_stream.response + self._iterator = self.__stream__() + self._state = ResponseStreamState(text_format=text_format, input_tools=input_tools) + + async def __anext__(self) -> ResponseStreamEvent[TextFormatT]: + return await self._iterator.__anext__() + + async def __aiter__(self) -> AsyncIterator[ResponseStreamEvent[TextFormatT]]: + async for item in self._iterator: + yield item + + async def __stream__(self) -> AsyncIterator[ResponseStreamEvent[TextFormatT]]: + async for sse_event in self._raw_stream: + events_to_fire = self._state.handle_event(sse_event) + for event in events_to_fire: + yield event + + async def __aenter__(self) -> Self: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + await self.close() + + async def close(self) -> None: + """ + Close the response and release the connection. + + Automatically called if the response body is read to completion. + """ + await self._response.aclose() + + async def get_final_response(self) -> ParsedResponse[TextFormatT]: + """Waits until the stream has been read to completion and returns + the accumulated `ParsedResponse` object. + """ + await self.until_done() + response = self._state._completed_response + if not response: + raise RuntimeError("Didn't receive a `response.completed` event.") + + return response + + async def until_done(self) -> Self: + """Blocks until the stream has been consumed.""" + await consume_async_iterator(self) + return self + + +class AsyncResponseStreamManager(Generic[TextFormatT]): + def __init__( + self, + api_request: Awaitable[AsyncStream[RawResponseStreamEvent]], + *, + text_format: type[TextFormatT] | NotGiven, + input_tools: Iterable[ToolParam] | NotGiven, + ) -> None: + self.__stream: AsyncResponseStream[TextFormatT] | None = None + self.__api_request = api_request + self.__text_format = text_format + self.__input_tools = input_tools + + async def __aenter__(self) -> AsyncResponseStream[TextFormatT]: + raw_stream = await self.__api_request + + self.__stream = AsyncResponseStream( + raw_stream=raw_stream, + text_format=self.__text_format, + input_tools=self.__input_tools, + ) + + return self.__stream + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: + if self.__stream is not None: + await self.__stream.close() + + +class ResponseStreamState(Generic[TextFormatT]): + def __init__( + self, + *, + input_tools: Iterable[ToolParam] | NotGiven, + text_format: type[TextFormatT] | NotGiven, + ) -> None: + self.__current_snapshot: ParsedResponseSnapshot | None = None + self._completed_response: ParsedResponse[TextFormatT] | None = None + self._input_tools = [tool for tool in input_tools] if is_given(input_tools) else [] + self._text_format = text_format + self._rich_text_format: type | NotGiven = text_format if inspect.isclass(text_format) else NOT_GIVEN + + def handle_event(self, event: RawResponseStreamEvent) -> List[ResponseStreamEvent[TextFormatT]]: + self.__current_snapshot = snapshot = self.accumulate_event(event) + + events: List[ResponseStreamEvent[TextFormatT]] = [] + + if event.type == "response.output_text.delta": + output = snapshot.output[event.output_index] + assert output.type == "message" + + content = output.content[event.content_index] + assert content.type == "output_text" + + events.append( + build( + ResponseTextDeltaEvent, + content_index=event.content_index, + delta=event.delta, + item_id=event.item_id, + output_index=event.output_index, + type="response.output_text.delta", + snapshot=content.text, + ) + ) + elif event.type == "response.output_text.done": + output = snapshot.output[event.output_index] + assert output.type == "message" + + content = output.content[event.content_index] + assert content.type == "output_text" + + events.append( + build( + ResponseTextDoneEvent[TextFormatT], + content_index=event.content_index, + item_id=event.item_id, + output_index=event.output_index, + type="response.output_text.done", + text=event.text, + parsed=parse_text(event.text, text_format=self._text_format), + ) + ) + elif event.type == "response.function_call_arguments.delta": + output = snapshot.output[event.output_index] + assert output.type == "function_call" + + events.append( + build( + ResponseFunctionCallArgumentsDeltaEvent, + delta=event.delta, + item_id=event.item_id, + output_index=event.output_index, + type="response.function_call_arguments.delta", + snapshot=output.arguments, + ) + ) + + elif event.type == "response.completed": + response = self._completed_response + assert response is not None + + events.append( + build( + ResponseCompletedEvent, + type="response.completed", + response=response, + ) + ) + else: + events.append(event) + + return events + + def accumulate_event(self, event: RawResponseStreamEvent) -> ParsedResponseSnapshot: + snapshot = self.__current_snapshot + if snapshot is None: + return self._create_initial_response(event) + + if event.type == "response.output_item.added": + if event.item.type == "function_call": + snapshot.output.append( + construct_type_unchecked( + type_=cast(Any, ParsedResponseFunctionToolCall), value=event.item.to_dict() + ) + ) + elif event.item.type == "message": + snapshot.output.append( + construct_type_unchecked(type_=cast(Any, ParsedResponseOutputMessage), value=event.item.to_dict()) + ) + else: + snapshot.output.append(event.item) + elif event.type == "response.content_part.added": + output = snapshot.output[event.output_index] + if output.type == "message": + output.content.append( + construct_type_unchecked(type_=cast(Any, ParsedContent), value=event.part.to_dict()) + ) + elif event.type == "response.output_text.delta": + output = snapshot.output[event.output_index] + if output.type == "message": + content = output.content[event.content_index] + assert content.type == "output_text" + content.text += event.delta + elif event.type == "response.function_call_arguments.delta": + output = snapshot.output[event.output_index] + if output.type == "function_call": + output.arguments += event.delta + elif event.type == "response.completed": + self._completed_response = parse_response( + text_format=self._text_format, + response=event.response, + input_tools=self._input_tools, + ) + + return snapshot + + def _create_initial_response(self, event: RawResponseStreamEvent) -> ParsedResponseSnapshot: + if event.type != "response.created": + raise RuntimeError(f"Expected to have received `response.created` before `{event.type}`") + + return construct_type_unchecked(type_=ParsedResponseSnapshot, value=event.response.to_dict()) diff --git a/src/openai/lib/streaming/responses/_types.py b/src/openai/lib/streaming/responses/_types.py new file mode 100644 index 0000000000..6d3fd90e40 --- /dev/null +++ b/src/openai/lib/streaming/responses/_types.py @@ -0,0 +1,10 @@ +from __future__ import annotations + +from typing_extensions import TypeAlias + +from ....types.responses import ParsedResponse + +ParsedResponseSnapshot: TypeAlias = ParsedResponse[object] +"""Snapshot type representing an in-progress accumulation of +a `ParsedResponse` object. +""" diff --git a/src/openai/resources/__init__.py b/src/openai/resources/__init__.py index e2cc1c4b0c..d3457cf319 100644 --- a/src/openai/resources/__init__.py +++ b/src/openai/resources/__init__.py @@ -64,6 +64,14 @@ UploadsWithStreamingResponse, AsyncUploadsWithStreamingResponse, ) +from .responses import ( + Responses, + AsyncResponses, + ResponsesWithRawResponse, + AsyncResponsesWithRawResponse, + ResponsesWithStreamingResponse, + AsyncResponsesWithStreamingResponse, +) from .embeddings import ( Embeddings, AsyncEmbeddings, @@ -96,6 +104,14 @@ ModerationsWithStreamingResponse, AsyncModerationsWithStreamingResponse, ) +from .vector_stores import ( + VectorStores, + AsyncVectorStores, + VectorStoresWithRawResponse, + AsyncVectorStoresWithRawResponse, + VectorStoresWithStreamingResponse, + AsyncVectorStoresWithStreamingResponse, +) __all__ = [ "Completions", @@ -152,6 +168,12 @@ "AsyncFineTuningWithRawResponse", "FineTuningWithStreamingResponse", "AsyncFineTuningWithStreamingResponse", + "VectorStores", + "AsyncVectorStores", + "VectorStoresWithRawResponse", + "AsyncVectorStoresWithRawResponse", + "VectorStoresWithStreamingResponse", + "AsyncVectorStoresWithStreamingResponse", "Beta", "AsyncBeta", "BetaWithRawResponse", @@ -170,4 +192,10 @@ "AsyncUploadsWithRawResponse", "UploadsWithStreamingResponse", "AsyncUploadsWithStreamingResponse", + "Responses", + "AsyncResponses", + "ResponsesWithRawResponse", + "AsyncResponsesWithRawResponse", + "ResponsesWithStreamingResponse", + "AsyncResponsesWithStreamingResponse", ] diff --git a/src/openai/resources/beta/__init__.py b/src/openai/resources/beta/__init__.py index 01f5338757..87fea25267 100644 --- a/src/openai/resources/beta/__init__.py +++ b/src/openai/resources/beta/__init__.py @@ -24,22 +24,8 @@ AssistantsWithStreamingResponse, AsyncAssistantsWithStreamingResponse, ) -from .vector_stores import ( - VectorStores, - AsyncVectorStores, - VectorStoresWithRawResponse, - AsyncVectorStoresWithRawResponse, - VectorStoresWithStreamingResponse, - AsyncVectorStoresWithStreamingResponse, -) __all__ = [ - "VectorStores", - "AsyncVectorStores", - "VectorStoresWithRawResponse", - "AsyncVectorStoresWithRawResponse", - "VectorStoresWithStreamingResponse", - "AsyncVectorStoresWithStreamingResponse", "Assistants", "AsyncAssistants", "AssistantsWithRawResponse", diff --git a/src/openai/resources/beta/assistants.py b/src/openai/resources/beta/assistants.py index ffecd8f9e9..1c7cbf3737 100644 --- a/src/openai/resources/beta/assistants.py +++ b/src/openai/resources/beta/assistants.py @@ -27,6 +27,7 @@ from ...types.shared.chat_model import ChatModel from ...types.beta.assistant_deleted import AssistantDeleted from ...types.shared_params.metadata import Metadata +from ...types.shared.reasoning_effort import ReasoningEffort from ...types.beta.assistant_tool_param import AssistantToolParam from ...types.beta.assistant_response_format_option_param import AssistantResponseFormatOptionParam @@ -61,7 +62,7 @@ def create( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_resources: Optional[assistant_create_params.ToolResources] | NotGiven = NOT_GIVEN, @@ -98,7 +99,7 @@ def create( name: The name of the assistant. The maximum length is 256 characters. - reasoning_effort: **o1 and o3-mini models only** + reasoning_effort: **o-series models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently @@ -256,7 +257,7 @@ def update( ] | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_resources: Optional[assistant_update_params.ToolResources] | NotGiven = NOT_GIVEN, @@ -294,7 +295,7 @@ def update( name: The name of the assistant. The maximum length is 256 characters. - reasoning_effort: **o1 and o3-mini models only** + reasoning_effort: **o-series models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently @@ -504,7 +505,7 @@ async def create( instructions: Optional[str] | NotGiven = NOT_GIVEN, metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_resources: Optional[assistant_create_params.ToolResources] | NotGiven = NOT_GIVEN, @@ -541,7 +542,7 @@ async def create( name: The name of the assistant. The maximum length is 256 characters. - reasoning_effort: **o1 and o3-mini models only** + reasoning_effort: **o-series models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently @@ -699,7 +700,7 @@ async def update( ] | NotGiven = NOT_GIVEN, name: Optional[str] | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_resources: Optional[assistant_update_params.ToolResources] | NotGiven = NOT_GIVEN, @@ -737,7 +738,7 @@ async def update( name: The name of the assistant. The maximum length is 256 characters. - reasoning_effort: **o1 and o3-mini models only** + reasoning_effort: **o-series models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently diff --git a/src/openai/resources/beta/beta.py b/src/openai/resources/beta/beta.py index 5d71cff3f1..62fc8258b9 100644 --- a/src/openai/resources/beta/beta.py +++ b/src/openai/resources/beta/beta.py @@ -29,14 +29,6 @@ RealtimeWithStreamingResponse, AsyncRealtimeWithStreamingResponse, ) -from .vector_stores.vector_stores import ( - VectorStores, - AsyncVectorStores, - VectorStoresWithRawResponse, - AsyncVectorStoresWithRawResponse, - VectorStoresWithStreamingResponse, - AsyncVectorStoresWithStreamingResponse, -) __all__ = ["Beta", "AsyncBeta"] @@ -50,10 +42,6 @@ def chat(self) -> Chat: def realtime(self) -> Realtime: return Realtime(self._client) - @cached_property - def vector_stores(self) -> VectorStores: - return VectorStores(self._client) - @cached_property def assistants(self) -> Assistants: return Assistants(self._client) @@ -91,10 +79,6 @@ def chat(self) -> AsyncChat: def realtime(self) -> AsyncRealtime: return AsyncRealtime(self._client) - @cached_property - def vector_stores(self) -> AsyncVectorStores: - return AsyncVectorStores(self._client) - @cached_property def assistants(self) -> AsyncAssistants: return AsyncAssistants(self._client) @@ -131,10 +115,6 @@ def __init__(self, beta: Beta) -> None: def realtime(self) -> RealtimeWithRawResponse: return RealtimeWithRawResponse(self._beta.realtime) - @cached_property - def vector_stores(self) -> VectorStoresWithRawResponse: - return VectorStoresWithRawResponse(self._beta.vector_stores) - @cached_property def assistants(self) -> AssistantsWithRawResponse: return AssistantsWithRawResponse(self._beta.assistants) @@ -152,10 +132,6 @@ def __init__(self, beta: AsyncBeta) -> None: def realtime(self) -> AsyncRealtimeWithRawResponse: return AsyncRealtimeWithRawResponse(self._beta.realtime) - @cached_property - def vector_stores(self) -> AsyncVectorStoresWithRawResponse: - return AsyncVectorStoresWithRawResponse(self._beta.vector_stores) - @cached_property def assistants(self) -> AsyncAssistantsWithRawResponse: return AsyncAssistantsWithRawResponse(self._beta.assistants) @@ -173,10 +149,6 @@ def __init__(self, beta: Beta) -> None: def realtime(self) -> RealtimeWithStreamingResponse: return RealtimeWithStreamingResponse(self._beta.realtime) - @cached_property - def vector_stores(self) -> VectorStoresWithStreamingResponse: - return VectorStoresWithStreamingResponse(self._beta.vector_stores) - @cached_property def assistants(self) -> AssistantsWithStreamingResponse: return AssistantsWithStreamingResponse(self._beta.assistants) @@ -194,10 +166,6 @@ def __init__(self, beta: AsyncBeta) -> None: def realtime(self) -> AsyncRealtimeWithStreamingResponse: return AsyncRealtimeWithStreamingResponse(self._beta.realtime) - @cached_property - def vector_stores(self) -> AsyncVectorStoresWithStreamingResponse: - return AsyncVectorStoresWithStreamingResponse(self._beta.vector_stores) - @cached_property def assistants(self) -> AsyncAssistantsWithStreamingResponse: return AsyncAssistantsWithStreamingResponse(self._beta.assistants) diff --git a/src/openai/resources/beta/chat/completions.py b/src/openai/resources/beta/chat/completions.py index 0c631b9821..545a3f4087 100644 --- a/src/openai/resources/beta/chat/completions.py +++ b/src/openai/resources/beta/chat/completions.py @@ -15,10 +15,7 @@ from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper from ...._streaming import Stream -from ....types.chat import ( - ChatCompletionReasoningEffort, - completion_create_params, -) +from ....types.chat import completion_create_params from ...._base_client import make_request_options from ....lib._parsing import ( ResponseFormatT, @@ -28,11 +25,10 @@ ) from ....types.chat_model import ChatModel from ....lib.streaming.chat import ChatCompletionStreamManager, AsyncChatCompletionStreamManager -from ....types.shared_params import Metadata +from ....types.shared_params import Metadata, ReasoningEffort from ....types.chat.chat_completion import ChatCompletion from ....types.chat.chat_completion_chunk import ChatCompletionChunk from ....types.chat.parsed_chat_completion import ParsedChatCompletion -from ....types.chat.chat_completion_modality import ChatCompletionModality from ....types.chat.chat_completion_tool_param import ChatCompletionToolParam from ....types.chat.chat_completion_audio_param import ChatCompletionAudioParam from ....types.chat.chat_completion_message_param import ChatCompletionMessageParam @@ -78,15 +74,15 @@ def parse( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, + modalities: Optional[List[Literal["text", "audio"]]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[ChatCompletionReasoningEffort] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, - stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -95,6 +91,7 @@ def parse( top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, + web_search_options: completion_create_params.WebSearchOptions | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -192,6 +189,7 @@ def parser(raw_completion: ChatCompletion) -> ParsedChatCompletion[ResponseForma "top_logprobs": top_logprobs, "top_p": top_p, "user": user, + "web_search_options": web_search_options, }, completion_create_params.CompletionCreateParams, ), @@ -223,15 +221,15 @@ def stream( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, + modalities: Optional[List[Literal["text", "audio"]]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[ChatCompletionReasoningEffort] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, - stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -240,6 +238,7 @@ def stream( top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, + web_search_options: completion_create_params.WebSearchOptions | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -306,6 +305,7 @@ def stream( top_logprobs=top_logprobs, top_p=top_p, user=user, + web_search_options=web_search_options, extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, @@ -353,15 +353,15 @@ async def parse( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, + modalities: Optional[List[Literal["text", "audio"]]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[ChatCompletionReasoningEffort] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, - stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -370,6 +370,7 @@ async def parse( top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, + web_search_options: completion_create_params.WebSearchOptions | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -467,6 +468,7 @@ def parser(raw_completion: ChatCompletion) -> ParsedChatCompletion[ResponseForma "top_logprobs": top_logprobs, "top_p": top_p, "user": user, + "web_search_options": web_search_options, }, completion_create_params.CompletionCreateParams, ), @@ -498,15 +500,15 @@ def stream( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, + modalities: Optional[List[Literal["text", "audio"]]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[ChatCompletionReasoningEffort] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, - stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -515,6 +517,7 @@ def stream( top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, + web_search_options: completion_create_params.WebSearchOptions | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -586,6 +589,7 @@ def stream( extra_query=extra_query, extra_body=extra_body, timeout=timeout, + web_search_options=web_search_options, ) return AsyncChatCompletionStreamManager( api_request, diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index b819678be6..acb1c9b261 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -48,6 +48,7 @@ from .....types.beta.threads.run import Run from .....types.shared.chat_model import ChatModel from .....types.shared_params.metadata import Metadata +from .....types.shared.reasoning_effort import ReasoningEffort from .....types.beta.assistant_tool_param import AssistantToolParam from .....types.beta.assistant_stream_event import AssistantStreamEvent from .....types.beta.threads.runs.run_step_include import RunStepInclude @@ -96,7 +97,7 @@ def create( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -165,7 +166,7 @@ def create( [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. - reasoning_effort: **o1 and o3-mini models only** + reasoning_effort: **o-series models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently @@ -247,7 +248,7 @@ def create( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -319,7 +320,7 @@ def create( [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. - reasoning_effort: **o1 and o3-mini models only** + reasoning_effort: **o-series models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently @@ -397,7 +398,7 @@ def create( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -469,7 +470,7 @@ def create( [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. - reasoning_effort: **o1 and o3-mini models only** + reasoning_effort: **o-series models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently @@ -546,7 +547,7 @@ def create( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -800,7 +801,7 @@ def create_and_poll( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -871,7 +872,7 @@ def create_and_stream( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -903,7 +904,7 @@ def create_and_stream( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -935,7 +936,7 @@ def create_and_stream( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -1054,7 +1055,7 @@ def stream( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -1086,7 +1087,7 @@ def stream( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -1118,7 +1119,7 @@ def stream( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -1505,7 +1506,7 @@ async def create( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -1574,7 +1575,7 @@ async def create( [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. - reasoning_effort: **o1 and o3-mini models only** + reasoning_effort: **o-series models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently @@ -1656,7 +1657,7 @@ async def create( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -1728,7 +1729,7 @@ async def create( [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. - reasoning_effort: **o1 and o3-mini models only** + reasoning_effort: **o-series models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently @@ -1806,7 +1807,7 @@ async def create( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -1878,7 +1879,7 @@ async def create( [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. - reasoning_effort: **o1 and o3-mini models only** + reasoning_effort: **o-series models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently @@ -1955,7 +1956,7 @@ async def create( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -2209,7 +2210,7 @@ async def create_and_poll( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -2460,7 +2461,7 @@ def stream( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -2492,7 +2493,7 @@ def stream( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, @@ -2524,7 +2525,7 @@ def stream( metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, model: Union[str, ChatModel, None] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[Literal["low", "medium", "high"]] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: Optional[AssistantResponseFormatOptionParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, diff --git a/src/openai/resources/chat/completions/completions.py b/src/openai/resources/chat/completions/completions.py index 708b1ff166..d28be012c9 100644 --- a/src/openai/resources/chat/completions/completions.py +++ b/src/openai/resources/chat/completions/completions.py @@ -31,7 +31,6 @@ from ....pagination import SyncCursorPage, AsyncCursorPage from ....types.chat import ( ChatCompletionAudioParam, - ChatCompletionReasoningEffort, completion_list_params, completion_create_params, completion_update_params, @@ -40,13 +39,12 @@ from ....types.shared.chat_model import ChatModel from ....types.chat.chat_completion import ChatCompletion from ....types.shared_params.metadata import Metadata +from ....types.shared.reasoning_effort import ReasoningEffort from ....types.chat.chat_completion_chunk import ChatCompletionChunk from ....types.chat.chat_completion_deleted import ChatCompletionDeleted -from ....types.chat.chat_completion_modality import ChatCompletionModality from ....types.chat.chat_completion_tool_param import ChatCompletionToolParam from ....types.chat.chat_completion_audio_param import ChatCompletionAudioParam from ....types.chat.chat_completion_message_param import ChatCompletionMessageParam -from ....types.chat.chat_completion_reasoning_effort import ChatCompletionReasoningEffort from ....types.chat.chat_completion_stream_options_param import ChatCompletionStreamOptionsParam from ....types.chat.chat_completion_prediction_content_param import ChatCompletionPredictionContentParam from ....types.chat.chat_completion_tool_choice_option_param import ChatCompletionToolChoiceOptionParam @@ -93,16 +91,16 @@ def create( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, + modalities: Optional[List[Literal["text", "audio"]]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[ChatCompletionReasoningEffort] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, - stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, @@ -112,6 +110,7 @@ def create( top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, + web_search_options: completion_create_params.WebSearchOptions | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -119,9 +118,15 @@ def create( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ChatCompletion: - """Creates a model response for the given chat conversation. + """ + **Starting a new project?** We recommend trying + [Responses](https://platform.openai.com/docs/api-reference/responses) to take + advantage of the latest OpenAI platform features. Compare + [Chat Completions with Responses](https://platform.openai.com/docs/guides/responses-vs-chat-completions?api-mode=responses). + + --- - Learn more in the + Creates a model response for the given chat conversation. Learn more in the [text generation](https://platform.openai.com/docs/guides/text-generation), [vision](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio) guides. @@ -140,9 +145,11 @@ def create( [images](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio). - model: ID of the model to use. See the - [model endpoint compatibility](https://platform.openai.com/docs/models#model-endpoint-compatibility) - table for details on which models work with the Chat API. + model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + wide range of models with different capabilities, performance characteristics, + and price points. Refer to the + [model guide](https://platform.openai.com/docs/models) to browse and compare + available models. audio: Parameters for audio output. Required when audio output is requested with `modalities: ["audio"]`. @@ -203,8 +210,8 @@ def create( Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters. - modalities: Output types that you would like the model to generate for this request. Most - models are capable of generating text, which is the default: + modalities: Output types that you would like the model to generate. Most models are capable + of generating text, which is the default: `["text"]` @@ -229,7 +236,7 @@ def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - reasoning_effort: **o1 and o3-mini models only** + reasoning_effort: **o-series models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently @@ -243,16 +250,9 @@ def create( in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the - message the model generates is valid JSON. - - **Important:** when using JSON mode, you **must** also instruct the model to - produce JSON yourself via a system or user message. Without this, the model may - generate an unending stream of whitespace until the generation reaches the token - limit, resulting in a long-running and seemingly "stuck" request. Also note that - the message content may be partially cut off if `finish_reason="length"`, which - indicates the generation exceeded `max_tokens` or the conversation exceeded the - max context length. + Setting to `{ "type": "json_object" }` enables the older JSON mode, which + ensures the message the model generates is valid JSON. Using `json_schema` is + preferred for models that support it. seed: This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and @@ -267,23 +267,29 @@ def create( utilize scale tier credits until they are exhausted. - If set to 'auto', and the Project is not Scale tier enabled, the request will be processed using the default service tier with a lower uptime SLA and no - latency guarantee. + latency guarentee. - If set to 'default', the request will be processed using the default service - tier with a lower uptime SLA and no latency guarantee. + tier with a lower uptime SLA and no latency guarentee. - When not set, the default behavior is 'auto'. - stop: Up to 4 sequences where the API will stop generating further tokens. + When this parameter is set, the response body will include the `service_tier` + utilized. + + stop: Up to 4 sequences where the API will stop generating further tokens. The + returned text will not contain the stop sequence. store: Whether or not to store the output of this chat completion request for use in our [model distillation](https://platform.openai.com/docs/guides/distillation) or [evals](https://platform.openai.com/docs/guides/evals) products. - stream: If set, partial message deltas will be sent, like in ChatGPT. Tokens will be - sent as data-only - [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) - as they become available, with the stream terminated by a `data: [DONE]` - message. - [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + stream: If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming) + for more information, along with the + [streaming responses](https://platform.openai.com/docs/guides/streaming-responses) + guide for more information on how to handle the streaming events. stream_options: Options for streaming response. Only set this when you set `stream: true`. @@ -320,6 +326,10 @@ def create( and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + web_search_options: This tool searches the web for relevant results to use in a response. Learn more + about the + [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat). + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -346,16 +356,16 @@ def create( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, + modalities: Optional[List[Literal["text", "audio"]]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[ChatCompletionReasoningEffort] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, - stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -364,6 +374,7 @@ def create( top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, + web_search_options: completion_create_params.WebSearchOptions | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -371,9 +382,15 @@ def create( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Stream[ChatCompletionChunk]: - """Creates a model response for the given chat conversation. + """ + **Starting a new project?** We recommend trying + [Responses](https://platform.openai.com/docs/api-reference/responses) to take + advantage of the latest OpenAI platform features. Compare + [Chat Completions with Responses](https://platform.openai.com/docs/guides/responses-vs-chat-completions?api-mode=responses). + + --- - Learn more in the + Creates a model response for the given chat conversation. Learn more in the [text generation](https://platform.openai.com/docs/guides/text-generation), [vision](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio) guides. @@ -392,16 +409,20 @@ def create( [images](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio). - model: ID of the model to use. See the - [model endpoint compatibility](https://platform.openai.com/docs/models#model-endpoint-compatibility) - table for details on which models work with the Chat API. - - stream: If set, partial message deltas will be sent, like in ChatGPT. Tokens will be - sent as data-only - [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) - as they become available, with the stream terminated by a `data: [DONE]` - message. - [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + wide range of models with different capabilities, performance characteristics, + and price points. Refer to the + [model guide](https://platform.openai.com/docs/models) to browse and compare + available models. + + stream: If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming) + for more information, along with the + [streaming responses](https://platform.openai.com/docs/guides/streaming-responses) + guide for more information on how to handle the streaming events. audio: Parameters for audio output. Required when audio output is requested with `modalities: ["audio"]`. @@ -462,8 +483,8 @@ def create( Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters. - modalities: Output types that you would like the model to generate for this request. Most - models are capable of generating text, which is the default: + modalities: Output types that you would like the model to generate. Most models are capable + of generating text, which is the default: `["text"]` @@ -488,7 +509,7 @@ def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - reasoning_effort: **o1 and o3-mini models only** + reasoning_effort: **o-series models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently @@ -502,16 +523,9 @@ def create( in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the - message the model generates is valid JSON. - - **Important:** when using JSON mode, you **must** also instruct the model to - produce JSON yourself via a system or user message. Without this, the model may - generate an unending stream of whitespace until the generation reaches the token - limit, resulting in a long-running and seemingly "stuck" request. Also note that - the message content may be partially cut off if `finish_reason="length"`, which - indicates the generation exceeded `max_tokens` or the conversation exceeded the - max context length. + Setting to `{ "type": "json_object" }` enables the older JSON mode, which + ensures the message the model generates is valid JSON. Using `json_schema` is + preferred for models that support it. seed: This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and @@ -526,12 +540,16 @@ def create( utilize scale tier credits until they are exhausted. - If set to 'auto', and the Project is not Scale tier enabled, the request will be processed using the default service tier with a lower uptime SLA and no - latency guarantee. + latency guarentee. - If set to 'default', the request will be processed using the default service - tier with a lower uptime SLA and no latency guarantee. + tier with a lower uptime SLA and no latency guarentee. - When not set, the default behavior is 'auto'. - stop: Up to 4 sequences where the API will stop generating further tokens. + When this parameter is set, the response body will include the `service_tier` + utilized. + + stop: Up to 4 sequences where the API will stop generating further tokens. The + returned text will not contain the stop sequence. store: Whether or not to store the output of this chat completion request for use in our [model distillation](https://platform.openai.com/docs/guides/distillation) @@ -572,6 +590,10 @@ def create( and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + web_search_options: This tool searches the web for relevant results to use in a response. Learn more + about the + [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat). + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -598,16 +620,16 @@ def create( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, + modalities: Optional[List[Literal["text", "audio"]]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[ChatCompletionReasoningEffort] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, - stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -616,6 +638,7 @@ def create( top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, + web_search_options: completion_create_params.WebSearchOptions | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -623,9 +646,15 @@ def create( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ChatCompletion | Stream[ChatCompletionChunk]: - """Creates a model response for the given chat conversation. + """ + **Starting a new project?** We recommend trying + [Responses](https://platform.openai.com/docs/api-reference/responses) to take + advantage of the latest OpenAI platform features. Compare + [Chat Completions with Responses](https://platform.openai.com/docs/guides/responses-vs-chat-completions?api-mode=responses). + + --- - Learn more in the + Creates a model response for the given chat conversation. Learn more in the [text generation](https://platform.openai.com/docs/guides/text-generation), [vision](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio) guides. @@ -644,16 +673,20 @@ def create( [images](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio). - model: ID of the model to use. See the - [model endpoint compatibility](https://platform.openai.com/docs/models#model-endpoint-compatibility) - table for details on which models work with the Chat API. - - stream: If set, partial message deltas will be sent, like in ChatGPT. Tokens will be - sent as data-only - [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) - as they become available, with the stream terminated by a `data: [DONE]` - message. - [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + wide range of models with different capabilities, performance characteristics, + and price points. Refer to the + [model guide](https://platform.openai.com/docs/models) to browse and compare + available models. + + stream: If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming) + for more information, along with the + [streaming responses](https://platform.openai.com/docs/guides/streaming-responses) + guide for more information on how to handle the streaming events. audio: Parameters for audio output. Required when audio output is requested with `modalities: ["audio"]`. @@ -714,8 +747,8 @@ def create( Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters. - modalities: Output types that you would like the model to generate for this request. Most - models are capable of generating text, which is the default: + modalities: Output types that you would like the model to generate. Most models are capable + of generating text, which is the default: `["text"]` @@ -740,7 +773,7 @@ def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - reasoning_effort: **o1 and o3-mini models only** + reasoning_effort: **o-series models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently @@ -754,16 +787,9 @@ def create( in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the - message the model generates is valid JSON. - - **Important:** when using JSON mode, you **must** also instruct the model to - produce JSON yourself via a system or user message. Without this, the model may - generate an unending stream of whitespace until the generation reaches the token - limit, resulting in a long-running and seemingly "stuck" request. Also note that - the message content may be partially cut off if `finish_reason="length"`, which - indicates the generation exceeded `max_tokens` or the conversation exceeded the - max context length. + Setting to `{ "type": "json_object" }` enables the older JSON mode, which + ensures the message the model generates is valid JSON. Using `json_schema` is + preferred for models that support it. seed: This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and @@ -778,12 +804,16 @@ def create( utilize scale tier credits until they are exhausted. - If set to 'auto', and the Project is not Scale tier enabled, the request will be processed using the default service tier with a lower uptime SLA and no - latency guarantee. + latency guarentee. - If set to 'default', the request will be processed using the default service - tier with a lower uptime SLA and no latency guarantee. + tier with a lower uptime SLA and no latency guarentee. - When not set, the default behavior is 'auto'. - stop: Up to 4 sequences where the API will stop generating further tokens. + When this parameter is set, the response body will include the `service_tier` + utilized. + + stop: Up to 4 sequences where the API will stop generating further tokens. The + returned text will not contain the stop sequence. store: Whether or not to store the output of this chat completion request for use in our [model distillation](https://platform.openai.com/docs/guides/distillation) @@ -824,6 +854,10 @@ def create( and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + web_search_options: This tool searches the web for relevant results to use in a response. Learn more + about the + [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat). + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -849,16 +883,16 @@ def create( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, + modalities: Optional[List[Literal["text", "audio"]]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[ChatCompletionReasoningEffort] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, - stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, @@ -868,6 +902,7 @@ def create( top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, + web_search_options: completion_create_params.WebSearchOptions | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -910,6 +945,7 @@ def create( "top_logprobs": top_logprobs, "top_p": top_p, "user": user, + "web_search_options": web_search_options, }, completion_create_params.CompletionCreateParams, ), @@ -934,7 +970,7 @@ def retrieve( ) -> ChatCompletion: """Get a stored chat completion. - Only chat completions that have been created with + Only Chat Completions that have been created with the `store` parameter set to `true` will be returned. Args: @@ -970,7 +1006,7 @@ def update( ) -> ChatCompletion: """Modify a stored chat completion. - Only chat completions that have been created + Only Chat Completions that have been created with the `store` parameter set to `true` can be modified. Currently, the only supported modification is to update the `metadata` field. @@ -1016,24 +1052,24 @@ def list( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> SyncCursorPage[ChatCompletion]: - """List stored chat completions. + """List stored Chat Completions. - Only chat completions that have been stored with + Only Chat Completions that have been stored with the `store` parameter set to `true` will be returned. Args: after: Identifier for the last chat completion from the previous pagination request. - limit: Number of chat completions to retrieve. + limit: Number of Chat Completions to retrieve. metadata: - A list of metadata keys to filter the chat completions by. Example: + A list of metadata keys to filter the Chat Completions by. Example: `metadata[key1]=value1&metadata[key2]=value2` - model: The model used to generate the chat completions. + model: The model used to generate the Chat Completions. - order: Sort order for chat completions by timestamp. Use `asc` for ascending order or + order: Sort order for Chat Completions by timestamp. Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`. extra_headers: Send extra headers @@ -1079,7 +1115,7 @@ def delete( ) -> ChatCompletionDeleted: """Delete a stored chat completion. - Only chat completions that have been created + Only Chat Completions that have been created with the `store` parameter set to `true` can be deleted. Args: @@ -1141,16 +1177,16 @@ async def create( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, + modalities: Optional[List[Literal["text", "audio"]]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[ChatCompletionReasoningEffort] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, - stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, @@ -1160,6 +1196,7 @@ async def create( top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, + web_search_options: completion_create_params.WebSearchOptions | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -1167,9 +1204,15 @@ async def create( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ChatCompletion: - """Creates a model response for the given chat conversation. + """ + **Starting a new project?** We recommend trying + [Responses](https://platform.openai.com/docs/api-reference/responses) to take + advantage of the latest OpenAI platform features. Compare + [Chat Completions with Responses](https://platform.openai.com/docs/guides/responses-vs-chat-completions?api-mode=responses). + + --- - Learn more in the + Creates a model response for the given chat conversation. Learn more in the [text generation](https://platform.openai.com/docs/guides/text-generation), [vision](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio) guides. @@ -1188,9 +1231,11 @@ async def create( [images](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio). - model: ID of the model to use. See the - [model endpoint compatibility](https://platform.openai.com/docs/models#model-endpoint-compatibility) - table for details on which models work with the Chat API. + model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + wide range of models with different capabilities, performance characteristics, + and price points. Refer to the + [model guide](https://platform.openai.com/docs/models) to browse and compare + available models. audio: Parameters for audio output. Required when audio output is requested with `modalities: ["audio"]`. @@ -1251,8 +1296,8 @@ async def create( Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters. - modalities: Output types that you would like the model to generate for this request. Most - models are capable of generating text, which is the default: + modalities: Output types that you would like the model to generate. Most models are capable + of generating text, which is the default: `["text"]` @@ -1277,7 +1322,7 @@ async def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - reasoning_effort: **o1 and o3-mini models only** + reasoning_effort: **o-series models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently @@ -1291,16 +1336,9 @@ async def create( in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the - message the model generates is valid JSON. - - **Important:** when using JSON mode, you **must** also instruct the model to - produce JSON yourself via a system or user message. Without this, the model may - generate an unending stream of whitespace until the generation reaches the token - limit, resulting in a long-running and seemingly "stuck" request. Also note that - the message content may be partially cut off if `finish_reason="length"`, which - indicates the generation exceeded `max_tokens` or the conversation exceeded the - max context length. + Setting to `{ "type": "json_object" }` enables the older JSON mode, which + ensures the message the model generates is valid JSON. Using `json_schema` is + preferred for models that support it. seed: This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and @@ -1315,23 +1353,29 @@ async def create( utilize scale tier credits until they are exhausted. - If set to 'auto', and the Project is not Scale tier enabled, the request will be processed using the default service tier with a lower uptime SLA and no - latency guarantee. + latency guarentee. - If set to 'default', the request will be processed using the default service - tier with a lower uptime SLA and no latency guarantee. + tier with a lower uptime SLA and no latency guarentee. - When not set, the default behavior is 'auto'. - stop: Up to 4 sequences where the API will stop generating further tokens. + When this parameter is set, the response body will include the `service_tier` + utilized. + + stop: Up to 4 sequences where the API will stop generating further tokens. The + returned text will not contain the stop sequence. store: Whether or not to store the output of this chat completion request for use in our [model distillation](https://platform.openai.com/docs/guides/distillation) or [evals](https://platform.openai.com/docs/guides/evals) products. - stream: If set, partial message deltas will be sent, like in ChatGPT. Tokens will be - sent as data-only - [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) - as they become available, with the stream terminated by a `data: [DONE]` - message. - [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + stream: If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming) + for more information, along with the + [streaming responses](https://platform.openai.com/docs/guides/streaming-responses) + guide for more information on how to handle the streaming events. stream_options: Options for streaming response. Only set this when you set `stream: true`. @@ -1368,6 +1412,10 @@ async def create( and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + web_search_options: This tool searches the web for relevant results to use in a response. Learn more + about the + [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat). + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -1394,16 +1442,16 @@ async def create( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, + modalities: Optional[List[Literal["text", "audio"]]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[ChatCompletionReasoningEffort] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, - stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -1412,6 +1460,7 @@ async def create( top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, + web_search_options: completion_create_params.WebSearchOptions | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -1419,9 +1468,15 @@ async def create( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AsyncStream[ChatCompletionChunk]: - """Creates a model response for the given chat conversation. + """ + **Starting a new project?** We recommend trying + [Responses](https://platform.openai.com/docs/api-reference/responses) to take + advantage of the latest OpenAI platform features. Compare + [Chat Completions with Responses](https://platform.openai.com/docs/guides/responses-vs-chat-completions?api-mode=responses). + + --- - Learn more in the + Creates a model response for the given chat conversation. Learn more in the [text generation](https://platform.openai.com/docs/guides/text-generation), [vision](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio) guides. @@ -1440,16 +1495,20 @@ async def create( [images](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio). - model: ID of the model to use. See the - [model endpoint compatibility](https://platform.openai.com/docs/models#model-endpoint-compatibility) - table for details on which models work with the Chat API. - - stream: If set, partial message deltas will be sent, like in ChatGPT. Tokens will be - sent as data-only - [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) - as they become available, with the stream terminated by a `data: [DONE]` - message. - [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + wide range of models with different capabilities, performance characteristics, + and price points. Refer to the + [model guide](https://platform.openai.com/docs/models) to browse and compare + available models. + + stream: If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming) + for more information, along with the + [streaming responses](https://platform.openai.com/docs/guides/streaming-responses) + guide for more information on how to handle the streaming events. audio: Parameters for audio output. Required when audio output is requested with `modalities: ["audio"]`. @@ -1510,8 +1569,8 @@ async def create( Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters. - modalities: Output types that you would like the model to generate for this request. Most - models are capable of generating text, which is the default: + modalities: Output types that you would like the model to generate. Most models are capable + of generating text, which is the default: `["text"]` @@ -1536,7 +1595,7 @@ async def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - reasoning_effort: **o1 and o3-mini models only** + reasoning_effort: **o-series models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently @@ -1550,16 +1609,9 @@ async def create( in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the - message the model generates is valid JSON. - - **Important:** when using JSON mode, you **must** also instruct the model to - produce JSON yourself via a system or user message. Without this, the model may - generate an unending stream of whitespace until the generation reaches the token - limit, resulting in a long-running and seemingly "stuck" request. Also note that - the message content may be partially cut off if `finish_reason="length"`, which - indicates the generation exceeded `max_tokens` or the conversation exceeded the - max context length. + Setting to `{ "type": "json_object" }` enables the older JSON mode, which + ensures the message the model generates is valid JSON. Using `json_schema` is + preferred for models that support it. seed: This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and @@ -1574,12 +1626,16 @@ async def create( utilize scale tier credits until they are exhausted. - If set to 'auto', and the Project is not Scale tier enabled, the request will be processed using the default service tier with a lower uptime SLA and no - latency guarantee. + latency guarentee. - If set to 'default', the request will be processed using the default service - tier with a lower uptime SLA and no latency guarantee. + tier with a lower uptime SLA and no latency guarentee. - When not set, the default behavior is 'auto'. - stop: Up to 4 sequences where the API will stop generating further tokens. + When this parameter is set, the response body will include the `service_tier` + utilized. + + stop: Up to 4 sequences where the API will stop generating further tokens. The + returned text will not contain the stop sequence. store: Whether or not to store the output of this chat completion request for use in our [model distillation](https://platform.openai.com/docs/guides/distillation) @@ -1620,6 +1676,10 @@ async def create( and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + web_search_options: This tool searches the web for relevant results to use in a response. Learn more + about the + [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat). + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -1646,16 +1706,16 @@ async def create( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, + modalities: Optional[List[Literal["text", "audio"]]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[ChatCompletionReasoningEffort] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, - stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -1664,6 +1724,7 @@ async def create( top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, + web_search_options: completion_create_params.WebSearchOptions | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -1671,9 +1732,15 @@ async def create( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ChatCompletion | AsyncStream[ChatCompletionChunk]: - """Creates a model response for the given chat conversation. + """ + **Starting a new project?** We recommend trying + [Responses](https://platform.openai.com/docs/api-reference/responses) to take + advantage of the latest OpenAI platform features. Compare + [Chat Completions with Responses](https://platform.openai.com/docs/guides/responses-vs-chat-completions?api-mode=responses). + + --- - Learn more in the + Creates a model response for the given chat conversation. Learn more in the [text generation](https://platform.openai.com/docs/guides/text-generation), [vision](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio) guides. @@ -1692,16 +1759,20 @@ async def create( [images](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio). - model: ID of the model to use. See the - [model endpoint compatibility](https://platform.openai.com/docs/models#model-endpoint-compatibility) - table for details on which models work with the Chat API. - - stream: If set, partial message deltas will be sent, like in ChatGPT. Tokens will be - sent as data-only - [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) - as they become available, with the stream terminated by a `data: [DONE]` - message. - [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + wide range of models with different capabilities, performance characteristics, + and price points. Refer to the + [model guide](https://platform.openai.com/docs/models) to browse and compare + available models. + + stream: If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming) + for more information, along with the + [streaming responses](https://platform.openai.com/docs/guides/streaming-responses) + guide for more information on how to handle the streaming events. audio: Parameters for audio output. Required when audio output is requested with `modalities: ["audio"]`. @@ -1762,8 +1833,8 @@ async def create( Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters. - modalities: Output types that you would like the model to generate for this request. Most - models are capable of generating text, which is the default: + modalities: Output types that you would like the model to generate. Most models are capable + of generating text, which is the default: `["text"]` @@ -1788,7 +1859,7 @@ async def create( whether they appear in the text so far, increasing the model's likelihood to talk about new topics. - reasoning_effort: **o1 and o3-mini models only** + reasoning_effort: **o-series models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently @@ -1802,16 +1873,9 @@ async def create( in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the - message the model generates is valid JSON. - - **Important:** when using JSON mode, you **must** also instruct the model to - produce JSON yourself via a system or user message. Without this, the model may - generate an unending stream of whitespace until the generation reaches the token - limit, resulting in a long-running and seemingly "stuck" request. Also note that - the message content may be partially cut off if `finish_reason="length"`, which - indicates the generation exceeded `max_tokens` or the conversation exceeded the - max context length. + Setting to `{ "type": "json_object" }` enables the older JSON mode, which + ensures the message the model generates is valid JSON. Using `json_schema` is + preferred for models that support it. seed: This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and @@ -1826,12 +1890,16 @@ async def create( utilize scale tier credits until they are exhausted. - If set to 'auto', and the Project is not Scale tier enabled, the request will be processed using the default service tier with a lower uptime SLA and no - latency guarantee. + latency guarentee. - If set to 'default', the request will be processed using the default service - tier with a lower uptime SLA and no latency guarantee. + tier with a lower uptime SLA and no latency guarentee. - When not set, the default behavior is 'auto'. - stop: Up to 4 sequences where the API will stop generating further tokens. + When this parameter is set, the response body will include the `service_tier` + utilized. + + stop: Up to 4 sequences where the API will stop generating further tokens. The + returned text will not contain the stop sequence. store: Whether or not to store the output of this chat completion request for use in our [model distillation](https://platform.openai.com/docs/guides/distillation) @@ -1872,6 +1940,10 @@ async def create( and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + web_search_options: This tool searches the web for relevant results to use in a response. Learn more + about the + [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat). + extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -1897,16 +1969,16 @@ async def create( max_completion_tokens: Optional[int] | NotGiven = NOT_GIVEN, max_tokens: Optional[int] | NotGiven = NOT_GIVEN, metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - modalities: Optional[List[ChatCompletionModality]] | NotGiven = NOT_GIVEN, + modalities: Optional[List[Literal["text", "audio"]]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, parallel_tool_calls: bool | NotGiven = NOT_GIVEN, prediction: Optional[ChatCompletionPredictionContentParam] | NotGiven = NOT_GIVEN, presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, - reasoning_effort: Optional[ChatCompletionReasoningEffort] | NotGiven = NOT_GIVEN, + reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, - stop: Union[Optional[str], List[str]] | NotGiven = NOT_GIVEN, + stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, @@ -1916,6 +1988,7 @@ async def create( top_logprobs: Optional[int] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, + web_search_options: completion_create_params.WebSearchOptions | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -1958,6 +2031,7 @@ async def create( "top_logprobs": top_logprobs, "top_p": top_p, "user": user, + "web_search_options": web_search_options, }, completion_create_params.CompletionCreateParams, ), @@ -1982,7 +2056,7 @@ async def retrieve( ) -> ChatCompletion: """Get a stored chat completion. - Only chat completions that have been created with + Only Chat Completions that have been created with the `store` parameter set to `true` will be returned. Args: @@ -2018,7 +2092,7 @@ async def update( ) -> ChatCompletion: """Modify a stored chat completion. - Only chat completions that have been created + Only Chat Completions that have been created with the `store` parameter set to `true` can be modified. Currently, the only supported modification is to update the `metadata` field. @@ -2064,24 +2138,24 @@ def list( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AsyncPaginator[ChatCompletion, AsyncCursorPage[ChatCompletion]]: - """List stored chat completions. + """List stored Chat Completions. - Only chat completions that have been stored with + Only Chat Completions that have been stored with the `store` parameter set to `true` will be returned. Args: after: Identifier for the last chat completion from the previous pagination request. - limit: Number of chat completions to retrieve. + limit: Number of Chat Completions to retrieve. metadata: - A list of metadata keys to filter the chat completions by. Example: + A list of metadata keys to filter the Chat Completions by. Example: `metadata[key1]=value1&metadata[key2]=value2` - model: The model used to generate the chat completions. + model: The model used to generate the Chat Completions. - order: Sort order for chat completions by timestamp. Use `asc` for ascending order or + order: Sort order for Chat Completions by timestamp. Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`. extra_headers: Send extra headers @@ -2127,7 +2201,7 @@ async def delete( ) -> ChatCompletionDeleted: """Delete a stored chat completion. - Only chat completions that have been created + Only Chat Completions that have been created with the `store` parameter set to `true` can be deleted. Args: diff --git a/src/openai/resources/chat/completions/messages.py b/src/openai/resources/chat/completions/messages.py index b71d670927..fac15fba8b 100644 --- a/src/openai/resources/chat/completions/messages.py +++ b/src/openai/resources/chat/completions/messages.py @@ -56,7 +56,7 @@ def list( ) -> SyncCursorPage[ChatCompletionStoreMessage]: """Get the messages in a stored chat completion. - Only chat completions that have + Only Chat Completions that have been created with the `store` parameter set to `true` will be returned. Args: @@ -134,7 +134,7 @@ def list( ) -> AsyncPaginator[ChatCompletionStoreMessage, AsyncCursorPage[ChatCompletionStoreMessage]]: """Get the messages in a stored chat completion. - Only chat completions that have + Only Chat Completions that have been created with the `store` parameter set to `true` will be returned. Args: diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index af453e1e21..2eaa4a6401 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -96,14 +96,10 @@ def create( Args: file: The File object (not file name) to be uploaded. - purpose: The intended purpose of the uploaded file. - - Use "assistants" for - [Assistants](https://platform.openai.com/docs/api-reference/assistants) and - [Message](https://platform.openai.com/docs/api-reference/messages) files, - "vision" for Assistants image file inputs, "batch" for - [Batch API](https://platform.openai.com/docs/guides/batch), and "fine-tune" for - [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning). + purpose: The intended purpose of the uploaded file. One of: - `assistants`: Used in the + Assistants API - `batch`: Used in the Batch API - `fine-tune`: Used for + fine-tuning - `vision`: Images used for vision fine-tuning - `user_data`: + Flexible file type for any purpose - `evals`: Used for eval data sets extra_headers: Send extra headers @@ -412,14 +408,10 @@ async def create( Args: file: The File object (not file name) to be uploaded. - purpose: The intended purpose of the uploaded file. - - Use "assistants" for - [Assistants](https://platform.openai.com/docs/api-reference/assistants) and - [Message](https://platform.openai.com/docs/api-reference/messages) files, - "vision" for Assistants image file inputs, "batch" for - [Batch API](https://platform.openai.com/docs/guides/batch), and "fine-tune" for - [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning). + purpose: The intended purpose of the uploaded file. One of: - `assistants`: Used in the + Assistants API - `batch`: Used in the Batch API - `fine-tune`: Used for + fine-tuning - `vision`: Images used for vision fine-tuning - `user_data`: + Flexible file type for any purpose - `evals`: Used for eval data sets extra_headers: Send extra headers diff --git a/src/openai/resources/responses/__init__.py b/src/openai/resources/responses/__init__.py new file mode 100644 index 0000000000..ad19218b01 --- /dev/null +++ b/src/openai/resources/responses/__init__.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .responses import ( + Responses, + AsyncResponses, + ResponsesWithRawResponse, + AsyncResponsesWithRawResponse, + ResponsesWithStreamingResponse, + AsyncResponsesWithStreamingResponse, +) +from .input_items import ( + InputItems, + AsyncInputItems, + InputItemsWithRawResponse, + AsyncInputItemsWithRawResponse, + InputItemsWithStreamingResponse, + AsyncInputItemsWithStreamingResponse, +) + +__all__ = [ + "InputItems", + "AsyncInputItems", + "InputItemsWithRawResponse", + "AsyncInputItemsWithRawResponse", + "InputItemsWithStreamingResponse", + "AsyncInputItemsWithStreamingResponse", + "Responses", + "AsyncResponses", + "ResponsesWithRawResponse", + "AsyncResponsesWithRawResponse", + "ResponsesWithStreamingResponse", + "AsyncResponsesWithStreamingResponse", +] diff --git a/src/openai/resources/responses/input_items.py b/src/openai/resources/responses/input_items.py new file mode 100644 index 0000000000..10e7d545dc --- /dev/null +++ b/src/openai/resources/responses/input_items.py @@ -0,0 +1,223 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Any, cast +from typing_extensions import Literal + +import httpx + +from ... import _legacy_response +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ..._utils import maybe_transform +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ...pagination import SyncCursorPage, AsyncCursorPage +from ..._base_client import AsyncPaginator, make_request_options +from ...types.responses import input_item_list_params +from ...types.responses.response_item_list import Data + +__all__ = ["InputItems", "AsyncInputItems"] + + +class InputItems(SyncAPIResource): + @cached_property + def with_raw_response(self) -> InputItemsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return InputItemsWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> InputItemsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return InputItemsWithStreamingResponse(self) + + def list( + self, + response_id: str, + *, + after: str | NotGiven = NOT_GIVEN, + before: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> SyncCursorPage[Data]: + """ + Returns a list of input items for a given response. + + Args: + after: An item ID to list items after, used in pagination. + + before: An item ID to list items before, used in pagination. + + limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the default is 20. + + order: The order to return the input items in. Default is `asc`. + + - `asc`: Return the input items in ascending order. + - `desc`: Return the input items in descending order. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not response_id: + raise ValueError(f"Expected a non-empty value for `response_id` but received {response_id!r}") + return self._get_api_list( + f"/responses/{response_id}/input_items", + page=SyncCursorPage[Data], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "before": before, + "limit": limit, + "order": order, + }, + input_item_list_params.InputItemListParams, + ), + ), + model=cast(Any, Data), # Union types cannot be passed in as arguments in the type system + ) + + +class AsyncInputItems(AsyncAPIResource): + @cached_property + def with_raw_response(self) -> AsyncInputItemsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return AsyncInputItemsWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncInputItemsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return AsyncInputItemsWithStreamingResponse(self) + + def list( + self, + response_id: str, + *, + after: str | NotGiven = NOT_GIVEN, + before: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncPaginator[Data, AsyncCursorPage[Data]]: + """ + Returns a list of input items for a given response. + + Args: + after: An item ID to list items after, used in pagination. + + before: An item ID to list items before, used in pagination. + + limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the default is 20. + + order: The order to return the input items in. Default is `asc`. + + - `asc`: Return the input items in ascending order. + - `desc`: Return the input items in descending order. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not response_id: + raise ValueError(f"Expected a non-empty value for `response_id` but received {response_id!r}") + return self._get_api_list( + f"/responses/{response_id}/input_items", + page=AsyncCursorPage[Data], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "before": before, + "limit": limit, + "order": order, + }, + input_item_list_params.InputItemListParams, + ), + ), + model=cast(Any, Data), # Union types cannot be passed in as arguments in the type system + ) + + +class InputItemsWithRawResponse: + def __init__(self, input_items: InputItems) -> None: + self._input_items = input_items + + self.list = _legacy_response.to_raw_response_wrapper( + input_items.list, + ) + + +class AsyncInputItemsWithRawResponse: + def __init__(self, input_items: AsyncInputItems) -> None: + self._input_items = input_items + + self.list = _legacy_response.async_to_raw_response_wrapper( + input_items.list, + ) + + +class InputItemsWithStreamingResponse: + def __init__(self, input_items: InputItems) -> None: + self._input_items = input_items + + self.list = to_streamed_response_wrapper( + input_items.list, + ) + + +class AsyncInputItemsWithStreamingResponse: + def __init__(self, input_items: AsyncInputItems) -> None: + self._input_items = input_items + + self.list = async_to_streamed_response_wrapper( + input_items.list, + ) diff --git a/src/openai/resources/responses/responses.py b/src/openai/resources/responses/responses.py new file mode 100644 index 0000000000..0c70a2ef22 --- /dev/null +++ b/src/openai/resources/responses/responses.py @@ -0,0 +1,1790 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Any, List, Type, Union, Iterable, Optional, cast +from functools import partial +from typing_extensions import Literal, overload + +import httpx + +from ... import _legacy_response +from ..._types import NOT_GIVEN, Body, Query, Headers, NoneType, NotGiven +from ..._utils import ( + is_given, + required_args, + maybe_transform, + async_maybe_transform, +) +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from .input_items import ( + InputItems, + AsyncInputItems, + InputItemsWithRawResponse, + AsyncInputItemsWithRawResponse, + InputItemsWithStreamingResponse, + AsyncInputItemsWithStreamingResponse, +) +from ..._streaming import Stream, AsyncStream +from ...lib._tools import PydanticFunctionTool, ResponsesPydanticFunctionTool +from ..._base_client import make_request_options +from ...types.responses import response_create_params, response_retrieve_params +from ...lib._parsing._responses import ( + TextFormatT, + parse_response, + type_to_text_format_param as _type_to_text_format_param, +) +from ...types.shared.chat_model import ChatModel +from ...types.responses.response import Response +from ...types.responses.tool_param import ToolParam, ParseableToolParam +from ...types.shared_params.metadata import Metadata +from ...types.shared_params.reasoning import Reasoning +from ...types.responses.parsed_response import ParsedResponse +from ...lib.streaming.responses._responses import ResponseStreamManager, AsyncResponseStreamManager +from ...types.responses.response_includable import ResponseIncludable +from ...types.responses.response_input_param import ResponseInputParam +from ...types.responses.response_stream_event import ResponseStreamEvent +from ...types.responses.response_text_config_param import ResponseTextConfigParam + +__all__ = ["Responses", "AsyncResponses"] + + +class Responses(SyncAPIResource): + @cached_property + def input_items(self) -> InputItems: + return InputItems(self._client) + + @cached_property + def with_raw_response(self) -> ResponsesWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return ResponsesWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> ResponsesWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return ResponsesWithStreamingResponse(self) + + @overload + def create( + self, + *, + input: Union[str, ResponseInputParam], + model: Union[str, ChatModel], + include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, + previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, + reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, + tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, + tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Response: + """Creates a model response. + + Provide + [text](https://platform.openai.com/docs/guides/text) or + [image](https://platform.openai.com/docs/guides/images) inputs to generate + [text](https://platform.openai.com/docs/guides/text) or + [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have + the model call your own + [custom code](https://platform.openai.com/docs/guides/function-calling) or use + built-in [tools](https://platform.openai.com/docs/guides/tools) like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search) to use + your own data as input for the model's response. + + Args: + input: Text, image, or file inputs to the model, used to generate a response. + + Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Image inputs](https://platform.openai.com/docs/guides/images) + - [File inputs](https://platform.openai.com/docs/guides/pdf-files) + - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) + - [Function calling](https://platform.openai.com/docs/guides/function-calling) + + model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + wide range of models with different capabilities, performance characteristics, + and price points. Refer to the + [model guide](https://platform.openai.com/docs/models) to browse and compare + available models. + + include: Specify additional output data to include in the model response. Currently + supported values are: + + - `file_search_call.results`: Include the search results of the file search tool + call. + - `message.input_image.image_url`: Include image urls from the input message. + - `computer_call_output.output.image_url`: Include image urls from the computer + call output. + + instructions: Inserts a system (or developer) message as the first item in the model's + context. + + When using along with `previous_response_id`, the instructions from a previous + response will be not be carried over to the next response. This makes it simple + to swap out system (or developer) messages in new responses. + + max_output_tokens: An upper bound for the number of tokens that can be generated for a response, + including visible output tokens and + [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + + parallel_tool_calls: Whether to allow the model to run tool calls in parallel. + + previous_response_id: The unique ID of the previous response to the model. Use this to create + multi-turn conversations. Learn more about + [conversation state](https://platform.openai.com/docs/guides/conversation-state). + + reasoning: **o-series models only** + + Configuration options for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). + + store: Whether to store the generated model response for later retrieval via API. + + stream: If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) + for more information. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. We generally recommend altering this or `top_p` but + not both. + + text: Configuration options for a text response from the model. Can be plain text or + structured JSON data. Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + + tool_choice: How the model should select which tool (or tools) to use when generating a + response. See the `tools` parameter to see how to specify which tools the model + can call. + + tools: An array of tools the model may call while generating a response. You can + specify which tool to use by setting the `tool_choice` parameter. + + The two categories of tools you can provide the model are: + + - **Built-in tools**: Tools that are provided by OpenAI that extend the model's + capabilities, like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search). + Learn more about + [built-in tools](https://platform.openai.com/docs/guides/tools). + - **Function calls (custom tools)**: Functions that are defined by you, enabling + the model to call your own code. Learn more about + [function calling](https://platform.openai.com/docs/guides/function-calling). + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + truncation: The truncation strategy to use for the model response. + + - `auto`: If the context of this response and previous ones exceeds the model's + context window size, the model will truncate the response to fit the context + window by dropping input items in the middle of the conversation. + - `disabled` (default): If a model response will exceed the context window size + for a model, the request will fail with a 400 error. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + def create( + self, + *, + input: Union[str, ResponseInputParam], + model: Union[str, ChatModel], + stream: Literal[True], + include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, + previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, + reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, + tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, + tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Stream[ResponseStreamEvent]: + """Creates a model response. + + Provide + [text](https://platform.openai.com/docs/guides/text) or + [image](https://platform.openai.com/docs/guides/images) inputs to generate + [text](https://platform.openai.com/docs/guides/text) or + [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have + the model call your own + [custom code](https://platform.openai.com/docs/guides/function-calling) or use + built-in [tools](https://platform.openai.com/docs/guides/tools) like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search) to use + your own data as input for the model's response. + + Args: + input: Text, image, or file inputs to the model, used to generate a response. + + Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Image inputs](https://platform.openai.com/docs/guides/images) + - [File inputs](https://platform.openai.com/docs/guides/pdf-files) + - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) + - [Function calling](https://platform.openai.com/docs/guides/function-calling) + + model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + wide range of models with different capabilities, performance characteristics, + and price points. Refer to the + [model guide](https://platform.openai.com/docs/models) to browse and compare + available models. + + stream: If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) + for more information. + + include: Specify additional output data to include in the model response. Currently + supported values are: + + - `file_search_call.results`: Include the search results of the file search tool + call. + - `message.input_image.image_url`: Include image urls from the input message. + - `computer_call_output.output.image_url`: Include image urls from the computer + call output. + + instructions: Inserts a system (or developer) message as the first item in the model's + context. + + When using along with `previous_response_id`, the instructions from a previous + response will be not be carried over to the next response. This makes it simple + to swap out system (or developer) messages in new responses. + + max_output_tokens: An upper bound for the number of tokens that can be generated for a response, + including visible output tokens and + [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + + parallel_tool_calls: Whether to allow the model to run tool calls in parallel. + + previous_response_id: The unique ID of the previous response to the model. Use this to create + multi-turn conversations. Learn more about + [conversation state](https://platform.openai.com/docs/guides/conversation-state). + + reasoning: **o-series models only** + + Configuration options for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). + + store: Whether to store the generated model response for later retrieval via API. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. We generally recommend altering this or `top_p` but + not both. + + text: Configuration options for a text response from the model. Can be plain text or + structured JSON data. Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + + tool_choice: How the model should select which tool (or tools) to use when generating a + response. See the `tools` parameter to see how to specify which tools the model + can call. + + tools: An array of tools the model may call while generating a response. You can + specify which tool to use by setting the `tool_choice` parameter. + + The two categories of tools you can provide the model are: + + - **Built-in tools**: Tools that are provided by OpenAI that extend the model's + capabilities, like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search). + Learn more about + [built-in tools](https://platform.openai.com/docs/guides/tools). + - **Function calls (custom tools)**: Functions that are defined by you, enabling + the model to call your own code. Learn more about + [function calling](https://platform.openai.com/docs/guides/function-calling). + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + truncation: The truncation strategy to use for the model response. + + - `auto`: If the context of this response and previous ones exceeds the model's + context window size, the model will truncate the response to fit the context + window by dropping input items in the middle of the conversation. + - `disabled` (default): If a model response will exceed the context window size + for a model, the request will fail with a 400 error. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + def create( + self, + *, + input: Union[str, ResponseInputParam], + model: Union[str, ChatModel], + stream: bool, + include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, + previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, + reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, + tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, + tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Response | Stream[ResponseStreamEvent]: + """Creates a model response. + + Provide + [text](https://platform.openai.com/docs/guides/text) or + [image](https://platform.openai.com/docs/guides/images) inputs to generate + [text](https://platform.openai.com/docs/guides/text) or + [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have + the model call your own + [custom code](https://platform.openai.com/docs/guides/function-calling) or use + built-in [tools](https://platform.openai.com/docs/guides/tools) like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search) to use + your own data as input for the model's response. + + Args: + input: Text, image, or file inputs to the model, used to generate a response. + + Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Image inputs](https://platform.openai.com/docs/guides/images) + - [File inputs](https://platform.openai.com/docs/guides/pdf-files) + - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) + - [Function calling](https://platform.openai.com/docs/guides/function-calling) + + model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + wide range of models with different capabilities, performance characteristics, + and price points. Refer to the + [model guide](https://platform.openai.com/docs/models) to browse and compare + available models. + + stream: If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) + for more information. + + include: Specify additional output data to include in the model response. Currently + supported values are: + + - `file_search_call.results`: Include the search results of the file search tool + call. + - `message.input_image.image_url`: Include image urls from the input message. + - `computer_call_output.output.image_url`: Include image urls from the computer + call output. + + instructions: Inserts a system (or developer) message as the first item in the model's + context. + + When using along with `previous_response_id`, the instructions from a previous + response will be not be carried over to the next response. This makes it simple + to swap out system (or developer) messages in new responses. + + max_output_tokens: An upper bound for the number of tokens that can be generated for a response, + including visible output tokens and + [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + + parallel_tool_calls: Whether to allow the model to run tool calls in parallel. + + previous_response_id: The unique ID of the previous response to the model. Use this to create + multi-turn conversations. Learn more about + [conversation state](https://platform.openai.com/docs/guides/conversation-state). + + reasoning: **o-series models only** + + Configuration options for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). + + store: Whether to store the generated model response for later retrieval via API. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. We generally recommend altering this or `top_p` but + not both. + + text: Configuration options for a text response from the model. Can be plain text or + structured JSON data. Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + + tool_choice: How the model should select which tool (or tools) to use when generating a + response. See the `tools` parameter to see how to specify which tools the model + can call. + + tools: An array of tools the model may call while generating a response. You can + specify which tool to use by setting the `tool_choice` parameter. + + The two categories of tools you can provide the model are: + + - **Built-in tools**: Tools that are provided by OpenAI that extend the model's + capabilities, like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search). + Learn more about + [built-in tools](https://platform.openai.com/docs/guides/tools). + - **Function calls (custom tools)**: Functions that are defined by you, enabling + the model to call your own code. Learn more about + [function calling](https://platform.openai.com/docs/guides/function-calling). + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + truncation: The truncation strategy to use for the model response. + + - `auto`: If the context of this response and previous ones exceeds the model's + context window size, the model will truncate the response to fit the context + window by dropping input items in the middle of the conversation. + - `disabled` (default): If a model response will exceed the context window size + for a model, the request will fail with a 400 error. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @required_args(["input", "model"], ["input", "model", "stream"]) + def create( + self, + *, + input: Union[str, ResponseInputParam], + model: Union[str, ChatModel], + include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, + previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, + reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, + tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, + tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Response | Stream[ResponseStreamEvent]: + return self._post( + "/responses", + body=maybe_transform( + { + "input": input, + "model": model, + "include": include, + "instructions": instructions, + "max_output_tokens": max_output_tokens, + "metadata": metadata, + "parallel_tool_calls": parallel_tool_calls, + "previous_response_id": previous_response_id, + "reasoning": reasoning, + "store": store, + "stream": stream, + "temperature": temperature, + "text": text, + "tool_choice": tool_choice, + "tools": tools, + "top_p": top_p, + "truncation": truncation, + "user": user, + }, + response_create_params.ResponseCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Response, + stream=stream or False, + stream_cls=Stream[ResponseStreamEvent], + ) + + def stream( + self, + *, + input: Union[str, ResponseInputParam], + model: Union[str, ChatModel], + text_format: type[TextFormatT] | NotGiven = NOT_GIVEN, + tools: Iterable[ParseableToolParam] | NotGiven = NOT_GIVEN, + include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, + previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, + reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, + tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> ResponseStreamManager[TextFormatT]: + if is_given(text_format): + if not text: + text = {} + + if "format" in text: + raise TypeError("Cannot mix and match text.format with text_format") + + text["format"] = _type_to_text_format_param(text_format) + + tools = _make_tools(tools) + + api_request: partial[Stream[ResponseStreamEvent]] = partial( + self.create, + input=input, + model=model, + tools=tools, + include=include, + instructions=instructions, + max_output_tokens=max_output_tokens, + metadata=metadata, + parallel_tool_calls=parallel_tool_calls, + previous_response_id=previous_response_id, + store=store, + stream=True, + temperature=temperature, + text=text, + tool_choice=tool_choice, + reasoning=reasoning, + top_p=top_p, + truncation=truncation, + user=user, + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + ) + + return ResponseStreamManager( + api_request, + text_format=text_format, + input_tools=tools, + ) + + def parse( + self, + *, + input: Union[str, ResponseInputParam], + model: Union[str, ChatModel], + text_format: type[TextFormatT] | NotGiven = NOT_GIVEN, + tools: Iterable[ParseableToolParam] | NotGiven = NOT_GIVEN, + include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, + previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, + reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, + tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> ParsedResponse[TextFormatT]: + if is_given(text_format): + if not text: + text = {} + + if "format" in text: + raise TypeError("Cannot mix and match text.format with text_format") + + text["format"] = _type_to_text_format_param(text_format) + + tools = _make_tools(tools) + + def parser(raw_response: Response) -> ParsedResponse[TextFormatT]: + return parse_response( + input_tools=tools, + text_format=text_format, + response=raw_response, + ) + + return self._post( + "/responses", + body=maybe_transform( + { + "input": input, + "model": model, + "include": include, + "instructions": instructions, + "max_output_tokens": max_output_tokens, + "metadata": metadata, + "parallel_tool_calls": parallel_tool_calls, + "previous_response_id": previous_response_id, + "reasoning": reasoning, + "store": store, + "stream": stream, + "temperature": temperature, + "text": text, + "tool_choice": tool_choice, + "tools": tools, + "top_p": top_p, + "truncation": truncation, + "user": user, + }, + response_create_params.ResponseCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + post_parser=parser, + ), + # we turn the `Response` instance into a `ParsedResponse` + # in the `parser` function above + cast_to=cast(Type[ParsedResponse[TextFormatT]], Response), + ) + + def retrieve( + self, + response_id: str, + *, + include: List[ResponseIncludable] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Response: + """ + Retrieves a model response with the given ID. + + Args: + include: Additional fields to include in the response. See the `include` parameter for + Response creation above for more information. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not response_id: + raise ValueError(f"Expected a non-empty value for `response_id` but received {response_id!r}") + return self._get( + f"/responses/{response_id}", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform({"include": include}, response_retrieve_params.ResponseRetrieveParams), + ), + cast_to=Response, + ) + + def delete( + self, + response_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> None: + """ + Deletes a model response with the given ID. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not response_id: + raise ValueError(f"Expected a non-empty value for `response_id` but received {response_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._delete( + f"/responses/{response_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class AsyncResponses(AsyncAPIResource): + @cached_property + def input_items(self) -> AsyncInputItems: + return AsyncInputItems(self._client) + + @cached_property + def with_raw_response(self) -> AsyncResponsesWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return AsyncResponsesWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncResponsesWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return AsyncResponsesWithStreamingResponse(self) + + @overload + async def create( + self, + *, + input: Union[str, ResponseInputParam], + model: Union[str, ChatModel], + include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, + previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, + reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, + tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, + tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Response: + """Creates a model response. + + Provide + [text](https://platform.openai.com/docs/guides/text) or + [image](https://platform.openai.com/docs/guides/images) inputs to generate + [text](https://platform.openai.com/docs/guides/text) or + [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have + the model call your own + [custom code](https://platform.openai.com/docs/guides/function-calling) or use + built-in [tools](https://platform.openai.com/docs/guides/tools) like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search) to use + your own data as input for the model's response. + + Args: + input: Text, image, or file inputs to the model, used to generate a response. + + Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Image inputs](https://platform.openai.com/docs/guides/images) + - [File inputs](https://platform.openai.com/docs/guides/pdf-files) + - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) + - [Function calling](https://platform.openai.com/docs/guides/function-calling) + + model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + wide range of models with different capabilities, performance characteristics, + and price points. Refer to the + [model guide](https://platform.openai.com/docs/models) to browse and compare + available models. + + include: Specify additional output data to include in the model response. Currently + supported values are: + + - `file_search_call.results`: Include the search results of the file search tool + call. + - `message.input_image.image_url`: Include image urls from the input message. + - `computer_call_output.output.image_url`: Include image urls from the computer + call output. + + instructions: Inserts a system (or developer) message as the first item in the model's + context. + + When using along with `previous_response_id`, the instructions from a previous + response will be not be carried over to the next response. This makes it simple + to swap out system (or developer) messages in new responses. + + max_output_tokens: An upper bound for the number of tokens that can be generated for a response, + including visible output tokens and + [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + + parallel_tool_calls: Whether to allow the model to run tool calls in parallel. + + previous_response_id: The unique ID of the previous response to the model. Use this to create + multi-turn conversations. Learn more about + [conversation state](https://platform.openai.com/docs/guides/conversation-state). + + reasoning: **o-series models only** + + Configuration options for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). + + store: Whether to store the generated model response for later retrieval via API. + + stream: If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) + for more information. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. We generally recommend altering this or `top_p` but + not both. + + text: Configuration options for a text response from the model. Can be plain text or + structured JSON data. Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + + tool_choice: How the model should select which tool (or tools) to use when generating a + response. See the `tools` parameter to see how to specify which tools the model + can call. + + tools: An array of tools the model may call while generating a response. You can + specify which tool to use by setting the `tool_choice` parameter. + + The two categories of tools you can provide the model are: + + - **Built-in tools**: Tools that are provided by OpenAI that extend the model's + capabilities, like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search). + Learn more about + [built-in tools](https://platform.openai.com/docs/guides/tools). + - **Function calls (custom tools)**: Functions that are defined by you, enabling + the model to call your own code. Learn more about + [function calling](https://platform.openai.com/docs/guides/function-calling). + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + truncation: The truncation strategy to use for the model response. + + - `auto`: If the context of this response and previous ones exceeds the model's + context window size, the model will truncate the response to fit the context + window by dropping input items in the middle of the conversation. + - `disabled` (default): If a model response will exceed the context window size + for a model, the request will fail with a 400 error. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + async def create( + self, + *, + input: Union[str, ResponseInputParam], + model: Union[str, ChatModel], + stream: Literal[True], + include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, + previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, + reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, + tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, + tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncStream[ResponseStreamEvent]: + """Creates a model response. + + Provide + [text](https://platform.openai.com/docs/guides/text) or + [image](https://platform.openai.com/docs/guides/images) inputs to generate + [text](https://platform.openai.com/docs/guides/text) or + [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have + the model call your own + [custom code](https://platform.openai.com/docs/guides/function-calling) or use + built-in [tools](https://platform.openai.com/docs/guides/tools) like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search) to use + your own data as input for the model's response. + + Args: + input: Text, image, or file inputs to the model, used to generate a response. + + Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Image inputs](https://platform.openai.com/docs/guides/images) + - [File inputs](https://platform.openai.com/docs/guides/pdf-files) + - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) + - [Function calling](https://platform.openai.com/docs/guides/function-calling) + + model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + wide range of models with different capabilities, performance characteristics, + and price points. Refer to the + [model guide](https://platform.openai.com/docs/models) to browse and compare + available models. + + stream: If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) + for more information. + + include: Specify additional output data to include in the model response. Currently + supported values are: + + - `file_search_call.results`: Include the search results of the file search tool + call. + - `message.input_image.image_url`: Include image urls from the input message. + - `computer_call_output.output.image_url`: Include image urls from the computer + call output. + + instructions: Inserts a system (or developer) message as the first item in the model's + context. + + When using along with `previous_response_id`, the instructions from a previous + response will be not be carried over to the next response. This makes it simple + to swap out system (or developer) messages in new responses. + + max_output_tokens: An upper bound for the number of tokens that can be generated for a response, + including visible output tokens and + [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + + parallel_tool_calls: Whether to allow the model to run tool calls in parallel. + + previous_response_id: The unique ID of the previous response to the model. Use this to create + multi-turn conversations. Learn more about + [conversation state](https://platform.openai.com/docs/guides/conversation-state). + + reasoning: **o-series models only** + + Configuration options for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). + + store: Whether to store the generated model response for later retrieval via API. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. We generally recommend altering this or `top_p` but + not both. + + text: Configuration options for a text response from the model. Can be plain text or + structured JSON data. Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + + tool_choice: How the model should select which tool (or tools) to use when generating a + response. See the `tools` parameter to see how to specify which tools the model + can call. + + tools: An array of tools the model may call while generating a response. You can + specify which tool to use by setting the `tool_choice` parameter. + + The two categories of tools you can provide the model are: + + - **Built-in tools**: Tools that are provided by OpenAI that extend the model's + capabilities, like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search). + Learn more about + [built-in tools](https://platform.openai.com/docs/guides/tools). + - **Function calls (custom tools)**: Functions that are defined by you, enabling + the model to call your own code. Learn more about + [function calling](https://platform.openai.com/docs/guides/function-calling). + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + truncation: The truncation strategy to use for the model response. + + - `auto`: If the context of this response and previous ones exceeds the model's + context window size, the model will truncate the response to fit the context + window by dropping input items in the middle of the conversation. + - `disabled` (default): If a model response will exceed the context window size + for a model, the request will fail with a 400 error. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + async def create( + self, + *, + input: Union[str, ResponseInputParam], + model: Union[str, ChatModel], + stream: bool, + include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, + previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, + reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, + tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, + tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Response | AsyncStream[ResponseStreamEvent]: + """Creates a model response. + + Provide + [text](https://platform.openai.com/docs/guides/text) or + [image](https://platform.openai.com/docs/guides/images) inputs to generate + [text](https://platform.openai.com/docs/guides/text) or + [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have + the model call your own + [custom code](https://platform.openai.com/docs/guides/function-calling) or use + built-in [tools](https://platform.openai.com/docs/guides/tools) like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search) to use + your own data as input for the model's response. + + Args: + input: Text, image, or file inputs to the model, used to generate a response. + + Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Image inputs](https://platform.openai.com/docs/guides/images) + - [File inputs](https://platform.openai.com/docs/guides/pdf-files) + - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) + - [Function calling](https://platform.openai.com/docs/guides/function-calling) + + model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + wide range of models with different capabilities, performance characteristics, + and price points. Refer to the + [model guide](https://platform.openai.com/docs/models) to browse and compare + available models. + + stream: If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) + for more information. + + include: Specify additional output data to include in the model response. Currently + supported values are: + + - `file_search_call.results`: Include the search results of the file search tool + call. + - `message.input_image.image_url`: Include image urls from the input message. + - `computer_call_output.output.image_url`: Include image urls from the computer + call output. + + instructions: Inserts a system (or developer) message as the first item in the model's + context. + + When using along with `previous_response_id`, the instructions from a previous + response will be not be carried over to the next response. This makes it simple + to swap out system (or developer) messages in new responses. + + max_output_tokens: An upper bound for the number of tokens that can be generated for a response, + including visible output tokens and + [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + + parallel_tool_calls: Whether to allow the model to run tool calls in parallel. + + previous_response_id: The unique ID of the previous response to the model. Use this to create + multi-turn conversations. Learn more about + [conversation state](https://platform.openai.com/docs/guides/conversation-state). + + reasoning: **o-series models only** + + Configuration options for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). + + store: Whether to store the generated model response for later retrieval via API. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. We generally recommend altering this or `top_p` but + not both. + + text: Configuration options for a text response from the model. Can be plain text or + structured JSON data. Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + + tool_choice: How the model should select which tool (or tools) to use when generating a + response. See the `tools` parameter to see how to specify which tools the model + can call. + + tools: An array of tools the model may call while generating a response. You can + specify which tool to use by setting the `tool_choice` parameter. + + The two categories of tools you can provide the model are: + + - **Built-in tools**: Tools that are provided by OpenAI that extend the model's + capabilities, like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search). + Learn more about + [built-in tools](https://platform.openai.com/docs/guides/tools). + - **Function calls (custom tools)**: Functions that are defined by you, enabling + the model to call your own code. Learn more about + [function calling](https://platform.openai.com/docs/guides/function-calling). + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + truncation: The truncation strategy to use for the model response. + + - `auto`: If the context of this response and previous ones exceeds the model's + context window size, the model will truncate the response to fit the context + window by dropping input items in the middle of the conversation. + - `disabled` (default): If a model response will exceed the context window size + for a model, the request will fail with a 400 error. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @required_args(["input", "model"], ["input", "model", "stream"]) + async def create( + self, + *, + input: Union[str, ResponseInputParam], + model: Union[str, ChatModel], + include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, + previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, + reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, + tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, + tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Response | AsyncStream[ResponseStreamEvent]: + return await self._post( + "/responses", + body=await async_maybe_transform( + { + "input": input, + "model": model, + "include": include, + "instructions": instructions, + "max_output_tokens": max_output_tokens, + "metadata": metadata, + "parallel_tool_calls": parallel_tool_calls, + "previous_response_id": previous_response_id, + "reasoning": reasoning, + "store": store, + "stream": stream, + "temperature": temperature, + "text": text, + "tool_choice": tool_choice, + "tools": tools, + "top_p": top_p, + "truncation": truncation, + "user": user, + }, + response_create_params.ResponseCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Response, + stream=stream or False, + stream_cls=AsyncStream[ResponseStreamEvent], + ) + + def stream( + self, + *, + input: Union[str, ResponseInputParam], + model: Union[str, ChatModel], + text_format: type[TextFormatT] | NotGiven = NOT_GIVEN, + tools: Iterable[ParseableToolParam] | NotGiven = NOT_GIVEN, + include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, + previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, + reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, + tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncResponseStreamManager[TextFormatT]: + if is_given(text_format): + if not text: + text = {} + + if "format" in text: + raise TypeError("Cannot mix and match text.format with text_format") + + text["format"] = _type_to_text_format_param(text_format) + + tools = _make_tools(tools) + + api_request = self.create( + input=input, + model=model, + tools=tools, + include=include, + instructions=instructions, + max_output_tokens=max_output_tokens, + metadata=metadata, + parallel_tool_calls=parallel_tool_calls, + previous_response_id=previous_response_id, + store=store, + stream=True, + temperature=temperature, + text=text, + tool_choice=tool_choice, + reasoning=reasoning, + top_p=top_p, + truncation=truncation, + user=user, + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + ) + + return AsyncResponseStreamManager( + api_request, + text_format=text_format, + input_tools=tools, + ) + + async def parse( + self, + *, + input: Union[str, ResponseInputParam], + model: Union[str, ChatModel], + text_format: type[TextFormatT] | NotGiven = NOT_GIVEN, + tools: Iterable[ParseableToolParam] | NotGiven = NOT_GIVEN, + include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, + previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, + reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, + tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> ParsedResponse[TextFormatT]: + if is_given(text_format): + if not text: + text = {} + + if "format" in text: + raise TypeError("Cannot mix and match text.format with text_format") + + text["format"] = _type_to_text_format_param(text_format) + + tools = _make_tools(tools) + + def parser(raw_response: Response) -> ParsedResponse[TextFormatT]: + return parse_response( + input_tools=tools, + text_format=text_format, + response=raw_response, + ) + + return await self._post( + "/responses", + body=maybe_transform( + { + "input": input, + "model": model, + "include": include, + "instructions": instructions, + "max_output_tokens": max_output_tokens, + "metadata": metadata, + "parallel_tool_calls": parallel_tool_calls, + "previous_response_id": previous_response_id, + "reasoning": reasoning, + "store": store, + "stream": stream, + "temperature": temperature, + "text": text, + "tool_choice": tool_choice, + "tools": tools, + "top_p": top_p, + "truncation": truncation, + "user": user, + }, + response_create_params.ResponseCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + post_parser=parser, + ), + # we turn the `Response` instance into a `ParsedResponse` + # in the `parser` function above + cast_to=cast(Type[ParsedResponse[TextFormatT]], Response), + ) + + async def retrieve( + self, + response_id: str, + *, + include: List[ResponseIncludable] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Response: + """ + Retrieves a model response with the given ID. + + Args: + include: Additional fields to include in the response. See the `include` parameter for + Response creation above for more information. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not response_id: + raise ValueError(f"Expected a non-empty value for `response_id` but received {response_id!r}") + return await self._get( + f"/responses/{response_id}", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + {"include": include}, response_retrieve_params.ResponseRetrieveParams + ), + ), + cast_to=Response, + ) + + async def delete( + self, + response_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> None: + """ + Deletes a model response with the given ID. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not response_id: + raise ValueError(f"Expected a non-empty value for `response_id` but received {response_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._delete( + f"/responses/{response_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class ResponsesWithRawResponse: + def __init__(self, responses: Responses) -> None: + self._responses = responses + + self.create = _legacy_response.to_raw_response_wrapper( + responses.create, + ) + self.retrieve = _legacy_response.to_raw_response_wrapper( + responses.retrieve, + ) + self.delete = _legacy_response.to_raw_response_wrapper( + responses.delete, + ) + + @cached_property + def input_items(self) -> InputItemsWithRawResponse: + return InputItemsWithRawResponse(self._responses.input_items) + + +class AsyncResponsesWithRawResponse: + def __init__(self, responses: AsyncResponses) -> None: + self._responses = responses + + self.create = _legacy_response.async_to_raw_response_wrapper( + responses.create, + ) + self.retrieve = _legacy_response.async_to_raw_response_wrapper( + responses.retrieve, + ) + self.delete = _legacy_response.async_to_raw_response_wrapper( + responses.delete, + ) + + @cached_property + def input_items(self) -> AsyncInputItemsWithRawResponse: + return AsyncInputItemsWithRawResponse(self._responses.input_items) + + +class ResponsesWithStreamingResponse: + def __init__(self, responses: Responses) -> None: + self._responses = responses + + self.create = to_streamed_response_wrapper( + responses.create, + ) + self.retrieve = to_streamed_response_wrapper( + responses.retrieve, + ) + self.delete = to_streamed_response_wrapper( + responses.delete, + ) + + @cached_property + def input_items(self) -> InputItemsWithStreamingResponse: + return InputItemsWithStreamingResponse(self._responses.input_items) + + +class AsyncResponsesWithStreamingResponse: + def __init__(self, responses: AsyncResponses) -> None: + self._responses = responses + + self.create = async_to_streamed_response_wrapper( + responses.create, + ) + self.retrieve = async_to_streamed_response_wrapper( + responses.retrieve, + ) + self.delete = async_to_streamed_response_wrapper( + responses.delete, + ) + + @cached_property + def input_items(self) -> AsyncInputItemsWithStreamingResponse: + return AsyncInputItemsWithStreamingResponse(self._responses.input_items) + + +def _make_tools(tools: Iterable[ParseableToolParam] | NotGiven) -> List[ToolParam] | NotGiven: + if not is_given(tools): + return NOT_GIVEN + + converted_tools: List[ToolParam] = [] + for tool in tools: + if tool["type"] != "function": + converted_tools.append(tool) + continue + + if "function" not in tool: + # standard Responses API case + converted_tools.append(tool) + continue + + function = cast(Any, tool)["function"] # pyright: ignore[reportUnnecessaryCast] + if not isinstance(function, PydanticFunctionTool): + raise Exception( + "Expected Chat Completions function tool shape to be created using `openai.pydantic_function_tool()`" + ) + + assert "parameters" in function + new_tool = ResponsesPydanticFunctionTool( + { + "type": "function", + "name": function["name"], + "description": function.get("description"), + "parameters": function["parameters"], + "strict": function.get("strict") or False, + }, + function.model, + ) + + converted_tools.append(new_tool.cast()) + + return converted_tools diff --git a/src/openai/resources/uploads/uploads.py b/src/openai/resources/uploads/uploads.py index 2028decef5..9297dbc2c3 100644 --- a/src/openai/resources/uploads/uploads.py +++ b/src/openai/resources/uploads/uploads.py @@ -193,10 +193,9 @@ def create( contains all the parts you uploaded. This File is usable in the rest of our platform as a regular File object. - For certain `purpose`s, the correct `mime_type` must be specified. Please refer - to documentation for the supported MIME types for your use case: - - - [Assistants](https://platform.openai.com/docs/assistants/tools/file-search#supported-files) + For certain `purpose` values, the correct `mime_type` must be specified. Please + refer to documentation for the + [supported MIME types for your use case](https://platform.openai.com/docs/assistants/tools/file-search#supported-files). For guidance on the proper filename extensions for each purpose, please follow the documentation on @@ -497,10 +496,9 @@ async def create( contains all the parts you uploaded. This File is usable in the rest of our platform as a regular File object. - For certain `purpose`s, the correct `mime_type` must be specified. Please refer - to documentation for the supported MIME types for your use case: - - - [Assistants](https://platform.openai.com/docs/assistants/tools/file-search#supported-files) + For certain `purpose` values, the correct `mime_type` must be specified. Please + refer to documentation for the + [supported MIME types for your use case](https://platform.openai.com/docs/assistants/tools/file-search#supported-files). For guidance on the proper filename extensions for each purpose, please follow the documentation on diff --git a/src/openai/resources/beta/vector_stores/__init__.py b/src/openai/resources/vector_stores/__init__.py similarity index 100% rename from src/openai/resources/beta/vector_stores/__init__.py rename to src/openai/resources/vector_stores/__init__.py diff --git a/src/openai/resources/beta/vector_stores/file_batches.py b/src/openai/resources/vector_stores/file_batches.py similarity index 93% rename from src/openai/resources/beta/vector_stores/file_batches.py rename to src/openai/resources/vector_stores/file_batches.py index 6d61e92c7f..9b4b64d35e 100644 --- a/src/openai/resources/beta/vector_stores/file_batches.py +++ b/src/openai/resources/vector_stores/file_batches.py @@ -3,31 +3,31 @@ from __future__ import annotations import asyncio -from typing import List, Iterable -from typing_extensions import Literal +from typing import Dict, List, Iterable, Optional +from typing_extensions import Union, Literal from concurrent.futures import Future, ThreadPoolExecutor, as_completed import httpx import sniffio -from .... import _legacy_response -from ....types import FileObject -from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes -from ...._utils import ( +from ... import _legacy_response +from ...types import FileChunkingStrategyParam +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes +from ..._utils import ( is_given, maybe_transform, async_maybe_transform, ) -from ...._compat import cached_property -from ...._resource import SyncAPIResource, AsyncAPIResource -from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper -from ....pagination import SyncCursorPage, AsyncCursorPage -from ....types.beta import FileChunkingStrategyParam -from ...._base_client import AsyncPaginator, make_request_options -from ....types.beta.vector_stores import file_batch_create_params, file_batch_list_files_params -from ....types.beta.file_chunking_strategy_param import FileChunkingStrategyParam -from ....types.beta.vector_stores.vector_store_file import VectorStoreFile -from ....types.beta.vector_stores.vector_store_file_batch import VectorStoreFileBatch +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ...pagination import SyncCursorPage, AsyncCursorPage +from ..._base_client import AsyncPaginator, make_request_options +from ...types.file_object import FileObject +from ...types.vector_stores import file_batch_create_params, file_batch_list_files_params +from ...types.file_chunking_strategy_param import FileChunkingStrategyParam +from ...types.vector_stores.vector_store_file import VectorStoreFile +from ...types.vector_stores.vector_store_file_batch import VectorStoreFileBatch __all__ = ["FileBatches", "AsyncFileBatches"] @@ -57,6 +57,7 @@ def create( vector_store_id: str, *, file_ids: List[str], + attributes: Optional[Dict[str, Union[str, float, bool]]] | NotGiven = NOT_GIVEN, chunking_strategy: FileChunkingStrategyParam | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -73,6 +74,12 @@ def create( the vector store should use. Useful for tools like `file_search` that can access files. + attributes: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. Keys are strings with a maximum + length of 64 characters. Values are strings with a maximum length of 512 + characters, booleans, or numbers. + chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. Only applicable if `file_ids` is non-empty. @@ -92,6 +99,7 @@ def create( body=maybe_transform( { "file_ids": file_ids, + "attributes": attributes, "chunking_strategy": chunking_strategy, }, file_batch_create_params.FileBatchCreateParams, @@ -386,6 +394,7 @@ async def create( vector_store_id: str, *, file_ids: List[str], + attributes: Optional[Dict[str, Union[str, float, bool]]] | NotGiven = NOT_GIVEN, chunking_strategy: FileChunkingStrategyParam | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -402,6 +411,12 @@ async def create( the vector store should use. Useful for tools like `file_search` that can access files. + attributes: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. Keys are strings with a maximum + length of 64 characters. Values are strings with a maximum length of 512 + characters, booleans, or numbers. + chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. Only applicable if `file_ids` is non-empty. @@ -421,6 +436,7 @@ async def create( body=await async_maybe_transform( { "file_ids": file_ids, + "attributes": attributes, "chunking_strategy": chunking_strategy, }, file_batch_create_params.FileBatchCreateParams, diff --git a/src/openai/resources/beta/vector_stores/files.py b/src/openai/resources/vector_stores/files.py similarity index 73% rename from src/openai/resources/beta/vector_stores/files.py rename to src/openai/resources/vector_stores/files.py index febf27a753..7d93798adf 100644 --- a/src/openai/resources/beta/vector_stores/files.py +++ b/src/openai/resources/vector_stores/files.py @@ -2,28 +2,29 @@ from __future__ import annotations -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Dict, Union, Optional from typing_extensions import Literal, assert_never import httpx -from .... import _legacy_response -from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes -from ...._utils import ( +from ... import _legacy_response +from ...types import FileChunkingStrategyParam +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes +from ..._utils import ( is_given, maybe_transform, async_maybe_transform, ) -from ...._compat import cached_property -from ...._resource import SyncAPIResource, AsyncAPIResource -from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper -from ....pagination import SyncCursorPage, AsyncCursorPage -from ....types.beta import FileChunkingStrategyParam -from ...._base_client import AsyncPaginator, make_request_options -from ....types.beta.vector_stores import file_list_params, file_create_params -from ....types.beta.file_chunking_strategy_param import FileChunkingStrategyParam -from ....types.beta.vector_stores.vector_store_file import VectorStoreFile -from ....types.beta.vector_stores.vector_store_file_deleted import VectorStoreFileDeleted +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ...pagination import SyncPage, AsyncPage, SyncCursorPage, AsyncCursorPage +from ..._base_client import AsyncPaginator, make_request_options +from ...types.vector_stores import file_list_params, file_create_params, file_update_params +from ...types.file_chunking_strategy_param import FileChunkingStrategyParam +from ...types.vector_stores.vector_store_file import VectorStoreFile +from ...types.vector_stores.file_content_response import FileContentResponse +from ...types.vector_stores.vector_store_file_deleted import VectorStoreFileDeleted __all__ = ["Files", "AsyncFiles"] @@ -53,6 +54,7 @@ def create( vector_store_id: str, *, file_id: str, + attributes: Optional[Dict[str, Union[str, float, bool]]] | NotGiven = NOT_GIVEN, chunking_strategy: FileChunkingStrategyParam | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -71,6 +73,12 @@ def create( vector store should use. Useful for tools like `file_search` that can access files. + attributes: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. Keys are strings with a maximum + length of 64 characters. Values are strings with a maximum length of 512 + characters, booleans, or numbers. + chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. Only applicable if `file_ids` is non-empty. @@ -90,6 +98,7 @@ def create( body=maybe_transform( { "file_id": file_id, + "attributes": attributes, "chunking_strategy": chunking_strategy, }, file_create_params.FileCreateParams, @@ -137,6 +146,51 @@ def retrieve( cast_to=VectorStoreFile, ) + def update( + self, + file_id: str, + *, + vector_store_id: str, + attributes: Optional[Dict[str, Union[str, float, bool]]], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> VectorStoreFile: + """ + Update attributes on a vector store file. + + Args: + attributes: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. Keys are strings with a maximum + length of 64 characters. Values are strings with a maximum length of 512 + characters, booleans, or numbers. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") + if not file_id: + raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return self._post( + f"/vector_stores/{vector_store_id}/files/{file_id}", + body=maybe_transform({"attributes": attributes}, file_update_params.FileUpdateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=VectorStoreFile, + ) + def list( self, vector_store_id: str, @@ -339,6 +393,44 @@ def upload_and_poll( poll_interval_ms=poll_interval_ms, ) + def content( + self, + file_id: str, + *, + vector_store_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> SyncPage[FileContentResponse]: + """ + Retrieve the parsed contents of a vector store file. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") + if not file_id: + raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return self._get_api_list( + f"/vector_stores/{vector_store_id}/files/{file_id}/content", + page=SyncPage[FileContentResponse], + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + model=FileContentResponse, + ) + class AsyncFiles(AsyncAPIResource): @cached_property @@ -365,6 +457,7 @@ async def create( vector_store_id: str, *, file_id: str, + attributes: Optional[Dict[str, Union[str, float, bool]]] | NotGiven = NOT_GIVEN, chunking_strategy: FileChunkingStrategyParam | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -383,6 +476,12 @@ async def create( vector store should use. Useful for tools like `file_search` that can access files. + attributes: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. Keys are strings with a maximum + length of 64 characters. Values are strings with a maximum length of 512 + characters, booleans, or numbers. + chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. Only applicable if `file_ids` is non-empty. @@ -402,6 +501,7 @@ async def create( body=await async_maybe_transform( { "file_id": file_id, + "attributes": attributes, "chunking_strategy": chunking_strategy, }, file_create_params.FileCreateParams, @@ -449,6 +549,51 @@ async def retrieve( cast_to=VectorStoreFile, ) + async def update( + self, + file_id: str, + *, + vector_store_id: str, + attributes: Optional[Dict[str, Union[str, float, bool]]], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> VectorStoreFile: + """ + Update attributes on a vector store file. + + Args: + attributes: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. Keys are strings with a maximum + length of 64 characters. Values are strings with a maximum length of 512 + characters, booleans, or numbers. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") + if not file_id: + raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return await self._post( + f"/vector_stores/{vector_store_id}/files/{file_id}", + body=await async_maybe_transform({"attributes": attributes}, file_update_params.FileUpdateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=VectorStoreFile, + ) + def list( self, vector_store_id: str, @@ -653,6 +798,44 @@ async def upload_and_poll( chunking_strategy=chunking_strategy, ) + def content( + self, + file_id: str, + *, + vector_store_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncPaginator[FileContentResponse, AsyncPage[FileContentResponse]]: + """ + Retrieve the parsed contents of a vector store file. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") + if not file_id: + raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return self._get_api_list( + f"/vector_stores/{vector_store_id}/files/{file_id}/content", + page=AsyncPage[FileContentResponse], + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + model=FileContentResponse, + ) + class FilesWithRawResponse: def __init__(self, files: Files) -> None: @@ -664,12 +847,18 @@ def __init__(self, files: Files) -> None: self.retrieve = _legacy_response.to_raw_response_wrapper( files.retrieve, ) + self.update = _legacy_response.to_raw_response_wrapper( + files.update, + ) self.list = _legacy_response.to_raw_response_wrapper( files.list, ) self.delete = _legacy_response.to_raw_response_wrapper( files.delete, ) + self.content = _legacy_response.to_raw_response_wrapper( + files.content, + ) class AsyncFilesWithRawResponse: @@ -682,12 +871,18 @@ def __init__(self, files: AsyncFiles) -> None: self.retrieve = _legacy_response.async_to_raw_response_wrapper( files.retrieve, ) + self.update = _legacy_response.async_to_raw_response_wrapper( + files.update, + ) self.list = _legacy_response.async_to_raw_response_wrapper( files.list, ) self.delete = _legacy_response.async_to_raw_response_wrapper( files.delete, ) + self.content = _legacy_response.async_to_raw_response_wrapper( + files.content, + ) class FilesWithStreamingResponse: @@ -700,12 +895,18 @@ def __init__(self, files: Files) -> None: self.retrieve = to_streamed_response_wrapper( files.retrieve, ) + self.update = to_streamed_response_wrapper( + files.update, + ) self.list = to_streamed_response_wrapper( files.list, ) self.delete = to_streamed_response_wrapper( files.delete, ) + self.content = to_streamed_response_wrapper( + files.content, + ) class AsyncFilesWithStreamingResponse: @@ -718,9 +919,15 @@ def __init__(self, files: AsyncFiles) -> None: self.retrieve = async_to_streamed_response_wrapper( files.retrieve, ) + self.update = async_to_streamed_response_wrapper( + files.update, + ) self.list = async_to_streamed_response_wrapper( files.list, ) self.delete = async_to_streamed_response_wrapper( files.delete, ) + self.content = async_to_streamed_response_wrapper( + files.content, + ) diff --git a/src/openai/resources/beta/vector_stores/vector_stores.py b/src/openai/resources/vector_stores/vector_stores.py similarity index 80% rename from src/openai/resources/beta/vector_stores/vector_stores.py rename to src/openai/resources/vector_stores/vector_stores.py index 1da52fb3c7..aaa6ed2757 100644 --- a/src/openai/resources/beta/vector_stores/vector_stores.py +++ b/src/openai/resources/vector_stores/vector_stores.py @@ -2,12 +2,12 @@ from __future__ import annotations -from typing import List, Optional +from typing import List, Union, Optional from typing_extensions import Literal import httpx -from .... import _legacy_response +from ... import _legacy_response from .files import ( Files, AsyncFiles, @@ -16,14 +16,22 @@ FilesWithStreamingResponse, AsyncFilesWithStreamingResponse, ) -from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ...._utils import ( +from ...types import ( + FileChunkingStrategyParam, + vector_store_list_params, + vector_store_create_params, + vector_store_search_params, + vector_store_update_params, +) +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ..._utils import ( maybe_transform, async_maybe_transform, ) -from ...._compat import cached_property -from ...._resource import SyncAPIResource, AsyncAPIResource -from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ...pagination import SyncPage, AsyncPage, SyncCursorPage, AsyncCursorPage from .file_batches import ( FileBatches, AsyncFileBatches, @@ -32,18 +40,12 @@ FileBatchesWithStreamingResponse, AsyncFileBatchesWithStreamingResponse, ) -from ....pagination import SyncCursorPage, AsyncCursorPage -from ....types.beta import ( - FileChunkingStrategyParam, - vector_store_list_params, - vector_store_create_params, - vector_store_update_params, -) -from ...._base_client import AsyncPaginator, make_request_options -from ....types.beta.vector_store import VectorStore -from ....types.shared_params.metadata import Metadata -from ....types.beta.vector_store_deleted import VectorStoreDeleted -from ....types.beta.file_chunking_strategy_param import FileChunkingStrategyParam +from ..._base_client import AsyncPaginator, make_request_options +from ...types.vector_store import VectorStore +from ...types.vector_store_deleted import VectorStoreDeleted +from ...types.shared_params.metadata import Metadata +from ...types.file_chunking_strategy_param import FileChunkingStrategyParam +from ...types.vector_store_search_response import VectorStoreSearchResponse __all__ = ["VectorStores", "AsyncVectorStores"] @@ -329,6 +331,69 @@ def delete( cast_to=VectorStoreDeleted, ) + def search( + self, + vector_store_id: str, + *, + query: Union[str, List[str]], + filters: vector_store_search_params.Filters | NotGiven = NOT_GIVEN, + max_num_results: int | NotGiven = NOT_GIVEN, + ranking_options: vector_store_search_params.RankingOptions | NotGiven = NOT_GIVEN, + rewrite_query: bool | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> SyncPage[VectorStoreSearchResponse]: + """ + Search a vector store for relevant chunks based on a query and file attributes + filter. + + Args: + query: A query string for a search + + filters: A filter to apply based on file attributes. + + max_num_results: The maximum number of results to return. This number should be between 1 and 50 + inclusive. + + ranking_options: Ranking options for search. + + rewrite_query: Whether to rewrite the natural language query for vector search. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return self._get_api_list( + f"/vector_stores/{vector_store_id}/search", + page=SyncPage[VectorStoreSearchResponse], + body=maybe_transform( + { + "query": query, + "filters": filters, + "max_num_results": max_num_results, + "ranking_options": ranking_options, + "rewrite_query": rewrite_query, + }, + vector_store_search_params.VectorStoreSearchParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + model=VectorStoreSearchResponse, + method="post", + ) + class AsyncVectorStores(AsyncAPIResource): @cached_property @@ -611,6 +676,69 @@ async def delete( cast_to=VectorStoreDeleted, ) + def search( + self, + vector_store_id: str, + *, + query: Union[str, List[str]], + filters: vector_store_search_params.Filters | NotGiven = NOT_GIVEN, + max_num_results: int | NotGiven = NOT_GIVEN, + ranking_options: vector_store_search_params.RankingOptions | NotGiven = NOT_GIVEN, + rewrite_query: bool | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncPaginator[VectorStoreSearchResponse, AsyncPage[VectorStoreSearchResponse]]: + """ + Search a vector store for relevant chunks based on a query and file attributes + filter. + + Args: + query: A query string for a search + + filters: A filter to apply based on file attributes. + + max_num_results: The maximum number of results to return. This number should be between 1 and 50 + inclusive. + + ranking_options: Ranking options for search. + + rewrite_query: Whether to rewrite the natural language query for vector search. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not vector_store_id: + raise ValueError(f"Expected a non-empty value for `vector_store_id` but received {vector_store_id!r}") + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return self._get_api_list( + f"/vector_stores/{vector_store_id}/search", + page=AsyncPage[VectorStoreSearchResponse], + body=maybe_transform( + { + "query": query, + "filters": filters, + "max_num_results": max_num_results, + "ranking_options": ranking_options, + "rewrite_query": rewrite_query, + }, + vector_store_search_params.VectorStoreSearchParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + model=VectorStoreSearchResponse, + method="post", + ) + class VectorStoresWithRawResponse: def __init__(self, vector_stores: VectorStores) -> None: @@ -631,6 +759,9 @@ def __init__(self, vector_stores: VectorStores) -> None: self.delete = _legacy_response.to_raw_response_wrapper( vector_stores.delete, ) + self.search = _legacy_response.to_raw_response_wrapper( + vector_stores.search, + ) @cached_property def files(self) -> FilesWithRawResponse: @@ -660,6 +791,9 @@ def __init__(self, vector_stores: AsyncVectorStores) -> None: self.delete = _legacy_response.async_to_raw_response_wrapper( vector_stores.delete, ) + self.search = _legacy_response.async_to_raw_response_wrapper( + vector_stores.search, + ) @cached_property def files(self) -> AsyncFilesWithRawResponse: @@ -689,6 +823,9 @@ def __init__(self, vector_stores: VectorStores) -> None: self.delete = to_streamed_response_wrapper( vector_stores.delete, ) + self.search = to_streamed_response_wrapper( + vector_stores.search, + ) @cached_property def files(self) -> FilesWithStreamingResponse: @@ -718,6 +855,9 @@ def __init__(self, vector_stores: AsyncVectorStores) -> None: self.delete = async_to_streamed_response_wrapper( vector_stores.delete, ) + self.search = async_to_streamed_response_wrapper( + vector_stores.search, + ) @cached_property def files(self) -> AsyncFilesWithStreamingResponse: diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index eb71ac6ccc..4c337d41c7 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -8,7 +8,11 @@ from .shared import ( Metadata as Metadata, ChatModel as ChatModel, + Reasoning as Reasoning, ErrorObject as ErrorObject, + CompoundFilter as CompoundFilter, + ReasoningEffort as ReasoningEffort, + ComparisonFilter as ComparisonFilter, FunctionDefinition as FunctionDefinition, FunctionParameters as FunctionParameters, ResponseFormatText as ResponseFormatText, @@ -27,6 +31,7 @@ from .file_content import FileContent as FileContent from .file_deleted import FileDeleted as FileDeleted from .file_purpose import FilePurpose as FilePurpose +from .vector_store import VectorStore as VectorStore from .model_deleted import ModelDeleted as ModelDeleted from .embedding_model import EmbeddingModel as EmbeddingModel from .images_response import ImagesResponse as ImagesResponse @@ -40,16 +45,32 @@ from .batch_create_params import BatchCreateParams as BatchCreateParams from .batch_request_counts import BatchRequestCounts as BatchRequestCounts from .upload_create_params import UploadCreateParams as UploadCreateParams +from .vector_store_deleted import VectorStoreDeleted as VectorStoreDeleted from .audio_response_format import AudioResponseFormat as AudioResponseFormat from .image_generate_params import ImageGenerateParams as ImageGenerateParams +from .file_chunking_strategy import FileChunkingStrategy as FileChunkingStrategy from .upload_complete_params import UploadCompleteParams as UploadCompleteParams from .embedding_create_params import EmbeddingCreateParams as EmbeddingCreateParams from .completion_create_params import CompletionCreateParams as CompletionCreateParams from .moderation_create_params import ModerationCreateParams as ModerationCreateParams +from .vector_store_list_params import VectorStoreListParams as VectorStoreListParams from .create_embedding_response import CreateEmbeddingResponse as CreateEmbeddingResponse from .moderation_create_response import ModerationCreateResponse as ModerationCreateResponse +from .vector_store_create_params import VectorStoreCreateParams as VectorStoreCreateParams +from .vector_store_search_params import VectorStoreSearchParams as VectorStoreSearchParams +from .vector_store_update_params import VectorStoreUpdateParams as VectorStoreUpdateParams from .moderation_text_input_param import ModerationTextInputParam as ModerationTextInputParam +from .file_chunking_strategy_param import FileChunkingStrategyParam as FileChunkingStrategyParam +from .vector_store_search_response import VectorStoreSearchResponse as VectorStoreSearchResponse from .websocket_connection_options import WebsocketConnectionOptions as WebsocketConnectionOptions from .image_create_variation_params import ImageCreateVariationParams as ImageCreateVariationParams +from .static_file_chunking_strategy import StaticFileChunkingStrategy as StaticFileChunkingStrategy from .moderation_image_url_input_param import ModerationImageURLInputParam as ModerationImageURLInputParam +from .auto_file_chunking_strategy_param import AutoFileChunkingStrategyParam as AutoFileChunkingStrategyParam from .moderation_multi_modal_input_param import ModerationMultiModalInputParam as ModerationMultiModalInputParam +from .other_file_chunking_strategy_object import OtherFileChunkingStrategyObject as OtherFileChunkingStrategyObject +from .static_file_chunking_strategy_param import StaticFileChunkingStrategyParam as StaticFileChunkingStrategyParam +from .static_file_chunking_strategy_object import StaticFileChunkingStrategyObject as StaticFileChunkingStrategyObject +from .static_file_chunking_strategy_object_param import ( + StaticFileChunkingStrategyObjectParam as StaticFileChunkingStrategyObjectParam, +) diff --git a/src/openai/types/beta/auto_file_chunking_strategy_param.py b/src/openai/types/auto_file_chunking_strategy_param.py similarity index 100% rename from src/openai/types/beta/auto_file_chunking_strategy_param.py rename to src/openai/types/auto_file_chunking_strategy_param.py diff --git a/src/openai/types/beta/__init__.py b/src/openai/types/beta/__init__.py index b9ea792bfa..5ba3eadf3c 100644 --- a/src/openai/types/beta/__init__.py +++ b/src/openai/types/beta/__init__.py @@ -4,7 +4,6 @@ from .thread import Thread as Thread from .assistant import Assistant as Assistant -from .vector_store import VectorStore as VectorStore from .function_tool import FunctionTool as FunctionTool from .assistant_tool import AssistantTool as AssistantTool from .thread_deleted import ThreadDeleted as ThreadDeleted @@ -14,35 +13,21 @@ from .assistant_tool_param import AssistantToolParam as AssistantToolParam from .thread_create_params import ThreadCreateParams as ThreadCreateParams from .thread_update_params import ThreadUpdateParams as ThreadUpdateParams -from .vector_store_deleted import VectorStoreDeleted as VectorStoreDeleted from .assistant_list_params import AssistantListParams as AssistantListParams from .assistant_tool_choice import AssistantToolChoice as AssistantToolChoice from .code_interpreter_tool import CodeInterpreterTool as CodeInterpreterTool from .assistant_stream_event import AssistantStreamEvent as AssistantStreamEvent -from .file_chunking_strategy import FileChunkingStrategy as FileChunkingStrategy from .file_search_tool_param import FileSearchToolParam as FileSearchToolParam from .assistant_create_params import AssistantCreateParams as AssistantCreateParams from .assistant_update_params import AssistantUpdateParams as AssistantUpdateParams -from .vector_store_list_params import VectorStoreListParams as VectorStoreListParams -from .vector_store_create_params import VectorStoreCreateParams as VectorStoreCreateParams -from .vector_store_update_params import VectorStoreUpdateParams as VectorStoreUpdateParams from .assistant_tool_choice_param import AssistantToolChoiceParam as AssistantToolChoiceParam from .code_interpreter_tool_param import CodeInterpreterToolParam as CodeInterpreterToolParam from .assistant_tool_choice_option import AssistantToolChoiceOption as AssistantToolChoiceOption -from .file_chunking_strategy_param import FileChunkingStrategyParam as FileChunkingStrategyParam from .thread_create_and_run_params import ThreadCreateAndRunParams as ThreadCreateAndRunParams -from .static_file_chunking_strategy import StaticFileChunkingStrategy as StaticFileChunkingStrategy from .assistant_tool_choice_function import AssistantToolChoiceFunction as AssistantToolChoiceFunction from .assistant_response_format_option import AssistantResponseFormatOption as AssistantResponseFormatOption -from .auto_file_chunking_strategy_param import AutoFileChunkingStrategyParam as AutoFileChunkingStrategyParam from .assistant_tool_choice_option_param import AssistantToolChoiceOptionParam as AssistantToolChoiceOptionParam -from .other_file_chunking_strategy_object import OtherFileChunkingStrategyObject as OtherFileChunkingStrategyObject -from .static_file_chunking_strategy_param import StaticFileChunkingStrategyParam as StaticFileChunkingStrategyParam from .assistant_tool_choice_function_param import AssistantToolChoiceFunctionParam as AssistantToolChoiceFunctionParam -from .static_file_chunking_strategy_object import StaticFileChunkingStrategyObject as StaticFileChunkingStrategyObject from .assistant_response_format_option_param import ( AssistantResponseFormatOptionParam as AssistantResponseFormatOptionParam, ) -from .static_file_chunking_strategy_object_param import ( - StaticFileChunkingStrategyObjectParam as StaticFileChunkingStrategyObjectParam, -) diff --git a/src/openai/types/beta/assistant_create_params.py b/src/openai/types/beta/assistant_create_params.py index e90aabfd3f..8b3c331850 100644 --- a/src/openai/types/beta/assistant_create_params.py +++ b/src/openai/types/beta/assistant_create_params.py @@ -3,12 +3,12 @@ from __future__ import annotations from typing import List, Union, Iterable, Optional -from typing_extensions import Literal, Required, TypedDict +from typing_extensions import Literal, Required, TypeAlias, TypedDict from ..shared.chat_model import ChatModel from .assistant_tool_param import AssistantToolParam from ..shared_params.metadata import Metadata -from .file_chunking_strategy_param import FileChunkingStrategyParam +from ..shared.reasoning_effort import ReasoningEffort from .assistant_response_format_option_param import AssistantResponseFormatOptionParam __all__ = [ @@ -17,6 +17,10 @@ "ToolResourcesCodeInterpreter", "ToolResourcesFileSearch", "ToolResourcesFileSearchVectorStore", + "ToolResourcesFileSearchVectorStoreChunkingStrategy", + "ToolResourcesFileSearchVectorStoreChunkingStrategyAuto", + "ToolResourcesFileSearchVectorStoreChunkingStrategyStatic", + "ToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic", ] @@ -53,8 +57,8 @@ class AssistantCreateParams(TypedDict, total=False): name: Optional[str] """The name of the assistant. The maximum length is 256 characters.""" - reasoning_effort: Optional[Literal["low", "medium", "high"]] - """**o1 and o3-mini models only** + reasoning_effort: Optional[ReasoningEffort] + """**o-series models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently @@ -127,12 +131,43 @@ class ToolResourcesCodeInterpreter(TypedDict, total=False): """ +class ToolResourcesFileSearchVectorStoreChunkingStrategyAuto(TypedDict, total=False): + type: Required[Literal["auto"]] + """Always `auto`.""" + + +class ToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic(TypedDict, total=False): + chunk_overlap_tokens: Required[int] + """The number of tokens that overlap between chunks. The default value is `400`. + + Note that the overlap must not exceed half of `max_chunk_size_tokens`. + """ + + max_chunk_size_tokens: Required[int] + """The maximum number of tokens in each chunk. + + The default value is `800`. The minimum value is `100` and the maximum value is + `4096`. + """ + + +class ToolResourcesFileSearchVectorStoreChunkingStrategyStatic(TypedDict, total=False): + static: Required[ToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic] + + type: Required[Literal["static"]] + """Always `static`.""" + + +ToolResourcesFileSearchVectorStoreChunkingStrategy: TypeAlias = Union[ + ToolResourcesFileSearchVectorStoreChunkingStrategyAuto, ToolResourcesFileSearchVectorStoreChunkingStrategyStatic +] + + class ToolResourcesFileSearchVectorStore(TypedDict, total=False): - chunking_strategy: FileChunkingStrategyParam + chunking_strategy: ToolResourcesFileSearchVectorStoreChunkingStrategy """The chunking strategy used to chunk the file(s). - If not set, will use the `auto` strategy. Only applicable if `file_ids` is - non-empty. + If not set, will use the `auto` strategy. """ file_ids: List[str] diff --git a/src/openai/types/beta/assistant_update_params.py b/src/openai/types/beta/assistant_update_params.py index 12a57a4063..d3ec7614fd 100644 --- a/src/openai/types/beta/assistant_update_params.py +++ b/src/openai/types/beta/assistant_update_params.py @@ -7,6 +7,7 @@ from .assistant_tool_param import AssistantToolParam from ..shared_params.metadata import Metadata +from ..shared.reasoning_effort import ReasoningEffort from .assistant_response_format_option_param import AssistantResponseFormatOptionParam __all__ = ["AssistantUpdateParams", "ToolResources", "ToolResourcesCodeInterpreter", "ToolResourcesFileSearch"] @@ -79,8 +80,8 @@ class AssistantUpdateParams(TypedDict, total=False): name: Optional[str] """The name of the assistant. The maximum length is 256 characters.""" - reasoning_effort: Optional[Literal["low", "medium", "high"]] - """**o1 and o3-mini models only** + reasoning_effort: Optional[ReasoningEffort] + """**o-series models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index d888fb3eee..065c390f4e 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -10,7 +10,6 @@ from .file_search_tool_param import FileSearchToolParam from ..shared_params.metadata import Metadata from .code_interpreter_tool_param import CodeInterpreterToolParam -from .file_chunking_strategy_param import FileChunkingStrategyParam from .assistant_tool_choice_option_param import AssistantToolChoiceOptionParam from .threads.message_content_part_param import MessageContentPartParam from .assistant_response_format_option_param import AssistantResponseFormatOptionParam @@ -26,6 +25,10 @@ "ThreadToolResourcesCodeInterpreter", "ThreadToolResourcesFileSearch", "ThreadToolResourcesFileSearchVectorStore", + "ThreadToolResourcesFileSearchVectorStoreChunkingStrategy", + "ThreadToolResourcesFileSearchVectorStoreChunkingStrategyAuto", + "ThreadToolResourcesFileSearchVectorStoreChunkingStrategyStatic", + "ThreadToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic", "ToolResources", "ToolResourcesCodeInterpreter", "ToolResourcesFileSearch", @@ -224,12 +227,44 @@ class ThreadToolResourcesCodeInterpreter(TypedDict, total=False): """ +class ThreadToolResourcesFileSearchVectorStoreChunkingStrategyAuto(TypedDict, total=False): + type: Required[Literal["auto"]] + """Always `auto`.""" + + +class ThreadToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic(TypedDict, total=False): + chunk_overlap_tokens: Required[int] + """The number of tokens that overlap between chunks. The default value is `400`. + + Note that the overlap must not exceed half of `max_chunk_size_tokens`. + """ + + max_chunk_size_tokens: Required[int] + """The maximum number of tokens in each chunk. + + The default value is `800`. The minimum value is `100` and the maximum value is + `4096`. + """ + + +class ThreadToolResourcesFileSearchVectorStoreChunkingStrategyStatic(TypedDict, total=False): + static: Required[ThreadToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic] + + type: Required[Literal["static"]] + """Always `static`.""" + + +ThreadToolResourcesFileSearchVectorStoreChunkingStrategy: TypeAlias = Union[ + ThreadToolResourcesFileSearchVectorStoreChunkingStrategyAuto, + ThreadToolResourcesFileSearchVectorStoreChunkingStrategyStatic, +] + + class ThreadToolResourcesFileSearchVectorStore(TypedDict, total=False): - chunking_strategy: FileChunkingStrategyParam + chunking_strategy: ThreadToolResourcesFileSearchVectorStoreChunkingStrategy """The chunking strategy used to chunk the file(s). - If not set, will use the `auto` strategy. Only applicable if `file_ids` is - non-empty. + If not set, will use the `auto` strategy. """ file_ids: List[str] diff --git a/src/openai/types/beta/thread_create_params.py b/src/openai/types/beta/thread_create_params.py index 127202753c..ec1ccf19a6 100644 --- a/src/openai/types/beta/thread_create_params.py +++ b/src/openai/types/beta/thread_create_params.py @@ -7,7 +7,6 @@ from ..shared_params.metadata import Metadata from .code_interpreter_tool_param import CodeInterpreterToolParam -from .file_chunking_strategy_param import FileChunkingStrategyParam from .threads.message_content_part_param import MessageContentPartParam __all__ = [ @@ -20,6 +19,10 @@ "ToolResourcesCodeInterpreter", "ToolResourcesFileSearch", "ToolResourcesFileSearchVectorStore", + "ToolResourcesFileSearchVectorStoreChunkingStrategy", + "ToolResourcesFileSearchVectorStoreChunkingStrategyAuto", + "ToolResourcesFileSearchVectorStoreChunkingStrategyStatic", + "ToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic", ] @@ -101,12 +104,43 @@ class ToolResourcesCodeInterpreter(TypedDict, total=False): """ +class ToolResourcesFileSearchVectorStoreChunkingStrategyAuto(TypedDict, total=False): + type: Required[Literal["auto"]] + """Always `auto`.""" + + +class ToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic(TypedDict, total=False): + chunk_overlap_tokens: Required[int] + """The number of tokens that overlap between chunks. The default value is `400`. + + Note that the overlap must not exceed half of `max_chunk_size_tokens`. + """ + + max_chunk_size_tokens: Required[int] + """The maximum number of tokens in each chunk. + + The default value is `800`. The minimum value is `100` and the maximum value is + `4096`. + """ + + +class ToolResourcesFileSearchVectorStoreChunkingStrategyStatic(TypedDict, total=False): + static: Required[ToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic] + + type: Required[Literal["static"]] + """Always `static`.""" + + +ToolResourcesFileSearchVectorStoreChunkingStrategy: TypeAlias = Union[ + ToolResourcesFileSearchVectorStoreChunkingStrategyAuto, ToolResourcesFileSearchVectorStoreChunkingStrategyStatic +] + + class ToolResourcesFileSearchVectorStore(TypedDict, total=False): - chunking_strategy: FileChunkingStrategyParam + chunking_strategy: ToolResourcesFileSearchVectorStoreChunkingStrategy """The chunking strategy used to chunk the file(s). - If not set, will use the `auto` strategy. Only applicable if `file_ids` is - non-empty. + If not set, will use the `auto` strategy. """ file_ids: List[str] diff --git a/src/openai/types/beta/threads/run_create_params.py b/src/openai/types/beta/threads/run_create_params.py index 098e50a1d9..fc70227862 100644 --- a/src/openai/types/beta/threads/run_create_params.py +++ b/src/openai/types/beta/threads/run_create_params.py @@ -9,6 +9,7 @@ from ..assistant_tool_param import AssistantToolParam from .runs.run_step_include import RunStepInclude from ...shared_params.metadata import Metadata +from ...shared.reasoning_effort import ReasoningEffort from .message_content_part_param import MessageContentPartParam from ..code_interpreter_tool_param import CodeInterpreterToolParam from ..assistant_tool_choice_option_param import AssistantToolChoiceOptionParam @@ -106,8 +107,8 @@ class RunCreateParamsBase(TypedDict, total=False): during tool use. """ - reasoning_effort: Optional[Literal["low", "medium", "high"]] - """**o1 and o3-mini models only** + reasoning_effort: Optional[ReasoningEffort] + """**o-series models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently diff --git a/src/openai/types/chat/chat_completion_audio_param.py b/src/openai/types/chat/chat_completion_audio_param.py index 1e20a52b41..6321417826 100644 --- a/src/openai/types/chat/chat_completion_audio_param.py +++ b/src/openai/types/chat/chat_completion_audio_param.py @@ -17,7 +17,6 @@ class ChatCompletionAudioParam(TypedDict, total=False): voice: Required[Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"]] """The voice the model uses to respond. - Supported voices are `ash`, `ballad`, `coral`, `sage`, and `verse` (also - supported but not recommended are `alloy`, `echo`, and `shimmer`; these voices - are less expressive). + Supported voices are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, and + `shimmer`. """ diff --git a/src/openai/types/chat/chat_completion_content_part_param.py b/src/openai/types/chat/chat_completion_content_part_param.py index 682d11f4c7..1293c54312 100644 --- a/src/openai/types/chat/chat_completion_content_part_param.py +++ b/src/openai/types/chat/chat_completion_content_part_param.py @@ -3,14 +3,39 @@ from __future__ import annotations from typing import Union -from typing_extensions import TypeAlias +from typing_extensions import Literal, Required, TypeAlias, TypedDict from .chat_completion_content_part_text_param import ChatCompletionContentPartTextParam from .chat_completion_content_part_image_param import ChatCompletionContentPartImageParam from .chat_completion_content_part_input_audio_param import ChatCompletionContentPartInputAudioParam -__all__ = ["ChatCompletionContentPartParam"] +__all__ = ["ChatCompletionContentPartParam", "File", "FileFile"] + + +class FileFile(TypedDict, total=False): + file_data: str + """ + The base64 encoded file data, used when passing the file to the model as a + string. + """ + + file_id: str + """The ID of an uploaded file to use as input.""" + + file_name: str + """The name of the file, used when passing the file to the model as a string.""" + + +class File(TypedDict, total=False): + file: Required[FileFile] + + type: Required[Literal["file"]] + """The type of the content part. Always `file`.""" + ChatCompletionContentPartParam: TypeAlias = Union[ - ChatCompletionContentPartTextParam, ChatCompletionContentPartImageParam, ChatCompletionContentPartInputAudioParam + ChatCompletionContentPartTextParam, + ChatCompletionContentPartImageParam, + ChatCompletionContentPartInputAudioParam, + File, ] diff --git a/src/openai/types/chat/chat_completion_message.py b/src/openai/types/chat/chat_completion_message.py index 704fa5d5d1..c659ac3da0 100644 --- a/src/openai/types/chat/chat_completion_message.py +++ b/src/openai/types/chat/chat_completion_message.py @@ -7,7 +7,29 @@ from .chat_completion_audio import ChatCompletionAudio from .chat_completion_message_tool_call import ChatCompletionMessageToolCall -__all__ = ["ChatCompletionMessage", "FunctionCall"] +__all__ = ["ChatCompletionMessage", "Annotation", "AnnotationURLCitation", "FunctionCall"] + + +class AnnotationURLCitation(BaseModel): + end_index: int + """The index of the last character of the URL citation in the message.""" + + start_index: int + """The index of the first character of the URL citation in the message.""" + + title: str + """The title of the web resource.""" + + url: str + """The URL of the web resource.""" + + +class Annotation(BaseModel): + type: Literal["url_citation"] + """The type of the URL citation. Always `url_citation`.""" + + url_citation: AnnotationURLCitation + """A URL citation when using web search.""" class FunctionCall(BaseModel): @@ -33,6 +55,12 @@ class ChatCompletionMessage(BaseModel): role: Literal["assistant"] """The role of the author of this message.""" + annotations: Optional[List[Annotation]] = None + """ + Annotations for the message, when applicable, as when using the + [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat). + """ + audio: Optional[ChatCompletionAudio] = None """ If the audio output modality is requested, this object contains data about the diff --git a/src/openai/types/chat/chat_completion_reasoning_effort.py b/src/openai/types/chat/chat_completion_reasoning_effort.py index 85249c53b1..e4785c90bf 100644 --- a/src/openai/types/chat/chat_completion_reasoning_effort.py +++ b/src/openai/types/chat/chat_completion_reasoning_effort.py @@ -1,8 +1,8 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing import Optional -from typing_extensions import Literal, TypeAlias + +from ..shared.reasoning_effort import ReasoningEffort __all__ = ["ChatCompletionReasoningEffort"] -ChatCompletionReasoningEffort: TypeAlias = Optional[Literal["low", "medium", "high"]] +ChatCompletionReasoningEffort = ReasoningEffort diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 4dd2812aba..05103fba91 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -7,11 +7,10 @@ from ..shared.chat_model import ChatModel from ..shared_params.metadata import Metadata -from .chat_completion_modality import ChatCompletionModality +from ..shared.reasoning_effort import ReasoningEffort from .chat_completion_tool_param import ChatCompletionToolParam from .chat_completion_audio_param import ChatCompletionAudioParam from .chat_completion_message_param import ChatCompletionMessageParam -from .chat_completion_reasoning_effort import ChatCompletionReasoningEffort from ..shared_params.function_parameters import FunctionParameters from ..shared_params.response_format_text import ResponseFormatText from .chat_completion_stream_options_param import ChatCompletionStreamOptionsParam @@ -26,6 +25,9 @@ "FunctionCall", "Function", "ResponseFormat", + "WebSearchOptions", + "WebSearchOptionsUserLocation", + "WebSearchOptionsUserLocationApproximate", "CompletionCreateParamsNonStreaming", "CompletionCreateParamsStreaming", ] @@ -43,11 +45,12 @@ class CompletionCreateParamsBase(TypedDict, total=False): """ model: Required[Union[str, ChatModel]] - """ID of the model to use. + """Model ID used to generate the response, like `gpt-4o` or `o1`. - See the - [model endpoint compatibility](https://platform.openai.com/docs/models#model-endpoint-compatibility) - table for details on which models work with the Chat API. + OpenAI offers a wide range of models with different capabilities, performance + characteristics, and price points. Refer to the + [model guide](https://platform.openai.com/docs/models) to browse and compare + available models. """ audio: Optional[ChatCompletionAudioParam] @@ -133,10 +136,10 @@ class CompletionCreateParamsBase(TypedDict, total=False): a maximum length of 512 characters. """ - modalities: Optional[List[ChatCompletionModality]] + modalities: Optional[List[Literal["text", "audio"]]] """ - Output types that you would like the model to generate for this request. Most - models are capable of generating text, which is the default: + Output types that you would like the model to generate. Most models are capable + of generating text, which is the default: `["text"]` @@ -174,8 +177,8 @@ class CompletionCreateParamsBase(TypedDict, total=False): far, increasing the model's likelihood to talk about new topics. """ - reasoning_effort: Optional[ChatCompletionReasoningEffort] - """**o1 and o3-mini models only** + reasoning_effort: Optional[ReasoningEffort] + """**o-series models only** Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently @@ -191,16 +194,9 @@ class CompletionCreateParamsBase(TypedDict, total=False): in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). - Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the - message the model generates is valid JSON. - - **Important:** when using JSON mode, you **must** also instruct the model to - produce JSON yourself via a system or user message. Without this, the model may - generate an unending stream of whitespace until the generation reaches the token - limit, resulting in a long-running and seemingly "stuck" request. Also note that - the message content may be partially cut off if `finish_reason="length"`, which - indicates the generation exceeded `max_tokens` or the conversation exceeded the - max context length. + Setting to `{ "type": "json_object" }` enables the older JSON mode, which + ensures the message the model generates is valid JSON. Using `json_schema` is + preferred for models that support it. """ seed: Optional[int] @@ -221,14 +217,20 @@ class CompletionCreateParamsBase(TypedDict, total=False): utilize scale tier credits until they are exhausted. - If set to 'auto', and the Project is not Scale tier enabled, the request will be processed using the default service tier with a lower uptime SLA and no - latency guarantee. + latency guarentee. - If set to 'default', the request will be processed using the default service - tier with a lower uptime SLA and no latency guarantee. + tier with a lower uptime SLA and no latency guarentee. - When not set, the default behavior is 'auto'. + + When this parameter is set, the response body will include the `service_tier` + utilized. """ - stop: Union[Optional[str], List[str]] - """Up to 4 sequences where the API will stop generating further tokens.""" + stop: Union[Optional[str], List[str], None] + """Up to 4 sequences where the API will stop generating further tokens. + + The returned text will not contain the stop sequence. + """ store: Optional[bool] """ @@ -292,6 +294,13 @@ class CompletionCreateParamsBase(TypedDict, total=False): [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). """ + web_search_options: WebSearchOptions + """ + This tool searches the web for relevant results to use in a response. Learn more + about the + [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat). + """ + FunctionCall: TypeAlias = Union[Literal["none", "auto"], ChatCompletionFunctionCallOptionParam] @@ -322,30 +331,73 @@ class Function(TypedDict, total=False): """ -ResponseFormat: TypeAlias = Union[ResponseFormatText, ResponseFormatJSONObject, ResponseFormatJSONSchema] +ResponseFormat: TypeAlias = Union[ResponseFormatText, ResponseFormatJSONSchema, ResponseFormatJSONObject] + + +class WebSearchOptionsUserLocationApproximate(TypedDict, total=False): + city: str + """Free text input for the city of the user, e.g. `San Francisco`.""" + + country: str + """ + The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of + the user, e.g. `US`. + """ + + region: str + """Free text input for the region of the user, e.g. `California`.""" + + timezone: str + """ + The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the + user, e.g. `America/Los_Angeles`. + """ + + +class WebSearchOptionsUserLocation(TypedDict, total=False): + approximate: Required[WebSearchOptionsUserLocationApproximate] + """Approximate location parameters for the search.""" + + type: Required[Literal["approximate"]] + """The type of location approximation. Always `approximate`.""" + + +class WebSearchOptions(TypedDict, total=False): + search_context_size: Literal["low", "medium", "high"] + """ + High level guidance for the amount of context window space to use for the + search. One of `low`, `medium`, or `high`. `medium` is the default. + """ + + user_location: Optional[WebSearchOptionsUserLocation] + """Approximate location parameters for the search.""" class CompletionCreateParamsNonStreaming(CompletionCreateParamsBase, total=False): stream: Optional[Literal[False]] - """If set, partial message deltas will be sent, like in ChatGPT. - - Tokens will be sent as data-only - [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) - as they become available, with the stream terminated by a `data: [DONE]` - message. - [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + """ + If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming) + for more information, along with the + [streaming responses](https://platform.openai.com/docs/guides/streaming-responses) + guide for more information on how to handle the streaming events. """ class CompletionCreateParamsStreaming(CompletionCreateParamsBase): stream: Required[Literal[True]] - """If set, partial message deltas will be sent, like in ChatGPT. - - Tokens will be sent as data-only - [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) - as they become available, with the stream terminated by a `data: [DONE]` - message. - [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions). + """ + If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming) + for more information, along with the + [streaming responses](https://platform.openai.com/docs/guides/streaming-responses) + guide for more information on how to handle the streaming events. """ diff --git a/src/openai/types/chat/completion_list_params.py b/src/openai/types/chat/completion_list_params.py index a8fce900ce..d93da834a3 100644 --- a/src/openai/types/chat/completion_list_params.py +++ b/src/openai/types/chat/completion_list_params.py @@ -15,19 +15,19 @@ class CompletionListParams(TypedDict, total=False): """Identifier for the last chat completion from the previous pagination request.""" limit: int - """Number of chat completions to retrieve.""" + """Number of Chat Completions to retrieve.""" metadata: Optional[Metadata] - """A list of metadata keys to filter the chat completions by. Example: + """A list of metadata keys to filter the Chat Completions by. Example: `metadata[key1]=value1&metadata[key2]=value2` """ model: str - """The model used to generate the chat completions.""" + """The model used to generate the Chat Completions.""" order: Literal["asc", "desc"] - """Sort order for chat completions by timestamp. + """Sort order for Chat Completions by timestamp. Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`. """ diff --git a/src/openai/types/beta/file_chunking_strategy.py b/src/openai/types/file_chunking_strategy.py similarity index 93% rename from src/openai/types/beta/file_chunking_strategy.py rename to src/openai/types/file_chunking_strategy.py index 406d69dd0e..ee96bd7884 100644 --- a/src/openai/types/beta/file_chunking_strategy.py +++ b/src/openai/types/file_chunking_strategy.py @@ -3,7 +3,7 @@ from typing import Union from typing_extensions import Annotated, TypeAlias -from ..._utils import PropertyInfo +from .._utils import PropertyInfo from .other_file_chunking_strategy_object import OtherFileChunkingStrategyObject from .static_file_chunking_strategy_object import StaticFileChunkingStrategyObject diff --git a/src/openai/types/beta/file_chunking_strategy_param.py b/src/openai/types/file_chunking_strategy_param.py similarity index 100% rename from src/openai/types/beta/file_chunking_strategy_param.py rename to src/openai/types/file_chunking_strategy_param.py diff --git a/src/openai/types/file_create_params.py b/src/openai/types/file_create_params.py index ecf7503358..728dfd350f 100644 --- a/src/openai/types/file_create_params.py +++ b/src/openai/types/file_create_params.py @@ -17,10 +17,8 @@ class FileCreateParams(TypedDict, total=False): purpose: Required[FilePurpose] """The intended purpose of the uploaded file. - Use "assistants" for - [Assistants](https://platform.openai.com/docs/api-reference/assistants) and - [Message](https://platform.openai.com/docs/api-reference/messages) files, - "vision" for Assistants image file inputs, "batch" for - [Batch API](https://platform.openai.com/docs/guides/batch), and "fine-tune" for - [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning). + One of: - `assistants`: Used in the Assistants API - `batch`: Used in the Batch + API - `fine-tune`: Used for fine-tuning - `vision`: Images used for vision + fine-tuning - `user_data`: Flexible file type for any purpose - `evals`: Used + for eval data sets """ diff --git a/src/openai/types/file_purpose.py b/src/openai/types/file_purpose.py index 32dc352c62..b2c2d5f9fc 100644 --- a/src/openai/types/file_purpose.py +++ b/src/openai/types/file_purpose.py @@ -4,4 +4,4 @@ __all__ = ["FilePurpose"] -FilePurpose: TypeAlias = Literal["assistants", "batch", "fine-tune", "vision"] +FilePurpose: TypeAlias = Literal["assistants", "batch", "fine-tune", "vision", "user_data", "evals"] diff --git a/src/openai/types/beta/other_file_chunking_strategy_object.py b/src/openai/types/other_file_chunking_strategy_object.py similarity index 89% rename from src/openai/types/beta/other_file_chunking_strategy_object.py rename to src/openai/types/other_file_chunking_strategy_object.py index 89da560be4..e4cd61a8fc 100644 --- a/src/openai/types/beta/other_file_chunking_strategy_object.py +++ b/src/openai/types/other_file_chunking_strategy_object.py @@ -2,7 +2,7 @@ from typing_extensions import Literal -from ..._models import BaseModel +from .._models import BaseModel __all__ = ["OtherFileChunkingStrategyObject"] diff --git a/src/openai/types/responses/__init__.py b/src/openai/types/responses/__init__.py new file mode 100644 index 0000000000..970a167d2c --- /dev/null +++ b/src/openai/types/responses/__init__.py @@ -0,0 +1,138 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .tool import Tool as Tool +from .response import Response as Response +from .tool_param import ToolParam as ToolParam +from .computer_tool import ComputerTool as ComputerTool +from .function_tool import FunctionTool as FunctionTool +from .response_error import ResponseError as ResponseError +from .response_usage import ResponseUsage as ResponseUsage +from .parsed_response import ( + ParsedContent as ParsedContent, + ParsedResponse as ParsedResponse, + ParsedResponseOutputItem as ParsedResponseOutputItem, + ParsedResponseOutputText as ParsedResponseOutputText, + ParsedResponseOutputMessage as ParsedResponseOutputMessage, + ParsedResponseFunctionToolCall as ParsedResponseFunctionToolCall, +) +from .response_status import ResponseStatus as ResponseStatus +from .web_search_tool import WebSearchTool as WebSearchTool +from .file_search_tool import FileSearchTool as FileSearchTool +from .tool_choice_types import ToolChoiceTypes as ToolChoiceTypes +from .response_item_list import ResponseItemList as ResponseItemList +from .computer_tool_param import ComputerToolParam as ComputerToolParam +from .function_tool_param import FunctionToolParam as FunctionToolParam +from .response_includable import ResponseIncludable as ResponseIncludable +from .response_input_file import ResponseInputFile as ResponseInputFile +from .response_input_text import ResponseInputText as ResponseInputText +from .tool_choice_options import ToolChoiceOptions as ToolChoiceOptions +from .response_error_event import ResponseErrorEvent as ResponseErrorEvent +from .response_input_image import ResponseInputImage as ResponseInputImage +from .response_input_param import ResponseInputParam as ResponseInputParam +from .response_output_item import ResponseOutputItem as ResponseOutputItem +from .response_output_text import ResponseOutputText as ResponseOutputText +from .response_text_config import ResponseTextConfig as ResponseTextConfig +from .tool_choice_function import ToolChoiceFunction as ToolChoiceFunction +from .response_failed_event import ResponseFailedEvent as ResponseFailedEvent +from .response_stream_event import ResponseStreamEvent as ResponseStreamEvent +from .web_search_tool_param import WebSearchToolParam as WebSearchToolParam +from .file_search_tool_param import FileSearchToolParam as FileSearchToolParam +from .input_item_list_params import InputItemListParams as InputItemListParams +from .response_create_params import ResponseCreateParams as ResponseCreateParams +from .response_created_event import ResponseCreatedEvent as ResponseCreatedEvent +from .response_input_content import ResponseInputContent as ResponseInputContent +from .response_output_message import ResponseOutputMessage as ResponseOutputMessage +from .response_output_refusal import ResponseOutputRefusal as ResponseOutputRefusal +from .tool_choice_types_param import ToolChoiceTypesParam as ToolChoiceTypesParam +from .easy_input_message_param import EasyInputMessageParam as EasyInputMessageParam +from .response_completed_event import ResponseCompletedEvent as ResponseCompletedEvent +from .response_retrieve_params import ResponseRetrieveParams as ResponseRetrieveParams +from .response_text_done_event import ResponseTextDoneEvent as ResponseTextDoneEvent +from .response_audio_done_event import ResponseAudioDoneEvent as ResponseAudioDoneEvent +from .response_incomplete_event import ResponseIncompleteEvent as ResponseIncompleteEvent +from .response_input_file_param import ResponseInputFileParam as ResponseInputFileParam +from .response_input_item_param import ResponseInputItemParam as ResponseInputItemParam +from .response_input_text_param import ResponseInputTextParam as ResponseInputTextParam +from .response_text_delta_event import ResponseTextDeltaEvent as ResponseTextDeltaEvent +from .response_audio_delta_event import ResponseAudioDeltaEvent as ResponseAudioDeltaEvent +from .response_in_progress_event import ResponseInProgressEvent as ResponseInProgressEvent +from .response_input_image_param import ResponseInputImageParam as ResponseInputImageParam +from .response_output_text_param import ResponseOutputTextParam as ResponseOutputTextParam +from .response_text_config_param import ResponseTextConfigParam as ResponseTextConfigParam +from .tool_choice_function_param import ToolChoiceFunctionParam as ToolChoiceFunctionParam +from .response_computer_tool_call import ResponseComputerToolCall as ResponseComputerToolCall +from .response_format_text_config import ResponseFormatTextConfig as ResponseFormatTextConfig +from .response_function_tool_call import ResponseFunctionToolCall as ResponseFunctionToolCall +from .response_refusal_done_event import ResponseRefusalDoneEvent as ResponseRefusalDoneEvent +from .response_function_web_search import ResponseFunctionWebSearch as ResponseFunctionWebSearch +from .response_input_content_param import ResponseInputContentParam as ResponseInputContentParam +from .response_refusal_delta_event import ResponseRefusalDeltaEvent as ResponseRefusalDeltaEvent +from .response_output_message_param import ResponseOutputMessageParam as ResponseOutputMessageParam +from .response_output_refusal_param import ResponseOutputRefusalParam as ResponseOutputRefusalParam +from .response_file_search_tool_call import ResponseFileSearchToolCall as ResponseFileSearchToolCall +from .response_output_item_done_event import ResponseOutputItemDoneEvent as ResponseOutputItemDoneEvent +from .response_content_part_done_event import ResponseContentPartDoneEvent as ResponseContentPartDoneEvent +from .response_output_item_added_event import ResponseOutputItemAddedEvent as ResponseOutputItemAddedEvent +from .response_computer_tool_call_param import ResponseComputerToolCallParam as ResponseComputerToolCallParam +from .response_content_part_added_event import ResponseContentPartAddedEvent as ResponseContentPartAddedEvent +from .response_format_text_config_param import ResponseFormatTextConfigParam as ResponseFormatTextConfigParam +from .response_function_tool_call_param import ResponseFunctionToolCallParam as ResponseFunctionToolCallParam +from .response_function_web_search_param import ResponseFunctionWebSearchParam as ResponseFunctionWebSearchParam +from .response_code_interpreter_tool_call import ResponseCodeInterpreterToolCall as ResponseCodeInterpreterToolCall +from .response_input_message_content_list import ResponseInputMessageContentList as ResponseInputMessageContentList +from .response_audio_transcript_done_event import ResponseAudioTranscriptDoneEvent as ResponseAudioTranscriptDoneEvent +from .response_file_search_tool_call_param import ResponseFileSearchToolCallParam as ResponseFileSearchToolCallParam +from .response_text_annotation_delta_event import ResponseTextAnnotationDeltaEvent as ResponseTextAnnotationDeltaEvent +from .response_audio_transcript_delta_event import ( + ResponseAudioTranscriptDeltaEvent as ResponseAudioTranscriptDeltaEvent, +) +from .response_format_text_json_schema_config import ( + ResponseFormatTextJSONSchemaConfig as ResponseFormatTextJSONSchemaConfig, +) +from .response_web_search_call_completed_event import ( + ResponseWebSearchCallCompletedEvent as ResponseWebSearchCallCompletedEvent, +) +from .response_web_search_call_searching_event import ( + ResponseWebSearchCallSearchingEvent as ResponseWebSearchCallSearchingEvent, +) +from .response_file_search_call_completed_event import ( + ResponseFileSearchCallCompletedEvent as ResponseFileSearchCallCompletedEvent, +) +from .response_file_search_call_searching_event import ( + ResponseFileSearchCallSearchingEvent as ResponseFileSearchCallSearchingEvent, +) +from .response_input_message_content_list_param import ( + ResponseInputMessageContentListParam as ResponseInputMessageContentListParam, +) +from .response_web_search_call_in_progress_event import ( + ResponseWebSearchCallInProgressEvent as ResponseWebSearchCallInProgressEvent, +) +from .response_file_search_call_in_progress_event import ( + ResponseFileSearchCallInProgressEvent as ResponseFileSearchCallInProgressEvent, +) +from .response_function_call_arguments_done_event import ( + ResponseFunctionCallArgumentsDoneEvent as ResponseFunctionCallArgumentsDoneEvent, +) +from .response_function_call_arguments_delta_event import ( + ResponseFunctionCallArgumentsDeltaEvent as ResponseFunctionCallArgumentsDeltaEvent, +) +from .response_format_text_json_schema_config_param import ( + ResponseFormatTextJSONSchemaConfigParam as ResponseFormatTextJSONSchemaConfigParam, +) +from .response_code_interpreter_call_code_done_event import ( + ResponseCodeInterpreterCallCodeDoneEvent as ResponseCodeInterpreterCallCodeDoneEvent, +) +from .response_code_interpreter_call_completed_event import ( + ResponseCodeInterpreterCallCompletedEvent as ResponseCodeInterpreterCallCompletedEvent, +) +from .response_code_interpreter_call_code_delta_event import ( + ResponseCodeInterpreterCallCodeDeltaEvent as ResponseCodeInterpreterCallCodeDeltaEvent, +) +from .response_code_interpreter_call_in_progress_event import ( + ResponseCodeInterpreterCallInProgressEvent as ResponseCodeInterpreterCallInProgressEvent, +) +from .response_code_interpreter_call_interpreting_event import ( + ResponseCodeInterpreterCallInterpretingEvent as ResponseCodeInterpreterCallInterpretingEvent, +) diff --git a/src/openai/types/responses/computer_tool.py b/src/openai/types/responses/computer_tool.py new file mode 100644 index 0000000000..f0499cd950 --- /dev/null +++ b/src/openai/types/responses/computer_tool.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ComputerTool"] + + +class ComputerTool(BaseModel): + display_height: float + """The height of the computer display.""" + + display_width: float + """The width of the computer display.""" + + environment: Literal["mac", "windows", "ubuntu", "browser"] + """The type of computer environment to control.""" + + type: Literal["computer-preview"] + """The type of the computer use tool. Always `computer_use_preview`.""" diff --git a/src/openai/types/responses/computer_tool_param.py b/src/openai/types/responses/computer_tool_param.py new file mode 100644 index 0000000000..685b471378 --- /dev/null +++ b/src/openai/types/responses/computer_tool_param.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ComputerToolParam"] + + +class ComputerToolParam(TypedDict, total=False): + display_height: Required[float] + """The height of the computer display.""" + + display_width: Required[float] + """The width of the computer display.""" + + environment: Required[Literal["mac", "windows", "ubuntu", "browser"]] + """The type of computer environment to control.""" + + type: Required[Literal["computer-preview"]] + """The type of the computer use tool. Always `computer_use_preview`.""" diff --git a/src/openai/types/responses/easy_input_message_param.py b/src/openai/types/responses/easy_input_message_param.py new file mode 100644 index 0000000000..ef2f1c5f37 --- /dev/null +++ b/src/openai/types/responses/easy_input_message_param.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, Required, TypedDict + +from .response_input_message_content_list_param import ResponseInputMessageContentListParam + +__all__ = ["EasyInputMessageParam"] + + +class EasyInputMessageParam(TypedDict, total=False): + content: Required[Union[str, ResponseInputMessageContentListParam]] + """ + Text, image, or audio input to the model, used to generate a response. Can also + contain previous assistant responses. + """ + + role: Required[Literal["user", "assistant", "system", "developer"]] + """The role of the message input. + + One of `user`, `assistant`, `system`, or `developer`. + """ + + type: Literal["message"] + """The type of the message input. Always `message`.""" diff --git a/src/openai/types/responses/file_search_tool.py b/src/openai/types/responses/file_search_tool.py new file mode 100644 index 0000000000..683fc533fe --- /dev/null +++ b/src/openai/types/responses/file_search_tool.py @@ -0,0 +1,44 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from typing_extensions import Literal, TypeAlias + +from ..._models import BaseModel +from ..shared.compound_filter import CompoundFilter +from ..shared.comparison_filter import ComparisonFilter + +__all__ = ["FileSearchTool", "Filters", "RankingOptions"] + +Filters: TypeAlias = Union[ComparisonFilter, CompoundFilter] + + +class RankingOptions(BaseModel): + ranker: Optional[Literal["auto", "default-2024-11-15"]] = None + """The ranker to use for the file search.""" + + score_threshold: Optional[float] = None + """ + The score threshold for the file search, a number between 0 and 1. Numbers + closer to 1 will attempt to return only the most relevant results, but may + return fewer results. + """ + + +class FileSearchTool(BaseModel): + type: Literal["file_search"] + """The type of the file search tool. Always `file_search`.""" + + vector_store_ids: List[str] + """The IDs of the vector stores to search.""" + + filters: Optional[Filters] = None + """A filter to apply based on file attributes.""" + + max_num_results: Optional[int] = None + """The maximum number of results to return. + + This number should be between 1 and 50 inclusive. + """ + + ranking_options: Optional[RankingOptions] = None + """Ranking options for search.""" diff --git a/src/openai/types/responses/file_search_tool_param.py b/src/openai/types/responses/file_search_tool_param.py new file mode 100644 index 0000000000..2d6af8536b --- /dev/null +++ b/src/openai/types/responses/file_search_tool_param.py @@ -0,0 +1,45 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Union +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from ..shared_params.compound_filter import CompoundFilter +from ..shared_params.comparison_filter import ComparisonFilter + +__all__ = ["FileSearchToolParam", "Filters", "RankingOptions"] + +Filters: TypeAlias = Union[ComparisonFilter, CompoundFilter] + + +class RankingOptions(TypedDict, total=False): + ranker: Literal["auto", "default-2024-11-15"] + """The ranker to use for the file search.""" + + score_threshold: float + """ + The score threshold for the file search, a number between 0 and 1. Numbers + closer to 1 will attempt to return only the most relevant results, but may + return fewer results. + """ + + +class FileSearchToolParam(TypedDict, total=False): + type: Required[Literal["file_search"]] + """The type of the file search tool. Always `file_search`.""" + + vector_store_ids: Required[List[str]] + """The IDs of the vector stores to search.""" + + filters: Filters + """A filter to apply based on file attributes.""" + + max_num_results: int + """The maximum number of results to return. + + This number should be between 1 and 50 inclusive. + """ + + ranking_options: RankingOptions + """Ranking options for search.""" diff --git a/src/openai/types/responses/function_tool.py b/src/openai/types/responses/function_tool.py new file mode 100644 index 0000000000..236a2c7c63 --- /dev/null +++ b/src/openai/types/responses/function_tool.py @@ -0,0 +1,28 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["FunctionTool"] + + +class FunctionTool(BaseModel): + name: str + """The name of the function to call.""" + + parameters: Dict[str, object] + """A JSON schema object describing the parameters of the function.""" + + strict: bool + """Whether to enforce strict parameter validation. Default `true`.""" + + type: Literal["function"] + """The type of the function tool. Always `function`.""" + + description: Optional[str] = None + """A description of the function. + + Used by the model to determine whether or not to call the function. + """ diff --git a/src/openai/types/responses/function_tool_param.py b/src/openai/types/responses/function_tool_param.py new file mode 100644 index 0000000000..774a22e336 --- /dev/null +++ b/src/openai/types/responses/function_tool_param.py @@ -0,0 +1,28 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["FunctionToolParam"] + + +class FunctionToolParam(TypedDict, total=False): + name: Required[str] + """The name of the function to call.""" + + parameters: Required[Dict[str, object]] + """A JSON schema object describing the parameters of the function.""" + + strict: Required[bool] + """Whether to enforce strict parameter validation. Default `true`.""" + + type: Required[Literal["function"]] + """The type of the function tool. Always `function`.""" + + description: Optional[str] + """A description of the function. + + Used by the model to determine whether or not to call the function. + """ diff --git a/src/openai/types/responses/input_item_list_params.py b/src/openai/types/responses/input_item_list_params.py new file mode 100644 index 0000000000..e0b71f1ac5 --- /dev/null +++ b/src/openai/types/responses/input_item_list_params.py @@ -0,0 +1,28 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, TypedDict + +__all__ = ["InputItemListParams"] + + +class InputItemListParams(TypedDict, total=False): + after: str + """An item ID to list items after, used in pagination.""" + + before: str + """An item ID to list items before, used in pagination.""" + + limit: int + """A limit on the number of objects to be returned. + + Limit can range between 1 and 100, and the default is 20. + """ + + order: Literal["asc", "desc"] + """The order to return the input items in. Default is `asc`. + + - `asc`: Return the input items in ascending order. + - `desc`: Return the input items in descending order. + """ diff --git a/src/openai/types/responses/parsed_response.py b/src/openai/types/responses/parsed_response.py new file mode 100644 index 0000000000..3216a71ba9 --- /dev/null +++ b/src/openai/types/responses/parsed_response.py @@ -0,0 +1,77 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import TYPE_CHECKING, List, Union, Generic, TypeVar, Optional +from typing_extensions import Annotated, TypeAlias + +from ..._utils import PropertyInfo +from .response import Response +from ..._models import GenericModel +from ..._utils._transform import PropertyInfo +from .response_output_item import Reasoning +from .response_output_text import ResponseOutputText +from .response_output_message import ResponseOutputMessage +from .response_output_refusal import ResponseOutputRefusal +from .response_computer_tool_call import ResponseComputerToolCall +from .response_function_tool_call import ResponseFunctionToolCall +from .response_function_web_search import ResponseFunctionWebSearch +from .response_file_search_tool_call import ResponseFileSearchToolCall + +__all__ = ["ParsedResponse", "ParsedResponseOutputMessage", "ParsedResponseOutputText"] + +ContentType = TypeVar("ContentType") + +# we need to disable this check because we're overriding properties +# with subclasses of their types which is technically unsound as +# properties can be mutated. +# pyright: reportIncompatibleVariableOverride=false + + +class ParsedResponseOutputText(ResponseOutputText, GenericModel, Generic[ContentType]): + parsed: Optional[ContentType] = None + + +ParsedContent: TypeAlias = Annotated[ + Union[ParsedResponseOutputText[ContentType], ResponseOutputRefusal], + PropertyInfo(discriminator="type"), +] + + +class ParsedResponseOutputMessage(ResponseOutputMessage, GenericModel, Generic[ContentType]): + if TYPE_CHECKING: + content: List[ParsedContent[ContentType]] # type: ignore[assignment] + else: + content: List[ParsedContent] + + +class ParsedResponseFunctionToolCall(ResponseFunctionToolCall): + parsed_arguments: object = None + + +ParsedResponseOutputItem: TypeAlias = Annotated[ + Union[ + ParsedResponseOutputMessage[ContentType], + ParsedResponseFunctionToolCall, + ResponseFileSearchToolCall, + ResponseFunctionWebSearch, + ResponseComputerToolCall, + Reasoning, + ], + PropertyInfo(discriminator="type"), +] + + +class ParsedResponse(Response, GenericModel, Generic[ContentType]): + if TYPE_CHECKING: + output: List[ParsedResponseOutputItem[ContentType]] # type: ignore[assignment] + else: + output: List[ParsedResponseOutputItem] + + @property + def output_parsed(self) -> Optional[ContentType]: + for output in self.output: + if output.type == "message": + for content in output.content: + if content.type == "output_text" and content.parsed: + return content.parsed + + return None diff --git a/src/openai/types/responses/response.py b/src/openai/types/responses/response.py new file mode 100644 index 0000000000..66887ae9b5 --- /dev/null +++ b/src/openai/types/responses/response.py @@ -0,0 +1,204 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from typing_extensions import Literal, TypeAlias + +from .tool import Tool +from ..._models import BaseModel +from .response_error import ResponseError +from .response_usage import ResponseUsage +from .response_status import ResponseStatus +from ..shared.metadata import Metadata +from ..shared.reasoning import Reasoning +from .tool_choice_types import ToolChoiceTypes +from ..shared.chat_model import ChatModel +from .tool_choice_options import ToolChoiceOptions +from .response_output_item import ResponseOutputItem +from .response_text_config import ResponseTextConfig +from .tool_choice_function import ToolChoiceFunction + +__all__ = ["Response", "IncompleteDetails", "ToolChoice"] + + +class IncompleteDetails(BaseModel): + reason: Optional[Literal["max_output_tokens", "content_filter"]] = None + """The reason why the response is incomplete.""" + + +ToolChoice: TypeAlias = Union[ToolChoiceOptions, ToolChoiceTypes, ToolChoiceFunction] + + +class Response(BaseModel): + id: str + """Unique identifier for this Response.""" + + created_at: float + """Unix timestamp (in seconds) of when this Response was created.""" + + error: Optional[ResponseError] = None + """An error object returned when the model fails to generate a Response.""" + + incomplete_details: Optional[IncompleteDetails] = None + """Details about why the response is incomplete.""" + + instructions: Optional[str] = None + """ + Inserts a system (or developer) message as the first item in the model's + context. + + When using along with `previous_response_id`, the instructions from a previous + response will be not be carried over to the next response. This makes it simple + to swap out system (or developer) messages in new responses. + """ + + metadata: Optional[Metadata] = None + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + """ + + model: Union[str, ChatModel] + """Model ID used to generate the response, like `gpt-4o` or `o1`. + + OpenAI offers a wide range of models with different capabilities, performance + characteristics, and price points. Refer to the + [model guide](https://platform.openai.com/docs/models) to browse and compare + available models. + """ + + object: Literal["response"] + """The object type of this resource - always set to `response`.""" + + output: List[ResponseOutputItem] + """An array of content items generated by the model. + + - The length and order of items in the `output` array is dependent on the + model's response. + - Rather than accessing the first item in the `output` array and assuming it's + an `assistant` message with the content generated by the model, you might + consider using the `output_text` property where supported in SDKs. + """ + + parallel_tool_calls: bool + """Whether to allow the model to run tool calls in parallel.""" + + temperature: Optional[float] = None + """What sampling temperature to use, between 0 and 2. + + Higher values like 0.8 will make the output more random, while lower values like + 0.2 will make it more focused and deterministic. We generally recommend altering + this or `top_p` but not both. + """ + + tool_choice: ToolChoice + """ + How the model should select which tool (or tools) to use when generating a + response. See the `tools` parameter to see how to specify which tools the model + can call. + """ + + tools: List[Tool] + """An array of tools the model may call while generating a response. + + You can specify which tool to use by setting the `tool_choice` parameter. + + The two categories of tools you can provide the model are: + + - **Built-in tools**: Tools that are provided by OpenAI that extend the model's + capabilities, like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search). + Learn more about + [built-in tools](https://platform.openai.com/docs/guides/tools). + - **Function calls (custom tools)**: Functions that are defined by you, enabling + the model to call your own code. Learn more about + [function calling](https://platform.openai.com/docs/guides/function-calling). + """ + + top_p: Optional[float] = None + """ + An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + """ + + max_output_tokens: Optional[int] = None + """ + An upper bound for the number of tokens that can be generated for a response, + including visible output tokens and + [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). + """ + + previous_response_id: Optional[str] = None + """The unique ID of the previous response to the model. + + Use this to create multi-turn conversations. Learn more about + [conversation state](https://platform.openai.com/docs/guides/conversation-state). + """ + + reasoning: Optional[Reasoning] = None + """**o-series models only** + + Configuration options for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). + """ + + status: Optional[ResponseStatus] = None + """The status of the response generation. + + One of `completed`, `failed`, `in_progress`, or `incomplete`. + """ + + text: Optional[ResponseTextConfig] = None + """Configuration options for a text response from the model. + + Can be plain text or structured JSON data. Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + """ + + truncation: Optional[Literal["auto", "disabled"]] = None + """The truncation strategy to use for the model response. + + - `auto`: If the context of this response and previous ones exceeds the model's + context window size, the model will truncate the response to fit the context + window by dropping input items in the middle of the conversation. + - `disabled` (default): If a model response will exceed the context window size + for a model, the request will fail with a 400 error. + """ + + usage: Optional[ResponseUsage] = None + """ + Represents token usage details including input tokens, output tokens, a + breakdown of output tokens, and the total tokens used. + """ + + user: Optional[str] = None + """ + A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + """ + + @property + def output_text(self) -> str: + """Convenience property that aggregates all `output_text` items from the `output` + list. + + If no `output_text` content blocks exist, then an empty string is returned. + """ + texts: List[str] = [] + for output in self.output: + if output.type == "message": + for content in output.content: + if content.type == "output_text": + texts.append(content.text) + + return "".join(texts) diff --git a/src/openai/types/responses/response_audio_delta_event.py b/src/openai/types/responses/response_audio_delta_event.py new file mode 100644 index 0000000000..f3d77fac52 --- /dev/null +++ b/src/openai/types/responses/response_audio_delta_event.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseAudioDeltaEvent"] + + +class ResponseAudioDeltaEvent(BaseModel): + delta: str + """A chunk of Base64 encoded response audio bytes.""" + + type: Literal["response.audio.delta"] + """The type of the event. Always `response.audio.delta`.""" diff --git a/src/openai/types/responses/response_audio_done_event.py b/src/openai/types/responses/response_audio_done_event.py new file mode 100644 index 0000000000..5654f8e398 --- /dev/null +++ b/src/openai/types/responses/response_audio_done_event.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseAudioDoneEvent"] + + +class ResponseAudioDoneEvent(BaseModel): + type: Literal["response.audio.done"] + """The type of the event. Always `response.audio.done`.""" diff --git a/src/openai/types/responses/response_audio_transcript_delta_event.py b/src/openai/types/responses/response_audio_transcript_delta_event.py new file mode 100644 index 0000000000..69b6660f3f --- /dev/null +++ b/src/openai/types/responses/response_audio_transcript_delta_event.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseAudioTranscriptDeltaEvent"] + + +class ResponseAudioTranscriptDeltaEvent(BaseModel): + delta: str + """The partial transcript of the audio response.""" + + type: Literal["response.audio.transcript.delta"] + """The type of the event. Always `response.audio.transcript.delta`.""" diff --git a/src/openai/types/responses/response_audio_transcript_done_event.py b/src/openai/types/responses/response_audio_transcript_done_event.py new file mode 100644 index 0000000000..1a20319f83 --- /dev/null +++ b/src/openai/types/responses/response_audio_transcript_done_event.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseAudioTranscriptDoneEvent"] + + +class ResponseAudioTranscriptDoneEvent(BaseModel): + type: Literal["response.audio.transcript.done"] + """The type of the event. Always `response.audio.transcript.done`.""" diff --git a/src/openai/types/responses/response_code_interpreter_call_code_delta_event.py b/src/openai/types/responses/response_code_interpreter_call_code_delta_event.py new file mode 100644 index 0000000000..7527238d06 --- /dev/null +++ b/src/openai/types/responses/response_code_interpreter_call_code_delta_event.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseCodeInterpreterCallCodeDeltaEvent"] + + +class ResponseCodeInterpreterCallCodeDeltaEvent(BaseModel): + delta: str + """The partial code snippet added by the code interpreter.""" + + output_index: int + """The index of the output item that the code interpreter call is in progress.""" + + type: Literal["response.code_interpreter_call.code.delta"] + """The type of the event. Always `response.code_interpreter_call.code.delta`.""" diff --git a/src/openai/types/responses/response_code_interpreter_call_code_done_event.py b/src/openai/types/responses/response_code_interpreter_call_code_done_event.py new file mode 100644 index 0000000000..f84d4cf3e8 --- /dev/null +++ b/src/openai/types/responses/response_code_interpreter_call_code_done_event.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseCodeInterpreterCallCodeDoneEvent"] + + +class ResponseCodeInterpreterCallCodeDoneEvent(BaseModel): + code: str + """The final code snippet output by the code interpreter.""" + + output_index: int + """The index of the output item that the code interpreter call is in progress.""" + + type: Literal["response.code_interpreter_call.code.done"] + """The type of the event. Always `response.code_interpreter_call.code.done`.""" diff --git a/src/openai/types/responses/response_code_interpreter_call_completed_event.py b/src/openai/types/responses/response_code_interpreter_call_completed_event.py new file mode 100644 index 0000000000..b0cb73fb72 --- /dev/null +++ b/src/openai/types/responses/response_code_interpreter_call_completed_event.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel +from .response_code_interpreter_tool_call import ResponseCodeInterpreterToolCall + +__all__ = ["ResponseCodeInterpreterCallCompletedEvent"] + + +class ResponseCodeInterpreterCallCompletedEvent(BaseModel): + code_interpreter_call: ResponseCodeInterpreterToolCall + """A tool call to run code.""" + + output_index: int + """The index of the output item that the code interpreter call is in progress.""" + + type: Literal["response.code_interpreter_call.completed"] + """The type of the event. Always `response.code_interpreter_call.completed`.""" diff --git a/src/openai/types/responses/response_code_interpreter_call_in_progress_event.py b/src/openai/types/responses/response_code_interpreter_call_in_progress_event.py new file mode 100644 index 0000000000..64b739f308 --- /dev/null +++ b/src/openai/types/responses/response_code_interpreter_call_in_progress_event.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel +from .response_code_interpreter_tool_call import ResponseCodeInterpreterToolCall + +__all__ = ["ResponseCodeInterpreterCallInProgressEvent"] + + +class ResponseCodeInterpreterCallInProgressEvent(BaseModel): + code_interpreter_call: ResponseCodeInterpreterToolCall + """A tool call to run code.""" + + output_index: int + """The index of the output item that the code interpreter call is in progress.""" + + type: Literal["response.code_interpreter_call.in_progress"] + """The type of the event. Always `response.code_interpreter_call.in_progress`.""" diff --git a/src/openai/types/responses/response_code_interpreter_call_interpreting_event.py b/src/openai/types/responses/response_code_interpreter_call_interpreting_event.py new file mode 100644 index 0000000000..3100eac175 --- /dev/null +++ b/src/openai/types/responses/response_code_interpreter_call_interpreting_event.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel +from .response_code_interpreter_tool_call import ResponseCodeInterpreterToolCall + +__all__ = ["ResponseCodeInterpreterCallInterpretingEvent"] + + +class ResponseCodeInterpreterCallInterpretingEvent(BaseModel): + code_interpreter_call: ResponseCodeInterpreterToolCall + """A tool call to run code.""" + + output_index: int + """The index of the output item that the code interpreter call is in progress.""" + + type: Literal["response.code_interpreter_call.interpreting"] + """The type of the event. Always `response.code_interpreter_call.interpreting`.""" diff --git a/src/openai/types/responses/response_code_interpreter_tool_call.py b/src/openai/types/responses/response_code_interpreter_tool_call.py new file mode 100644 index 0000000000..d5a5057074 --- /dev/null +++ b/src/openai/types/responses/response_code_interpreter_tool_call.py @@ -0,0 +1,52 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union +from typing_extensions import Literal, Annotated, TypeAlias + +from ..._utils import PropertyInfo +from ..._models import BaseModel + +__all__ = ["ResponseCodeInterpreterToolCall", "Result", "ResultLogs", "ResultFiles", "ResultFilesFile"] + + +class ResultLogs(BaseModel): + logs: str + """The logs of the code interpreter tool call.""" + + type: Literal["logs"] + """The type of the code interpreter text output. Always `logs`.""" + + +class ResultFilesFile(BaseModel): + file_id: str + """The ID of the file.""" + + mime_type: str + """The MIME type of the file.""" + + +class ResultFiles(BaseModel): + files: List[ResultFilesFile] + + type: Literal["files"] + """The type of the code interpreter file output. Always `files`.""" + + +Result: TypeAlias = Annotated[Union[ResultLogs, ResultFiles], PropertyInfo(discriminator="type")] + + +class ResponseCodeInterpreterToolCall(BaseModel): + id: str + """The unique ID of the code interpreter tool call.""" + + code: str + """The code to run.""" + + results: List[Result] + """The results of the code interpreter tool call.""" + + status: Literal["in_progress", "interpreting", "completed"] + """The status of the code interpreter tool call.""" + + type: Literal["code_interpreter_call"] + """The type of the code interpreter tool call. Always `code_interpreter_call`.""" diff --git a/src/openai/types/responses/response_completed_event.py b/src/openai/types/responses/response_completed_event.py new file mode 100644 index 0000000000..a944f248ef --- /dev/null +++ b/src/openai/types/responses/response_completed_event.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from .response import Response +from ..._models import BaseModel + +__all__ = ["ResponseCompletedEvent"] + + +class ResponseCompletedEvent(BaseModel): + response: Response + """Properties of the completed response.""" + + type: Literal["response.completed"] + """The type of the event. Always `response.completed`.""" diff --git a/src/openai/types/responses/response_computer_tool_call.py b/src/openai/types/responses/response_computer_tool_call.py new file mode 100644 index 0000000000..994837567a --- /dev/null +++ b/src/openai/types/responses/response_computer_tool_call.py @@ -0,0 +1,212 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union +from typing_extensions import Literal, Annotated, TypeAlias + +from ..._utils import PropertyInfo +from ..._models import BaseModel + +__all__ = [ + "ResponseComputerToolCall", + "Action", + "ActionClick", + "ActionDoubleClick", + "ActionDrag", + "ActionDragPath", + "ActionKeypress", + "ActionMove", + "ActionScreenshot", + "ActionScroll", + "ActionType", + "ActionWait", + "PendingSafetyCheck", +] + + +class ActionClick(BaseModel): + button: Literal["left", "right", "wheel", "back", "forward"] + """Indicates which mouse button was pressed during the click. + + One of `left`, `right`, `wheel`, `back`, or `forward`. + """ + + type: Literal["click"] + """Specifies the event type. + + For a click action, this property is always set to `click`. + """ + + x: int + """The x-coordinate where the click occurred.""" + + y: int + """The y-coordinate where the click occurred.""" + + +class ActionDoubleClick(BaseModel): + type: Literal["double_click"] + """Specifies the event type. + + For a double click action, this property is always set to `double_click`. + """ + + x: int + """The x-coordinate where the double click occurred.""" + + y: int + """The y-coordinate where the double click occurred.""" + + +class ActionDragPath(BaseModel): + x: int + """The x-coordinate.""" + + y: int + """The y-coordinate.""" + + +class ActionDrag(BaseModel): + path: List[ActionDragPath] + """An array of coordinates representing the path of the drag action. + + Coordinates will appear as an array of objects, eg + + ``` + [ + { x: 100, y: 200 }, + { x: 200, y: 300 } + ] + ``` + """ + + type: Literal["drag"] + """Specifies the event type. + + For a drag action, this property is always set to `drag`. + """ + + +class ActionKeypress(BaseModel): + keys: List[str] + """The combination of keys the model is requesting to be pressed. + + This is an array of strings, each representing a key. + """ + + type: Literal["keypress"] + """Specifies the event type. + + For a keypress action, this property is always set to `keypress`. + """ + + +class ActionMove(BaseModel): + type: Literal["move"] + """Specifies the event type. + + For a move action, this property is always set to `move`. + """ + + x: int + """The x-coordinate to move to.""" + + y: int + """The y-coordinate to move to.""" + + +class ActionScreenshot(BaseModel): + type: Literal["screenshot"] + """Specifies the event type. + + For a screenshot action, this property is always set to `screenshot`. + """ + + +class ActionScroll(BaseModel): + scroll_x: int + """The horizontal scroll distance.""" + + scroll_y: int + """The vertical scroll distance.""" + + type: Literal["scroll"] + """Specifies the event type. + + For a scroll action, this property is always set to `scroll`. + """ + + x: int + """The x-coordinate where the scroll occurred.""" + + y: int + """The y-coordinate where the scroll occurred.""" + + +class ActionType(BaseModel): + text: str + """The text to type.""" + + type: Literal["type"] + """Specifies the event type. + + For a type action, this property is always set to `type`. + """ + + +class ActionWait(BaseModel): + type: Literal["wait"] + """Specifies the event type. + + For a wait action, this property is always set to `wait`. + """ + + +Action: TypeAlias = Annotated[ + Union[ + ActionClick, + ActionDoubleClick, + ActionDrag, + ActionKeypress, + ActionMove, + ActionScreenshot, + ActionScroll, + ActionType, + ActionWait, + ], + PropertyInfo(discriminator="type"), +] + + +class PendingSafetyCheck(BaseModel): + id: str + """The ID of the pending safety check.""" + + code: str + """The type of the pending safety check.""" + + message: str + """Details about the pending safety check.""" + + +class ResponseComputerToolCall(BaseModel): + id: str + """The unique ID of the computer call.""" + + action: Action + """A click action.""" + + call_id: str + """An identifier used when responding to the tool call with output.""" + + pending_safety_checks: List[PendingSafetyCheck] + """The pending safety checks for the computer call.""" + + status: Literal["in_progress", "completed", "incomplete"] + """The status of the item. + + One of `in_progress`, `completed`, or `incomplete`. Populated when items are + returned via API. + """ + + type: Literal["computer_call"] + """The type of the computer call. Always `computer_call`.""" diff --git a/src/openai/types/responses/response_computer_tool_call_param.py b/src/openai/types/responses/response_computer_tool_call_param.py new file mode 100644 index 0000000000..d4ef56ab5c --- /dev/null +++ b/src/openai/types/responses/response_computer_tool_call_param.py @@ -0,0 +1,208 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Union, Iterable +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +__all__ = [ + "ResponseComputerToolCallParam", + "Action", + "ActionClick", + "ActionDoubleClick", + "ActionDrag", + "ActionDragPath", + "ActionKeypress", + "ActionMove", + "ActionScreenshot", + "ActionScroll", + "ActionType", + "ActionWait", + "PendingSafetyCheck", +] + + +class ActionClick(TypedDict, total=False): + button: Required[Literal["left", "right", "wheel", "back", "forward"]] + """Indicates which mouse button was pressed during the click. + + One of `left`, `right`, `wheel`, `back`, or `forward`. + """ + + type: Required[Literal["click"]] + """Specifies the event type. + + For a click action, this property is always set to `click`. + """ + + x: Required[int] + """The x-coordinate where the click occurred.""" + + y: Required[int] + """The y-coordinate where the click occurred.""" + + +class ActionDoubleClick(TypedDict, total=False): + type: Required[Literal["double_click"]] + """Specifies the event type. + + For a double click action, this property is always set to `double_click`. + """ + + x: Required[int] + """The x-coordinate where the double click occurred.""" + + y: Required[int] + """The y-coordinate where the double click occurred.""" + + +class ActionDragPath(TypedDict, total=False): + x: Required[int] + """The x-coordinate.""" + + y: Required[int] + """The y-coordinate.""" + + +class ActionDrag(TypedDict, total=False): + path: Required[Iterable[ActionDragPath]] + """An array of coordinates representing the path of the drag action. + + Coordinates will appear as an array of objects, eg + + ``` + [ + { x: 100, y: 200 }, + { x: 200, y: 300 } + ] + ``` + """ + + type: Required[Literal["drag"]] + """Specifies the event type. + + For a drag action, this property is always set to `drag`. + """ + + +class ActionKeypress(TypedDict, total=False): + keys: Required[List[str]] + """The combination of keys the model is requesting to be pressed. + + This is an array of strings, each representing a key. + """ + + type: Required[Literal["keypress"]] + """Specifies the event type. + + For a keypress action, this property is always set to `keypress`. + """ + + +class ActionMove(TypedDict, total=False): + type: Required[Literal["move"]] + """Specifies the event type. + + For a move action, this property is always set to `move`. + """ + + x: Required[int] + """The x-coordinate to move to.""" + + y: Required[int] + """The y-coordinate to move to.""" + + +class ActionScreenshot(TypedDict, total=False): + type: Required[Literal["screenshot"]] + """Specifies the event type. + + For a screenshot action, this property is always set to `screenshot`. + """ + + +class ActionScroll(TypedDict, total=False): + scroll_x: Required[int] + """The horizontal scroll distance.""" + + scroll_y: Required[int] + """The vertical scroll distance.""" + + type: Required[Literal["scroll"]] + """Specifies the event type. + + For a scroll action, this property is always set to `scroll`. + """ + + x: Required[int] + """The x-coordinate where the scroll occurred.""" + + y: Required[int] + """The y-coordinate where the scroll occurred.""" + + +class ActionType(TypedDict, total=False): + text: Required[str] + """The text to type.""" + + type: Required[Literal["type"]] + """Specifies the event type. + + For a type action, this property is always set to `type`. + """ + + +class ActionWait(TypedDict, total=False): + type: Required[Literal["wait"]] + """Specifies the event type. + + For a wait action, this property is always set to `wait`. + """ + + +Action: TypeAlias = Union[ + ActionClick, + ActionDoubleClick, + ActionDrag, + ActionKeypress, + ActionMove, + ActionScreenshot, + ActionScroll, + ActionType, + ActionWait, +] + + +class PendingSafetyCheck(TypedDict, total=False): + id: Required[str] + """The ID of the pending safety check.""" + + code: Required[str] + """The type of the pending safety check.""" + + message: Required[str] + """Details about the pending safety check.""" + + +class ResponseComputerToolCallParam(TypedDict, total=False): + id: Required[str] + """The unique ID of the computer call.""" + + action: Required[Action] + """A click action.""" + + call_id: Required[str] + """An identifier used when responding to the tool call with output.""" + + pending_safety_checks: Required[Iterable[PendingSafetyCheck]] + """The pending safety checks for the computer call.""" + + status: Required[Literal["in_progress", "completed", "incomplete"]] + """The status of the item. + + One of `in_progress`, `completed`, or `incomplete`. Populated when items are + returned via API. + """ + + type: Required[Literal["computer_call"]] + """The type of the computer call. Always `computer_call`.""" diff --git a/src/openai/types/responses/response_content_part_added_event.py b/src/openai/types/responses/response_content_part_added_event.py new file mode 100644 index 0000000000..93f5ec4b0c --- /dev/null +++ b/src/openai/types/responses/response_content_part_added_event.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Literal, Annotated, TypeAlias + +from ..._utils import PropertyInfo +from ..._models import BaseModel +from .response_output_text import ResponseOutputText +from .response_output_refusal import ResponseOutputRefusal + +__all__ = ["ResponseContentPartAddedEvent", "Part"] + +Part: TypeAlias = Annotated[Union[ResponseOutputText, ResponseOutputRefusal], PropertyInfo(discriminator="type")] + + +class ResponseContentPartAddedEvent(BaseModel): + content_index: int + """The index of the content part that was added.""" + + item_id: str + """The ID of the output item that the content part was added to.""" + + output_index: int + """The index of the output item that the content part was added to.""" + + part: Part + """The content part that was added.""" + + type: Literal["response.content_part.added"] + """The type of the event. Always `response.content_part.added`.""" diff --git a/src/openai/types/responses/response_content_part_done_event.py b/src/openai/types/responses/response_content_part_done_event.py new file mode 100644 index 0000000000..4ec0739877 --- /dev/null +++ b/src/openai/types/responses/response_content_part_done_event.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Literal, Annotated, TypeAlias + +from ..._utils import PropertyInfo +from ..._models import BaseModel +from .response_output_text import ResponseOutputText +from .response_output_refusal import ResponseOutputRefusal + +__all__ = ["ResponseContentPartDoneEvent", "Part"] + +Part: TypeAlias = Annotated[Union[ResponseOutputText, ResponseOutputRefusal], PropertyInfo(discriminator="type")] + + +class ResponseContentPartDoneEvent(BaseModel): + content_index: int + """The index of the content part that is done.""" + + item_id: str + """The ID of the output item that the content part was added to.""" + + output_index: int + """The index of the output item that the content part was added to.""" + + part: Part + """The content part that is done.""" + + type: Literal["response.content_part.done"] + """The type of the event. Always `response.content_part.done`.""" diff --git a/src/openai/types/responses/response_create_params.py b/src/openai/types/responses/response_create_params.py new file mode 100644 index 0000000000..d5b2fdeb1a --- /dev/null +++ b/src/openai/types/responses/response_create_params.py @@ -0,0 +1,204 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Union, Iterable, Optional +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .tool_param import ToolParam +from ..shared.chat_model import ChatModel +from .response_includable import ResponseIncludable +from .tool_choice_options import ToolChoiceOptions +from .response_input_param import ResponseInputParam +from ..shared_params.metadata import Metadata +from .tool_choice_types_param import ToolChoiceTypesParam +from ..shared_params.reasoning import Reasoning +from .response_text_config_param import ResponseTextConfigParam +from .tool_choice_function_param import ToolChoiceFunctionParam + +__all__ = [ + "ResponseCreateParamsBase", + "ToolChoice", + "ResponseCreateParamsNonStreaming", + "ResponseCreateParamsStreaming", +] + + +class ResponseCreateParamsBase(TypedDict, total=False): + input: Required[Union[str, ResponseInputParam]] + """Text, image, or file inputs to the model, used to generate a response. + + Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Image inputs](https://platform.openai.com/docs/guides/images) + - [File inputs](https://platform.openai.com/docs/guides/pdf-files) + - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) + - [Function calling](https://platform.openai.com/docs/guides/function-calling) + """ + + model: Required[Union[str, ChatModel]] + """Model ID used to generate the response, like `gpt-4o` or `o1`. + + OpenAI offers a wide range of models with different capabilities, performance + characteristics, and price points. Refer to the + [model guide](https://platform.openai.com/docs/models) to browse and compare + available models. + """ + + include: Optional[List[ResponseIncludable]] + """Specify additional output data to include in the model response. + + Currently supported values are: + + - `file_search_call.results`: Include the search results of the file search tool + call. + - `message.input_image.image_url`: Include image urls from the input message. + - `computer_call_output.output.image_url`: Include image urls from the computer + call output. + """ + + instructions: Optional[str] + """ + Inserts a system (or developer) message as the first item in the model's + context. + + When using along with `previous_response_id`, the instructions from a previous + response will be not be carried over to the next response. This makes it simple + to swap out system (or developer) messages in new responses. + """ + + max_output_tokens: Optional[int] + """ + An upper bound for the number of tokens that can be generated for a response, + including visible output tokens and + [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). + """ + + metadata: Optional[Metadata] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + """ + + parallel_tool_calls: Optional[bool] + """Whether to allow the model to run tool calls in parallel.""" + + previous_response_id: Optional[str] + """The unique ID of the previous response to the model. + + Use this to create multi-turn conversations. Learn more about + [conversation state](https://platform.openai.com/docs/guides/conversation-state). + """ + + reasoning: Optional[Reasoning] + """**o-series models only** + + Configuration options for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). + """ + + store: Optional[bool] + """Whether to store the generated model response for later retrieval via API.""" + + temperature: Optional[float] + """What sampling temperature to use, between 0 and 2. + + Higher values like 0.8 will make the output more random, while lower values like + 0.2 will make it more focused and deterministic. We generally recommend altering + this or `top_p` but not both. + """ + + text: ResponseTextConfigParam + """Configuration options for a text response from the model. + + Can be plain text or structured JSON data. Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + """ + + tool_choice: ToolChoice + """ + How the model should select which tool (or tools) to use when generating a + response. See the `tools` parameter to see how to specify which tools the model + can call. + """ + + tools: Iterable[ToolParam] + """An array of tools the model may call while generating a response. + + You can specify which tool to use by setting the `tool_choice` parameter. + + The two categories of tools you can provide the model are: + + - **Built-in tools**: Tools that are provided by OpenAI that extend the model's + capabilities, like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search). + Learn more about + [built-in tools](https://platform.openai.com/docs/guides/tools). + - **Function calls (custom tools)**: Functions that are defined by you, enabling + the model to call your own code. Learn more about + [function calling](https://platform.openai.com/docs/guides/function-calling). + """ + + top_p: Optional[float] + """ + An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + """ + + truncation: Optional[Literal["auto", "disabled"]] + """The truncation strategy to use for the model response. + + - `auto`: If the context of this response and previous ones exceeds the model's + context window size, the model will truncate the response to fit the context + window by dropping input items in the middle of the conversation. + - `disabled` (default): If a model response will exceed the context window size + for a model, the request will fail with a 400 error. + """ + + user: str + """ + A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + """ + + +ToolChoice: TypeAlias = Union[ToolChoiceOptions, ToolChoiceTypesParam, ToolChoiceFunctionParam] + + +class ResponseCreateParamsNonStreaming(ResponseCreateParamsBase, total=False): + stream: Optional[Literal[False]] + """ + If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) + for more information. + """ + + +class ResponseCreateParamsStreaming(ResponseCreateParamsBase): + stream: Required[Literal[True]] + """ + If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) + for more information. + """ + + +ResponseCreateParams = Union[ResponseCreateParamsNonStreaming, ResponseCreateParamsStreaming] diff --git a/src/openai/types/responses/response_created_event.py b/src/openai/types/responses/response_created_event.py new file mode 100644 index 0000000000..7a524cec87 --- /dev/null +++ b/src/openai/types/responses/response_created_event.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from .response import Response +from ..._models import BaseModel + +__all__ = ["ResponseCreatedEvent"] + + +class ResponseCreatedEvent(BaseModel): + response: Response + """The response that was created.""" + + type: Literal["response.created"] + """The type of the event. Always `response.created`.""" diff --git a/src/openai/types/responses/response_error.py b/src/openai/types/responses/response_error.py new file mode 100644 index 0000000000..90f1fcf5da --- /dev/null +++ b/src/openai/types/responses/response_error.py @@ -0,0 +1,34 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseError"] + + +class ResponseError(BaseModel): + code: Literal[ + "server_error", + "rate_limit_exceeded", + "invalid_prompt", + "vector_store_timeout", + "invalid_image", + "invalid_image_format", + "invalid_base64_image", + "invalid_image_url", + "image_too_large", + "image_too_small", + "image_parse_error", + "image_content_policy_violation", + "invalid_image_mode", + "image_file_too_large", + "unsupported_image_media_type", + "empty_image_file", + "failed_to_download_image", + "image_file_not_found", + ] + """The error code for the response.""" + + message: str + """A human-readable description of the error.""" diff --git a/src/openai/types/responses/response_error_event.py b/src/openai/types/responses/response_error_event.py new file mode 100644 index 0000000000..1b7e605d02 --- /dev/null +++ b/src/openai/types/responses/response_error_event.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseErrorEvent"] + + +class ResponseErrorEvent(BaseModel): + code: Optional[str] = None + """The error code.""" + + message: str + """The error message.""" + + param: Optional[str] = None + """The error parameter.""" + + type: Literal["error"] + """The type of the event. Always `error`.""" diff --git a/src/openai/types/responses/response_failed_event.py b/src/openai/types/responses/response_failed_event.py new file mode 100644 index 0000000000..3e8f75d8c4 --- /dev/null +++ b/src/openai/types/responses/response_failed_event.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from .response import Response +from ..._models import BaseModel + +__all__ = ["ResponseFailedEvent"] + + +class ResponseFailedEvent(BaseModel): + response: Response + """The response that failed.""" + + type: Literal["response.failed"] + """The type of the event. Always `response.failed`.""" diff --git a/src/openai/types/responses/response_file_search_call_completed_event.py b/src/openai/types/responses/response_file_search_call_completed_event.py new file mode 100644 index 0000000000..4b86083369 --- /dev/null +++ b/src/openai/types/responses/response_file_search_call_completed_event.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseFileSearchCallCompletedEvent"] + + +class ResponseFileSearchCallCompletedEvent(BaseModel): + item_id: str + """The ID of the output item that the file search call is initiated.""" + + output_index: int + """The index of the output item that the file search call is initiated.""" + + type: Literal["response.file_search_call.completed"] + """The type of the event. Always `response.file_search_call.completed`.""" diff --git a/src/openai/types/responses/response_file_search_call_in_progress_event.py b/src/openai/types/responses/response_file_search_call_in_progress_event.py new file mode 100644 index 0000000000..eb42e3dad6 --- /dev/null +++ b/src/openai/types/responses/response_file_search_call_in_progress_event.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseFileSearchCallInProgressEvent"] + + +class ResponseFileSearchCallInProgressEvent(BaseModel): + item_id: str + """The ID of the output item that the file search call is initiated.""" + + output_index: int + """The index of the output item that the file search call is initiated.""" + + type: Literal["response.file_search_call.in_progress"] + """The type of the event. Always `response.file_search_call.in_progress`.""" diff --git a/src/openai/types/responses/response_file_search_call_searching_event.py b/src/openai/types/responses/response_file_search_call_searching_event.py new file mode 100644 index 0000000000..3cd8905de6 --- /dev/null +++ b/src/openai/types/responses/response_file_search_call_searching_event.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseFileSearchCallSearchingEvent"] + + +class ResponseFileSearchCallSearchingEvent(BaseModel): + item_id: str + """The ID of the output item that the file search call is initiated.""" + + output_index: int + """The index of the output item that the file search call is searching.""" + + type: Literal["response.file_search_call.searching"] + """The type of the event. Always `response.file_search_call.searching`.""" diff --git a/src/openai/types/responses/response_file_search_tool_call.py b/src/openai/types/responses/response_file_search_tool_call.py new file mode 100644 index 0000000000..ef1c6a5608 --- /dev/null +++ b/src/openai/types/responses/response_file_search_tool_call.py @@ -0,0 +1,51 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, List, Union, Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseFileSearchToolCall", "Result"] + + +class Result(BaseModel): + attributes: Optional[Dict[str, Union[str, float, bool]]] = None + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. Keys are + strings with a maximum length of 64 characters. Values are strings with a + maximum length of 512 characters, booleans, or numbers. + """ + + file_id: Optional[str] = None + """The unique ID of the file.""" + + filename: Optional[str] = None + """The name of the file.""" + + score: Optional[float] = None + """The relevance score of the file - a value between 0 and 1.""" + + text: Optional[str] = None + """The text that was retrieved from the file.""" + + +class ResponseFileSearchToolCall(BaseModel): + id: str + """The unique ID of the file search tool call.""" + + queries: List[str] + """The queries used to search for files.""" + + status: Literal["in_progress", "searching", "completed", "incomplete", "failed"] + """The status of the file search tool call. + + One of `in_progress`, `searching`, `incomplete` or `failed`, + """ + + type: Literal["file_search_call"] + """The type of the file search tool call. Always `file_search_call`.""" + + results: Optional[List[Result]] = None + """The results of the file search tool call.""" diff --git a/src/openai/types/responses/response_file_search_tool_call_param.py b/src/openai/types/responses/response_file_search_tool_call_param.py new file mode 100644 index 0000000000..9a4177cf81 --- /dev/null +++ b/src/openai/types/responses/response_file_search_tool_call_param.py @@ -0,0 +1,51 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List, Union, Iterable, Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ResponseFileSearchToolCallParam", "Result"] + + +class Result(TypedDict, total=False): + attributes: Optional[Dict[str, Union[str, float, bool]]] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. Keys are + strings with a maximum length of 64 characters. Values are strings with a + maximum length of 512 characters, booleans, or numbers. + """ + + file_id: str + """The unique ID of the file.""" + + filename: str + """The name of the file.""" + + score: float + """The relevance score of the file - a value between 0 and 1.""" + + text: str + """The text that was retrieved from the file.""" + + +class ResponseFileSearchToolCallParam(TypedDict, total=False): + id: Required[str] + """The unique ID of the file search tool call.""" + + queries: Required[List[str]] + """The queries used to search for files.""" + + status: Required[Literal["in_progress", "searching", "completed", "incomplete", "failed"]] + """The status of the file search tool call. + + One of `in_progress`, `searching`, `incomplete` or `failed`, + """ + + type: Required[Literal["file_search_call"]] + """The type of the file search tool call. Always `file_search_call`.""" + + results: Optional[Iterable[Result]] + """The results of the file search tool call.""" diff --git a/src/openai/types/responses/response_format_text_config.py b/src/openai/types/responses/response_format_text_config.py new file mode 100644 index 0000000000..a4896bf9fe --- /dev/null +++ b/src/openai/types/responses/response_format_text_config.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Annotated, TypeAlias + +from ..._utils import PropertyInfo +from ..shared.response_format_text import ResponseFormatText +from ..shared.response_format_json_object import ResponseFormatJSONObject +from .response_format_text_json_schema_config import ResponseFormatTextJSONSchemaConfig + +__all__ = ["ResponseFormatTextConfig"] + +ResponseFormatTextConfig: TypeAlias = Annotated[ + Union[ResponseFormatText, ResponseFormatTextJSONSchemaConfig, ResponseFormatJSONObject], + PropertyInfo(discriminator="type"), +] diff --git a/src/openai/types/responses/response_format_text_config_param.py b/src/openai/types/responses/response_format_text_config_param.py new file mode 100644 index 0000000000..fcaf8f3fb6 --- /dev/null +++ b/src/openai/types/responses/response_format_text_config_param.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import TypeAlias + +from ..shared_params.response_format_text import ResponseFormatText +from ..shared_params.response_format_json_object import ResponseFormatJSONObject +from .response_format_text_json_schema_config_param import ResponseFormatTextJSONSchemaConfigParam + +__all__ = ["ResponseFormatTextConfigParam"] + +ResponseFormatTextConfigParam: TypeAlias = Union[ + ResponseFormatText, ResponseFormatTextJSONSchemaConfigParam, ResponseFormatJSONObject +] diff --git a/src/openai/types/responses/response_format_text_json_schema_config.py b/src/openai/types/responses/response_format_text_json_schema_config.py new file mode 100644 index 0000000000..3cf066370f --- /dev/null +++ b/src/openai/types/responses/response_format_text_json_schema_config.py @@ -0,0 +1,43 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional +from typing_extensions import Literal + +from pydantic import Field as FieldInfo + +from ..._models import BaseModel + +__all__ = ["ResponseFormatTextJSONSchemaConfig"] + + +class ResponseFormatTextJSONSchemaConfig(BaseModel): + schema_: Dict[str, object] = FieldInfo(alias="schema") + """ + The schema for the response format, described as a JSON Schema object. Learn how + to build JSON schemas [here](https://json-schema.org/). + """ + + type: Literal["json_schema"] + """The type of response format being defined. Always `json_schema`.""" + + description: Optional[str] = None + """ + A description of what the response format is for, used by the model to determine + how to respond in the format. + """ + + name: Optional[str] = None + """The name of the response format. + + Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length + of 64. + """ + + strict: Optional[bool] = None + """ + Whether to enable strict schema adherence when generating the output. If set to + true, the model will always follow the exact schema defined in the `schema` + field. Only a subset of JSON Schema is supported when `strict` is `true`. To + learn more, read the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + """ diff --git a/src/openai/types/responses/response_format_text_json_schema_config_param.py b/src/openai/types/responses/response_format_text_json_schema_config_param.py new file mode 100644 index 0000000000..211c5d1eff --- /dev/null +++ b/src/openai/types/responses/response_format_text_json_schema_config_param.py @@ -0,0 +1,41 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ResponseFormatTextJSONSchemaConfigParam"] + + +class ResponseFormatTextJSONSchemaConfigParam(TypedDict, total=False): + schema: Required[Dict[str, object]] + """ + The schema for the response format, described as a JSON Schema object. Learn how + to build JSON schemas [here](https://json-schema.org/). + """ + + type: Required[Literal["json_schema"]] + """The type of response format being defined. Always `json_schema`.""" + + description: str + """ + A description of what the response format is for, used by the model to determine + how to respond in the format. + """ + + name: str + """The name of the response format. + + Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length + of 64. + """ + + strict: Optional[bool] + """ + Whether to enable strict schema adherence when generating the output. If set to + true, the model will always follow the exact schema defined in the `schema` + field. Only a subset of JSON Schema is supported when `strict` is `true`. To + learn more, read the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + """ diff --git a/src/openai/types/responses/response_function_call_arguments_delta_event.py b/src/openai/types/responses/response_function_call_arguments_delta_event.py new file mode 100644 index 0000000000..0989b7caeb --- /dev/null +++ b/src/openai/types/responses/response_function_call_arguments_delta_event.py @@ -0,0 +1,23 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseFunctionCallArgumentsDeltaEvent"] + + +class ResponseFunctionCallArgumentsDeltaEvent(BaseModel): + delta: str + """The function-call arguments delta that is added.""" + + item_id: str + """The ID of the output item that the function-call arguments delta is added to.""" + + output_index: int + """ + The index of the output item that the function-call arguments delta is added to. + """ + + type: Literal["response.function_call_arguments.delta"] + """The type of the event. Always `response.function_call_arguments.delta`.""" diff --git a/src/openai/types/responses/response_function_call_arguments_done_event.py b/src/openai/types/responses/response_function_call_arguments_done_event.py new file mode 100644 index 0000000000..1d805a57c6 --- /dev/null +++ b/src/openai/types/responses/response_function_call_arguments_done_event.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseFunctionCallArgumentsDoneEvent"] + + +class ResponseFunctionCallArgumentsDoneEvent(BaseModel): + arguments: str + """The function-call arguments.""" + + item_id: str + """The ID of the item.""" + + output_index: int + """The index of the output item.""" + + type: Literal["response.function_call_arguments.done"] diff --git a/src/openai/types/responses/response_function_tool_call.py b/src/openai/types/responses/response_function_tool_call.py new file mode 100644 index 0000000000..5d82906cb7 --- /dev/null +++ b/src/openai/types/responses/response_function_tool_call.py @@ -0,0 +1,32 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseFunctionToolCall"] + + +class ResponseFunctionToolCall(BaseModel): + id: str + """The unique ID of the function tool call.""" + + arguments: str + """A JSON string of the arguments to pass to the function.""" + + call_id: str + """The unique ID of the function tool call generated by the model.""" + + name: str + """The name of the function to run.""" + + type: Literal["function_call"] + """The type of the function tool call. Always `function_call`.""" + + status: Optional[Literal["in_progress", "completed", "incomplete"]] = None + """The status of the item. + + One of `in_progress`, `completed`, or `incomplete`. Populated when items are + returned via API. + """ diff --git a/src/openai/types/responses/response_function_tool_call_param.py b/src/openai/types/responses/response_function_tool_call_param.py new file mode 100644 index 0000000000..51b947a764 --- /dev/null +++ b/src/openai/types/responses/response_function_tool_call_param.py @@ -0,0 +1,31 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ResponseFunctionToolCallParam"] + + +class ResponseFunctionToolCallParam(TypedDict, total=False): + id: Required[str] + """The unique ID of the function tool call.""" + + arguments: Required[str] + """A JSON string of the arguments to pass to the function.""" + + call_id: Required[str] + """The unique ID of the function tool call generated by the model.""" + + name: Required[str] + """The name of the function to run.""" + + type: Required[Literal["function_call"]] + """The type of the function tool call. Always `function_call`.""" + + status: Literal["in_progress", "completed", "incomplete"] + """The status of the item. + + One of `in_progress`, `completed`, or `incomplete`. Populated when items are + returned via API. + """ diff --git a/src/openai/types/responses/response_function_web_search.py b/src/openai/types/responses/response_function_web_search.py new file mode 100644 index 0000000000..44734b681f --- /dev/null +++ b/src/openai/types/responses/response_function_web_search.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseFunctionWebSearch"] + + +class ResponseFunctionWebSearch(BaseModel): + id: str + """The unique ID of the web search tool call.""" + + status: Literal["in_progress", "searching", "completed", "failed"] + """The status of the web search tool call.""" + + type: Literal["web_search_call"] + """The type of the web search tool call. Always `web_search_call`.""" diff --git a/src/openai/types/responses/response_function_web_search_param.py b/src/openai/types/responses/response_function_web_search_param.py new file mode 100644 index 0000000000..d413e60b12 --- /dev/null +++ b/src/openai/types/responses/response_function_web_search_param.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ResponseFunctionWebSearchParam"] + + +class ResponseFunctionWebSearchParam(TypedDict, total=False): + id: Required[str] + """The unique ID of the web search tool call.""" + + status: Required[Literal["in_progress", "searching", "completed", "failed"]] + """The status of the web search tool call.""" + + type: Required[Literal["web_search_call"]] + """The type of the web search tool call. Always `web_search_call`.""" diff --git a/src/openai/types/responses/response_in_progress_event.py b/src/openai/types/responses/response_in_progress_event.py new file mode 100644 index 0000000000..7d96cbb8ad --- /dev/null +++ b/src/openai/types/responses/response_in_progress_event.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from .response import Response +from ..._models import BaseModel + +__all__ = ["ResponseInProgressEvent"] + + +class ResponseInProgressEvent(BaseModel): + response: Response + """The response that is in progress.""" + + type: Literal["response.in_progress"] + """The type of the event. Always `response.in_progress`.""" diff --git a/src/openai/types/responses/response_includable.py b/src/openai/types/responses/response_includable.py new file mode 100644 index 0000000000..83489fa7f1 --- /dev/null +++ b/src/openai/types/responses/response_includable.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["ResponseIncludable"] + +ResponseIncludable: TypeAlias = Literal[ + "file_search_call.results", "message.input_image.image_url", "computer_call_output.output.image_url" +] diff --git a/src/openai/types/responses/response_incomplete_event.py b/src/openai/types/responses/response_incomplete_event.py new file mode 100644 index 0000000000..742b789c7e --- /dev/null +++ b/src/openai/types/responses/response_incomplete_event.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from .response import Response +from ..._models import BaseModel + +__all__ = ["ResponseIncompleteEvent"] + + +class ResponseIncompleteEvent(BaseModel): + response: Response + """The response that was incomplete.""" + + type: Literal["response.incomplete"] + """The type of the event. Always `response.incomplete`.""" diff --git a/src/openai/types/responses/response_input_content.py b/src/openai/types/responses/response_input_content.py new file mode 100644 index 0000000000..1726909a17 --- /dev/null +++ b/src/openai/types/responses/response_input_content.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Annotated, TypeAlias + +from ..._utils import PropertyInfo +from .response_input_file import ResponseInputFile +from .response_input_text import ResponseInputText +from .response_input_image import ResponseInputImage + +__all__ = ["ResponseInputContent"] + +ResponseInputContent: TypeAlias = Annotated[ + Union[ResponseInputText, ResponseInputImage, ResponseInputFile], PropertyInfo(discriminator="type") +] diff --git a/src/openai/types/responses/response_input_content_param.py b/src/openai/types/responses/response_input_content_param.py new file mode 100644 index 0000000000..7791cdfd8e --- /dev/null +++ b/src/openai/types/responses/response_input_content_param.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import TypeAlias + +from .response_input_file_param import ResponseInputFileParam +from .response_input_text_param import ResponseInputTextParam +from .response_input_image_param import ResponseInputImageParam + +__all__ = ["ResponseInputContentParam"] + +ResponseInputContentParam: TypeAlias = Union[ResponseInputTextParam, ResponseInputImageParam, ResponseInputFileParam] diff --git a/src/openai/types/responses/response_input_file.py b/src/openai/types/responses/response_input_file.py new file mode 100644 index 0000000000..00b35dc844 --- /dev/null +++ b/src/openai/types/responses/response_input_file.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseInputFile"] + + +class ResponseInputFile(BaseModel): + type: Literal["input_file"] + """The type of the input item. Always `input_file`.""" + + file_data: Optional[str] = None + """The content of the file to be sent to the model.""" + + file_id: Optional[str] = None + """The ID of the file to be sent to the model.""" + + filename: Optional[str] = None + """The name of the file to be sent to the model.""" diff --git a/src/openai/types/responses/response_input_file_param.py b/src/openai/types/responses/response_input_file_param.py new file mode 100644 index 0000000000..dc06a4ea2d --- /dev/null +++ b/src/openai/types/responses/response_input_file_param.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ResponseInputFileParam"] + + +class ResponseInputFileParam(TypedDict, total=False): + type: Required[Literal["input_file"]] + """The type of the input item. Always `input_file`.""" + + file_data: str + """The content of the file to be sent to the model.""" + + file_id: str + """The ID of the file to be sent to the model.""" + + filename: str + """The name of the file to be sent to the model.""" diff --git a/src/openai/types/responses/response_input_image.py b/src/openai/types/responses/response_input_image.py new file mode 100644 index 0000000000..d719f44e9b --- /dev/null +++ b/src/openai/types/responses/response_input_image.py @@ -0,0 +1,28 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseInputImage"] + + +class ResponseInputImage(BaseModel): + detail: Literal["high", "low", "auto"] + """The detail level of the image to be sent to the model. + + One of `high`, `low`, or `auto`. Defaults to `auto`. + """ + + type: Literal["input_image"] + """The type of the input item. Always `input_image`.""" + + file_id: Optional[str] = None + """The ID of the file to be sent to the model.""" + + image_url: Optional[str] = None + """The URL of the image to be sent to the model. + + A fully qualified URL or base64 encoded image in a data URL. + """ diff --git a/src/openai/types/responses/response_input_image_param.py b/src/openai/types/responses/response_input_image_param.py new file mode 100644 index 0000000000..5dd4db2b5d --- /dev/null +++ b/src/openai/types/responses/response_input_image_param.py @@ -0,0 +1,28 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ResponseInputImageParam"] + + +class ResponseInputImageParam(TypedDict, total=False): + detail: Required[Literal["high", "low", "auto"]] + """The detail level of the image to be sent to the model. + + One of `high`, `low`, or `auto`. Defaults to `auto`. + """ + + type: Required[Literal["input_image"]] + """The type of the input item. Always `input_image`.""" + + file_id: Optional[str] + """The ID of the file to be sent to the model.""" + + image_url: Optional[str] + """The URL of the image to be sent to the model. + + A fully qualified URL or base64 encoded image in a data URL. + """ diff --git a/src/openai/types/responses/response_input_item_param.py b/src/openai/types/responses/response_input_item_param.py new file mode 100644 index 0000000000..c9daaa6a89 --- /dev/null +++ b/src/openai/types/responses/response_input_item_param.py @@ -0,0 +1,174 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .easy_input_message_param import EasyInputMessageParam +from .response_output_message_param import ResponseOutputMessageParam +from .response_computer_tool_call_param import ResponseComputerToolCallParam +from .response_function_tool_call_param import ResponseFunctionToolCallParam +from .response_function_web_search_param import ResponseFunctionWebSearchParam +from .response_file_search_tool_call_param import ResponseFileSearchToolCallParam +from .response_input_message_content_list_param import ResponseInputMessageContentListParam + +__all__ = [ + "ResponseInputItemParam", + "Message", + "ComputerCallOutput", + "ComputerCallOutputOutput", + "ComputerCallOutputAcknowledgedSafetyCheck", + "FunctionCallOutput", + "Reasoning", + "ReasoningContent", + "ItemReference", +] + + +class Message(TypedDict, total=False): + content: Required[ResponseInputMessageContentListParam] + """ + A list of one or many input items to the model, containing different content + types. + """ + + role: Required[Literal["user", "system", "developer"]] + """The role of the message input. One of `user`, `system`, or `developer`.""" + + status: Literal["in_progress", "completed", "incomplete"] + """The status of item. + + One of `in_progress`, `completed`, or `incomplete`. Populated when items are + returned via API. + """ + + type: Literal["message"] + """The type of the message input. Always set to `message`.""" + + +class ComputerCallOutputOutput(TypedDict, total=False): + type: Required[Literal["computer_screenshot"]] + """Specifies the event type. + + For a computer screenshot, this property is always set to `computer_screenshot`. + """ + + file_id: str + """The identifier of an uploaded file that contains the screenshot.""" + + image_url: str + """The URL of the screenshot image.""" + + +class ComputerCallOutputAcknowledgedSafetyCheck(TypedDict, total=False): + id: Required[str] + """The ID of the pending safety check.""" + + code: Required[str] + """The type of the pending safety check.""" + + message: Required[str] + """Details about the pending safety check.""" + + +class ComputerCallOutput(TypedDict, total=False): + call_id: Required[str] + """The ID of the computer tool call that produced the output.""" + + output: Required[ComputerCallOutputOutput] + """A computer screenshot image used with the computer use tool.""" + + type: Required[Literal["computer_call_output"]] + """The type of the computer tool call output. Always `computer_call_output`.""" + + id: str + """The ID of the computer tool call output.""" + + acknowledged_safety_checks: Iterable[ComputerCallOutputAcknowledgedSafetyCheck] + """ + The safety checks reported by the API that have been acknowledged by the + developer. + """ + + status: Literal["in_progress", "completed", "incomplete"] + """The status of the message input. + + One of `in_progress`, `completed`, or `incomplete`. Populated when input items + are returned via API. + """ + + +class FunctionCallOutput(TypedDict, total=False): + call_id: Required[str] + """The unique ID of the function tool call generated by the model.""" + + output: Required[str] + """A JSON string of the output of the function tool call.""" + + type: Required[Literal["function_call_output"]] + """The type of the function tool call output. Always `function_call_output`.""" + + id: str + """The unique ID of the function tool call output. + + Populated when this item is returned via API. + """ + + status: Literal["in_progress", "completed", "incomplete"] + """The status of the item. + + One of `in_progress`, `completed`, or `incomplete`. Populated when items are + returned via API. + """ + + +class ReasoningContent(TypedDict, total=False): + text: Required[str] + """ + A short summary of the reasoning used by the model when generating the response. + """ + + type: Required[Literal["reasoning_summary"]] + """The type of the object. Always `text`.""" + + +class Reasoning(TypedDict, total=False): + id: Required[str] + """The unique identifier of the reasoning content.""" + + content: Required[Iterable[ReasoningContent]] + """Reasoning text contents.""" + + type: Required[Literal["reasoning"]] + """The type of the object. Always `reasoning`.""" + + status: Literal["in_progress", "completed", "incomplete"] + """The status of the item. + + One of `in_progress`, `completed`, or `incomplete`. Populated when items are + returned via API. + """ + + +class ItemReference(TypedDict, total=False): + id: Required[str] + """The ID of the item to reference.""" + + type: Required[Literal["item_reference"]] + """The type of item to reference. Always `item_reference`.""" + + +ResponseInputItemParam: TypeAlias = Union[ + EasyInputMessageParam, + Message, + ResponseOutputMessageParam, + ResponseFileSearchToolCallParam, + ResponseComputerToolCallParam, + ComputerCallOutput, + ResponseFunctionWebSearchParam, + ResponseFunctionToolCallParam, + FunctionCallOutput, + Reasoning, + ItemReference, +] diff --git a/src/openai/types/responses/response_input_message_content_list.py b/src/openai/types/responses/response_input_message_content_list.py new file mode 100644 index 0000000000..99b7c10f12 --- /dev/null +++ b/src/openai/types/responses/response_input_message_content_list.py @@ -0,0 +1,10 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List +from typing_extensions import TypeAlias + +from .response_input_content import ResponseInputContent + +__all__ = ["ResponseInputMessageContentList"] + +ResponseInputMessageContentList: TypeAlias = List[ResponseInputContent] diff --git a/src/openai/types/responses/response_input_message_content_list_param.py b/src/openai/types/responses/response_input_message_content_list_param.py new file mode 100644 index 0000000000..080613df0d --- /dev/null +++ b/src/openai/types/responses/response_input_message_content_list_param.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Union +from typing_extensions import TypeAlias + +from .response_input_file_param import ResponseInputFileParam +from .response_input_text_param import ResponseInputTextParam +from .response_input_image_param import ResponseInputImageParam + +__all__ = ["ResponseInputMessageContentListParam", "ResponseInputContentParam"] + +ResponseInputContentParam: TypeAlias = Union[ResponseInputTextParam, ResponseInputImageParam, ResponseInputFileParam] + +ResponseInputMessageContentListParam: TypeAlias = List[ResponseInputContentParam] diff --git a/src/openai/types/responses/response_input_param.py b/src/openai/types/responses/response_input_param.py new file mode 100644 index 0000000000..c81308500d --- /dev/null +++ b/src/openai/types/responses/response_input_param.py @@ -0,0 +1,177 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Union, Iterable +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .easy_input_message_param import EasyInputMessageParam +from .response_output_message_param import ResponseOutputMessageParam +from .response_computer_tool_call_param import ResponseComputerToolCallParam +from .response_function_tool_call_param import ResponseFunctionToolCallParam +from .response_function_web_search_param import ResponseFunctionWebSearchParam +from .response_file_search_tool_call_param import ResponseFileSearchToolCallParam +from .response_input_message_content_list_param import ResponseInputMessageContentListParam + +__all__ = [ + "ResponseInputParam", + "ResponseInputItemParam", + "Message", + "ComputerCallOutput", + "ComputerCallOutputOutput", + "ComputerCallOutputAcknowledgedSafetyCheck", + "FunctionCallOutput", + "Reasoning", + "ReasoningContent", + "ItemReference", +] + + +class Message(TypedDict, total=False): + content: Required[ResponseInputMessageContentListParam] + """ + A list of one or many input items to the model, containing different content + types. + """ + + role: Required[Literal["user", "system", "developer"]] + """The role of the message input. One of `user`, `system`, or `developer`.""" + + status: Literal["in_progress", "completed", "incomplete"] + """The status of item. + + One of `in_progress`, `completed`, or `incomplete`. Populated when items are + returned via API. + """ + + type: Literal["message"] + """The type of the message input. Always set to `message`.""" + + +class ComputerCallOutputOutput(TypedDict, total=False): + type: Required[Literal["computer_screenshot"]] + """Specifies the event type. + + For a computer screenshot, this property is always set to `computer_screenshot`. + """ + + file_id: str + """The identifier of an uploaded file that contains the screenshot.""" + + image_url: str + """The URL of the screenshot image.""" + + +class ComputerCallOutputAcknowledgedSafetyCheck(TypedDict, total=False): + id: Required[str] + """The ID of the pending safety check.""" + + code: Required[str] + """The type of the pending safety check.""" + + message: Required[str] + """Details about the pending safety check.""" + + +class ComputerCallOutput(TypedDict, total=False): + call_id: Required[str] + """The ID of the computer tool call that produced the output.""" + + output: Required[ComputerCallOutputOutput] + """A computer screenshot image used with the computer use tool.""" + + type: Required[Literal["computer_call_output"]] + """The type of the computer tool call output. Always `computer_call_output`.""" + + id: str + """The ID of the computer tool call output.""" + + acknowledged_safety_checks: Iterable[ComputerCallOutputAcknowledgedSafetyCheck] + """ + The safety checks reported by the API that have been acknowledged by the + developer. + """ + + status: Literal["in_progress", "completed", "incomplete"] + """The status of the message input. + + One of `in_progress`, `completed`, or `incomplete`. Populated when input items + are returned via API. + """ + + +class FunctionCallOutput(TypedDict, total=False): + call_id: Required[str] + """The unique ID of the function tool call generated by the model.""" + + output: Required[str] + """A JSON string of the output of the function tool call.""" + + type: Required[Literal["function_call_output"]] + """The type of the function tool call output. Always `function_call_output`.""" + + id: str + """The unique ID of the function tool call output. + + Populated when this item is returned via API. + """ + + status: Literal["in_progress", "completed", "incomplete"] + """The status of the item. + + One of `in_progress`, `completed`, or `incomplete`. Populated when items are + returned via API. + """ + + +class ReasoningContent(TypedDict, total=False): + text: Required[str] + """ + A short summary of the reasoning used by the model when generating the response. + """ + + type: Required[Literal["reasoning_summary"]] + """The type of the object. Always `text`.""" + + +class Reasoning(TypedDict, total=False): + id: Required[str] + """The unique identifier of the reasoning content.""" + + content: Required[Iterable[ReasoningContent]] + """Reasoning text contents.""" + + type: Required[Literal["reasoning"]] + """The type of the object. Always `reasoning`.""" + + status: Literal["in_progress", "completed", "incomplete"] + """The status of the item. + + One of `in_progress`, `completed`, or `incomplete`. Populated when items are + returned via API. + """ + + +class ItemReference(TypedDict, total=False): + id: Required[str] + """The ID of the item to reference.""" + + type: Required[Literal["item_reference"]] + """The type of item to reference. Always `item_reference`.""" + + +ResponseInputItemParam: TypeAlias = Union[ + EasyInputMessageParam, + Message, + ResponseOutputMessageParam, + ResponseFileSearchToolCallParam, + ResponseComputerToolCallParam, + ComputerCallOutput, + ResponseFunctionWebSearchParam, + ResponseFunctionToolCallParam, + FunctionCallOutput, + Reasoning, + ItemReference, +] + +ResponseInputParam: TypeAlias = List[ResponseInputItemParam] diff --git a/src/openai/types/responses/response_input_text.py b/src/openai/types/responses/response_input_text.py new file mode 100644 index 0000000000..ba8d1ea18b --- /dev/null +++ b/src/openai/types/responses/response_input_text.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseInputText"] + + +class ResponseInputText(BaseModel): + text: str + """The text input to the model.""" + + type: Literal["input_text"] + """The type of the input item. Always `input_text`.""" diff --git a/src/openai/types/responses/response_input_text_param.py b/src/openai/types/responses/response_input_text_param.py new file mode 100644 index 0000000000..f2ba834082 --- /dev/null +++ b/src/openai/types/responses/response_input_text_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ResponseInputTextParam"] + + +class ResponseInputTextParam(TypedDict, total=False): + text: Required[str] + """The text input to the model.""" + + type: Required[Literal["input_text"]] + """The type of the input item. Always `input_text`.""" diff --git a/src/openai/types/responses/response_item_list.py b/src/openai/types/responses/response_item_list.py new file mode 100644 index 0000000000..7c3e4d7f82 --- /dev/null +++ b/src/openai/types/responses/response_item_list.py @@ -0,0 +1,152 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias + +from ..._utils import PropertyInfo +from ..._models import BaseModel +from .response_output_message import ResponseOutputMessage +from .response_computer_tool_call import ResponseComputerToolCall +from .response_function_tool_call import ResponseFunctionToolCall +from .response_function_web_search import ResponseFunctionWebSearch +from .response_file_search_tool_call import ResponseFileSearchToolCall +from .response_input_message_content_list import ResponseInputMessageContentList + +__all__ = [ + "ResponseItemList", + "Data", + "DataMessage", + "DataComputerCallOutput", + "DataComputerCallOutputOutput", + "DataComputerCallOutputAcknowledgedSafetyCheck", + "DataFunctionCallOutput", +] + + +class DataMessage(BaseModel): + id: str + """The unique ID of the message input.""" + + content: ResponseInputMessageContentList + """ + A list of one or many input items to the model, containing different content + types. + """ + + role: Literal["user", "system", "developer"] + """The role of the message input. One of `user`, `system`, or `developer`.""" + + status: Optional[Literal["in_progress", "completed", "incomplete"]] = None + """The status of item. + + One of `in_progress`, `completed`, or `incomplete`. Populated when items are + returned via API. + """ + + type: Optional[Literal["message"]] = None + """The type of the message input. Always set to `message`.""" + + +class DataComputerCallOutputOutput(BaseModel): + type: Literal["computer_screenshot"] + """Specifies the event type. + + For a computer screenshot, this property is always set to `computer_screenshot`. + """ + + file_id: Optional[str] = None + """The identifier of an uploaded file that contains the screenshot.""" + + image_url: Optional[str] = None + """The URL of the screenshot image.""" + + +class DataComputerCallOutputAcknowledgedSafetyCheck(BaseModel): + id: str + """The ID of the pending safety check.""" + + code: str + """The type of the pending safety check.""" + + message: str + """Details about the pending safety check.""" + + +class DataComputerCallOutput(BaseModel): + id: str + """The unique ID of the computer call tool output.""" + + call_id: str + """The ID of the computer tool call that produced the output.""" + + output: DataComputerCallOutputOutput + """A computer screenshot image used with the computer use tool.""" + + type: Literal["computer_call_output"] + """The type of the computer tool call output. Always `computer_call_output`.""" + + acknowledged_safety_checks: Optional[List[DataComputerCallOutputAcknowledgedSafetyCheck]] = None + """ + The safety checks reported by the API that have been acknowledged by the + developer. + """ + + status: Optional[Literal["in_progress", "completed", "incomplete"]] = None + """The status of the message input. + + One of `in_progress`, `completed`, or `incomplete`. Populated when input items + are returned via API. + """ + + +class DataFunctionCallOutput(BaseModel): + id: str + """The unique ID of the function call tool output.""" + + call_id: str + """The unique ID of the function tool call generated by the model.""" + + output: str + """A JSON string of the output of the function tool call.""" + + type: Literal["function_call_output"] + """The type of the function tool call output. Always `function_call_output`.""" + + status: Optional[Literal["in_progress", "completed", "incomplete"]] = None + """The status of the item. + + One of `in_progress`, `completed`, or `incomplete`. Populated when items are + returned via API. + """ + + +Data: TypeAlias = Annotated[ + Union[ + DataMessage, + ResponseOutputMessage, + ResponseFileSearchToolCall, + ResponseComputerToolCall, + DataComputerCallOutput, + ResponseFunctionWebSearch, + ResponseFunctionToolCall, + DataFunctionCallOutput, + ], + PropertyInfo(discriminator="type"), +] + + +class ResponseItemList(BaseModel): + data: List[Data] + """A list of items used to generate this response.""" + + first_id: str + """The ID of the first item in the list.""" + + has_more: bool + """Whether there are more items available.""" + + last_id: str + """The ID of the last item in the list.""" + + object: Literal["list"] + """The type of object returned, must be `list`.""" diff --git a/src/openai/types/responses/response_output_item.py b/src/openai/types/responses/response_output_item.py new file mode 100644 index 0000000000..45d5cc0094 --- /dev/null +++ b/src/openai/types/responses/response_output_item.py @@ -0,0 +1,55 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias + +from ..._utils import PropertyInfo +from ..._models import BaseModel +from .response_output_message import ResponseOutputMessage +from .response_computer_tool_call import ResponseComputerToolCall +from .response_function_tool_call import ResponseFunctionToolCall +from .response_function_web_search import ResponseFunctionWebSearch +from .response_file_search_tool_call import ResponseFileSearchToolCall + +__all__ = ["ResponseOutputItem", "Reasoning", "ReasoningContent"] + + +class ReasoningContent(BaseModel): + text: str + """ + A short summary of the reasoning used by the model when generating the response. + """ + + type: Literal["reasoning_summary"] + """The type of the object. Always `text`.""" + + +class Reasoning(BaseModel): + id: str + """The unique identifier of the reasoning content.""" + + content: List[ReasoningContent] + """Reasoning text contents.""" + + type: Literal["reasoning"] + """The type of the object. Always `reasoning`.""" + + status: Optional[Literal["in_progress", "completed", "incomplete"]] = None + """The status of the item. + + One of `in_progress`, `completed`, or `incomplete`. Populated when items are + returned via API. + """ + + +ResponseOutputItem: TypeAlias = Annotated[ + Union[ + ResponseOutputMessage, + ResponseFileSearchToolCall, + ResponseFunctionToolCall, + ResponseFunctionWebSearch, + ResponseComputerToolCall, + Reasoning, + ], + PropertyInfo(discriminator="type"), +] diff --git a/src/openai/types/responses/response_output_item_added_event.py b/src/openai/types/responses/response_output_item_added_event.py new file mode 100644 index 0000000000..7344fb9a6c --- /dev/null +++ b/src/openai/types/responses/response_output_item_added_event.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel +from .response_output_item import ResponseOutputItem + +__all__ = ["ResponseOutputItemAddedEvent"] + + +class ResponseOutputItemAddedEvent(BaseModel): + item: ResponseOutputItem + """The output item that was added.""" + + output_index: int + """The index of the output item that was added.""" + + type: Literal["response.output_item.added"] + """The type of the event. Always `response.output_item.added`.""" diff --git a/src/openai/types/responses/response_output_item_done_event.py b/src/openai/types/responses/response_output_item_done_event.py new file mode 100644 index 0000000000..a0a871a019 --- /dev/null +++ b/src/openai/types/responses/response_output_item_done_event.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel +from .response_output_item import ResponseOutputItem + +__all__ = ["ResponseOutputItemDoneEvent"] + + +class ResponseOutputItemDoneEvent(BaseModel): + item: ResponseOutputItem + """The output item that was marked done.""" + + output_index: int + """The index of the output item that was marked done.""" + + type: Literal["response.output_item.done"] + """The type of the event. Always `response.output_item.done`.""" diff --git a/src/openai/types/responses/response_output_message.py b/src/openai/types/responses/response_output_message.py new file mode 100644 index 0000000000..3864aa2111 --- /dev/null +++ b/src/openai/types/responses/response_output_message.py @@ -0,0 +1,34 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union +from typing_extensions import Literal, Annotated, TypeAlias + +from ..._utils import PropertyInfo +from ..._models import BaseModel +from .response_output_text import ResponseOutputText +from .response_output_refusal import ResponseOutputRefusal + +__all__ = ["ResponseOutputMessage", "Content"] + +Content: TypeAlias = Annotated[Union[ResponseOutputText, ResponseOutputRefusal], PropertyInfo(discriminator="type")] + + +class ResponseOutputMessage(BaseModel): + id: str + """The unique ID of the output message.""" + + content: List[Content] + """The content of the output message.""" + + role: Literal["assistant"] + """The role of the output message. Always `assistant`.""" + + status: Literal["in_progress", "completed", "incomplete"] + """The status of the message input. + + One of `in_progress`, `completed`, or `incomplete`. Populated when input items + are returned via API. + """ + + type: Literal["message"] + """The type of the output message. Always `message`.""" diff --git a/src/openai/types/responses/response_output_message_param.py b/src/openai/types/responses/response_output_message_param.py new file mode 100644 index 0000000000..46cbbd20de --- /dev/null +++ b/src/openai/types/responses/response_output_message_param.py @@ -0,0 +1,34 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .response_output_text_param import ResponseOutputTextParam +from .response_output_refusal_param import ResponseOutputRefusalParam + +__all__ = ["ResponseOutputMessageParam", "Content"] + +Content: TypeAlias = Union[ResponseOutputTextParam, ResponseOutputRefusalParam] + + +class ResponseOutputMessageParam(TypedDict, total=False): + id: Required[str] + """The unique ID of the output message.""" + + content: Required[Iterable[Content]] + """The content of the output message.""" + + role: Required[Literal["assistant"]] + """The role of the output message. Always `assistant`.""" + + status: Required[Literal["in_progress", "completed", "incomplete"]] + """The status of the message input. + + One of `in_progress`, `completed`, or `incomplete`. Populated when input items + are returned via API. + """ + + type: Required[Literal["message"]] + """The type of the output message. Always `message`.""" diff --git a/src/openai/types/responses/response_output_refusal.py b/src/openai/types/responses/response_output_refusal.py new file mode 100644 index 0000000000..eba581070d --- /dev/null +++ b/src/openai/types/responses/response_output_refusal.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseOutputRefusal"] + + +class ResponseOutputRefusal(BaseModel): + refusal: str + """The refusal explanationfrom the model.""" + + type: Literal["refusal"] + """The type of the refusal. Always `refusal`.""" diff --git a/src/openai/types/responses/response_output_refusal_param.py b/src/openai/types/responses/response_output_refusal_param.py new file mode 100644 index 0000000000..53140a6080 --- /dev/null +++ b/src/openai/types/responses/response_output_refusal_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ResponseOutputRefusalParam"] + + +class ResponseOutputRefusalParam(TypedDict, total=False): + refusal: Required[str] + """The refusal explanationfrom the model.""" + + type: Required[Literal["refusal"]] + """The type of the refusal. Always `refusal`.""" diff --git a/src/openai/types/responses/response_output_text.py b/src/openai/types/responses/response_output_text.py new file mode 100644 index 0000000000..fa653cd1af --- /dev/null +++ b/src/openai/types/responses/response_output_text.py @@ -0,0 +1,64 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union +from typing_extensions import Literal, Annotated, TypeAlias + +from ..._utils import PropertyInfo +from ..._models import BaseModel + +__all__ = ["ResponseOutputText", "Annotation", "AnnotationFileCitation", "AnnotationURLCitation", "AnnotationFilePath"] + + +class AnnotationFileCitation(BaseModel): + file_id: str + """The ID of the file.""" + + index: int + """The index of the file in the list of files.""" + + type: Literal["file_citation"] + """The type of the file citation. Always `file_citation`.""" + + +class AnnotationURLCitation(BaseModel): + end_index: int + """The index of the last character of the URL citation in the message.""" + + start_index: int + """The index of the first character of the URL citation in the message.""" + + title: str + """The title of the web resource.""" + + type: Literal["url_citation"] + """The type of the URL citation. Always `url_citation`.""" + + url: str + """The URL of the web resource.""" + + +class AnnotationFilePath(BaseModel): + file_id: str + """The ID of the file.""" + + index: int + """The index of the file in the list of files.""" + + type: Literal["file_path"] + """The type of the file path. Always `file_path`.""" + + +Annotation: TypeAlias = Annotated[ + Union[AnnotationFileCitation, AnnotationURLCitation, AnnotationFilePath], PropertyInfo(discriminator="type") +] + + +class ResponseOutputText(BaseModel): + annotations: List[Annotation] + """The annotations of the text output.""" + + text: str + """The text output from the model.""" + + type: Literal["output_text"] + """The type of the output text. Always `output_text`.""" diff --git a/src/openai/types/responses/response_output_text_param.py b/src/openai/types/responses/response_output_text_param.py new file mode 100644 index 0000000000..1f0967285f --- /dev/null +++ b/src/openai/types/responses/response_output_text_param.py @@ -0,0 +1,67 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +__all__ = [ + "ResponseOutputTextParam", + "Annotation", + "AnnotationFileCitation", + "AnnotationURLCitation", + "AnnotationFilePath", +] + + +class AnnotationFileCitation(TypedDict, total=False): + file_id: Required[str] + """The ID of the file.""" + + index: Required[int] + """The index of the file in the list of files.""" + + type: Required[Literal["file_citation"]] + """The type of the file citation. Always `file_citation`.""" + + +class AnnotationURLCitation(TypedDict, total=False): + end_index: Required[int] + """The index of the last character of the URL citation in the message.""" + + start_index: Required[int] + """The index of the first character of the URL citation in the message.""" + + title: Required[str] + """The title of the web resource.""" + + type: Required[Literal["url_citation"]] + """The type of the URL citation. Always `url_citation`.""" + + url: Required[str] + """The URL of the web resource.""" + + +class AnnotationFilePath(TypedDict, total=False): + file_id: Required[str] + """The ID of the file.""" + + index: Required[int] + """The index of the file in the list of files.""" + + type: Required[Literal["file_path"]] + """The type of the file path. Always `file_path`.""" + + +Annotation: TypeAlias = Union[AnnotationFileCitation, AnnotationURLCitation, AnnotationFilePath] + + +class ResponseOutputTextParam(TypedDict, total=False): + annotations: Required[Iterable[Annotation]] + """The annotations of the text output.""" + + text: Required[str] + """The text output from the model.""" + + type: Required[Literal["output_text"]] + """The type of the output text. Always `output_text`.""" diff --git a/src/openai/types/responses/response_refusal_delta_event.py b/src/openai/types/responses/response_refusal_delta_event.py new file mode 100644 index 0000000000..04dcdf1c8c --- /dev/null +++ b/src/openai/types/responses/response_refusal_delta_event.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseRefusalDeltaEvent"] + + +class ResponseRefusalDeltaEvent(BaseModel): + content_index: int + """The index of the content part that the refusal text is added to.""" + + delta: str + """The refusal text that is added.""" + + item_id: str + """The ID of the output item that the refusal text is added to.""" + + output_index: int + """The index of the output item that the refusal text is added to.""" + + type: Literal["response.refusal.delta"] + """The type of the event. Always `response.refusal.delta`.""" diff --git a/src/openai/types/responses/response_refusal_done_event.py b/src/openai/types/responses/response_refusal_done_event.py new file mode 100644 index 0000000000..a9b6f4b055 --- /dev/null +++ b/src/openai/types/responses/response_refusal_done_event.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseRefusalDoneEvent"] + + +class ResponseRefusalDoneEvent(BaseModel): + content_index: int + """The index of the content part that the refusal text is finalized.""" + + item_id: str + """The ID of the output item that the refusal text is finalized.""" + + output_index: int + """The index of the output item that the refusal text is finalized.""" + + refusal: str + """The refusal text that is finalized.""" + + type: Literal["response.refusal.done"] + """The type of the event. Always `response.refusal.done`.""" diff --git a/src/openai/types/responses/response_retrieve_params.py b/src/openai/types/responses/response_retrieve_params.py new file mode 100644 index 0000000000..137bf4dcee --- /dev/null +++ b/src/openai/types/responses/response_retrieve_params.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List +from typing_extensions import TypedDict + +from .response_includable import ResponseIncludable + +__all__ = ["ResponseRetrieveParams"] + + +class ResponseRetrieveParams(TypedDict, total=False): + include: List[ResponseIncludable] + """Additional fields to include in the response. + + See the `include` parameter for Response creation above for more information. + """ diff --git a/src/openai/types/responses/response_status.py b/src/openai/types/responses/response_status.py new file mode 100644 index 0000000000..934d17cda3 --- /dev/null +++ b/src/openai/types/responses/response_status.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["ResponseStatus"] + +ResponseStatus: TypeAlias = Literal["completed", "failed", "in_progress", "incomplete"] diff --git a/src/openai/types/responses/response_stream_event.py b/src/openai/types/responses/response_stream_event.py new file mode 100644 index 0000000000..446863b175 --- /dev/null +++ b/src/openai/types/responses/response_stream_event.py @@ -0,0 +1,78 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Annotated, TypeAlias + +from ..._utils import PropertyInfo +from .response_error_event import ResponseErrorEvent +from .response_failed_event import ResponseFailedEvent +from .response_created_event import ResponseCreatedEvent +from .response_completed_event import ResponseCompletedEvent +from .response_text_done_event import ResponseTextDoneEvent +from .response_audio_done_event import ResponseAudioDoneEvent +from .response_incomplete_event import ResponseIncompleteEvent +from .response_text_delta_event import ResponseTextDeltaEvent +from .response_audio_delta_event import ResponseAudioDeltaEvent +from .response_in_progress_event import ResponseInProgressEvent +from .response_refusal_done_event import ResponseRefusalDoneEvent +from .response_refusal_delta_event import ResponseRefusalDeltaEvent +from .response_output_item_done_event import ResponseOutputItemDoneEvent +from .response_content_part_done_event import ResponseContentPartDoneEvent +from .response_output_item_added_event import ResponseOutputItemAddedEvent +from .response_content_part_added_event import ResponseContentPartAddedEvent +from .response_audio_transcript_done_event import ResponseAudioTranscriptDoneEvent +from .response_text_annotation_delta_event import ResponseTextAnnotationDeltaEvent +from .response_audio_transcript_delta_event import ResponseAudioTranscriptDeltaEvent +from .response_web_search_call_completed_event import ResponseWebSearchCallCompletedEvent +from .response_web_search_call_searching_event import ResponseWebSearchCallSearchingEvent +from .response_file_search_call_completed_event import ResponseFileSearchCallCompletedEvent +from .response_file_search_call_searching_event import ResponseFileSearchCallSearchingEvent +from .response_web_search_call_in_progress_event import ResponseWebSearchCallInProgressEvent +from .response_file_search_call_in_progress_event import ResponseFileSearchCallInProgressEvent +from .response_function_call_arguments_done_event import ResponseFunctionCallArgumentsDoneEvent +from .response_function_call_arguments_delta_event import ResponseFunctionCallArgumentsDeltaEvent +from .response_code_interpreter_call_code_done_event import ResponseCodeInterpreterCallCodeDoneEvent +from .response_code_interpreter_call_completed_event import ResponseCodeInterpreterCallCompletedEvent +from .response_code_interpreter_call_code_delta_event import ResponseCodeInterpreterCallCodeDeltaEvent +from .response_code_interpreter_call_in_progress_event import ResponseCodeInterpreterCallInProgressEvent +from .response_code_interpreter_call_interpreting_event import ResponseCodeInterpreterCallInterpretingEvent + +__all__ = ["ResponseStreamEvent"] + +ResponseStreamEvent: TypeAlias = Annotated[ + Union[ + ResponseAudioDeltaEvent, + ResponseAudioDoneEvent, + ResponseAudioTranscriptDeltaEvent, + ResponseAudioTranscriptDoneEvent, + ResponseCodeInterpreterCallCodeDeltaEvent, + ResponseCodeInterpreterCallCodeDoneEvent, + ResponseCodeInterpreterCallCompletedEvent, + ResponseCodeInterpreterCallInProgressEvent, + ResponseCodeInterpreterCallInterpretingEvent, + ResponseCompletedEvent, + ResponseContentPartAddedEvent, + ResponseContentPartDoneEvent, + ResponseCreatedEvent, + ResponseErrorEvent, + ResponseFileSearchCallCompletedEvent, + ResponseFileSearchCallInProgressEvent, + ResponseFileSearchCallSearchingEvent, + ResponseFunctionCallArgumentsDeltaEvent, + ResponseFunctionCallArgumentsDoneEvent, + ResponseInProgressEvent, + ResponseFailedEvent, + ResponseIncompleteEvent, + ResponseOutputItemAddedEvent, + ResponseOutputItemDoneEvent, + ResponseRefusalDeltaEvent, + ResponseRefusalDoneEvent, + ResponseTextAnnotationDeltaEvent, + ResponseTextDeltaEvent, + ResponseTextDoneEvent, + ResponseWebSearchCallCompletedEvent, + ResponseWebSearchCallInProgressEvent, + ResponseWebSearchCallSearchingEvent, + ], + PropertyInfo(discriminator="type"), +] diff --git a/src/openai/types/responses/response_text_annotation_delta_event.py b/src/openai/types/responses/response_text_annotation_delta_event.py new file mode 100644 index 0000000000..4f2582282a --- /dev/null +++ b/src/openai/types/responses/response_text_annotation_delta_event.py @@ -0,0 +1,79 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Literal, Annotated, TypeAlias + +from ..._utils import PropertyInfo +from ..._models import BaseModel + +__all__ = [ + "ResponseTextAnnotationDeltaEvent", + "Annotation", + "AnnotationFileCitation", + "AnnotationURLCitation", + "AnnotationFilePath", +] + + +class AnnotationFileCitation(BaseModel): + file_id: str + """The ID of the file.""" + + index: int + """The index of the file in the list of files.""" + + type: Literal["file_citation"] + """The type of the file citation. Always `file_citation`.""" + + +class AnnotationURLCitation(BaseModel): + end_index: int + """The index of the last character of the URL citation in the message.""" + + start_index: int + """The index of the first character of the URL citation in the message.""" + + title: str + """The title of the web resource.""" + + type: Literal["url_citation"] + """The type of the URL citation. Always `url_citation`.""" + + url: str + """The URL of the web resource.""" + + +class AnnotationFilePath(BaseModel): + file_id: str + """The ID of the file.""" + + index: int + """The index of the file in the list of files.""" + + type: Literal["file_path"] + """The type of the file path. Always `file_path`.""" + + +Annotation: TypeAlias = Annotated[ + Union[AnnotationFileCitation, AnnotationURLCitation, AnnotationFilePath], PropertyInfo(discriminator="type") +] + + +class ResponseTextAnnotationDeltaEvent(BaseModel): + annotation: Annotation + """A citation to a file.""" + + annotation_index: int + """The index of the annotation that was added.""" + + content_index: int + """The index of the content part that the text annotation was added to.""" + + item_id: str + """The ID of the output item that the text annotation was added to.""" + + output_index: int + """The index of the output item that the text annotation was added to.""" + + type: Literal["response.output_text.annotation.added"] + """The type of the event. Always `response.output_text.annotation.added`.""" diff --git a/src/openai/types/responses/response_text_config.py b/src/openai/types/responses/response_text_config.py new file mode 100644 index 0000000000..a1894a9176 --- /dev/null +++ b/src/openai/types/responses/response_text_config.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from ..._models import BaseModel +from .response_format_text_config import ResponseFormatTextConfig + +__all__ = ["ResponseTextConfig"] + + +class ResponseTextConfig(BaseModel): + format: Optional[ResponseFormatTextConfig] = None + """An object specifying the format that the model must output. + + Configuring `{ "type": "json_schema" }` enables Structured Outputs, which + ensures the model will match your supplied JSON schema. Learn more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + + The default format is `{ "type": "text" }` with no additional options. + + **Not recommended for gpt-4o and newer models:** + + Setting to `{ "type": "json_object" }` enables the older JSON mode, which + ensures the message the model generates is valid JSON. Using `json_schema` is + preferred for models that support it. + """ diff --git a/src/openai/types/responses/response_text_config_param.py b/src/openai/types/responses/response_text_config_param.py new file mode 100644 index 0000000000..aec064bf89 --- /dev/null +++ b/src/openai/types/responses/response_text_config_param.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +from .response_format_text_config_param import ResponseFormatTextConfigParam + +__all__ = ["ResponseTextConfigParam"] + + +class ResponseTextConfigParam(TypedDict, total=False): + format: ResponseFormatTextConfigParam + """An object specifying the format that the model must output. + + Configuring `{ "type": "json_schema" }` enables Structured Outputs, which + ensures the model will match your supplied JSON schema. Learn more in the + [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). + + The default format is `{ "type": "text" }` with no additional options. + + **Not recommended for gpt-4o and newer models:** + + Setting to `{ "type": "json_object" }` enables the older JSON mode, which + ensures the message the model generates is valid JSON. Using `json_schema` is + preferred for models that support it. + """ diff --git a/src/openai/types/responses/response_text_delta_event.py b/src/openai/types/responses/response_text_delta_event.py new file mode 100644 index 0000000000..751a5e2a19 --- /dev/null +++ b/src/openai/types/responses/response_text_delta_event.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseTextDeltaEvent"] + + +class ResponseTextDeltaEvent(BaseModel): + content_index: int + """The index of the content part that the text delta was added to.""" + + delta: str + """The text delta that was added.""" + + item_id: str + """The ID of the output item that the text delta was added to.""" + + output_index: int + """The index of the output item that the text delta was added to.""" + + type: Literal["response.output_text.delta"] + """The type of the event. Always `response.output_text.delta`.""" diff --git a/src/openai/types/responses/response_text_done_event.py b/src/openai/types/responses/response_text_done_event.py new file mode 100644 index 0000000000..9b5c5e020c --- /dev/null +++ b/src/openai/types/responses/response_text_done_event.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseTextDoneEvent"] + + +class ResponseTextDoneEvent(BaseModel): + content_index: int + """The index of the content part that the text content is finalized.""" + + item_id: str + """The ID of the output item that the text content is finalized.""" + + output_index: int + """The index of the output item that the text content is finalized.""" + + text: str + """The text content that is finalized.""" + + type: Literal["response.output_text.done"] + """The type of the event. Always `response.output_text.done`.""" diff --git a/src/openai/types/responses/response_usage.py b/src/openai/types/responses/response_usage.py new file mode 100644 index 0000000000..ef631c5882 --- /dev/null +++ b/src/openai/types/responses/response_usage.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +from ..._models import BaseModel + +__all__ = ["ResponseUsage", "OutputTokensDetails"] + + +class OutputTokensDetails(BaseModel): + reasoning_tokens: int + """The number of reasoning tokens.""" + + +class ResponseUsage(BaseModel): + input_tokens: int + """The number of input tokens.""" + + output_tokens: int + """The number of output tokens.""" + + output_tokens_details: OutputTokensDetails + """A detailed breakdown of the output tokens.""" + + total_tokens: int + """The total number of tokens used.""" diff --git a/src/openai/types/responses/response_web_search_call_completed_event.py b/src/openai/types/responses/response_web_search_call_completed_event.py new file mode 100644 index 0000000000..76f26766a1 --- /dev/null +++ b/src/openai/types/responses/response_web_search_call_completed_event.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseWebSearchCallCompletedEvent"] + + +class ResponseWebSearchCallCompletedEvent(BaseModel): + item_id: str + """Unique ID for the output item associated with the web search call.""" + + output_index: int + """The index of the output item that the web search call is associated with.""" + + type: Literal["response.web_search_call.completed"] + """The type of the event. Always `response.web_search_call.completed`.""" diff --git a/src/openai/types/responses/response_web_search_call_in_progress_event.py b/src/openai/types/responses/response_web_search_call_in_progress_event.py new file mode 100644 index 0000000000..681ce6d94b --- /dev/null +++ b/src/openai/types/responses/response_web_search_call_in_progress_event.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseWebSearchCallInProgressEvent"] + + +class ResponseWebSearchCallInProgressEvent(BaseModel): + item_id: str + """Unique ID for the output item associated with the web search call.""" + + output_index: int + """The index of the output item that the web search call is associated with.""" + + type: Literal["response.web_search_call.in_progress"] + """The type of the event. Always `response.web_search_call.in_progress`.""" diff --git a/src/openai/types/responses/response_web_search_call_searching_event.py b/src/openai/types/responses/response_web_search_call_searching_event.py new file mode 100644 index 0000000000..c885d98918 --- /dev/null +++ b/src/openai/types/responses/response_web_search_call_searching_event.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseWebSearchCallSearchingEvent"] + + +class ResponseWebSearchCallSearchingEvent(BaseModel): + item_id: str + """Unique ID for the output item associated with the web search call.""" + + output_index: int + """The index of the output item that the web search call is associated with.""" + + type: Literal["response.web_search_call.searching"] + """The type of the event. Always `response.web_search_call.searching`.""" diff --git a/src/openai/types/responses/tool.py b/src/openai/types/responses/tool.py new file mode 100644 index 0000000000..de5d5524d4 --- /dev/null +++ b/src/openai/types/responses/tool.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Annotated, TypeAlias + +from ..._utils import PropertyInfo +from .computer_tool import ComputerTool +from .function_tool import FunctionTool +from .web_search_tool import WebSearchTool +from .file_search_tool import FileSearchTool + +__all__ = ["Tool"] + +Tool: TypeAlias = Annotated[ + Union[FileSearchTool, FunctionTool, ComputerTool, WebSearchTool], PropertyInfo(discriminator="type") +] diff --git a/src/openai/types/responses/tool_choice_function.py b/src/openai/types/responses/tool_choice_function.py new file mode 100644 index 0000000000..8d2a4f2822 --- /dev/null +++ b/src/openai/types/responses/tool_choice_function.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ToolChoiceFunction"] + + +class ToolChoiceFunction(BaseModel): + name: str + """The name of the function to call.""" + + type: Literal["function"] + """For function calling, the type is always `function`.""" diff --git a/src/openai/types/responses/tool_choice_function_param.py b/src/openai/types/responses/tool_choice_function_param.py new file mode 100644 index 0000000000..910537fd97 --- /dev/null +++ b/src/openai/types/responses/tool_choice_function_param.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ToolChoiceFunctionParam"] + + +class ToolChoiceFunctionParam(TypedDict, total=False): + name: Required[str] + """The name of the function to call.""" + + type: Required[Literal["function"]] + """For function calling, the type is always `function`.""" diff --git a/src/openai/types/responses/tool_choice_options.py b/src/openai/types/responses/tool_choice_options.py new file mode 100644 index 0000000000..c200db54e1 --- /dev/null +++ b/src/openai/types/responses/tool_choice_options.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["ToolChoiceOptions"] + +ToolChoiceOptions: TypeAlias = Literal["none", "auto", "required"] diff --git a/src/openai/types/responses/tool_choice_types.py b/src/openai/types/responses/tool_choice_types.py new file mode 100644 index 0000000000..4942808f14 --- /dev/null +++ b/src/openai/types/responses/tool_choice_types.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ToolChoiceTypes"] + + +class ToolChoiceTypes(BaseModel): + type: Literal["file_search", "web_search_preview", "computer_use_preview", "web_search_preview_2025_03_11"] + """The type of hosted tool the model should to use. + + Learn more about + [built-in tools](https://platform.openai.com/docs/guides/tools). + + Allowed values are: + + - `file_search` + - `web_search_preview` + - `computer_use_preview` + """ diff --git a/src/openai/types/responses/tool_choice_types_param.py b/src/openai/types/responses/tool_choice_types_param.py new file mode 100644 index 0000000000..b14f2a9eb0 --- /dev/null +++ b/src/openai/types/responses/tool_choice_types_param.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ToolChoiceTypesParam"] + + +class ToolChoiceTypesParam(TypedDict, total=False): + type: Required[ + Literal["file_search", "web_search_preview", "computer_use_preview", "web_search_preview_2025_03_11"] + ] + """The type of hosted tool the model should to use. + + Learn more about + [built-in tools](https://platform.openai.com/docs/guides/tools). + + Allowed values are: + + - `file_search` + - `web_search_preview` + - `computer_use_preview` + """ diff --git a/src/openai/types/responses/tool_param.py b/src/openai/types/responses/tool_param.py new file mode 100644 index 0000000000..be1cf82452 --- /dev/null +++ b/src/openai/types/responses/tool_param.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import TypeAlias + +from .computer_tool_param import ComputerToolParam +from .function_tool_param import FunctionToolParam +from .web_search_tool_param import WebSearchToolParam +from .file_search_tool_param import FileSearchToolParam +from ..chat.chat_completion_tool_param import ChatCompletionToolParam + +__all__ = ["ToolParam"] + +ToolParam: TypeAlias = Union[FileSearchToolParam, FunctionToolParam, ComputerToolParam, WebSearchToolParam] + +ParseableToolParam: TypeAlias = Union[ToolParam, ChatCompletionToolParam] diff --git a/src/openai/types/responses/web_search_tool.py b/src/openai/types/responses/web_search_tool.py new file mode 100644 index 0000000000..bee270bf85 --- /dev/null +++ b/src/openai/types/responses/web_search_tool.py @@ -0,0 +1,48 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["WebSearchTool", "UserLocation"] + + +class UserLocation(BaseModel): + type: Literal["approximate"] + """The type of location approximation. Always `approximate`.""" + + city: Optional[str] = None + """Free text input for the city of the user, e.g. `San Francisco`.""" + + country: Optional[str] = None + """ + The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of + the user, e.g. `US`. + """ + + region: Optional[str] = None + """Free text input for the region of the user, e.g. `California`.""" + + timezone: Optional[str] = None + """ + The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the + user, e.g. `America/Los_Angeles`. + """ + + +class WebSearchTool(BaseModel): + type: Literal["web_search_preview", "web_search_preview_2025_03_11"] + """The type of the web search tool. One of: + + - `web_search_preview` + - `web_search_preview_2025_03_11` + """ + + search_context_size: Optional[Literal["low", "medium", "high"]] = None + """ + High level guidance for the amount of context window space to use for the + search. One of `low`, `medium`, or `high`. `medium` is the default. + """ + + user_location: Optional[UserLocation] = None diff --git a/src/openai/types/responses/web_search_tool_param.py b/src/openai/types/responses/web_search_tool_param.py new file mode 100644 index 0000000000..8ee36ffb47 --- /dev/null +++ b/src/openai/types/responses/web_search_tool_param.py @@ -0,0 +1,48 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["WebSearchToolParam", "UserLocation"] + + +class UserLocation(TypedDict, total=False): + type: Required[Literal["approximate"]] + """The type of location approximation. Always `approximate`.""" + + city: str + """Free text input for the city of the user, e.g. `San Francisco`.""" + + country: str + """ + The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of + the user, e.g. `US`. + """ + + region: str + """Free text input for the region of the user, e.g. `California`.""" + + timezone: str + """ + The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the + user, e.g. `America/Los_Angeles`. + """ + + +class WebSearchToolParam(TypedDict, total=False): + type: Required[Literal["web_search_preview", "web_search_preview_2025_03_11"]] + """The type of the web search tool. One of: + + - `web_search_preview` + - `web_search_preview_2025_03_11` + """ + + search_context_size: Literal["low", "medium", "high"] + """ + High level guidance for the amount of context window space to use for the + search. One of `low`, `medium`, or `high`. `medium` is the default. + """ + + user_location: Optional[UserLocation] diff --git a/src/openai/types/shared/__init__.py b/src/openai/types/shared/__init__.py index 4cf367b1cc..6ccc2313cc 100644 --- a/src/openai/types/shared/__init__.py +++ b/src/openai/types/shared/__init__.py @@ -1,8 +1,12 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from .metadata import Metadata as Metadata +from .reasoning import Reasoning as Reasoning from .chat_model import ChatModel as ChatModel from .error_object import ErrorObject as ErrorObject +from .compound_filter import CompoundFilter as CompoundFilter +from .reasoning_effort import ReasoningEffort as ReasoningEffort +from .comparison_filter import ComparisonFilter as ComparisonFilter from .function_definition import FunctionDefinition as FunctionDefinition from .function_parameters import FunctionParameters as FunctionParameters from .response_format_text import ResponseFormatText as ResponseFormatText diff --git a/src/openai/types/shared/chat_model.py b/src/openai/types/shared/chat_model.py index 6fe705a0b4..31d7104e6e 100644 --- a/src/openai/types/shared/chat_model.py +++ b/src/openai/types/shared/chat_model.py @@ -13,6 +13,9 @@ "o1-preview-2024-09-12", "o1-mini", "o1-mini-2024-09-12", + "computer-use-preview", + "computer-use-preview-2025-02-04", + "computer-use-preview-2025-03-11", "gpt-4.5-preview", "gpt-4.5-preview-2025-02-27", "gpt-4o", diff --git a/src/openai/types/shared/comparison_filter.py b/src/openai/types/shared/comparison_filter.py new file mode 100644 index 0000000000..2ec2651ff2 --- /dev/null +++ b/src/openai/types/shared/comparison_filter.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ComparisonFilter"] + + +class ComparisonFilter(BaseModel): + key: str + """The key to compare against the value.""" + + type: Literal["eq", "ne", "gt", "gte", "lt", "lte"] + """Specifies the comparison operator: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`. + + - `eq`: equals + - `ne`: not equal + - `gt`: greater than + - `gte`: greater than or equal + - `lt`: less than + - `lte`: less than or equal + """ + + value: Union[str, float, bool] + """ + The value to compare against the attribute key; supports string, number, or + boolean types. + """ diff --git a/src/openai/types/shared/compound_filter.py b/src/openai/types/shared/compound_filter.py new file mode 100644 index 0000000000..3aefa43647 --- /dev/null +++ b/src/openai/types/shared/compound_filter.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union +from typing_extensions import Literal, TypeAlias + +from ..._models import BaseModel +from .comparison_filter import ComparisonFilter + +__all__ = ["CompoundFilter", "Filter"] + +Filter: TypeAlias = Union[ComparisonFilter, object] + + +class CompoundFilter(BaseModel): + filters: List[Filter] + """Array of filters to combine. + + Items can be `ComparisonFilter` or `CompoundFilter`. + """ + + type: Literal["and", "or"] + """Type of operation: `and` or `or`.""" diff --git a/src/openai/types/shared/reasoning.py b/src/openai/types/shared/reasoning.py new file mode 100644 index 0000000000..50821a1727 --- /dev/null +++ b/src/openai/types/shared/reasoning.py @@ -0,0 +1,28 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel +from .reasoning_effort import ReasoningEffort + +__all__ = ["Reasoning"] + + +class Reasoning(BaseModel): + effort: Optional[ReasoningEffort] = None + """**o-series models only** + + Constrains effort on reasoning for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + supported values are `low`, `medium`, and `high`. Reducing reasoning effort can + result in faster responses and fewer tokens used on reasoning in a response. + """ + + generate_summary: Optional[Literal["concise", "detailed"]] = None + """**o-series models only** + + A summary of the reasoning performed by the model. This can be useful for + debugging and understanding the model's reasoning process. One of `concise` or + `detailed`. + """ diff --git a/src/openai/types/shared/reasoning_effort.py b/src/openai/types/shared/reasoning_effort.py new file mode 100644 index 0000000000..ace21b67e4 --- /dev/null +++ b/src/openai/types/shared/reasoning_effort.py @@ -0,0 +1,8 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal, TypeAlias + +__all__ = ["ReasoningEffort"] + +ReasoningEffort: TypeAlias = Optional[Literal["low", "medium", "high"]] diff --git a/src/openai/types/shared/response_format_json_object.py b/src/openai/types/shared/response_format_json_object.py index 107728dd2e..2aaa5dbdfe 100644 --- a/src/openai/types/shared/response_format_json_object.py +++ b/src/openai/types/shared/response_format_json_object.py @@ -9,4 +9,4 @@ class ResponseFormatJSONObject(BaseModel): type: Literal["json_object"] - """The type of response format being defined: `json_object`""" + """The type of response format being defined. Always `json_object`.""" diff --git a/src/openai/types/shared/response_format_json_schema.py b/src/openai/types/shared/response_format_json_schema.py index 3194a4fe91..c7924446f4 100644 --- a/src/openai/types/shared/response_format_json_schema.py +++ b/src/openai/types/shared/response_format_json_schema.py @@ -25,20 +25,24 @@ class JSONSchema(BaseModel): """ schema_: Optional[Dict[str, object]] = FieldInfo(alias="schema", default=None) - """The schema for the response format, described as a JSON Schema object.""" + """ + The schema for the response format, described as a JSON Schema object. Learn how + to build JSON schemas [here](https://json-schema.org/). + """ strict: Optional[bool] = None - """Whether to enable strict schema adherence when generating the output. - - If set to true, the model will always follow the exact schema defined in the - `schema` field. Only a subset of JSON Schema is supported when `strict` is - `true`. To learn more, read the + """ + Whether to enable strict schema adherence when generating the output. If set to + true, the model will always follow the exact schema defined in the `schema` + field. Only a subset of JSON Schema is supported when `strict` is `true`. To + learn more, read the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). """ class ResponseFormatJSONSchema(BaseModel): json_schema: JSONSchema + """Structured Outputs configuration options, including a JSON Schema.""" type: Literal["json_schema"] - """The type of response format being defined: `json_schema`""" + """The type of response format being defined. Always `json_schema`.""" diff --git a/src/openai/types/shared/response_format_text.py b/src/openai/types/shared/response_format_text.py index 6721fe0973..f0c8cfb700 100644 --- a/src/openai/types/shared/response_format_text.py +++ b/src/openai/types/shared/response_format_text.py @@ -9,4 +9,4 @@ class ResponseFormatText(BaseModel): type: Literal["text"] - """The type of response format being defined: `text`""" + """The type of response format being defined. Always `text`.""" diff --git a/src/openai/types/shared_params/__init__.py b/src/openai/types/shared_params/__init__.py index 47a747b2d4..4a4a8cdf1e 100644 --- a/src/openai/types/shared_params/__init__.py +++ b/src/openai/types/shared_params/__init__.py @@ -1,7 +1,11 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from .metadata import Metadata as Metadata +from .reasoning import Reasoning as Reasoning from .chat_model import ChatModel as ChatModel +from .compound_filter import CompoundFilter as CompoundFilter +from .reasoning_effort import ReasoningEffort as ReasoningEffort +from .comparison_filter import ComparisonFilter as ComparisonFilter from .function_definition import FunctionDefinition as FunctionDefinition from .function_parameters import FunctionParameters as FunctionParameters from .response_format_text import ResponseFormatText as ResponseFormatText diff --git a/src/openai/types/shared_params/chat_model.py b/src/openai/types/shared_params/chat_model.py index 0ac3f31611..55649876eb 100644 --- a/src/openai/types/shared_params/chat_model.py +++ b/src/openai/types/shared_params/chat_model.py @@ -15,6 +15,9 @@ "o1-preview-2024-09-12", "o1-mini", "o1-mini-2024-09-12", + "computer-use-preview", + "computer-use-preview-2025-02-04", + "computer-use-preview-2025-03-11", "gpt-4.5-preview", "gpt-4.5-preview-2025-02-27", "gpt-4o", diff --git a/src/openai/types/shared_params/comparison_filter.py b/src/openai/types/shared_params/comparison_filter.py new file mode 100644 index 0000000000..38edd315ed --- /dev/null +++ b/src/openai/types/shared_params/comparison_filter.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ComparisonFilter"] + + +class ComparisonFilter(TypedDict, total=False): + key: Required[str] + """The key to compare against the value.""" + + type: Required[Literal["eq", "ne", "gt", "gte", "lt", "lte"]] + """Specifies the comparison operator: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`. + + - `eq`: equals + - `ne`: not equal + - `gt`: greater than + - `gte`: greater than or equal + - `lt`: less than + - `lte`: less than or equal + """ + + value: Required[Union[str, float, bool]] + """ + The value to compare against the attribute key; supports string, number, or + boolean types. + """ diff --git a/src/openai/types/shared_params/compound_filter.py b/src/openai/types/shared_params/compound_filter.py new file mode 100644 index 0000000000..d12e9b1bda --- /dev/null +++ b/src/openai/types/shared_params/compound_filter.py @@ -0,0 +1,23 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .comparison_filter import ComparisonFilter + +__all__ = ["CompoundFilter", "Filter"] + +Filter: TypeAlias = Union[ComparisonFilter, object] + + +class CompoundFilter(TypedDict, total=False): + filters: Required[Iterable[Filter]] + """Array of filters to combine. + + Items can be `ComparisonFilter` or `CompoundFilter`. + """ + + type: Required[Literal["and", "or"]] + """Type of operation: `and` or `or`.""" diff --git a/src/openai/types/shared_params/reasoning.py b/src/openai/types/shared_params/reasoning.py new file mode 100644 index 0000000000..f2b5c5963a --- /dev/null +++ b/src/openai/types/shared_params/reasoning.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, Required, TypedDict + +from ..shared.reasoning_effort import ReasoningEffort + +__all__ = ["Reasoning"] + + +class Reasoning(TypedDict, total=False): + effort: Required[Optional[ReasoningEffort]] + """**o-series models only** + + Constrains effort on reasoning for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently + supported values are `low`, `medium`, and `high`. Reducing reasoning effort can + result in faster responses and fewer tokens used on reasoning in a response. + """ + + generate_summary: Optional[Literal["concise", "detailed"]] + """**o-series models only** + + A summary of the reasoning performed by the model. This can be useful for + debugging and understanding the model's reasoning process. One of `concise` or + `detailed`. + """ diff --git a/src/openai/types/shared_params/reasoning_effort.py b/src/openai/types/shared_params/reasoning_effort.py new file mode 100644 index 0000000000..6052c5ae15 --- /dev/null +++ b/src/openai/types/shared_params/reasoning_effort.py @@ -0,0 +1,10 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal, TypeAlias + +__all__ = ["ReasoningEffort"] + +ReasoningEffort: TypeAlias = Optional[Literal["low", "medium", "high"]] diff --git a/src/openai/types/shared_params/response_format_json_object.py b/src/openai/types/shared_params/response_format_json_object.py index 8419c6cb56..d4d1deaae5 100644 --- a/src/openai/types/shared_params/response_format_json_object.py +++ b/src/openai/types/shared_params/response_format_json_object.py @@ -9,4 +9,4 @@ class ResponseFormatJSONObject(TypedDict, total=False): type: Required[Literal["json_object"]] - """The type of response format being defined: `json_object`""" + """The type of response format being defined. Always `json_object`.""" diff --git a/src/openai/types/shared_params/response_format_json_schema.py b/src/openai/types/shared_params/response_format_json_schema.py index 4b60fae8ee..5b0a13ee06 100644 --- a/src/openai/types/shared_params/response_format_json_schema.py +++ b/src/openai/types/shared_params/response_format_json_schema.py @@ -23,20 +23,24 @@ class JSONSchema(TypedDict, total=False): """ schema: Dict[str, object] - """The schema for the response format, described as a JSON Schema object.""" + """ + The schema for the response format, described as a JSON Schema object. Learn how + to build JSON schemas [here](https://json-schema.org/). + """ strict: Optional[bool] - """Whether to enable strict schema adherence when generating the output. - - If set to true, the model will always follow the exact schema defined in the - `schema` field. Only a subset of JSON Schema is supported when `strict` is - `true`. To learn more, read the + """ + Whether to enable strict schema adherence when generating the output. If set to + true, the model will always follow the exact schema defined in the `schema` + field. Only a subset of JSON Schema is supported when `strict` is `true`. To + learn more, read the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). """ class ResponseFormatJSONSchema(TypedDict, total=False): json_schema: Required[JSONSchema] + """Structured Outputs configuration options, including a JSON Schema.""" type: Required[Literal["json_schema"]] - """The type of response format being defined: `json_schema`""" + """The type of response format being defined. Always `json_schema`.""" diff --git a/src/openai/types/shared_params/response_format_text.py b/src/openai/types/shared_params/response_format_text.py index 5bec7fc503..c3ef2b0816 100644 --- a/src/openai/types/shared_params/response_format_text.py +++ b/src/openai/types/shared_params/response_format_text.py @@ -9,4 +9,4 @@ class ResponseFormatText(TypedDict, total=False): type: Required[Literal["text"]] - """The type of response format being defined: `text`""" + """The type of response format being defined. Always `text`.""" diff --git a/src/openai/types/beta/static_file_chunking_strategy.py b/src/openai/types/static_file_chunking_strategy.py similarity index 94% rename from src/openai/types/beta/static_file_chunking_strategy.py rename to src/openai/types/static_file_chunking_strategy.py index 6080093517..2813bc6630 100644 --- a/src/openai/types/beta/static_file_chunking_strategy.py +++ b/src/openai/types/static_file_chunking_strategy.py @@ -1,7 +1,7 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from ..._models import BaseModel +from .._models import BaseModel __all__ = ["StaticFileChunkingStrategy"] diff --git a/src/openai/types/beta/static_file_chunking_strategy_object.py b/src/openai/types/static_file_chunking_strategy_object.py similarity index 92% rename from src/openai/types/beta/static_file_chunking_strategy_object.py rename to src/openai/types/static_file_chunking_strategy_object.py index 896c4b8320..2a95dce5b3 100644 --- a/src/openai/types/beta/static_file_chunking_strategy_object.py +++ b/src/openai/types/static_file_chunking_strategy_object.py @@ -2,7 +2,7 @@ from typing_extensions import Literal -from ..._models import BaseModel +from .._models import BaseModel from .static_file_chunking_strategy import StaticFileChunkingStrategy __all__ = ["StaticFileChunkingStrategyObject"] diff --git a/src/openai/types/beta/static_file_chunking_strategy_object_param.py b/src/openai/types/static_file_chunking_strategy_object_param.py similarity index 100% rename from src/openai/types/beta/static_file_chunking_strategy_object_param.py rename to src/openai/types/static_file_chunking_strategy_object_param.py diff --git a/src/openai/types/beta/static_file_chunking_strategy_param.py b/src/openai/types/static_file_chunking_strategy_param.py similarity index 100% rename from src/openai/types/beta/static_file_chunking_strategy_param.py rename to src/openai/types/static_file_chunking_strategy_param.py diff --git a/src/openai/types/beta/vector_store.py b/src/openai/types/vector_store.py similarity index 97% rename from src/openai/types/beta/vector_store.py rename to src/openai/types/vector_store.py index b947dfb79d..2473a442d2 100644 --- a/src/openai/types/beta/vector_store.py +++ b/src/openai/types/vector_store.py @@ -3,8 +3,8 @@ from typing import Optional from typing_extensions import Literal -from ..._models import BaseModel -from ..shared.metadata import Metadata +from .._models import BaseModel +from .shared.metadata import Metadata __all__ = ["VectorStore", "FileCounts", "ExpiresAfter"] diff --git a/src/openai/types/beta/vector_store_create_params.py b/src/openai/types/vector_store_create_params.py similarity index 97% rename from src/openai/types/beta/vector_store_create_params.py rename to src/openai/types/vector_store_create_params.py index faca6d9000..365d0936b1 100644 --- a/src/openai/types/beta/vector_store_create_params.py +++ b/src/openai/types/vector_store_create_params.py @@ -5,7 +5,7 @@ from typing import List, Optional from typing_extensions import Literal, Required, TypedDict -from ..shared_params.metadata import Metadata +from .shared_params.metadata import Metadata from .file_chunking_strategy_param import FileChunkingStrategyParam __all__ = ["VectorStoreCreateParams", "ExpiresAfter"] diff --git a/src/openai/types/beta/vector_store_deleted.py b/src/openai/types/vector_store_deleted.py similarity index 89% rename from src/openai/types/beta/vector_store_deleted.py rename to src/openai/types/vector_store_deleted.py index 21ccda1db5..dfac9ce8bd 100644 --- a/src/openai/types/beta/vector_store_deleted.py +++ b/src/openai/types/vector_store_deleted.py @@ -2,7 +2,7 @@ from typing_extensions import Literal -from ..._models import BaseModel +from .._models import BaseModel __all__ = ["VectorStoreDeleted"] diff --git a/src/openai/types/beta/vector_store_list_params.py b/src/openai/types/vector_store_list_params.py similarity index 100% rename from src/openai/types/beta/vector_store_list_params.py rename to src/openai/types/vector_store_list_params.py diff --git a/src/openai/types/vector_store_search_params.py b/src/openai/types/vector_store_search_params.py new file mode 100644 index 0000000000..17573d0f61 --- /dev/null +++ b/src/openai/types/vector_store_search_params.py @@ -0,0 +1,40 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Union +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .shared_params.compound_filter import CompoundFilter +from .shared_params.comparison_filter import ComparisonFilter + +__all__ = ["VectorStoreSearchParams", "Filters", "RankingOptions"] + + +class VectorStoreSearchParams(TypedDict, total=False): + query: Required[Union[str, List[str]]] + """A query string for a search""" + + filters: Filters + """A filter to apply based on file attributes.""" + + max_num_results: int + """The maximum number of results to return. + + This number should be between 1 and 50 inclusive. + """ + + ranking_options: RankingOptions + """Ranking options for search.""" + + rewrite_query: bool + """Whether to rewrite the natural language query for vector search.""" + + +Filters: TypeAlias = Union[ComparisonFilter, CompoundFilter] + + +class RankingOptions(TypedDict, total=False): + ranker: Literal["auto", "default-2024-11-15"] + + score_threshold: float diff --git a/src/openai/types/vector_store_search_response.py b/src/openai/types/vector_store_search_response.py new file mode 100644 index 0000000000..d78b71bfba --- /dev/null +++ b/src/openai/types/vector_store_search_response.py @@ -0,0 +1,39 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, List, Union, Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["VectorStoreSearchResponse", "Content"] + + +class Content(BaseModel): + text: str + """The text content returned from search.""" + + type: Literal["text"] + """The type of content.""" + + +class VectorStoreSearchResponse(BaseModel): + attributes: Optional[Dict[str, Union[str, float, bool]]] = None + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. Keys are + strings with a maximum length of 64 characters. Values are strings with a + maximum length of 512 characters, booleans, or numbers. + """ + + content: List[Content] + """Content chunks from the file.""" + + file_id: str + """The ID of the vector store file.""" + + filename: str + """The name of the vector store file.""" + + score: float + """The similarity score for the result.""" diff --git a/src/openai/types/beta/vector_store_update_params.py b/src/openai/types/vector_store_update_params.py similarity index 96% rename from src/openai/types/beta/vector_store_update_params.py rename to src/openai/types/vector_store_update_params.py index e91b3ba5ad..4f6ac63963 100644 --- a/src/openai/types/beta/vector_store_update_params.py +++ b/src/openai/types/vector_store_update_params.py @@ -5,7 +5,7 @@ from typing import Optional from typing_extensions import Literal, Required, TypedDict -from ..shared_params.metadata import Metadata +from .shared_params.metadata import Metadata __all__ = ["VectorStoreUpdateParams", "ExpiresAfter"] diff --git a/src/openai/types/beta/vector_stores/__init__.py b/src/openai/types/vector_stores/__init__.py similarity index 82% rename from src/openai/types/beta/vector_stores/__init__.py rename to src/openai/types/vector_stores/__init__.py index ff05dd63d8..96ce301481 100644 --- a/src/openai/types/beta/vector_stores/__init__.py +++ b/src/openai/types/vector_stores/__init__.py @@ -5,6 +5,8 @@ from .file_list_params import FileListParams as FileListParams from .vector_store_file import VectorStoreFile as VectorStoreFile from .file_create_params import FileCreateParams as FileCreateParams +from .file_update_params import FileUpdateParams as FileUpdateParams +from .file_content_response import FileContentResponse as FileContentResponse from .vector_store_file_batch import VectorStoreFileBatch as VectorStoreFileBatch from .file_batch_create_params import FileBatchCreateParams as FileBatchCreateParams from .vector_store_file_deleted import VectorStoreFileDeleted as VectorStoreFileDeleted diff --git a/src/openai/types/beta/vector_stores/file_batch_create_params.py b/src/openai/types/vector_stores/file_batch_create_params.py similarity index 61% rename from src/openai/types/beta/vector_stores/file_batch_create_params.py rename to src/openai/types/vector_stores/file_batch_create_params.py index e42ea99cd1..1a470f757a 100644 --- a/src/openai/types/beta/vector_stores/file_batch_create_params.py +++ b/src/openai/types/vector_stores/file_batch_create_params.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import List +from typing import Dict, List, Union, Optional from typing_extensions import Required, TypedDict from ..file_chunking_strategy_param import FileChunkingStrategyParam @@ -18,6 +18,15 @@ class FileBatchCreateParams(TypedDict, total=False): files. """ + attributes: Optional[Dict[str, Union[str, float, bool]]] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. Keys are + strings with a maximum length of 64 characters. Values are strings with a + maximum length of 512 characters, booleans, or numbers. + """ + chunking_strategy: FileChunkingStrategyParam """The chunking strategy used to chunk the file(s). diff --git a/src/openai/types/beta/vector_stores/file_batch_list_files_params.py b/src/openai/types/vector_stores/file_batch_list_files_params.py similarity index 100% rename from src/openai/types/beta/vector_stores/file_batch_list_files_params.py rename to src/openai/types/vector_stores/file_batch_list_files_params.py diff --git a/src/openai/types/vector_stores/file_content_response.py b/src/openai/types/vector_stores/file_content_response.py new file mode 100644 index 0000000000..32db2f2ce9 --- /dev/null +++ b/src/openai/types/vector_stores/file_content_response.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from ..._models import BaseModel + +__all__ = ["FileContentResponse"] + + +class FileContentResponse(BaseModel): + text: Optional[str] = None + """The text content""" + + type: Optional[str] = None + """The content type (currently only `"text"`)""" diff --git a/src/openai/types/beta/vector_stores/file_create_params.py b/src/openai/types/vector_stores/file_create_params.py similarity index 60% rename from src/openai/types/beta/vector_stores/file_create_params.py rename to src/openai/types/vector_stores/file_create_params.py index d074d766e6..5b8989251a 100644 --- a/src/openai/types/beta/vector_stores/file_create_params.py +++ b/src/openai/types/vector_stores/file_create_params.py @@ -2,6 +2,7 @@ from __future__ import annotations +from typing import Dict, Union, Optional from typing_extensions import Required, TypedDict from ..file_chunking_strategy_param import FileChunkingStrategyParam @@ -17,6 +18,15 @@ class FileCreateParams(TypedDict, total=False): files. """ + attributes: Optional[Dict[str, Union[str, float, bool]]] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. Keys are + strings with a maximum length of 64 characters. Values are strings with a + maximum length of 512 characters, booleans, or numbers. + """ + chunking_strategy: FileChunkingStrategyParam """The chunking strategy used to chunk the file(s). diff --git a/src/openai/types/beta/vector_stores/file_list_params.py b/src/openai/types/vector_stores/file_list_params.py similarity index 100% rename from src/openai/types/beta/vector_stores/file_list_params.py rename to src/openai/types/vector_stores/file_list_params.py diff --git a/src/openai/types/vector_stores/file_update_params.py b/src/openai/types/vector_stores/file_update_params.py new file mode 100644 index 0000000000..ebf540d046 --- /dev/null +++ b/src/openai/types/vector_stores/file_update_params.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Union, Optional +from typing_extensions import Required, TypedDict + +__all__ = ["FileUpdateParams"] + + +class FileUpdateParams(TypedDict, total=False): + vector_store_id: Required[str] + + attributes: Required[Optional[Dict[str, Union[str, float, bool]]]] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. Keys are + strings with a maximum length of 64 characters. Values are strings with a + maximum length of 512 characters, booleans, or numbers. + """ diff --git a/src/openai/types/beta/vector_stores/vector_store_file.py b/src/openai/types/vector_stores/vector_store_file.py similarity index 76% rename from src/openai/types/beta/vector_stores/vector_store_file.py rename to src/openai/types/vector_stores/vector_store_file.py index e4608e159c..b59a61dfb0 100644 --- a/src/openai/types/beta/vector_stores/vector_store_file.py +++ b/src/openai/types/vector_stores/vector_store_file.py @@ -1,9 +1,9 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing import Optional +from typing import Dict, Union, Optional from typing_extensions import Literal -from ...._models import BaseModel +from ..._models import BaseModel from ..file_chunking_strategy import FileChunkingStrategy __all__ = ["VectorStoreFile", "LastError"] @@ -54,5 +54,14 @@ class VectorStoreFile(BaseModel): attached to. """ + attributes: Optional[Dict[str, Union[str, float, bool]]] = None + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. Keys are + strings with a maximum length of 64 characters. Values are strings with a + maximum length of 512 characters, booleans, or numbers. + """ + chunking_strategy: Optional[FileChunkingStrategy] = None """The strategy used to chunk the file.""" diff --git a/src/openai/types/beta/vector_stores/vector_store_file_batch.py b/src/openai/types/vector_stores/vector_store_file_batch.py similarity index 97% rename from src/openai/types/beta/vector_stores/vector_store_file_batch.py rename to src/openai/types/vector_stores/vector_store_file_batch.py index df130a58de..57dbfbd809 100644 --- a/src/openai/types/beta/vector_stores/vector_store_file_batch.py +++ b/src/openai/types/vector_stores/vector_store_file_batch.py @@ -2,7 +2,7 @@ from typing_extensions import Literal -from ...._models import BaseModel +from ..._models import BaseModel __all__ = ["VectorStoreFileBatch", "FileCounts"] diff --git a/src/openai/types/beta/vector_stores/vector_store_file_deleted.py b/src/openai/types/vector_stores/vector_store_file_deleted.py similarity index 89% rename from src/openai/types/beta/vector_stores/vector_store_file_deleted.py rename to src/openai/types/vector_stores/vector_store_file_deleted.py index ae37f84364..5c856f26cd 100644 --- a/src/openai/types/beta/vector_stores/vector_store_file_deleted.py +++ b/src/openai/types/vector_stores/vector_store_file_deleted.py @@ -2,7 +2,7 @@ from typing_extensions import Literal -from ...._models import BaseModel +from ..._models import BaseModel __all__ = ["VectorStoreFileDeleted"] diff --git a/tests/api_resources/beta/vector_stores/test_files.py b/tests/api_resources/beta/vector_stores/test_files.py deleted file mode 100644 index 36622e699b..0000000000 --- a/tests/api_resources/beta/vector_stores/test_files.py +++ /dev/null @@ -1,420 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -from __future__ import annotations - -import os -from typing import Any, cast - -import pytest - -from openai import OpenAI, AsyncOpenAI -from tests.utils import assert_matches_type -from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta.vector_stores import ( - VectorStoreFile, - VectorStoreFileDeleted, -) - -base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") - - -class TestFiles: - parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) - - @parametrize - def test_method_create(self, client: OpenAI) -> None: - file = client.beta.vector_stores.files.create( - "vs_abc123", - file_id="string", - ) - assert_matches_type(VectorStoreFile, file, path=["response"]) - - @parametrize - def test_method_create_with_all_params(self, client: OpenAI) -> None: - file = client.beta.vector_stores.files.create( - "vs_abc123", - file_id="string", - chunking_strategy={"type": "auto"}, - ) - assert_matches_type(VectorStoreFile, file, path=["response"]) - - @parametrize - def test_raw_response_create(self, client: OpenAI) -> None: - response = client.beta.vector_stores.files.with_raw_response.create( - "vs_abc123", - file_id="string", - ) - - assert response.is_closed is True - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - file = response.parse() - assert_matches_type(VectorStoreFile, file, path=["response"]) - - @parametrize - def test_streaming_response_create(self, client: OpenAI) -> None: - with client.beta.vector_stores.files.with_streaming_response.create( - "vs_abc123", - file_id="string", - ) as response: - assert not response.is_closed - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - - file = response.parse() - assert_matches_type(VectorStoreFile, file, path=["response"]) - - assert cast(Any, response.is_closed) is True - - @parametrize - def test_path_params_create(self, client: OpenAI) -> None: - with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): - client.beta.vector_stores.files.with_raw_response.create( - "", - file_id="string", - ) - - @parametrize - def test_method_retrieve(self, client: OpenAI) -> None: - file = client.beta.vector_stores.files.retrieve( - "file-abc123", - vector_store_id="vs_abc123", - ) - assert_matches_type(VectorStoreFile, file, path=["response"]) - - @parametrize - def test_raw_response_retrieve(self, client: OpenAI) -> None: - response = client.beta.vector_stores.files.with_raw_response.retrieve( - "file-abc123", - vector_store_id="vs_abc123", - ) - - assert response.is_closed is True - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - file = response.parse() - assert_matches_type(VectorStoreFile, file, path=["response"]) - - @parametrize - def test_streaming_response_retrieve(self, client: OpenAI) -> None: - with client.beta.vector_stores.files.with_streaming_response.retrieve( - "file-abc123", - vector_store_id="vs_abc123", - ) as response: - assert not response.is_closed - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - - file = response.parse() - assert_matches_type(VectorStoreFile, file, path=["response"]) - - assert cast(Any, response.is_closed) is True - - @parametrize - def test_path_params_retrieve(self, client: OpenAI) -> None: - with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): - client.beta.vector_stores.files.with_raw_response.retrieve( - "file-abc123", - vector_store_id="", - ) - - with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): - client.beta.vector_stores.files.with_raw_response.retrieve( - "", - vector_store_id="vs_abc123", - ) - - @parametrize - def test_method_list(self, client: OpenAI) -> None: - file = client.beta.vector_stores.files.list( - "string", - ) - assert_matches_type(SyncCursorPage[VectorStoreFile], file, path=["response"]) - - @parametrize - def test_method_list_with_all_params(self, client: OpenAI) -> None: - file = client.beta.vector_stores.files.list( - "string", - after="string", - before="string", - filter="in_progress", - limit=0, - order="asc", - ) - assert_matches_type(SyncCursorPage[VectorStoreFile], file, path=["response"]) - - @parametrize - def test_raw_response_list(self, client: OpenAI) -> None: - response = client.beta.vector_stores.files.with_raw_response.list( - "string", - ) - - assert response.is_closed is True - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - file = response.parse() - assert_matches_type(SyncCursorPage[VectorStoreFile], file, path=["response"]) - - @parametrize - def test_streaming_response_list(self, client: OpenAI) -> None: - with client.beta.vector_stores.files.with_streaming_response.list( - "string", - ) as response: - assert not response.is_closed - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - - file = response.parse() - assert_matches_type(SyncCursorPage[VectorStoreFile], file, path=["response"]) - - assert cast(Any, response.is_closed) is True - - @parametrize - def test_path_params_list(self, client: OpenAI) -> None: - with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): - client.beta.vector_stores.files.with_raw_response.list( - "", - ) - - @parametrize - def test_method_delete(self, client: OpenAI) -> None: - file = client.beta.vector_stores.files.delete( - "string", - vector_store_id="string", - ) - assert_matches_type(VectorStoreFileDeleted, file, path=["response"]) - - @parametrize - def test_raw_response_delete(self, client: OpenAI) -> None: - response = client.beta.vector_stores.files.with_raw_response.delete( - "string", - vector_store_id="string", - ) - - assert response.is_closed is True - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - file = response.parse() - assert_matches_type(VectorStoreFileDeleted, file, path=["response"]) - - @parametrize - def test_streaming_response_delete(self, client: OpenAI) -> None: - with client.beta.vector_stores.files.with_streaming_response.delete( - "string", - vector_store_id="string", - ) as response: - assert not response.is_closed - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - - file = response.parse() - assert_matches_type(VectorStoreFileDeleted, file, path=["response"]) - - assert cast(Any, response.is_closed) is True - - @parametrize - def test_path_params_delete(self, client: OpenAI) -> None: - with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): - client.beta.vector_stores.files.with_raw_response.delete( - "string", - vector_store_id="", - ) - - with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): - client.beta.vector_stores.files.with_raw_response.delete( - "", - vector_store_id="string", - ) - - -class TestAsyncFiles: - parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) - - @parametrize - async def test_method_create(self, async_client: AsyncOpenAI) -> None: - file = await async_client.beta.vector_stores.files.create( - "vs_abc123", - file_id="string", - ) - assert_matches_type(VectorStoreFile, file, path=["response"]) - - @parametrize - async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: - file = await async_client.beta.vector_stores.files.create( - "vs_abc123", - file_id="string", - chunking_strategy={"type": "auto"}, - ) - assert_matches_type(VectorStoreFile, file, path=["response"]) - - @parametrize - async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: - response = await async_client.beta.vector_stores.files.with_raw_response.create( - "vs_abc123", - file_id="string", - ) - - assert response.is_closed is True - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - file = response.parse() - assert_matches_type(VectorStoreFile, file, path=["response"]) - - @parametrize - async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: - async with async_client.beta.vector_stores.files.with_streaming_response.create( - "vs_abc123", - file_id="string", - ) as response: - assert not response.is_closed - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - - file = await response.parse() - assert_matches_type(VectorStoreFile, file, path=["response"]) - - assert cast(Any, response.is_closed) is True - - @parametrize - async def test_path_params_create(self, async_client: AsyncOpenAI) -> None: - with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): - await async_client.beta.vector_stores.files.with_raw_response.create( - "", - file_id="string", - ) - - @parametrize - async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: - file = await async_client.beta.vector_stores.files.retrieve( - "file-abc123", - vector_store_id="vs_abc123", - ) - assert_matches_type(VectorStoreFile, file, path=["response"]) - - @parametrize - async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: - response = await async_client.beta.vector_stores.files.with_raw_response.retrieve( - "file-abc123", - vector_store_id="vs_abc123", - ) - - assert response.is_closed is True - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - file = response.parse() - assert_matches_type(VectorStoreFile, file, path=["response"]) - - @parametrize - async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: - async with async_client.beta.vector_stores.files.with_streaming_response.retrieve( - "file-abc123", - vector_store_id="vs_abc123", - ) as response: - assert not response.is_closed - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - - file = await response.parse() - assert_matches_type(VectorStoreFile, file, path=["response"]) - - assert cast(Any, response.is_closed) is True - - @parametrize - async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: - with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): - await async_client.beta.vector_stores.files.with_raw_response.retrieve( - "file-abc123", - vector_store_id="", - ) - - with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): - await async_client.beta.vector_stores.files.with_raw_response.retrieve( - "", - vector_store_id="vs_abc123", - ) - - @parametrize - async def test_method_list(self, async_client: AsyncOpenAI) -> None: - file = await async_client.beta.vector_stores.files.list( - "string", - ) - assert_matches_type(AsyncCursorPage[VectorStoreFile], file, path=["response"]) - - @parametrize - async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: - file = await async_client.beta.vector_stores.files.list( - "string", - after="string", - before="string", - filter="in_progress", - limit=0, - order="asc", - ) - assert_matches_type(AsyncCursorPage[VectorStoreFile], file, path=["response"]) - - @parametrize - async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: - response = await async_client.beta.vector_stores.files.with_raw_response.list( - "string", - ) - - assert response.is_closed is True - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - file = response.parse() - assert_matches_type(AsyncCursorPage[VectorStoreFile], file, path=["response"]) - - @parametrize - async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: - async with async_client.beta.vector_stores.files.with_streaming_response.list( - "string", - ) as response: - assert not response.is_closed - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - - file = await response.parse() - assert_matches_type(AsyncCursorPage[VectorStoreFile], file, path=["response"]) - - assert cast(Any, response.is_closed) is True - - @parametrize - async def test_path_params_list(self, async_client: AsyncOpenAI) -> None: - with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): - await async_client.beta.vector_stores.files.with_raw_response.list( - "", - ) - - @parametrize - async def test_method_delete(self, async_client: AsyncOpenAI) -> None: - file = await async_client.beta.vector_stores.files.delete( - "string", - vector_store_id="string", - ) - assert_matches_type(VectorStoreFileDeleted, file, path=["response"]) - - @parametrize - async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None: - response = await async_client.beta.vector_stores.files.with_raw_response.delete( - "string", - vector_store_id="string", - ) - - assert response.is_closed is True - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - file = response.parse() - assert_matches_type(VectorStoreFileDeleted, file, path=["response"]) - - @parametrize - async def test_streaming_response_delete(self, async_client: AsyncOpenAI) -> None: - async with async_client.beta.vector_stores.files.with_streaming_response.delete( - "string", - vector_store_id="string", - ) as response: - assert not response.is_closed - assert response.http_request.headers.get("X-Stainless-Lang") == "python" - - file = await response.parse() - assert_matches_type(VectorStoreFileDeleted, file, path=["response"]) - - assert cast(Any, response.is_closed) is True - - @parametrize - async def test_path_params_delete(self, async_client: AsyncOpenAI) -> None: - with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): - await async_client.beta.vector_stores.files.with_raw_response.delete( - "string", - vector_store_id="", - ) - - with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): - await async_client.beta.vector_stores.files.with_raw_response.delete( - "", - vector_store_id="string", - ) diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index 48b687a70e..d4ccc494dd 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -74,9 +74,9 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: presence_penalty=-2, reasoning_effort="low", response_format={"type": "text"}, - seed=0, + seed=-9007199254740991, service_tier="auto", - stop="string", + stop="\n", store=True, stream=False, stream_options={"include_usage": True}, @@ -96,6 +96,18 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: top_logprobs=0, top_p=1, user="user-1234", + web_search_options={ + "search_context_size": "low", + "user_location": { + "approximate": { + "city": "city", + "country": "country", + "region": "region", + "timezone": "timezone", + }, + "type": "approximate", + }, + }, ) assert_matches_type(ChatCompletion, completion, path=["response"]) @@ -189,9 +201,9 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: presence_penalty=-2, reasoning_effort="low", response_format={"type": "text"}, - seed=0, + seed=-9007199254740991, service_tier="auto", - stop="string", + stop="\n", store=True, stream_options={"include_usage": True}, temperature=1, @@ -210,6 +222,18 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: top_logprobs=0, top_p=1, user="user-1234", + web_search_options={ + "search_context_size": "low", + "user_location": { + "approximate": { + "city": "city", + "country": "country", + "region": "region", + "timezone": "timezone", + }, + "type": "approximate", + }, + }, ) completion_stream.response.close() @@ -477,9 +501,9 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn presence_penalty=-2, reasoning_effort="low", response_format={"type": "text"}, - seed=0, + seed=-9007199254740991, service_tier="auto", - stop="string", + stop="\n", store=True, stream=False, stream_options={"include_usage": True}, @@ -499,6 +523,18 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn top_logprobs=0, top_p=1, user="user-1234", + web_search_options={ + "search_context_size": "low", + "user_location": { + "approximate": { + "city": "city", + "country": "country", + "region": "region", + "timezone": "timezone", + }, + "type": "approximate", + }, + }, ) assert_matches_type(ChatCompletion, completion, path=["response"]) @@ -592,9 +628,9 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn presence_penalty=-2, reasoning_effort="low", response_format={"type": "text"}, - seed=0, + seed=-9007199254740991, service_tier="auto", - stop="string", + stop="\n", store=True, stream_options={"include_usage": True}, temperature=1, @@ -613,6 +649,18 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn top_logprobs=0, top_p=1, user="user-1234", + web_search_options={ + "search_context_size": "low", + "user_location": { + "approximate": { + "city": "city", + "country": "country", + "region": "region", + "timezone": "timezone", + }, + "type": "approximate", + }, + }, ) await completion_stream.response.aclose() diff --git a/tests/api_resources/beta/vector_stores/__init__.py b/tests/api_resources/responses/__init__.py similarity index 100% rename from tests/api_resources/beta/vector_stores/__init__.py rename to tests/api_resources/responses/__init__.py diff --git a/tests/api_resources/responses/test_input_items.py b/tests/api_resources/responses/test_input_items.py new file mode 100644 index 0000000000..28c5e8ca1f --- /dev/null +++ b/tests/api_resources/responses/test_input_items.py @@ -0,0 +1,121 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai.pagination import SyncCursorPage, AsyncCursorPage +from openai.types.responses.response_item_list import Data + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") + + +class TestInputItems: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + def test_method_list(self, client: OpenAI) -> None: + input_item = client.responses.input_items.list( + response_id="response_id", + ) + assert_matches_type(SyncCursorPage[Data], input_item, path=["response"]) + + @parametrize + def test_method_list_with_all_params(self, client: OpenAI) -> None: + input_item = client.responses.input_items.list( + response_id="response_id", + after="after", + before="before", + limit=0, + order="asc", + ) + assert_matches_type(SyncCursorPage[Data], input_item, path=["response"]) + + @parametrize + def test_raw_response_list(self, client: OpenAI) -> None: + response = client.responses.input_items.with_raw_response.list( + response_id="response_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + input_item = response.parse() + assert_matches_type(SyncCursorPage[Data], input_item, path=["response"]) + + @parametrize + def test_streaming_response_list(self, client: OpenAI) -> None: + with client.responses.input_items.with_streaming_response.list( + response_id="response_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + input_item = response.parse() + assert_matches_type(SyncCursorPage[Data], input_item, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_list(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `response_id` but received ''"): + client.responses.input_items.with_raw_response.list( + response_id="", + ) + + +class TestAsyncInputItems: + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + async def test_method_list(self, async_client: AsyncOpenAI) -> None: + input_item = await async_client.responses.input_items.list( + response_id="response_id", + ) + assert_matches_type(AsyncCursorPage[Data], input_item, path=["response"]) + + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: + input_item = await async_client.responses.input_items.list( + response_id="response_id", + after="after", + before="before", + limit=0, + order="asc", + ) + assert_matches_type(AsyncCursorPage[Data], input_item, path=["response"]) + + @parametrize + async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: + response = await async_client.responses.input_items.with_raw_response.list( + response_id="response_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + input_item = response.parse() + assert_matches_type(AsyncCursorPage[Data], input_item, path=["response"]) + + @parametrize + async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: + async with async_client.responses.input_items.with_streaming_response.list( + response_id="response_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + input_item = await response.parse() + assert_matches_type(AsyncCursorPage[Data], input_item, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_list(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `response_id` but received ''"): + await async_client.responses.input_items.with_raw_response.list( + response_id="", + ) diff --git a/tests/api_resources/test_responses.py b/tests/api_resources/test_responses.py new file mode 100644 index 0000000000..e45a5becf3 --- /dev/null +++ b/tests/api_resources/test_responses.py @@ -0,0 +1,498 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai.types.responses import Response + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") + + +class TestResponses: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + def test_method_create_overload_1(self, client: OpenAI) -> None: + response = client.responses.create( + input="string", + model="gpt-4o", + ) + assert_matches_type(Response, response, path=["response"]) + + @parametrize + def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: + response = client.responses.create( + input="string", + model="gpt-4o", + include=["file_search_call.results"], + instructions="instructions", + max_output_tokens=0, + metadata={"foo": "string"}, + parallel_tool_calls=True, + previous_response_id="previous_response_id", + reasoning={ + "effort": "low", + "generate_summary": "concise", + }, + store=True, + stream=False, + temperature=1, + text={"format": {"type": "text"}}, + tool_choice="none", + tools=[ + { + "type": "file_search", + "vector_store_ids": ["string"], + "filters": { + "key": "key", + "type": "eq", + "value": "string", + }, + "max_num_results": 0, + "ranking_options": { + "ranker": "auto", + "score_threshold": 0, + }, + } + ], + top_p=1, + truncation="auto", + user="user-1234", + ) + assert_matches_type(Response, response, path=["response"]) + + @parametrize + def test_raw_response_create_overload_1(self, client: OpenAI) -> None: + http_response = client.responses.with_raw_response.create( + input="string", + model="gpt-4o", + ) + + assert http_response.is_closed is True + assert http_response.http_request.headers.get("X-Stainless-Lang") == "python" + response = http_response.parse() + assert_matches_type(Response, response, path=["response"]) + + @parametrize + def test_streaming_response_create_overload_1(self, client: OpenAI) -> None: + with client.responses.with_streaming_response.create( + input="string", + model="gpt-4o", + ) as http_response: + assert not http_response.is_closed + assert http_response.http_request.headers.get("X-Stainless-Lang") == "python" + + response = http_response.parse() + assert_matches_type(Response, response, path=["response"]) + + assert cast(Any, http_response.is_closed) is True + + @parametrize + def test_method_create_overload_2(self, client: OpenAI) -> None: + response_stream = client.responses.create( + input="string", + model="gpt-4o", + stream=True, + ) + response_stream.response.close() + + @parametrize + def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: + response_stream = client.responses.create( + input="string", + model="gpt-4o", + stream=True, + include=["file_search_call.results"], + instructions="instructions", + max_output_tokens=0, + metadata={"foo": "string"}, + parallel_tool_calls=True, + previous_response_id="previous_response_id", + reasoning={ + "effort": "low", + "generate_summary": "concise", + }, + store=True, + temperature=1, + text={"format": {"type": "text"}}, + tool_choice="none", + tools=[ + { + "type": "file_search", + "vector_store_ids": ["string"], + "filters": { + "key": "key", + "type": "eq", + "value": "string", + }, + "max_num_results": 0, + "ranking_options": { + "ranker": "auto", + "score_threshold": 0, + }, + } + ], + top_p=1, + truncation="auto", + user="user-1234", + ) + response_stream.response.close() + + @parametrize + def test_raw_response_create_overload_2(self, client: OpenAI) -> None: + response = client.responses.with_raw_response.create( + input="string", + model="gpt-4o", + stream=True, + ) + + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + stream = response.parse() + stream.close() + + @parametrize + def test_streaming_response_create_overload_2(self, client: OpenAI) -> None: + with client.responses.with_streaming_response.create( + input="string", + model="gpt-4o", + stream=True, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + stream = response.parse() + stream.close() + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_method_retrieve(self, client: OpenAI) -> None: + response = client.responses.retrieve( + response_id="resp_677efb5139a88190b512bc3fef8e535d", + ) + assert_matches_type(Response, response, path=["response"]) + + @parametrize + def test_method_retrieve_with_all_params(self, client: OpenAI) -> None: + response = client.responses.retrieve( + response_id="resp_677efb5139a88190b512bc3fef8e535d", + include=["file_search_call.results"], + ) + assert_matches_type(Response, response, path=["response"]) + + @parametrize + def test_raw_response_retrieve(self, client: OpenAI) -> None: + http_response = client.responses.with_raw_response.retrieve( + response_id="resp_677efb5139a88190b512bc3fef8e535d", + ) + + assert http_response.is_closed is True + assert http_response.http_request.headers.get("X-Stainless-Lang") == "python" + response = http_response.parse() + assert_matches_type(Response, response, path=["response"]) + + @parametrize + def test_streaming_response_retrieve(self, client: OpenAI) -> None: + with client.responses.with_streaming_response.retrieve( + response_id="resp_677efb5139a88190b512bc3fef8e535d", + ) as http_response: + assert not http_response.is_closed + assert http_response.http_request.headers.get("X-Stainless-Lang") == "python" + + response = http_response.parse() + assert_matches_type(Response, response, path=["response"]) + + assert cast(Any, http_response.is_closed) is True + + @parametrize + def test_path_params_retrieve(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `response_id` but received ''"): + client.responses.with_raw_response.retrieve( + response_id="", + ) + + @parametrize + def test_method_delete(self, client: OpenAI) -> None: + response = client.responses.delete( + "resp_677efb5139a88190b512bc3fef8e535d", + ) + assert response is None + + @parametrize + def test_raw_response_delete(self, client: OpenAI) -> None: + http_response = client.responses.with_raw_response.delete( + "resp_677efb5139a88190b512bc3fef8e535d", + ) + + assert http_response.is_closed is True + assert http_response.http_request.headers.get("X-Stainless-Lang") == "python" + response = http_response.parse() + assert response is None + + @parametrize + def test_streaming_response_delete(self, client: OpenAI) -> None: + with client.responses.with_streaming_response.delete( + "resp_677efb5139a88190b512bc3fef8e535d", + ) as http_response: + assert not http_response.is_closed + assert http_response.http_request.headers.get("X-Stainless-Lang") == "python" + + response = http_response.parse() + assert response is None + + assert cast(Any, http_response.is_closed) is True + + @parametrize + def test_path_params_delete(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `response_id` but received ''"): + client.responses.with_raw_response.delete( + "", + ) + + +class TestAsyncResponses: + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + async def test_method_create_overload_1(self, async_client: AsyncOpenAI) -> None: + response = await async_client.responses.create( + input="string", + model="gpt-4o", + ) + assert_matches_type(Response, response, path=["response"]) + + @parametrize + async def test_method_create_with_all_params_overload_1(self, async_client: AsyncOpenAI) -> None: + response = await async_client.responses.create( + input="string", + model="gpt-4o", + include=["file_search_call.results"], + instructions="instructions", + max_output_tokens=0, + metadata={"foo": "string"}, + parallel_tool_calls=True, + previous_response_id="previous_response_id", + reasoning={ + "effort": "low", + "generate_summary": "concise", + }, + store=True, + stream=False, + temperature=1, + text={"format": {"type": "text"}}, + tool_choice="none", + tools=[ + { + "type": "file_search", + "vector_store_ids": ["string"], + "filters": { + "key": "key", + "type": "eq", + "value": "string", + }, + "max_num_results": 0, + "ranking_options": { + "ranker": "auto", + "score_threshold": 0, + }, + } + ], + top_p=1, + truncation="auto", + user="user-1234", + ) + assert_matches_type(Response, response, path=["response"]) + + @parametrize + async def test_raw_response_create_overload_1(self, async_client: AsyncOpenAI) -> None: + http_response = await async_client.responses.with_raw_response.create( + input="string", + model="gpt-4o", + ) + + assert http_response.is_closed is True + assert http_response.http_request.headers.get("X-Stainless-Lang") == "python" + response = http_response.parse() + assert_matches_type(Response, response, path=["response"]) + + @parametrize + async def test_streaming_response_create_overload_1(self, async_client: AsyncOpenAI) -> None: + async with async_client.responses.with_streaming_response.create( + input="string", + model="gpt-4o", + ) as http_response: + assert not http_response.is_closed + assert http_response.http_request.headers.get("X-Stainless-Lang") == "python" + + response = await http_response.parse() + assert_matches_type(Response, response, path=["response"]) + + assert cast(Any, http_response.is_closed) is True + + @parametrize + async def test_method_create_overload_2(self, async_client: AsyncOpenAI) -> None: + response_stream = await async_client.responses.create( + input="string", + model="gpt-4o", + stream=True, + ) + await response_stream.response.aclose() + + @parametrize + async def test_method_create_with_all_params_overload_2(self, async_client: AsyncOpenAI) -> None: + response_stream = await async_client.responses.create( + input="string", + model="gpt-4o", + stream=True, + include=["file_search_call.results"], + instructions="instructions", + max_output_tokens=0, + metadata={"foo": "string"}, + parallel_tool_calls=True, + previous_response_id="previous_response_id", + reasoning={ + "effort": "low", + "generate_summary": "concise", + }, + store=True, + temperature=1, + text={"format": {"type": "text"}}, + tool_choice="none", + tools=[ + { + "type": "file_search", + "vector_store_ids": ["string"], + "filters": { + "key": "key", + "type": "eq", + "value": "string", + }, + "max_num_results": 0, + "ranking_options": { + "ranker": "auto", + "score_threshold": 0, + }, + } + ], + top_p=1, + truncation="auto", + user="user-1234", + ) + await response_stream.response.aclose() + + @parametrize + async def test_raw_response_create_overload_2(self, async_client: AsyncOpenAI) -> None: + response = await async_client.responses.with_raw_response.create( + input="string", + model="gpt-4o", + stream=True, + ) + + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + stream = response.parse() + await stream.close() + + @parametrize + async def test_streaming_response_create_overload_2(self, async_client: AsyncOpenAI) -> None: + async with async_client.responses.with_streaming_response.create( + input="string", + model="gpt-4o", + stream=True, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + stream = await response.parse() + await stream.close() + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: + response = await async_client.responses.retrieve( + response_id="resp_677efb5139a88190b512bc3fef8e535d", + ) + assert_matches_type(Response, response, path=["response"]) + + @parametrize + async def test_method_retrieve_with_all_params(self, async_client: AsyncOpenAI) -> None: + response = await async_client.responses.retrieve( + response_id="resp_677efb5139a88190b512bc3fef8e535d", + include=["file_search_call.results"], + ) + assert_matches_type(Response, response, path=["response"]) + + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: + http_response = await async_client.responses.with_raw_response.retrieve( + response_id="resp_677efb5139a88190b512bc3fef8e535d", + ) + + assert http_response.is_closed is True + assert http_response.http_request.headers.get("X-Stainless-Lang") == "python" + response = http_response.parse() + assert_matches_type(Response, response, path=["response"]) + + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: + async with async_client.responses.with_streaming_response.retrieve( + response_id="resp_677efb5139a88190b512bc3fef8e535d", + ) as http_response: + assert not http_response.is_closed + assert http_response.http_request.headers.get("X-Stainless-Lang") == "python" + + response = await http_response.parse() + assert_matches_type(Response, response, path=["response"]) + + assert cast(Any, http_response.is_closed) is True + + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `response_id` but received ''"): + await async_client.responses.with_raw_response.retrieve( + response_id="", + ) + + @parametrize + async def test_method_delete(self, async_client: AsyncOpenAI) -> None: + response = await async_client.responses.delete( + "resp_677efb5139a88190b512bc3fef8e535d", + ) + assert response is None + + @parametrize + async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None: + http_response = await async_client.responses.with_raw_response.delete( + "resp_677efb5139a88190b512bc3fef8e535d", + ) + + assert http_response.is_closed is True + assert http_response.http_request.headers.get("X-Stainless-Lang") == "python" + response = http_response.parse() + assert response is None + + @parametrize + async def test_streaming_response_delete(self, async_client: AsyncOpenAI) -> None: + async with async_client.responses.with_streaming_response.delete( + "resp_677efb5139a88190b512bc3fef8e535d", + ) as http_response: + assert not http_response.is_closed + assert http_response.http_request.headers.get("X-Stainless-Lang") == "python" + + response = await http_response.parse() + assert response is None + + assert cast(Any, http_response.is_closed) is True + + @parametrize + async def test_path_params_delete(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `response_id` but received ''"): + await async_client.responses.with_raw_response.delete( + "", + ) diff --git a/tests/api_resources/beta/test_vector_stores.py b/tests/api_resources/test_vector_stores.py similarity index 60% rename from tests/api_resources/beta/test_vector_stores.py rename to tests/api_resources/test_vector_stores.py index e13b8c7613..54bb75bc1d 100644 --- a/tests/api_resources/beta/test_vector_stores.py +++ b/tests/api_resources/test_vector_stores.py @@ -9,11 +9,12 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type -from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta import ( +from openai.types import ( VectorStore, VectorStoreDeleted, + VectorStoreSearchResponse, ) +from openai.pagination import SyncPage, AsyncPage, SyncCursorPage, AsyncCursorPage base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") @@ -23,12 +24,12 @@ class TestVectorStores: @parametrize def test_method_create(self, client: OpenAI) -> None: - vector_store = client.beta.vector_stores.create() + vector_store = client.vector_stores.create() assert_matches_type(VectorStore, vector_store, path=["response"]) @parametrize def test_method_create_with_all_params(self, client: OpenAI) -> None: - vector_store = client.beta.vector_stores.create( + vector_store = client.vector_stores.create( chunking_strategy={"type": "auto"}, expires_after={ "anchor": "last_active_at", @@ -42,7 +43,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: @parametrize def test_raw_response_create(self, client: OpenAI) -> None: - response = client.beta.vector_stores.with_raw_response.create() + response = client.vector_stores.with_raw_response.create() assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -51,7 +52,7 @@ def test_raw_response_create(self, client: OpenAI) -> None: @parametrize def test_streaming_response_create(self, client: OpenAI) -> None: - with client.beta.vector_stores.with_streaming_response.create() as response: + with client.vector_stores.with_streaming_response.create() as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -62,15 +63,15 @@ def test_streaming_response_create(self, client: OpenAI) -> None: @parametrize def test_method_retrieve(self, client: OpenAI) -> None: - vector_store = client.beta.vector_stores.retrieve( - "string", + vector_store = client.vector_stores.retrieve( + "vector_store_id", ) assert_matches_type(VectorStore, vector_store, path=["response"]) @parametrize def test_raw_response_retrieve(self, client: OpenAI) -> None: - response = client.beta.vector_stores.with_raw_response.retrieve( - "string", + response = client.vector_stores.with_raw_response.retrieve( + "vector_store_id", ) assert response.is_closed is True @@ -80,8 +81,8 @@ def test_raw_response_retrieve(self, client: OpenAI) -> None: @parametrize def test_streaming_response_retrieve(self, client: OpenAI) -> None: - with client.beta.vector_stores.with_streaming_response.retrieve( - "string", + with client.vector_stores.with_streaming_response.retrieve( + "vector_store_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -94,21 +95,21 @@ def test_streaming_response_retrieve(self, client: OpenAI) -> None: @parametrize def test_path_params_retrieve(self, client: OpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): - client.beta.vector_stores.with_raw_response.retrieve( + client.vector_stores.with_raw_response.retrieve( "", ) @parametrize def test_method_update(self, client: OpenAI) -> None: - vector_store = client.beta.vector_stores.update( - "string", + vector_store = client.vector_stores.update( + vector_store_id="vector_store_id", ) assert_matches_type(VectorStore, vector_store, path=["response"]) @parametrize def test_method_update_with_all_params(self, client: OpenAI) -> None: - vector_store = client.beta.vector_stores.update( - "string", + vector_store = client.vector_stores.update( + vector_store_id="vector_store_id", expires_after={ "anchor": "last_active_at", "days": 1, @@ -120,8 +121,8 @@ def test_method_update_with_all_params(self, client: OpenAI) -> None: @parametrize def test_raw_response_update(self, client: OpenAI) -> None: - response = client.beta.vector_stores.with_raw_response.update( - "string", + response = client.vector_stores.with_raw_response.update( + vector_store_id="vector_store_id", ) assert response.is_closed is True @@ -131,8 +132,8 @@ def test_raw_response_update(self, client: OpenAI) -> None: @parametrize def test_streaming_response_update(self, client: OpenAI) -> None: - with client.beta.vector_stores.with_streaming_response.update( - "string", + with client.vector_stores.with_streaming_response.update( + vector_store_id="vector_store_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -145,20 +146,20 @@ def test_streaming_response_update(self, client: OpenAI) -> None: @parametrize def test_path_params_update(self, client: OpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): - client.beta.vector_stores.with_raw_response.update( - "", + client.vector_stores.with_raw_response.update( + vector_store_id="", ) @parametrize def test_method_list(self, client: OpenAI) -> None: - vector_store = client.beta.vector_stores.list() + vector_store = client.vector_stores.list() assert_matches_type(SyncCursorPage[VectorStore], vector_store, path=["response"]) @parametrize def test_method_list_with_all_params(self, client: OpenAI) -> None: - vector_store = client.beta.vector_stores.list( - after="string", - before="string", + vector_store = client.vector_stores.list( + after="after", + before="before", limit=0, order="asc", ) @@ -166,7 +167,7 @@ def test_method_list_with_all_params(self, client: OpenAI) -> None: @parametrize def test_raw_response_list(self, client: OpenAI) -> None: - response = client.beta.vector_stores.with_raw_response.list() + response = client.vector_stores.with_raw_response.list() assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -175,7 +176,7 @@ def test_raw_response_list(self, client: OpenAI) -> None: @parametrize def test_streaming_response_list(self, client: OpenAI) -> None: - with client.beta.vector_stores.with_streaming_response.list() as response: + with client.vector_stores.with_streaming_response.list() as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -186,15 +187,15 @@ def test_streaming_response_list(self, client: OpenAI) -> None: @parametrize def test_method_delete(self, client: OpenAI) -> None: - vector_store = client.beta.vector_stores.delete( - "string", + vector_store = client.vector_stores.delete( + "vector_store_id", ) assert_matches_type(VectorStoreDeleted, vector_store, path=["response"]) @parametrize def test_raw_response_delete(self, client: OpenAI) -> None: - response = client.beta.vector_stores.with_raw_response.delete( - "string", + response = client.vector_stores.with_raw_response.delete( + "vector_store_id", ) assert response.is_closed is True @@ -204,8 +205,8 @@ def test_raw_response_delete(self, client: OpenAI) -> None: @parametrize def test_streaming_response_delete(self, client: OpenAI) -> None: - with client.beta.vector_stores.with_streaming_response.delete( - "string", + with client.vector_stores.with_streaming_response.delete( + "vector_store_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -218,22 +219,83 @@ def test_streaming_response_delete(self, client: OpenAI) -> None: @parametrize def test_path_params_delete(self, client: OpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): - client.beta.vector_stores.with_raw_response.delete( + client.vector_stores.with_raw_response.delete( "", ) + @parametrize + def test_method_search(self, client: OpenAI) -> None: + vector_store = client.vector_stores.search( + vector_store_id="vs_abc123", + query="string", + ) + assert_matches_type(SyncPage[VectorStoreSearchResponse], vector_store, path=["response"]) + + @parametrize + def test_method_search_with_all_params(self, client: OpenAI) -> None: + vector_store = client.vector_stores.search( + vector_store_id="vs_abc123", + query="string", + filters={ + "key": "key", + "type": "eq", + "value": "string", + }, + max_num_results=1, + ranking_options={ + "ranker": "auto", + "score_threshold": 0, + }, + rewrite_query=True, + ) + assert_matches_type(SyncPage[VectorStoreSearchResponse], vector_store, path=["response"]) + + @parametrize + def test_raw_response_search(self, client: OpenAI) -> None: + response = client.vector_stores.with_raw_response.search( + vector_store_id="vs_abc123", + query="string", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + vector_store = response.parse() + assert_matches_type(SyncPage[VectorStoreSearchResponse], vector_store, path=["response"]) + + @parametrize + def test_streaming_response_search(self, client: OpenAI) -> None: + with client.vector_stores.with_streaming_response.search( + vector_store_id="vs_abc123", + query="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + vector_store = response.parse() + assert_matches_type(SyncPage[VectorStoreSearchResponse], vector_store, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_search(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + client.vector_stores.with_raw_response.search( + vector_store_id="", + query="string", + ) + class TestAsyncVectorStores: parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize async def test_method_create(self, async_client: AsyncOpenAI) -> None: - vector_store = await async_client.beta.vector_stores.create() + vector_store = await async_client.vector_stores.create() assert_matches_type(VectorStore, vector_store, path=["response"]) @parametrize async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: - vector_store = await async_client.beta.vector_stores.create( + vector_store = await async_client.vector_stores.create( chunking_strategy={"type": "auto"}, expires_after={ "anchor": "last_active_at", @@ -247,7 +309,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> @parametrize async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: - response = await async_client.beta.vector_stores.with_raw_response.create() + response = await async_client.vector_stores.with_raw_response.create() assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -256,7 +318,7 @@ async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: - async with async_client.beta.vector_stores.with_streaming_response.create() as response: + async with async_client.vector_stores.with_streaming_response.create() as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -267,15 +329,15 @@ async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> Non @parametrize async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: - vector_store = await async_client.beta.vector_stores.retrieve( - "string", + vector_store = await async_client.vector_stores.retrieve( + "vector_store_id", ) assert_matches_type(VectorStore, vector_store, path=["response"]) @parametrize async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: - response = await async_client.beta.vector_stores.with_raw_response.retrieve( - "string", + response = await async_client.vector_stores.with_raw_response.retrieve( + "vector_store_id", ) assert response.is_closed is True @@ -285,8 +347,8 @@ async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: - async with async_client.beta.vector_stores.with_streaming_response.retrieve( - "string", + async with async_client.vector_stores.with_streaming_response.retrieve( + "vector_store_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -299,21 +361,21 @@ async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> N @parametrize async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): - await async_client.beta.vector_stores.with_raw_response.retrieve( + await async_client.vector_stores.with_raw_response.retrieve( "", ) @parametrize async def test_method_update(self, async_client: AsyncOpenAI) -> None: - vector_store = await async_client.beta.vector_stores.update( - "string", + vector_store = await async_client.vector_stores.update( + vector_store_id="vector_store_id", ) assert_matches_type(VectorStore, vector_store, path=["response"]) @parametrize async def test_method_update_with_all_params(self, async_client: AsyncOpenAI) -> None: - vector_store = await async_client.beta.vector_stores.update( - "string", + vector_store = await async_client.vector_stores.update( + vector_store_id="vector_store_id", expires_after={ "anchor": "last_active_at", "days": 1, @@ -325,8 +387,8 @@ async def test_method_update_with_all_params(self, async_client: AsyncOpenAI) -> @parametrize async def test_raw_response_update(self, async_client: AsyncOpenAI) -> None: - response = await async_client.beta.vector_stores.with_raw_response.update( - "string", + response = await async_client.vector_stores.with_raw_response.update( + vector_store_id="vector_store_id", ) assert response.is_closed is True @@ -336,8 +398,8 @@ async def test_raw_response_update(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_streaming_response_update(self, async_client: AsyncOpenAI) -> None: - async with async_client.beta.vector_stores.with_streaming_response.update( - "string", + async with async_client.vector_stores.with_streaming_response.update( + vector_store_id="vector_store_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -350,20 +412,20 @@ async def test_streaming_response_update(self, async_client: AsyncOpenAI) -> Non @parametrize async def test_path_params_update(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): - await async_client.beta.vector_stores.with_raw_response.update( - "", + await async_client.vector_stores.with_raw_response.update( + vector_store_id="", ) @parametrize async def test_method_list(self, async_client: AsyncOpenAI) -> None: - vector_store = await async_client.beta.vector_stores.list() + vector_store = await async_client.vector_stores.list() assert_matches_type(AsyncCursorPage[VectorStore], vector_store, path=["response"]) @parametrize async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: - vector_store = await async_client.beta.vector_stores.list( - after="string", - before="string", + vector_store = await async_client.vector_stores.list( + after="after", + before="before", limit=0, order="asc", ) @@ -371,7 +433,7 @@ async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> N @parametrize async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: - response = await async_client.beta.vector_stores.with_raw_response.list() + response = await async_client.vector_stores.with_raw_response.list() assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -380,7 +442,7 @@ async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: - async with async_client.beta.vector_stores.with_streaming_response.list() as response: + async with async_client.vector_stores.with_streaming_response.list() as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -391,15 +453,15 @@ async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_method_delete(self, async_client: AsyncOpenAI) -> None: - vector_store = await async_client.beta.vector_stores.delete( - "string", + vector_store = await async_client.vector_stores.delete( + "vector_store_id", ) assert_matches_type(VectorStoreDeleted, vector_store, path=["response"]) @parametrize async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None: - response = await async_client.beta.vector_stores.with_raw_response.delete( - "string", + response = await async_client.vector_stores.with_raw_response.delete( + "vector_store_id", ) assert response.is_closed is True @@ -409,8 +471,8 @@ async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_streaming_response_delete(self, async_client: AsyncOpenAI) -> None: - async with async_client.beta.vector_stores.with_streaming_response.delete( - "string", + async with async_client.vector_stores.with_streaming_response.delete( + "vector_store_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -423,6 +485,67 @@ async def test_streaming_response_delete(self, async_client: AsyncOpenAI) -> Non @parametrize async def test_path_params_delete(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): - await async_client.beta.vector_stores.with_raw_response.delete( + await async_client.vector_stores.with_raw_response.delete( "", ) + + @parametrize + async def test_method_search(self, async_client: AsyncOpenAI) -> None: + vector_store = await async_client.vector_stores.search( + vector_store_id="vs_abc123", + query="string", + ) + assert_matches_type(AsyncPage[VectorStoreSearchResponse], vector_store, path=["response"]) + + @parametrize + async def test_method_search_with_all_params(self, async_client: AsyncOpenAI) -> None: + vector_store = await async_client.vector_stores.search( + vector_store_id="vs_abc123", + query="string", + filters={ + "key": "key", + "type": "eq", + "value": "string", + }, + max_num_results=1, + ranking_options={ + "ranker": "auto", + "score_threshold": 0, + }, + rewrite_query=True, + ) + assert_matches_type(AsyncPage[VectorStoreSearchResponse], vector_store, path=["response"]) + + @parametrize + async def test_raw_response_search(self, async_client: AsyncOpenAI) -> None: + response = await async_client.vector_stores.with_raw_response.search( + vector_store_id="vs_abc123", + query="string", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + vector_store = response.parse() + assert_matches_type(AsyncPage[VectorStoreSearchResponse], vector_store, path=["response"]) + + @parametrize + async def test_streaming_response_search(self, async_client: AsyncOpenAI) -> None: + async with async_client.vector_stores.with_streaming_response.search( + vector_store_id="vs_abc123", + query="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + vector_store = await response.parse() + assert_matches_type(AsyncPage[VectorStoreSearchResponse], vector_store, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_search(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + await async_client.vector_stores.with_raw_response.search( + vector_store_id="", + query="string", + ) diff --git a/tests/api_resources/vector_stores/__init__.py b/tests/api_resources/vector_stores/__init__.py new file mode 100644 index 0000000000..fd8019a9a1 --- /dev/null +++ b/tests/api_resources/vector_stores/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/beta/vector_stores/test_file_batches.py b/tests/api_resources/vector_stores/test_file_batches.py similarity index 68% rename from tests/api_resources/beta/vector_stores/test_file_batches.py rename to tests/api_resources/vector_stores/test_file_batches.py index 631f2669ad..0587cfc56a 100644 --- a/tests/api_resources/beta/vector_stores/test_file_batches.py +++ b/tests/api_resources/vector_stores/test_file_batches.py @@ -10,7 +10,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta.vector_stores import ( +from openai.types.vector_stores import ( VectorStoreFile, VectorStoreFileBatch, ) @@ -23,25 +23,26 @@ class TestFileBatches: @parametrize def test_method_create(self, client: OpenAI) -> None: - file_batch = client.beta.vector_stores.file_batches.create( - "vs_abc123", + file_batch = client.vector_stores.file_batches.create( + vector_store_id="vs_abc123", file_ids=["string"], ) assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) @parametrize def test_method_create_with_all_params(self, client: OpenAI) -> None: - file_batch = client.beta.vector_stores.file_batches.create( - "vs_abc123", + file_batch = client.vector_stores.file_batches.create( + vector_store_id="vs_abc123", file_ids=["string"], + attributes={"foo": "string"}, chunking_strategy={"type": "auto"}, ) assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) @parametrize def test_raw_response_create(self, client: OpenAI) -> None: - response = client.beta.vector_stores.file_batches.with_raw_response.create( - "vs_abc123", + response = client.vector_stores.file_batches.with_raw_response.create( + vector_store_id="vs_abc123", file_ids=["string"], ) @@ -52,8 +53,8 @@ def test_raw_response_create(self, client: OpenAI) -> None: @parametrize def test_streaming_response_create(self, client: OpenAI) -> None: - with client.beta.vector_stores.file_batches.with_streaming_response.create( - "vs_abc123", + with client.vector_stores.file_batches.with_streaming_response.create( + vector_store_id="vs_abc123", file_ids=["string"], ) as response: assert not response.is_closed @@ -67,23 +68,23 @@ def test_streaming_response_create(self, client: OpenAI) -> None: @parametrize def test_path_params_create(self, client: OpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): - client.beta.vector_stores.file_batches.with_raw_response.create( - "", + client.vector_stores.file_batches.with_raw_response.create( + vector_store_id="", file_ids=["string"], ) @parametrize def test_method_retrieve(self, client: OpenAI) -> None: - file_batch = client.beta.vector_stores.file_batches.retrieve( - "vsfb_abc123", + file_batch = client.vector_stores.file_batches.retrieve( + batch_id="vsfb_abc123", vector_store_id="vs_abc123", ) assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) @parametrize def test_raw_response_retrieve(self, client: OpenAI) -> None: - response = client.beta.vector_stores.file_batches.with_raw_response.retrieve( - "vsfb_abc123", + response = client.vector_stores.file_batches.with_raw_response.retrieve( + batch_id="vsfb_abc123", vector_store_id="vs_abc123", ) @@ -94,8 +95,8 @@ def test_raw_response_retrieve(self, client: OpenAI) -> None: @parametrize def test_streaming_response_retrieve(self, client: OpenAI) -> None: - with client.beta.vector_stores.file_batches.with_streaming_response.retrieve( - "vsfb_abc123", + with client.vector_stores.file_batches.with_streaming_response.retrieve( + batch_id="vsfb_abc123", vector_store_id="vs_abc123", ) as response: assert not response.is_closed @@ -109,30 +110,30 @@ def test_streaming_response_retrieve(self, client: OpenAI) -> None: @parametrize def test_path_params_retrieve(self, client: OpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): - client.beta.vector_stores.file_batches.with_raw_response.retrieve( - "vsfb_abc123", + client.vector_stores.file_batches.with_raw_response.retrieve( + batch_id="vsfb_abc123", vector_store_id="", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `batch_id` but received ''"): - client.beta.vector_stores.file_batches.with_raw_response.retrieve( - "", + client.vector_stores.file_batches.with_raw_response.retrieve( + batch_id="", vector_store_id="vs_abc123", ) @parametrize def test_method_cancel(self, client: OpenAI) -> None: - file_batch = client.beta.vector_stores.file_batches.cancel( - "string", - vector_store_id="string", + file_batch = client.vector_stores.file_batches.cancel( + batch_id="batch_id", + vector_store_id="vector_store_id", ) assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) @parametrize def test_raw_response_cancel(self, client: OpenAI) -> None: - response = client.beta.vector_stores.file_batches.with_raw_response.cancel( - "string", - vector_store_id="string", + response = client.vector_stores.file_batches.with_raw_response.cancel( + batch_id="batch_id", + vector_store_id="vector_store_id", ) assert response.is_closed is True @@ -142,9 +143,9 @@ def test_raw_response_cancel(self, client: OpenAI) -> None: @parametrize def test_streaming_response_cancel(self, client: OpenAI) -> None: - with client.beta.vector_stores.file_batches.with_streaming_response.cancel( - "string", - vector_store_id="string", + with client.vector_stores.file_batches.with_streaming_response.cancel( + batch_id="batch_id", + vector_store_id="vector_store_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -157,32 +158,32 @@ def test_streaming_response_cancel(self, client: OpenAI) -> None: @parametrize def test_path_params_cancel(self, client: OpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): - client.beta.vector_stores.file_batches.with_raw_response.cancel( - "string", + client.vector_stores.file_batches.with_raw_response.cancel( + batch_id="batch_id", vector_store_id="", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `batch_id` but received ''"): - client.beta.vector_stores.file_batches.with_raw_response.cancel( - "", - vector_store_id="string", + client.vector_stores.file_batches.with_raw_response.cancel( + batch_id="", + vector_store_id="vector_store_id", ) @parametrize def test_method_list_files(self, client: OpenAI) -> None: - file_batch = client.beta.vector_stores.file_batches.list_files( - "string", - vector_store_id="string", + file_batch = client.vector_stores.file_batches.list_files( + batch_id="batch_id", + vector_store_id="vector_store_id", ) assert_matches_type(SyncCursorPage[VectorStoreFile], file_batch, path=["response"]) @parametrize def test_method_list_files_with_all_params(self, client: OpenAI) -> None: - file_batch = client.beta.vector_stores.file_batches.list_files( - "string", - vector_store_id="string", - after="string", - before="string", + file_batch = client.vector_stores.file_batches.list_files( + batch_id="batch_id", + vector_store_id="vector_store_id", + after="after", + before="before", filter="in_progress", limit=0, order="asc", @@ -191,9 +192,9 @@ def test_method_list_files_with_all_params(self, client: OpenAI) -> None: @parametrize def test_raw_response_list_files(self, client: OpenAI) -> None: - response = client.beta.vector_stores.file_batches.with_raw_response.list_files( - "string", - vector_store_id="string", + response = client.vector_stores.file_batches.with_raw_response.list_files( + batch_id="batch_id", + vector_store_id="vector_store_id", ) assert response.is_closed is True @@ -203,9 +204,9 @@ def test_raw_response_list_files(self, client: OpenAI) -> None: @parametrize def test_streaming_response_list_files(self, client: OpenAI) -> None: - with client.beta.vector_stores.file_batches.with_streaming_response.list_files( - "string", - vector_store_id="string", + with client.vector_stores.file_batches.with_streaming_response.list_files( + batch_id="batch_id", + vector_store_id="vector_store_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -218,15 +219,15 @@ def test_streaming_response_list_files(self, client: OpenAI) -> None: @parametrize def test_path_params_list_files(self, client: OpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): - client.beta.vector_stores.file_batches.with_raw_response.list_files( - "string", + client.vector_stores.file_batches.with_raw_response.list_files( + batch_id="batch_id", vector_store_id="", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `batch_id` but received ''"): - client.beta.vector_stores.file_batches.with_raw_response.list_files( - "", - vector_store_id="string", + client.vector_stores.file_batches.with_raw_response.list_files( + batch_id="", + vector_store_id="vector_store_id", ) @@ -235,25 +236,26 @@ class TestAsyncFileBatches: @parametrize async def test_method_create(self, async_client: AsyncOpenAI) -> None: - file_batch = await async_client.beta.vector_stores.file_batches.create( - "vs_abc123", + file_batch = await async_client.vector_stores.file_batches.create( + vector_store_id="vs_abc123", file_ids=["string"], ) assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) @parametrize async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: - file_batch = await async_client.beta.vector_stores.file_batches.create( - "vs_abc123", + file_batch = await async_client.vector_stores.file_batches.create( + vector_store_id="vs_abc123", file_ids=["string"], + attributes={"foo": "string"}, chunking_strategy={"type": "auto"}, ) assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) @parametrize async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: - response = await async_client.beta.vector_stores.file_batches.with_raw_response.create( - "vs_abc123", + response = await async_client.vector_stores.file_batches.with_raw_response.create( + vector_store_id="vs_abc123", file_ids=["string"], ) @@ -264,8 +266,8 @@ async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: - async with async_client.beta.vector_stores.file_batches.with_streaming_response.create( - "vs_abc123", + async with async_client.vector_stores.file_batches.with_streaming_response.create( + vector_store_id="vs_abc123", file_ids=["string"], ) as response: assert not response.is_closed @@ -279,23 +281,23 @@ async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> Non @parametrize async def test_path_params_create(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): - await async_client.beta.vector_stores.file_batches.with_raw_response.create( - "", + await async_client.vector_stores.file_batches.with_raw_response.create( + vector_store_id="", file_ids=["string"], ) @parametrize async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: - file_batch = await async_client.beta.vector_stores.file_batches.retrieve( - "vsfb_abc123", + file_batch = await async_client.vector_stores.file_batches.retrieve( + batch_id="vsfb_abc123", vector_store_id="vs_abc123", ) assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) @parametrize async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: - response = await async_client.beta.vector_stores.file_batches.with_raw_response.retrieve( - "vsfb_abc123", + response = await async_client.vector_stores.file_batches.with_raw_response.retrieve( + batch_id="vsfb_abc123", vector_store_id="vs_abc123", ) @@ -306,8 +308,8 @@ async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: - async with async_client.beta.vector_stores.file_batches.with_streaming_response.retrieve( - "vsfb_abc123", + async with async_client.vector_stores.file_batches.with_streaming_response.retrieve( + batch_id="vsfb_abc123", vector_store_id="vs_abc123", ) as response: assert not response.is_closed @@ -321,30 +323,30 @@ async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> N @parametrize async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): - await async_client.beta.vector_stores.file_batches.with_raw_response.retrieve( - "vsfb_abc123", + await async_client.vector_stores.file_batches.with_raw_response.retrieve( + batch_id="vsfb_abc123", vector_store_id="", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `batch_id` but received ''"): - await async_client.beta.vector_stores.file_batches.with_raw_response.retrieve( - "", + await async_client.vector_stores.file_batches.with_raw_response.retrieve( + batch_id="", vector_store_id="vs_abc123", ) @parametrize async def test_method_cancel(self, async_client: AsyncOpenAI) -> None: - file_batch = await async_client.beta.vector_stores.file_batches.cancel( - "string", - vector_store_id="string", + file_batch = await async_client.vector_stores.file_batches.cancel( + batch_id="batch_id", + vector_store_id="vector_store_id", ) assert_matches_type(VectorStoreFileBatch, file_batch, path=["response"]) @parametrize async def test_raw_response_cancel(self, async_client: AsyncOpenAI) -> None: - response = await async_client.beta.vector_stores.file_batches.with_raw_response.cancel( - "string", - vector_store_id="string", + response = await async_client.vector_stores.file_batches.with_raw_response.cancel( + batch_id="batch_id", + vector_store_id="vector_store_id", ) assert response.is_closed is True @@ -354,9 +356,9 @@ async def test_raw_response_cancel(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_streaming_response_cancel(self, async_client: AsyncOpenAI) -> None: - async with async_client.beta.vector_stores.file_batches.with_streaming_response.cancel( - "string", - vector_store_id="string", + async with async_client.vector_stores.file_batches.with_streaming_response.cancel( + batch_id="batch_id", + vector_store_id="vector_store_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -369,32 +371,32 @@ async def test_streaming_response_cancel(self, async_client: AsyncOpenAI) -> Non @parametrize async def test_path_params_cancel(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): - await async_client.beta.vector_stores.file_batches.with_raw_response.cancel( - "string", + await async_client.vector_stores.file_batches.with_raw_response.cancel( + batch_id="batch_id", vector_store_id="", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `batch_id` but received ''"): - await async_client.beta.vector_stores.file_batches.with_raw_response.cancel( - "", - vector_store_id="string", + await async_client.vector_stores.file_batches.with_raw_response.cancel( + batch_id="", + vector_store_id="vector_store_id", ) @parametrize async def test_method_list_files(self, async_client: AsyncOpenAI) -> None: - file_batch = await async_client.beta.vector_stores.file_batches.list_files( - "string", - vector_store_id="string", + file_batch = await async_client.vector_stores.file_batches.list_files( + batch_id="batch_id", + vector_store_id="vector_store_id", ) assert_matches_type(AsyncCursorPage[VectorStoreFile], file_batch, path=["response"]) @parametrize async def test_method_list_files_with_all_params(self, async_client: AsyncOpenAI) -> None: - file_batch = await async_client.beta.vector_stores.file_batches.list_files( - "string", - vector_store_id="string", - after="string", - before="string", + file_batch = await async_client.vector_stores.file_batches.list_files( + batch_id="batch_id", + vector_store_id="vector_store_id", + after="after", + before="before", filter="in_progress", limit=0, order="asc", @@ -403,9 +405,9 @@ async def test_method_list_files_with_all_params(self, async_client: AsyncOpenAI @parametrize async def test_raw_response_list_files(self, async_client: AsyncOpenAI) -> None: - response = await async_client.beta.vector_stores.file_batches.with_raw_response.list_files( - "string", - vector_store_id="string", + response = await async_client.vector_stores.file_batches.with_raw_response.list_files( + batch_id="batch_id", + vector_store_id="vector_store_id", ) assert response.is_closed is True @@ -415,9 +417,9 @@ async def test_raw_response_list_files(self, async_client: AsyncOpenAI) -> None: @parametrize async def test_streaming_response_list_files(self, async_client: AsyncOpenAI) -> None: - async with async_client.beta.vector_stores.file_batches.with_streaming_response.list_files( - "string", - vector_store_id="string", + async with async_client.vector_stores.file_batches.with_streaming_response.list_files( + batch_id="batch_id", + vector_store_id="vector_store_id", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -430,13 +432,13 @@ async def test_streaming_response_list_files(self, async_client: AsyncOpenAI) -> @parametrize async def test_path_params_list_files(self, async_client: AsyncOpenAI) -> None: with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): - await async_client.beta.vector_stores.file_batches.with_raw_response.list_files( - "string", + await async_client.vector_stores.file_batches.with_raw_response.list_files( + batch_id="batch_id", vector_store_id="", ) with pytest.raises(ValueError, match=r"Expected a non-empty value for `batch_id` but received ''"): - await async_client.beta.vector_stores.file_batches.with_raw_response.list_files( - "", - vector_store_id="string", + await async_client.vector_stores.file_batches.with_raw_response.list_files( + batch_id="", + vector_store_id="vector_store_id", ) diff --git a/tests/api_resources/vector_stores/test_files.py b/tests/api_resources/vector_stores/test_files.py new file mode 100644 index 0000000000..c13442261e --- /dev/null +++ b/tests/api_resources/vector_stores/test_files.py @@ -0,0 +1,625 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai.pagination import SyncPage, AsyncPage, SyncCursorPage, AsyncCursorPage +from openai.types.vector_stores import ( + VectorStoreFile, + FileContentResponse, + VectorStoreFileDeleted, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") + + +class TestFiles: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + def test_method_create(self, client: OpenAI) -> None: + file = client.vector_stores.files.create( + vector_store_id="vs_abc123", + file_id="file_id", + ) + assert_matches_type(VectorStoreFile, file, path=["response"]) + + @parametrize + def test_method_create_with_all_params(self, client: OpenAI) -> None: + file = client.vector_stores.files.create( + vector_store_id="vs_abc123", + file_id="file_id", + attributes={"foo": "string"}, + chunking_strategy={"type": "auto"}, + ) + assert_matches_type(VectorStoreFile, file, path=["response"]) + + @parametrize + def test_raw_response_create(self, client: OpenAI) -> None: + response = client.vector_stores.files.with_raw_response.create( + vector_store_id="vs_abc123", + file_id="file_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(VectorStoreFile, file, path=["response"]) + + @parametrize + def test_streaming_response_create(self, client: OpenAI) -> None: + with client.vector_stores.files.with_streaming_response.create( + vector_store_id="vs_abc123", + file_id="file_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = response.parse() + assert_matches_type(VectorStoreFile, file, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_create(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + client.vector_stores.files.with_raw_response.create( + vector_store_id="", + file_id="file_id", + ) + + @parametrize + def test_method_retrieve(self, client: OpenAI) -> None: + file = client.vector_stores.files.retrieve( + file_id="file-abc123", + vector_store_id="vs_abc123", + ) + assert_matches_type(VectorStoreFile, file, path=["response"]) + + @parametrize + def test_raw_response_retrieve(self, client: OpenAI) -> None: + response = client.vector_stores.files.with_raw_response.retrieve( + file_id="file-abc123", + vector_store_id="vs_abc123", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(VectorStoreFile, file, path=["response"]) + + @parametrize + def test_streaming_response_retrieve(self, client: OpenAI) -> None: + with client.vector_stores.files.with_streaming_response.retrieve( + file_id="file-abc123", + vector_store_id="vs_abc123", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = response.parse() + assert_matches_type(VectorStoreFile, file, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_retrieve(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + client.vector_stores.files.with_raw_response.retrieve( + file_id="file-abc123", + vector_store_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): + client.vector_stores.files.with_raw_response.retrieve( + file_id="", + vector_store_id="vs_abc123", + ) + + @parametrize + def test_method_update(self, client: OpenAI) -> None: + file = client.vector_stores.files.update( + file_id="file-abc123", + vector_store_id="vs_abc123", + attributes={"foo": "string"}, + ) + assert_matches_type(VectorStoreFile, file, path=["response"]) + + @parametrize + def test_raw_response_update(self, client: OpenAI) -> None: + response = client.vector_stores.files.with_raw_response.update( + file_id="file-abc123", + vector_store_id="vs_abc123", + attributes={"foo": "string"}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(VectorStoreFile, file, path=["response"]) + + @parametrize + def test_streaming_response_update(self, client: OpenAI) -> None: + with client.vector_stores.files.with_streaming_response.update( + file_id="file-abc123", + vector_store_id="vs_abc123", + attributes={"foo": "string"}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = response.parse() + assert_matches_type(VectorStoreFile, file, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_update(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + client.vector_stores.files.with_raw_response.update( + file_id="file-abc123", + vector_store_id="", + attributes={"foo": "string"}, + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): + client.vector_stores.files.with_raw_response.update( + file_id="", + vector_store_id="vs_abc123", + attributes={"foo": "string"}, + ) + + @parametrize + def test_method_list(self, client: OpenAI) -> None: + file = client.vector_stores.files.list( + vector_store_id="vector_store_id", + ) + assert_matches_type(SyncCursorPage[VectorStoreFile], file, path=["response"]) + + @parametrize + def test_method_list_with_all_params(self, client: OpenAI) -> None: + file = client.vector_stores.files.list( + vector_store_id="vector_store_id", + after="after", + before="before", + filter="in_progress", + limit=0, + order="asc", + ) + assert_matches_type(SyncCursorPage[VectorStoreFile], file, path=["response"]) + + @parametrize + def test_raw_response_list(self, client: OpenAI) -> None: + response = client.vector_stores.files.with_raw_response.list( + vector_store_id="vector_store_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(SyncCursorPage[VectorStoreFile], file, path=["response"]) + + @parametrize + def test_streaming_response_list(self, client: OpenAI) -> None: + with client.vector_stores.files.with_streaming_response.list( + vector_store_id="vector_store_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = response.parse() + assert_matches_type(SyncCursorPage[VectorStoreFile], file, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_list(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + client.vector_stores.files.with_raw_response.list( + vector_store_id="", + ) + + @parametrize + def test_method_delete(self, client: OpenAI) -> None: + file = client.vector_stores.files.delete( + file_id="file_id", + vector_store_id="vector_store_id", + ) + assert_matches_type(VectorStoreFileDeleted, file, path=["response"]) + + @parametrize + def test_raw_response_delete(self, client: OpenAI) -> None: + response = client.vector_stores.files.with_raw_response.delete( + file_id="file_id", + vector_store_id="vector_store_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(VectorStoreFileDeleted, file, path=["response"]) + + @parametrize + def test_streaming_response_delete(self, client: OpenAI) -> None: + with client.vector_stores.files.with_streaming_response.delete( + file_id="file_id", + vector_store_id="vector_store_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = response.parse() + assert_matches_type(VectorStoreFileDeleted, file, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_delete(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + client.vector_stores.files.with_raw_response.delete( + file_id="file_id", + vector_store_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): + client.vector_stores.files.with_raw_response.delete( + file_id="", + vector_store_id="vector_store_id", + ) + + @parametrize + def test_method_content(self, client: OpenAI) -> None: + file = client.vector_stores.files.content( + file_id="file-abc123", + vector_store_id="vs_abc123", + ) + assert_matches_type(SyncPage[FileContentResponse], file, path=["response"]) + + @parametrize + def test_raw_response_content(self, client: OpenAI) -> None: + response = client.vector_stores.files.with_raw_response.content( + file_id="file-abc123", + vector_store_id="vs_abc123", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(SyncPage[FileContentResponse], file, path=["response"]) + + @parametrize + def test_streaming_response_content(self, client: OpenAI) -> None: + with client.vector_stores.files.with_streaming_response.content( + file_id="file-abc123", + vector_store_id="vs_abc123", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = response.parse() + assert_matches_type(SyncPage[FileContentResponse], file, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_content(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + client.vector_stores.files.with_raw_response.content( + file_id="file-abc123", + vector_store_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): + client.vector_stores.files.with_raw_response.content( + file_id="", + vector_store_id="vs_abc123", + ) + + +class TestAsyncFiles: + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + async def test_method_create(self, async_client: AsyncOpenAI) -> None: + file = await async_client.vector_stores.files.create( + vector_store_id="vs_abc123", + file_id="file_id", + ) + assert_matches_type(VectorStoreFile, file, path=["response"]) + + @parametrize + async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: + file = await async_client.vector_stores.files.create( + vector_store_id="vs_abc123", + file_id="file_id", + attributes={"foo": "string"}, + chunking_strategy={"type": "auto"}, + ) + assert_matches_type(VectorStoreFile, file, path=["response"]) + + @parametrize + async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: + response = await async_client.vector_stores.files.with_raw_response.create( + vector_store_id="vs_abc123", + file_id="file_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(VectorStoreFile, file, path=["response"]) + + @parametrize + async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: + async with async_client.vector_stores.files.with_streaming_response.create( + vector_store_id="vs_abc123", + file_id="file_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = await response.parse() + assert_matches_type(VectorStoreFile, file, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_create(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + await async_client.vector_stores.files.with_raw_response.create( + vector_store_id="", + file_id="file_id", + ) + + @parametrize + async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: + file = await async_client.vector_stores.files.retrieve( + file_id="file-abc123", + vector_store_id="vs_abc123", + ) + assert_matches_type(VectorStoreFile, file, path=["response"]) + + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: + response = await async_client.vector_stores.files.with_raw_response.retrieve( + file_id="file-abc123", + vector_store_id="vs_abc123", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(VectorStoreFile, file, path=["response"]) + + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: + async with async_client.vector_stores.files.with_streaming_response.retrieve( + file_id="file-abc123", + vector_store_id="vs_abc123", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = await response.parse() + assert_matches_type(VectorStoreFile, file, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + await async_client.vector_stores.files.with_raw_response.retrieve( + file_id="file-abc123", + vector_store_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): + await async_client.vector_stores.files.with_raw_response.retrieve( + file_id="", + vector_store_id="vs_abc123", + ) + + @parametrize + async def test_method_update(self, async_client: AsyncOpenAI) -> None: + file = await async_client.vector_stores.files.update( + file_id="file-abc123", + vector_store_id="vs_abc123", + attributes={"foo": "string"}, + ) + assert_matches_type(VectorStoreFile, file, path=["response"]) + + @parametrize + async def test_raw_response_update(self, async_client: AsyncOpenAI) -> None: + response = await async_client.vector_stores.files.with_raw_response.update( + file_id="file-abc123", + vector_store_id="vs_abc123", + attributes={"foo": "string"}, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(VectorStoreFile, file, path=["response"]) + + @parametrize + async def test_streaming_response_update(self, async_client: AsyncOpenAI) -> None: + async with async_client.vector_stores.files.with_streaming_response.update( + file_id="file-abc123", + vector_store_id="vs_abc123", + attributes={"foo": "string"}, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = await response.parse() + assert_matches_type(VectorStoreFile, file, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_update(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + await async_client.vector_stores.files.with_raw_response.update( + file_id="file-abc123", + vector_store_id="", + attributes={"foo": "string"}, + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): + await async_client.vector_stores.files.with_raw_response.update( + file_id="", + vector_store_id="vs_abc123", + attributes={"foo": "string"}, + ) + + @parametrize + async def test_method_list(self, async_client: AsyncOpenAI) -> None: + file = await async_client.vector_stores.files.list( + vector_store_id="vector_store_id", + ) + assert_matches_type(AsyncCursorPage[VectorStoreFile], file, path=["response"]) + + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: + file = await async_client.vector_stores.files.list( + vector_store_id="vector_store_id", + after="after", + before="before", + filter="in_progress", + limit=0, + order="asc", + ) + assert_matches_type(AsyncCursorPage[VectorStoreFile], file, path=["response"]) + + @parametrize + async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: + response = await async_client.vector_stores.files.with_raw_response.list( + vector_store_id="vector_store_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(AsyncCursorPage[VectorStoreFile], file, path=["response"]) + + @parametrize + async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: + async with async_client.vector_stores.files.with_streaming_response.list( + vector_store_id="vector_store_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = await response.parse() + assert_matches_type(AsyncCursorPage[VectorStoreFile], file, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_list(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + await async_client.vector_stores.files.with_raw_response.list( + vector_store_id="", + ) + + @parametrize + async def test_method_delete(self, async_client: AsyncOpenAI) -> None: + file = await async_client.vector_stores.files.delete( + file_id="file_id", + vector_store_id="vector_store_id", + ) + assert_matches_type(VectorStoreFileDeleted, file, path=["response"]) + + @parametrize + async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None: + response = await async_client.vector_stores.files.with_raw_response.delete( + file_id="file_id", + vector_store_id="vector_store_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(VectorStoreFileDeleted, file, path=["response"]) + + @parametrize + async def test_streaming_response_delete(self, async_client: AsyncOpenAI) -> None: + async with async_client.vector_stores.files.with_streaming_response.delete( + file_id="file_id", + vector_store_id="vector_store_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = await response.parse() + assert_matches_type(VectorStoreFileDeleted, file, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_delete(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + await async_client.vector_stores.files.with_raw_response.delete( + file_id="file_id", + vector_store_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): + await async_client.vector_stores.files.with_raw_response.delete( + file_id="", + vector_store_id="vector_store_id", + ) + + @parametrize + async def test_method_content(self, async_client: AsyncOpenAI) -> None: + file = await async_client.vector_stores.files.content( + file_id="file-abc123", + vector_store_id="vs_abc123", + ) + assert_matches_type(AsyncPage[FileContentResponse], file, path=["response"]) + + @parametrize + async def test_raw_response_content(self, async_client: AsyncOpenAI) -> None: + response = await async_client.vector_stores.files.with_raw_response.content( + file_id="file-abc123", + vector_store_id="vs_abc123", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + file = response.parse() + assert_matches_type(AsyncPage[FileContentResponse], file, path=["response"]) + + @parametrize + async def test_streaming_response_content(self, async_client: AsyncOpenAI) -> None: + async with async_client.vector_stores.files.with_streaming_response.content( + file_id="file-abc123", + vector_store_id="vs_abc123", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + file = await response.parse() + assert_matches_type(AsyncPage[FileContentResponse], file, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_content(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `vector_store_id` but received ''"): + await async_client.vector_stores.files.with_raw_response.content( + file_id="file-abc123", + vector_store_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `file_id` but received ''"): + await async_client.vector_stores.files.with_raw_response.content( + file_id="", + vector_store_id="vs_abc123", + ) diff --git a/tests/lib/chat/test_completions.py b/tests/lib/chat/test_completions.py index 74cee27b93..62fdd34c0a 100644 --- a/tests/lib/chat/test_completions.py +++ b/tests/lib/chat/test_completions.py @@ -58,6 +58,7 @@ def test_parse_nothing(client: OpenAI, respx_mock: MockRouter, monkeypatch: pyte index=0, logprobs=None, message=ParsedChatCompletionMessage[NoneType]( + annotations=None, audio=None, content="I'm unable to provide real-time weather updates. To get the current weather in San Francisco, I recommend checking a reliable weather website or app like the Weather Channel or a local news station.", @@ -126,6 +127,7 @@ class Location(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( + annotations=None, audio=None, content='{"city":"San Francisco","temperature":65,"units":"f"}', function_call=None, @@ -195,6 +197,7 @@ class Location(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( + annotations=None, audio=None, content='{"city":"San Francisco","temperature":65,"units":"f"}', function_call=None, @@ -266,6 +269,7 @@ class ColorDetection(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[ColorDetection]( + annotations=None, audio=None, content='{"color":"red","hex_color_code":"#FF0000"}', function_call=None, @@ -315,6 +319,7 @@ class Location(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( + annotations=None, audio=None, content='{"city":"San Francisco","temperature":64,"units":"f"}', function_call=None, @@ -329,6 +334,7 @@ class Location(BaseModel): index=1, logprobs=None, message=ParsedChatCompletionMessage[Location]( + annotations=None, audio=None, content='{"city":"San Francisco","temperature":65,"units":"f"}', function_call=None, @@ -343,6 +349,7 @@ class Location(BaseModel): index=2, logprobs=None, message=ParsedChatCompletionMessage[Location]( + annotations=None, audio=None, content='{"city":"San Francisco","temperature":63.0,"units":"f"}', function_call=None, @@ -393,6 +400,7 @@ class CalendarEvent: index=0, logprobs=None, message=ParsedChatCompletionMessage[CalendarEvent]( + annotations=None, audio=None, content='{"name":"Science Fair","date":"Friday","participants":["Alice","Bob"]}', function_call=None, @@ -454,6 +462,7 @@ def test_pydantic_tool_model_all_types(client: OpenAI, respx_mock: MockRouter, m index=0, logprobs=None, message=ParsedChatCompletionMessage[Query]( + annotations=None, audio=None, content=None, function_call=None, @@ -565,6 +574,7 @@ class Location(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( + annotations=None, audio=None, content=None, function_call=None, @@ -614,6 +624,7 @@ class GetWeatherArgs(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[NoneType]( + annotations=None, audio=None, content=None, function_call=None, @@ -686,6 +697,7 @@ class GetStockPrice(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[NoneType]( + annotations=None, audio=None, content=None, function_call=None, @@ -767,6 +779,7 @@ def test_parse_strict_tools(client: OpenAI, respx_mock: MockRouter, monkeypatch: index=0, logprobs=None, message=ParsedChatCompletionMessage[NoneType]( + annotations=None, audio=None, content=None, function_call=None, @@ -849,6 +862,7 @@ class Location(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( + annotations=None, audio=None, content='{"city":"San Francisco","temperature":58,"units":"f"}', function_call=None, @@ -924,6 +938,7 @@ class Location(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( + annotations=None, audio=None, content='{"city":"San Francisco","temperature":65,"units":"f"}', function_call=None, diff --git a/tests/lib/chat/test_completions_streaming.py b/tests/lib/chat/test_completions_streaming.py index 71b4173738..5852c5a343 100644 --- a/tests/lib/chat/test_completions_streaming.py +++ b/tests/lib/chat/test_completions_streaming.py @@ -63,6 +63,7 @@ def test_parse_nothing(client: OpenAI, respx_mock: MockRouter, monkeypatch: pyte index=0, logprobs=None, message=ParsedChatCompletionMessage[NoneType]( + annotations=None, audio=None, content="I'm unable to provide real-time weather updates. To get the current weather in San Francisco, I recommend checking a reliable weather website or a weather app.", @@ -141,6 +142,7 @@ def on_event(stream: ChatCompletionStream[Location], event: ChatCompletionStream index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( + annotations=None, audio=None, content='{"city":"San Francisco","temperature":61,"units":"f"}', function_call=None, @@ -318,6 +320,7 @@ class Location(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( + annotations=None, audio=None, content='{"city":"San Francisco","temperature":65,"units":"f"}', function_call=None, @@ -332,6 +335,7 @@ class Location(BaseModel): index=1, logprobs=None, message=ParsedChatCompletionMessage[Location]( + annotations=None, audio=None, content='{"city":"San Francisco","temperature":61,"units":"f"}', function_call=None, @@ -346,6 +350,7 @@ class Location(BaseModel): index=2, logprobs=None, message=ParsedChatCompletionMessage[Location]( + annotations=None, audio=None, content='{"city":"San Francisco","temperature":59,"units":"f"}', function_call=None, @@ -421,6 +426,7 @@ class Location(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[Location]( + annotations=None, audio=None, content=None, function_call=None, @@ -495,6 +501,7 @@ def test_content_logprobs_events(client: OpenAI, respx_mock: MockRouter, monkeyp refusal=None ), message=ParsedChatCompletionMessage[NoneType]( + annotations=None, audio=None, content='Foo!', function_call=None, @@ -606,6 +613,7 @@ class Location(BaseModel): ] ), message=ParsedChatCompletionMessage[Location]( + annotations=None, audio=None, content=None, function_call=None, @@ -652,6 +660,7 @@ class GetWeatherArgs(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[object]( + annotations=None, audio=None, content=None, function_call=None, @@ -684,6 +693,7 @@ class GetWeatherArgs(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[NoneType]( + annotations=None, audio=None, content=None, function_call=None, @@ -755,6 +765,7 @@ class GetStockPrice(BaseModel): index=0, logprobs=None, message=ParsedChatCompletionMessage[object]( + annotations=None, audio=None, content=None, function_call=None, @@ -863,6 +874,7 @@ def test_parse_strict_tools(client: OpenAI, respx_mock: MockRouter, monkeypatch: index=0, logprobs=None, message=ParsedChatCompletionMessage[object]( + annotations=None, audio=None, content=None, function_call=None, @@ -914,6 +926,7 @@ def test_non_pydantic_response_format(client: OpenAI, respx_mock: MockRouter, mo index=0, logprobs=None, message=ParsedChatCompletionMessage[NoneType]( + annotations=None, audio=None, content='\\n {\\n "location": "San Francisco, CA",\\n "weather": {\\n "temperature": "18°C",\\n "condition": "Partly Cloudy",\\n "humidity": "72%",\\n "windSpeed": "15 km/h",\\n "windDirection": "NW"\\n @@ -974,6 +987,7 @@ def test_allows_non_strict_tools_but_no_parsing( index=0, logprobs=None, message=ParsedChatCompletionMessage[NoneType]( + annotations=None, audio=None, content=None, function_call=None, @@ -1033,6 +1047,7 @@ def streamer(client: OpenAI) -> Iterator[ChatCompletionChunk]: index=0, logprobs=None, message=ParsedChatCompletionMessage[NoneType]( + annotations=None, audio=None, content="I'm unable to provide real-time weather updates. To get the current weather in San Francisco, I recommend checking a reliable weather website or a weather app.", From 849ec26310dde6f7c8a6d0cc8a93a067d3facb89 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 11 Mar 2025 16:31:57 +0000 Subject: [PATCH 716/816] release: 1.66.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index b8446e8608..fa1c44bbb5 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.65.5" + ".": "1.66.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index e2bf62a4df..fb576487cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.66.0 (2025-03-11) + +Full Changelog: [v1.65.5...v1.66.0](https://github.com/openai/openai-python/compare/v1.65.5...v1.66.0) + +### Features + +* **api:** add /v1/responses and built-in tools ([854df97](https://github.com/openai/openai-python/commit/854df97884736244d46060fd3d5a92916826ec8f)) + + +### Chores + +* export more types ([#2176](https://github.com/openai/openai-python/issues/2176)) ([a730f0e](https://github.com/openai/openai-python/commit/a730f0efedd228f96a49467f17fb19b6a219246c)) + ## 1.65.5 (2025-03-09) Full Changelog: [v1.65.4...v1.65.5](https://github.com/openai/openai-python/compare/v1.65.4...v1.65.5) diff --git a/pyproject.toml b/pyproject.toml index 09e79f5592..f362b5e264 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.65.5" +version = "1.66.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 859b56580d..74f5619299 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.65.5" # x-release-please-version +__version__ = "1.66.0" # x-release-please-version From 5f548eaa2ca330f163f9d4fb035e81eb225633b6 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 11 Mar 2025 19:52:46 +0000 Subject: [PATCH 717/816] fix(responses): correct computer use enum value (#2180) --- .stats.yml | 2 +- src/openai/types/responses/computer_tool.py | 2 +- src/openai/types/responses/computer_tool_param.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.stats.yml b/.stats.yml index 455874212c..9c4a2e5367 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 81 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-be834d63e326a82494e819085137f5eb15866f3fc787db1f3afe7168d419e18a.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-9ce5257763fb30c6e0e1ee2bef7e13baf661511e09572207e528d643da8e16b3.yml diff --git a/src/openai/types/responses/computer_tool.py b/src/openai/types/responses/computer_tool.py index f0499cd950..dffb7af7b7 100644 --- a/src/openai/types/responses/computer_tool.py +++ b/src/openai/types/responses/computer_tool.py @@ -17,5 +17,5 @@ class ComputerTool(BaseModel): environment: Literal["mac", "windows", "ubuntu", "browser"] """The type of computer environment to control.""" - type: Literal["computer-preview"] + type: Literal["computer_use_preview"] """The type of the computer use tool. Always `computer_use_preview`.""" diff --git a/src/openai/types/responses/computer_tool_param.py b/src/openai/types/responses/computer_tool_param.py index 685b471378..6b1072ffd2 100644 --- a/src/openai/types/responses/computer_tool_param.py +++ b/src/openai/types/responses/computer_tool_param.py @@ -17,5 +17,5 @@ class ComputerToolParam(TypedDict, total=False): environment: Required[Literal["mac", "windows", "ubuntu", "browser"]] """The type of computer environment to control.""" - type: Required[Literal["computer-preview"]] + type: Required[Literal["computer_use_preview"]] """The type of the computer use tool. Always `computer_use_preview`.""" From 5a1eded551ecd2e10d2508fc47ed1003e6675872 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 11 Mar 2025 19:53:21 +0000 Subject: [PATCH 718/816] release: 1.66.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 13 +++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index fa1c44bbb5..5d08177085 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.66.0" + ".": "1.66.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index fb576487cb..4068372dd6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 1.66.1 (2025-03-11) + +Full Changelog: [v1.66.0...v1.66.1](https://github.com/openai/openai-python/compare/v1.66.0...v1.66.1) + +### Bug Fixes + +* **responses:** correct computer use enum value ([#2180](https://github.com/openai/openai-python/issues/2180)) ([48f4628](https://github.com/openai/openai-python/commit/48f4628c5fb18ddd7d71e8730184f3ac50c4ffea)) + + +### Chores + +* **internal:** temporary commit ([afabec1](https://github.com/openai/openai-python/commit/afabec1b5b18b41ac870970d06e6c2f152ef7bbe)) + ## 1.66.0 (2025-03-11) Full Changelog: [v1.65.5...v1.66.0](https://github.com/openai/openai-python/compare/v1.65.5...v1.66.0) diff --git a/pyproject.toml b/pyproject.toml index f362b5e264..04ba80639b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.66.0" +version = "1.66.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 74f5619299..473c6aba83 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.66.0" # x-release-please-version +__version__ = "1.66.1" # x-release-please-version From 27ef73fd301c0e49d43d62fe7fbd17badd0c986d Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 11 Mar 2025 21:44:13 +0000 Subject: [PATCH 719/816] fix(responses): correct reasoning output type (#2181) --- .stats.yml | 2 +- api.md | 1 + src/openai/types/responses/__init__.py | 2 + src/openai/types/responses/parsed_response.py | 4 +- .../responses/response_input_item_param.py | 33 +--------------- .../types/responses/response_input_param.py | 33 +--------------- .../types/responses/response_output_item.py | 39 +++---------------- .../responses/response_reasoning_item.py | 36 +++++++++++++++++ .../response_reasoning_item_param.py | 36 +++++++++++++++++ 9 files changed, 87 insertions(+), 99 deletions(-) create mode 100644 src/openai/types/responses/response_reasoning_item.py create mode 100644 src/openai/types/responses/response_reasoning_item_param.py diff --git a/.stats.yml b/.stats.yml index 9c4a2e5367..edc2aaf89f 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 81 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-9ce5257763fb30c6e0e1ee2bef7e13baf661511e09572207e528d643da8e16b3.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-c8579861bc21d4d2155a5b9e8e7d54faee8083730673c4d32cbbe573d7fb4116.yml diff --git a/api.md b/api.md index 6827b88f0b..e760fe69c1 100644 --- a/api.md +++ b/api.md @@ -640,6 +640,7 @@ from openai.types.responses import ( ResponseOutputMessage, ResponseOutputRefusal, ResponseOutputText, + ResponseReasoningItem, ResponseRefusalDeltaEvent, ResponseRefusalDoneEvent, ResponseStatus, diff --git a/src/openai/types/responses/__init__.py b/src/openai/types/responses/__init__.py index 970a167d2c..7c0cf9e3f2 100644 --- a/src/openai/types/responses/__init__.py +++ b/src/openai/types/responses/__init__.py @@ -45,6 +45,7 @@ from .response_input_content import ResponseInputContent as ResponseInputContent from .response_output_message import ResponseOutputMessage as ResponseOutputMessage from .response_output_refusal import ResponseOutputRefusal as ResponseOutputRefusal +from .response_reasoning_item import ResponseReasoningItem as ResponseReasoningItem from .tool_choice_types_param import ToolChoiceTypesParam as ToolChoiceTypesParam from .easy_input_message_param import EasyInputMessageParam as EasyInputMessageParam from .response_completed_event import ResponseCompletedEvent as ResponseCompletedEvent @@ -71,6 +72,7 @@ from .response_refusal_delta_event import ResponseRefusalDeltaEvent as ResponseRefusalDeltaEvent from .response_output_message_param import ResponseOutputMessageParam as ResponseOutputMessageParam from .response_output_refusal_param import ResponseOutputRefusalParam as ResponseOutputRefusalParam +from .response_reasoning_item_param import ResponseReasoningItemParam as ResponseReasoningItemParam from .response_file_search_tool_call import ResponseFileSearchToolCall as ResponseFileSearchToolCall from .response_output_item_done_event import ResponseOutputItemDoneEvent as ResponseOutputItemDoneEvent from .response_content_part_done_event import ResponseContentPartDoneEvent as ResponseContentPartDoneEvent diff --git a/src/openai/types/responses/parsed_response.py b/src/openai/types/responses/parsed_response.py index 3216a71ba9..1263dfd648 100644 --- a/src/openai/types/responses/parsed_response.py +++ b/src/openai/types/responses/parsed_response.py @@ -7,10 +7,10 @@ from .response import Response from ..._models import GenericModel from ..._utils._transform import PropertyInfo -from .response_output_item import Reasoning from .response_output_text import ResponseOutputText from .response_output_message import ResponseOutputMessage from .response_output_refusal import ResponseOutputRefusal +from .response_reasoning_item import ResponseReasoningItem from .response_computer_tool_call import ResponseComputerToolCall from .response_function_tool_call import ResponseFunctionToolCall from .response_function_web_search import ResponseFunctionWebSearch @@ -54,7 +54,7 @@ class ParsedResponseFunctionToolCall(ResponseFunctionToolCall): ResponseFileSearchToolCall, ResponseFunctionWebSearch, ResponseComputerToolCall, - Reasoning, + ResponseReasoningItem, ], PropertyInfo(discriminator="type"), ] diff --git a/src/openai/types/responses/response_input_item_param.py b/src/openai/types/responses/response_input_item_param.py index c9daaa6a89..32ac13cabb 100644 --- a/src/openai/types/responses/response_input_item_param.py +++ b/src/openai/types/responses/response_input_item_param.py @@ -7,6 +7,7 @@ from .easy_input_message_param import EasyInputMessageParam from .response_output_message_param import ResponseOutputMessageParam +from .response_reasoning_item_param import ResponseReasoningItemParam from .response_computer_tool_call_param import ResponseComputerToolCallParam from .response_function_tool_call_param import ResponseFunctionToolCallParam from .response_function_web_search_param import ResponseFunctionWebSearchParam @@ -20,8 +21,6 @@ "ComputerCallOutputOutput", "ComputerCallOutputAcknowledgedSafetyCheck", "FunctionCallOutput", - "Reasoning", - "ReasoningContent", "ItemReference", ] @@ -123,34 +122,6 @@ class FunctionCallOutput(TypedDict, total=False): """ -class ReasoningContent(TypedDict, total=False): - text: Required[str] - """ - A short summary of the reasoning used by the model when generating the response. - """ - - type: Required[Literal["reasoning_summary"]] - """The type of the object. Always `text`.""" - - -class Reasoning(TypedDict, total=False): - id: Required[str] - """The unique identifier of the reasoning content.""" - - content: Required[Iterable[ReasoningContent]] - """Reasoning text contents.""" - - type: Required[Literal["reasoning"]] - """The type of the object. Always `reasoning`.""" - - status: Literal["in_progress", "completed", "incomplete"] - """The status of the item. - - One of `in_progress`, `completed`, or `incomplete`. Populated when items are - returned via API. - """ - - class ItemReference(TypedDict, total=False): id: Required[str] """The ID of the item to reference.""" @@ -169,6 +140,6 @@ class ItemReference(TypedDict, total=False): ResponseFunctionWebSearchParam, ResponseFunctionToolCallParam, FunctionCallOutput, - Reasoning, + ResponseReasoningItemParam, ItemReference, ] diff --git a/src/openai/types/responses/response_input_param.py b/src/openai/types/responses/response_input_param.py index c81308500d..b942f4868a 100644 --- a/src/openai/types/responses/response_input_param.py +++ b/src/openai/types/responses/response_input_param.py @@ -7,6 +7,7 @@ from .easy_input_message_param import EasyInputMessageParam from .response_output_message_param import ResponseOutputMessageParam +from .response_reasoning_item_param import ResponseReasoningItemParam from .response_computer_tool_call_param import ResponseComputerToolCallParam from .response_function_tool_call_param import ResponseFunctionToolCallParam from .response_function_web_search_param import ResponseFunctionWebSearchParam @@ -21,8 +22,6 @@ "ComputerCallOutputOutput", "ComputerCallOutputAcknowledgedSafetyCheck", "FunctionCallOutput", - "Reasoning", - "ReasoningContent", "ItemReference", ] @@ -124,34 +123,6 @@ class FunctionCallOutput(TypedDict, total=False): """ -class ReasoningContent(TypedDict, total=False): - text: Required[str] - """ - A short summary of the reasoning used by the model when generating the response. - """ - - type: Required[Literal["reasoning_summary"]] - """The type of the object. Always `text`.""" - - -class Reasoning(TypedDict, total=False): - id: Required[str] - """The unique identifier of the reasoning content.""" - - content: Required[Iterable[ReasoningContent]] - """Reasoning text contents.""" - - type: Required[Literal["reasoning"]] - """The type of the object. Always `reasoning`.""" - - status: Literal["in_progress", "completed", "incomplete"] - """The status of the item. - - One of `in_progress`, `completed`, or `incomplete`. Populated when items are - returned via API. - """ - - class ItemReference(TypedDict, total=False): id: Required[str] """The ID of the item to reference.""" @@ -170,7 +141,7 @@ class ItemReference(TypedDict, total=False): ResponseFunctionWebSearchParam, ResponseFunctionToolCallParam, FunctionCallOutput, - Reasoning, + ResponseReasoningItemParam, ItemReference, ] diff --git a/src/openai/types/responses/response_output_item.py b/src/openai/types/responses/response_output_item.py index 45d5cc0094..f1e9693195 100644 --- a/src/openai/types/responses/response_output_item.py +++ b/src/openai/types/responses/response_output_item.py @@ -1,46 +1,17 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing import List, Union, Optional -from typing_extensions import Literal, Annotated, TypeAlias +from typing import Union +from typing_extensions import Annotated, TypeAlias from ..._utils import PropertyInfo -from ..._models import BaseModel from .response_output_message import ResponseOutputMessage +from .response_reasoning_item import ResponseReasoningItem from .response_computer_tool_call import ResponseComputerToolCall from .response_function_tool_call import ResponseFunctionToolCall from .response_function_web_search import ResponseFunctionWebSearch from .response_file_search_tool_call import ResponseFileSearchToolCall -__all__ = ["ResponseOutputItem", "Reasoning", "ReasoningContent"] - - -class ReasoningContent(BaseModel): - text: str - """ - A short summary of the reasoning used by the model when generating the response. - """ - - type: Literal["reasoning_summary"] - """The type of the object. Always `text`.""" - - -class Reasoning(BaseModel): - id: str - """The unique identifier of the reasoning content.""" - - content: List[ReasoningContent] - """Reasoning text contents.""" - - type: Literal["reasoning"] - """The type of the object. Always `reasoning`.""" - - status: Optional[Literal["in_progress", "completed", "incomplete"]] = None - """The status of the item. - - One of `in_progress`, `completed`, or `incomplete`. Populated when items are - returned via API. - """ - +__all__ = ["ResponseOutputItem"] ResponseOutputItem: TypeAlias = Annotated[ Union[ @@ -49,7 +20,7 @@ class Reasoning(BaseModel): ResponseFunctionToolCall, ResponseFunctionWebSearch, ResponseComputerToolCall, - Reasoning, + ResponseReasoningItem, ], PropertyInfo(discriminator="type"), ] diff --git a/src/openai/types/responses/response_reasoning_item.py b/src/openai/types/responses/response_reasoning_item.py new file mode 100644 index 0000000000..57e5fbfe6d --- /dev/null +++ b/src/openai/types/responses/response_reasoning_item.py @@ -0,0 +1,36 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseReasoningItem", "Summary"] + + +class Summary(BaseModel): + text: str + """ + A short summary of the reasoning used by the model when generating the response. + """ + + type: Literal["summary_text"] + """The type of the object. Always `summary_text`.""" + + +class ResponseReasoningItem(BaseModel): + id: str + """The unique identifier of the reasoning content.""" + + summary: List[Summary] + """Reasoning text contents.""" + + type: Literal["reasoning"] + """The type of the object. Always `reasoning`.""" + + status: Optional[Literal["in_progress", "completed", "incomplete"]] = None + """The status of the item. + + One of `in_progress`, `completed`, or `incomplete`. Populated when items are + returned via API. + """ diff --git a/src/openai/types/responses/response_reasoning_item_param.py b/src/openai/types/responses/response_reasoning_item_param.py new file mode 100644 index 0000000000..adb49d6402 --- /dev/null +++ b/src/openai/types/responses/response_reasoning_item_param.py @@ -0,0 +1,36 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ResponseReasoningItemParam", "Summary"] + + +class Summary(TypedDict, total=False): + text: Required[str] + """ + A short summary of the reasoning used by the model when generating the response. + """ + + type: Required[Literal["summary_text"]] + """The type of the object. Always `summary_text`.""" + + +class ResponseReasoningItemParam(TypedDict, total=False): + id: Required[str] + """The unique identifier of the reasoning content.""" + + summary: Required[Iterable[Summary]] + """Reasoning text contents.""" + + type: Required[Literal["reasoning"]] + """The type of the object. Always `reasoning`.""" + + status: Literal["in_progress", "completed", "incomplete"] + """The status of the item. + + One of `in_progress`, `completed`, or `incomplete`. Populated when items are + returned via API. + """ From 16a10604fbd0d82c1382b84b417a1d6a2d33a7f1 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 11 Mar 2025 21:47:29 +0000 Subject: [PATCH 720/816] release: 1.66.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 5d08177085..4e427aab32 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.66.1" + ".": "1.66.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 4068372dd6..460dbb287e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.66.2 (2025-03-11) + +Full Changelog: [v1.66.1...v1.66.2](https://github.com/openai/openai-python/compare/v1.66.1...v1.66.2) + +### Bug Fixes + +* **responses:** correct reasoning output type ([#2181](https://github.com/openai/openai-python/issues/2181)) ([8cb1129](https://github.com/openai/openai-python/commit/8cb11299acc40c80061af275691cd09a2bf30c65)) + ## 1.66.1 (2025-03-11) Full Changelog: [v1.66.0...v1.66.1](https://github.com/openai/openai-python/compare/v1.66.0...v1.66.1) diff --git a/pyproject.toml b/pyproject.toml index 04ba80639b..a9d46a72b4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.66.1" +version = "1.66.2" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 473c6aba83..dc6a545c76 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.66.1" # x-release-please-version +__version__ = "1.66.2" # x-release-please-version From 4fb86f6a5efeac33309d87698d3dc397bec4da88 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 12 Mar 2025 19:36:15 +0000 Subject: [PATCH 721/816] fix: update module level client (#2185) --- src/openai/__init__.py | 3 +++ src/openai/_module_client.py | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/openai/__init__.py b/src/openai/__init__.py index fe85956a4a..7ce6df0817 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -356,8 +356,11 @@ def _reset_client() -> None: # type: ignore[reportUnusedFunction] images as images, models as models, batches as batches, + uploads as uploads, + responses as responses, embeddings as embeddings, completions as completions, fine_tuning as fine_tuning, moderations as moderations, + vector_stores as vector_stores, ) diff --git a/src/openai/_module_client.py b/src/openai/_module_client.py index 6f7356eb3c..e7d2657860 100644 --- a/src/openai/_module_client.py +++ b/src/openai/_module_client.py @@ -48,6 +48,18 @@ def __load__(self) -> resources.Batches: return _load_client().batches +class UploadsProxy(LazyProxy[resources.Uploads]): + @override + def __load__(self) -> resources.Uploads: + return _load_client().uploads + + +class ResponsesProxy(LazyProxy[resources.Responses]): + @override + def __load__(self) -> resources.Responses: + return _load_client().responses + + class EmbeddingsProxy(LazyProxy[resources.Embeddings]): @override def __load__(self) -> resources.Embeddings: @@ -72,6 +84,12 @@ def __load__(self) -> resources.FineTuning: return _load_client().fine_tuning +class VectorStoresProxy(LazyProxy[resources.VectorStores]): + @override + def __load__(self) -> resources.VectorStores: + return _load_client().vector_stores + + chat: resources.Chat = ChatProxy().__as_proxied__() beta: resources.Beta = BetaProxy().__as_proxied__() files: resources.Files = FilesProxy().__as_proxied__() @@ -79,7 +97,10 @@ def __load__(self) -> resources.FineTuning: images: resources.Images = ImagesProxy().__as_proxied__() models: resources.Models = ModelsProxy().__as_proxied__() batches: resources.Batches = BatchesProxy().__as_proxied__() +uploads: resources.Uploads = UploadsProxy().__as_proxied__() +responses: resources.Responses = ResponsesProxy().__as_proxied__() embeddings: resources.Embeddings = EmbeddingsProxy().__as_proxied__() completions: resources.Completions = CompletionsProxy().__as_proxied__() moderations: resources.Moderations = ModerationsProxy().__as_proxied__() fine_tuning: resources.FineTuning = FineTuningProxy().__as_proxied__() +vector_stores: resources.VectorStores = VectorStoresProxy().__as_proxied__() From 9dea82fb8cdd06683f9e8033b54cff219789af7f Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 12 Mar 2025 19:40:02 +0000 Subject: [PATCH 722/816] release: 1.66.3 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 4e427aab32..6d3d57b7ab 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.66.2" + ".": "1.66.3" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 460dbb287e..e799f6d117 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.66.3 (2025-03-12) + +Full Changelog: [v1.66.2...v1.66.3](https://github.com/openai/openai-python/compare/v1.66.2...v1.66.3) + +### Bug Fixes + +* update module level client ([#2185](https://github.com/openai/openai-python/issues/2185)) ([456f324](https://github.com/openai/openai-python/commit/456f3240a0c33e71521c6b73c32e8adc1b8cd3bc)) + ## 1.66.2 (2025-03-11) Full Changelog: [v1.66.1...v1.66.2](https://github.com/openai/openai-python/compare/v1.66.1...v1.66.2) diff --git a/pyproject.toml b/pyproject.toml index a9d46a72b4..3088eb2fb2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.66.2" +version = "1.66.3" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index dc6a545c76..6c4a192efc 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.66.2" # x-release-please-version +__version__ = "1.66.3" # x-release-please-version From 11eea35f9557c2e1f4126b722d3e274d8ef3ea7f Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 13 Mar 2025 16:48:23 +0000 Subject: [PATCH 723/816] chore(internal): remove extra empty newlines (#2195) --- pyproject.toml | 1 - 1 file changed, 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 3088eb2fb2..2608de2060 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -169,7 +169,6 @@ reportImplicitOverride = true reportImportCycles = false reportPrivateUsage = false - [tool.ruff] line-length = 120 output-format = "grouped" From d664ff22a9958efb7ccc297e280b6562dd14c6ca Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 14 Mar 2025 15:21:04 +0000 Subject: [PATCH 724/816] chore(internal): bump rye to 0.44.0 (#2200) --- .devcontainer/Dockerfile | 2 +- .github/workflows/ci.yml | 6 +++--- .github/workflows/create-releases.yml | 2 +- .github/workflows/publish-pypi.yml | 2 +- requirements-dev.lock | 1 + requirements.lock | 1 + 6 files changed, 8 insertions(+), 6 deletions(-) diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index 55d20255c9..ff261bad78 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -3,7 +3,7 @@ FROM mcr.microsoft.com/vscode/devcontainers/python:0-${VARIANT} USER vscode -RUN curl -sSf https://rye.astral.sh/get | RYE_VERSION="0.35.0" RYE_INSTALL_OPTION="--yes" bash +RUN curl -sSf https://rye.astral.sh/get | RYE_VERSION="0.44.0" RYE_INSTALL_OPTION="--yes" bash ENV PATH=/home/vscode/.rye/shims:$PATH RUN echo "[[ -d .venv ]] && source .venv/bin/activate || export PATH=\$PATH" >> /home/vscode/.bashrc diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d0e0ffe2f3..34dfde36fa 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,7 +21,7 @@ jobs: curl -sSf https://rye.astral.sh/get | bash echo "$HOME/.rye/shims" >> $GITHUB_PATH env: - RYE_VERSION: '0.35.0' + RYE_VERSION: '0.44.0' RYE_INSTALL_OPTION: '--yes' - name: Install dependencies @@ -43,7 +43,7 @@ jobs: curl -sSf https://rye.astral.sh/get | bash echo "$HOME/.rye/shims" >> $GITHUB_PATH env: - RYE_VERSION: '0.35.0' + RYE_VERSION: '0.44.0' RYE_INSTALL_OPTION: '--yes' - name: Bootstrap @@ -64,7 +64,7 @@ jobs: curl -sSf https://rye.astral.sh/get | bash echo "$HOME/.rye/shims" >> $GITHUB_PATH env: - RYE_VERSION: '0.35.0' + RYE_VERSION: '0.44.0' RYE_INSTALL_OPTION: '--yes' - name: Install dependencies run: | diff --git a/.github/workflows/create-releases.yml b/.github/workflows/create-releases.yml index 2a97049033..b3e1c679d4 100644 --- a/.github/workflows/create-releases.yml +++ b/.github/workflows/create-releases.yml @@ -28,7 +28,7 @@ jobs: curl -sSf https://rye.astral.sh/get | bash echo "$HOME/.rye/shims" >> $GITHUB_PATH env: - RYE_VERSION: '0.35.0' + RYE_VERSION: '0.44.0' RYE_INSTALL_OPTION: '--yes' - name: Publish to PyPI diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml index 76d0efca80..32bd6929e2 100644 --- a/.github/workflows/publish-pypi.yml +++ b/.github/workflows/publish-pypi.yml @@ -18,7 +18,7 @@ jobs: curl -sSf https://rye.astral.sh/get | bash echo "$HOME/.rye/shims" >> $GITHUB_PATH env: - RYE_VERSION: '0.35.0' + RYE_VERSION: '0.44.0' RYE_INSTALL_OPTION: '--yes' - name: Publish to PyPI diff --git a/requirements-dev.lock b/requirements-dev.lock index 5599057b66..48e49f926c 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -7,6 +7,7 @@ # all-features: true # with-sources: false # generate-hashes: false +# universal: false -e file:. annotated-types==0.6.0 diff --git a/requirements.lock b/requirements.lock index cbdff94fa3..b935c0ee59 100644 --- a/requirements.lock +++ b/requirements.lock @@ -7,6 +7,7 @@ # all-features: true # with-sources: false # generate-hashes: false +# universal: false -e file:. annotated-types==0.6.0 From b6ba4876bb5004dbd79b00dcf8ea345e141e1674 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 14 Mar 2025 19:21:28 +0000 Subject: [PATCH 725/816] chore(internal): remove CI condition (#2203) --- .github/workflows/ci.yml | 2 -- .github/workflows/create-releases.yml | 39 --------------------------- .github/workflows/publish-pypi.yml | 8 ++++-- .github/workflows/release-doctor.yml | 1 - .stats.yml | 2 +- bin/check-release-environment | 4 --- 6 files changed, 7 insertions(+), 49 deletions(-) delete mode 100644 .github/workflows/create-releases.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 34dfde36fa..06eb10c5f0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,7 +11,6 @@ jobs: lint: name: lint runs-on: ubuntu-latest - if: github.repository == 'openai/openai-python' steps: - uses: actions/checkout@v4 @@ -33,7 +32,6 @@ jobs: test: name: test runs-on: ubuntu-latest - if: github.repository == 'openai/openai-python' steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/create-releases.yml b/.github/workflows/create-releases.yml deleted file mode 100644 index b3e1c679d4..0000000000 --- a/.github/workflows/create-releases.yml +++ /dev/null @@ -1,39 +0,0 @@ -name: Create releases -on: - schedule: - - cron: '0 5 * * *' # every day at 5am UTC - push: - branches: - - main - -jobs: - release: - name: release - if: github.ref == 'refs/heads/main' && github.repository == 'openai/openai-python' - runs-on: ubuntu-latest - environment: publish - - steps: - - uses: actions/checkout@v4 - - - uses: stainless-api/trigger-release-please@v1 - id: release - with: - repo: ${{ github.event.repository.full_name }} - stainless-api-key: ${{ secrets.STAINLESS_API_KEY }} - - - name: Install Rye - if: ${{ steps.release.outputs.releases_created }} - run: | - curl -sSf https://rye.astral.sh/get | bash - echo "$HOME/.rye/shims" >> $GITHUB_PATH - env: - RYE_VERSION: '0.44.0' - RYE_INSTALL_OPTION: '--yes' - - - name: Publish to PyPI - if: ${{ steps.release.outputs.releases_created }} - run: | - bash ./bin/publish-pypi - env: - PYPI_TOKEN: ${{ secrets.OPENAI_PYPI_TOKEN || secrets.PYPI_TOKEN }} diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml index 32bd6929e2..b395b2f545 100644 --- a/.github/workflows/publish-pypi.yml +++ b/.github/workflows/publish-pypi.yml @@ -1,9 +1,13 @@ -# workflow for re-running publishing to PyPI in case it fails for some reason -# you can run this workflow by navigating to https://www.github.com/openai/openai-python/actions/workflows/publish-pypi.yml +# This workflow is triggered when a GitHub release is created. +# It can also be run manually to re-publish to PyPI in case it failed for some reason. +# You can run this workflow by navigating to https://www.github.com/openai/openai-python/actions/workflows/publish-pypi.yml name: Publish PyPI on: workflow_dispatch: + release: + types: [published] + jobs: publish: name: publish diff --git a/.github/workflows/release-doctor.yml b/.github/workflows/release-doctor.yml index e078964a6f..445f626d93 100644 --- a/.github/workflows/release-doctor.yml +++ b/.github/workflows/release-doctor.yml @@ -19,5 +19,4 @@ jobs: run: | bash ./bin/check-release-environment env: - STAINLESS_API_KEY: ${{ secrets.STAINLESS_API_KEY }} PYPI_TOKEN: ${{ secrets.OPENAI_PYPI_TOKEN || secrets.PYPI_TOKEN }} diff --git a/.stats.yml b/.stats.yml index edc2aaf89f..53c73037d5 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 81 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai-c8579861bc21d4d2155a5b9e8e7d54faee8083730673c4d32cbbe573d7fb4116.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-c8579861bc21d4d2155a5b9e8e7d54faee8083730673c4d32cbbe573d7fb4116.yml diff --git a/bin/check-release-environment b/bin/check-release-environment index 2cc5ad6352..5471b69edb 100644 --- a/bin/check-release-environment +++ b/bin/check-release-environment @@ -2,10 +2,6 @@ errors=() -if [ -z "${STAINLESS_API_KEY}" ]; then - errors+=("The STAINLESS_API_KEY secret has not been set. Please contact Stainless for an API key & set it in your organization secrets on GitHub.") -fi - if [ -z "${PYPI_TOKEN}" ]; then errors+=("The OPENAI_PYPI_TOKEN secret has not been set. Please set it in either this repository's secrets or your organization secrets.") fi From 1cb138b559fa937440388b5b160fc27561af29f7 Mon Sep 17 00:00:00 2001 From: meorphis Date: Fri, 14 Mar 2025 16:54:21 -0400 Subject: [PATCH 726/816] chore(internal): update release workflows --- .github/workflows/publish-pypi.yml | 8 ++------ .github/workflows/release-doctor.yml | 1 + 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml index b395b2f545..32bd6929e2 100644 --- a/.github/workflows/publish-pypi.yml +++ b/.github/workflows/publish-pypi.yml @@ -1,13 +1,9 @@ -# This workflow is triggered when a GitHub release is created. -# It can also be run manually to re-publish to PyPI in case it failed for some reason. -# You can run this workflow by navigating to https://www.github.com/openai/openai-python/actions/workflows/publish-pypi.yml +# workflow for re-running publishing to PyPI in case it fails for some reason +# you can run this workflow by navigating to https://www.github.com/openai/openai-python/actions/workflows/publish-pypi.yml name: Publish PyPI on: workflow_dispatch: - release: - types: [published] - jobs: publish: name: publish diff --git a/.github/workflows/release-doctor.yml b/.github/workflows/release-doctor.yml index 445f626d93..e078964a6f 100644 --- a/.github/workflows/release-doctor.yml +++ b/.github/workflows/release-doctor.yml @@ -19,4 +19,5 @@ jobs: run: | bash ./bin/check-release-environment env: + STAINLESS_API_KEY: ${{ secrets.STAINLESS_API_KEY }} PYPI_TOKEN: ${{ secrets.OPENAI_PYPI_TOKEN || secrets.PYPI_TOKEN }} From eb3d7ae36d2686645e15840ab369255157247dd9 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 14 Mar 2025 22:11:11 +0000 Subject: [PATCH 727/816] fix(types): handle more discriminated union shapes (#2206) --- src/openai/_models.py | 7 +++++-- tests/test_models.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/src/openai/_models.py b/src/openai/_models.py index 92986bfdf5..ff7c1f3392 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -66,7 +66,7 @@ from ._constants import RAW_RESPONSE_HEADER if TYPE_CHECKING: - from pydantic_core.core_schema import ModelField, LiteralSchema, ModelFieldsSchema + from pydantic_core.core_schema import ModelField, ModelSchema, LiteralSchema, ModelFieldsSchema __all__ = ["BaseModel", "GenericModel"] @@ -671,15 +671,18 @@ def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any, def _extract_field_schema_pv2(model: type[BaseModel], field_name: str) -> ModelField | None: schema = model.__pydantic_core_schema__ + if schema["type"] == "definitions": + schema = schema["schema"] + if schema["type"] != "model": return None + schema = cast("ModelSchema", schema) fields_schema = schema["schema"] if fields_schema["type"] != "model-fields": return None fields_schema = cast("ModelFieldsSchema", fields_schema) - field = fields_schema["fields"].get(field_name) if not field: return None diff --git a/tests/test_models.py b/tests/test_models.py index 30b17e3ac0..b9be1f3ea3 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -854,3 +854,35 @@ class Model(BaseModel): m = construct_type(value={"cls": "foo"}, type_=Model) assert isinstance(m, Model) assert isinstance(m.cls, str) + + +def test_discriminated_union_case() -> None: + class A(BaseModel): + type: Literal["a"] + + data: bool + + class B(BaseModel): + type: Literal["b"] + + data: List[Union[A, object]] + + class ModelA(BaseModel): + type: Literal["modelA"] + + data: int + + class ModelB(BaseModel): + type: Literal["modelB"] + + required: str + + data: Union[A, B] + + # when constructing ModelA | ModelB, value data doesn't match ModelB exactly - missing `required` + m = construct_type( + value={"type": "modelB", "data": {"type": "a", "data": True}}, + type_=cast(Any, Annotated[Union[ModelA, ModelB], PropertyInfo(discriminator="type")]), + ) + + assert isinstance(m, ModelB) From 5647865266af923b2e257ea0b5fc77e590542490 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 17 Mar 2025 13:04:17 +0000 Subject: [PATCH 728/816] fix(ci): ensure pip is always available (#2207) --- bin/publish-pypi | 1 + 1 file changed, 1 insertion(+) diff --git a/bin/publish-pypi b/bin/publish-pypi index 05bfccbb71..ebebf91657 100644 --- a/bin/publish-pypi +++ b/bin/publish-pypi @@ -5,5 +5,6 @@ mkdir -p dist rye build --clean # Patching importlib-metadata version until upstream library version is updated # https://github.com/pypa/twine/issues/977#issuecomment-2189800841 +"$HOME/.rye/self/bin/python3" -m ensurepip "$HOME/.rye/self/bin/python3" -m pip install 'importlib-metadata==7.2.1' rye publish --yes --token=$PYPI_TOKEN From 69919665d26d32c2c729ac7f1dc8db4e0d14d1a4 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 17 Mar 2025 15:52:16 +0000 Subject: [PATCH 729/816] fix(ci): remove publishing patch (#2208) --- bin/publish-pypi | 4 ---- pyproject.toml | 2 +- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/bin/publish-pypi b/bin/publish-pypi index ebebf91657..826054e924 100644 --- a/bin/publish-pypi +++ b/bin/publish-pypi @@ -3,8 +3,4 @@ set -eux mkdir -p dist rye build --clean -# Patching importlib-metadata version until upstream library version is updated -# https://github.com/pypa/twine/issues/977#issuecomment-2189800841 -"$HOME/.rye/self/bin/python3" -m ensurepip -"$HOME/.rye/self/bin/python3" -m pip install 'importlib-metadata==7.2.1' rye publish --yes --token=$PYPI_TOKEN diff --git a/pyproject.toml b/pyproject.toml index 2608de2060..0a9a931f6f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -99,7 +99,7 @@ typecheck = { chain = [ "typecheck:mypy" = "mypy ." [build-system] -requires = ["hatchling", "hatch-fancy-pypi-readme"] +requires = ["hatchling==1.26.3", "hatch-fancy-pypi-readme"] build-backend = "hatchling.build" [tool.hatch.build] From 17d78674d17e74b344f3701eb4ca6f5aa5cf1fc5 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 17 Mar 2025 15:52:49 +0000 Subject: [PATCH 730/816] release: 1.66.4 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 18 ++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 21 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 6d3d57b7ab..dac37ce406 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.66.3" + ".": "1.66.4" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index e799f6d117..1ed70082c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,23 @@ # Changelog +## 1.66.4 (2025-03-17) + +Full Changelog: [v1.66.3...v1.66.4](https://github.com/openai/openai-python/compare/v1.66.3...v1.66.4) + +### Bug Fixes + +* **ci:** ensure pip is always available ([#2207](https://github.com/openai/openai-python/issues/2207)) ([3f08e56](https://github.com/openai/openai-python/commit/3f08e56a48a04c2b7f03a4ad63f38228e25810e6)) +* **ci:** remove publishing patch ([#2208](https://github.com/openai/openai-python/issues/2208)) ([dd2dab7](https://github.com/openai/openai-python/commit/dd2dab7faf2a003da3e6af66780bd250be6e7f3f)) +* **types:** handle more discriminated union shapes ([#2206](https://github.com/openai/openai-python/issues/2206)) ([f85a9c6](https://github.com/openai/openai-python/commit/f85a9c633dcb9b64c0eb47d20151894742bbef22)) + + +### Chores + +* **internal:** bump rye to 0.44.0 ([#2200](https://github.com/openai/openai-python/issues/2200)) ([2dd3139](https://github.com/openai/openai-python/commit/2dd3139df6e7fe6307f9847e6527073e355e5047)) +* **internal:** remove CI condition ([#2203](https://github.com/openai/openai-python/issues/2203)) ([9620fdc](https://github.com/openai/openai-python/commit/9620fdcf4f2d01b6753ecc0abc16e5239c2b41e1)) +* **internal:** remove extra empty newlines ([#2195](https://github.com/openai/openai-python/issues/2195)) ([a1016a7](https://github.com/openai/openai-python/commit/a1016a78fe551e0f0e2562a0e81d1cb724d195da)) +* **internal:** update release workflows ([e2def44](https://github.com/openai/openai-python/commit/e2def4453323aa1cf8077df447fd55eb4c626393)) + ## 1.66.3 (2025-03-12) Full Changelog: [v1.66.2...v1.66.3](https://github.com/openai/openai-python/compare/v1.66.2...v1.66.3) diff --git a/pyproject.toml b/pyproject.toml index 0a9a931f6f..8247861185 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.66.3" +version = "1.66.4" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 6c4a192efc..df2f60a7dc 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.66.3" # x-release-please-version +__version__ = "1.66.4" # x-release-please-version From bff8da95ab1967426b92e0c0b899596a05606130 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 18 Mar 2025 21:50:14 +0000 Subject: [PATCH 731/816] release: 1.66.5 (#2223) * chore(internal): remove extra empty newlines (#2195) * chore(internal): bump rye to 0.44.0 (#2200) * chore(internal): remove CI condition (#2203) * chore(internal): update release workflows * fix(types): handle more discriminated union shapes (#2206) * fix(ci): ensure pip is always available (#2207) * fix(ci): remove publishing patch (#2208) * chore(internal): add back releases workflow * chore(internal): codegen related update (#2222) * fix(types): improve responses type names (#2224) * release: 1.66.5 --------- Co-authored-by: stainless-app[bot] <142633134+stainless-app[bot]@users.noreply.github.com> Co-authored-by: meorphis --- .github/workflows/create-releases.yml | 39 +++++ .release-please-manifest.json | 2 +- .stats.yml | 2 +- CHANGELOG.md | 14 ++ api.md | 8 +- pyproject.toml | 2 +- src/openai/_version.py | 2 +- src/openai/resources/batches.py | 16 +-- src/openai/resources/responses/input_items.py | 14 +- src/openai/types/batch_create_params.py | 9 +- .../types/chat/chat_completion_chunk.py | 7 +- .../chat_completion_content_part_param.py | 2 +- .../chat_completion_stream_options_param.py | 7 +- src/openai/types/responses/__init__.py | 15 ++ ...response_computer_tool_call_output_item.py | 47 ++++++ ...se_computer_tool_call_output_screenshot.py | 22 +++ ...puter_tool_call_output_screenshot_param.py | 21 +++ .../responses/response_function_tool_call.py | 6 +- .../response_function_tool_call_item.py | 11 ++ ...response_function_tool_call_output_item.py | 29 ++++ .../response_function_tool_call_param.py | 6 +- .../responses/response_input_item_param.py | 18 +-- .../responses/response_input_message_item.py | 33 +++++ .../types/responses/response_input_param.py | 18 +-- src/openai/types/responses/response_item.py | 30 ++++ .../types/responses/response_item_list.py | 136 +----------------- src/openai/types/responses/response_usage.py | 13 +- src/openai/types/shared/reasoning.py | 2 +- src/openai/types/shared_params/reasoning.py | 6 +- .../responses/test_input_items.py | 18 +-- tests/api_resources/test_batches.py | 16 +-- 31 files changed, 351 insertions(+), 220 deletions(-) create mode 100644 .github/workflows/create-releases.yml create mode 100644 src/openai/types/responses/response_computer_tool_call_output_item.py create mode 100644 src/openai/types/responses/response_computer_tool_call_output_screenshot.py create mode 100644 src/openai/types/responses/response_computer_tool_call_output_screenshot_param.py create mode 100644 src/openai/types/responses/response_function_tool_call_item.py create mode 100644 src/openai/types/responses/response_function_tool_call_output_item.py create mode 100644 src/openai/types/responses/response_input_message_item.py create mode 100644 src/openai/types/responses/response_item.py diff --git a/.github/workflows/create-releases.yml b/.github/workflows/create-releases.yml new file mode 100644 index 0000000000..b3e1c679d4 --- /dev/null +++ b/.github/workflows/create-releases.yml @@ -0,0 +1,39 @@ +name: Create releases +on: + schedule: + - cron: '0 5 * * *' # every day at 5am UTC + push: + branches: + - main + +jobs: + release: + name: release + if: github.ref == 'refs/heads/main' && github.repository == 'openai/openai-python' + runs-on: ubuntu-latest + environment: publish + + steps: + - uses: actions/checkout@v4 + + - uses: stainless-api/trigger-release-please@v1 + id: release + with: + repo: ${{ github.event.repository.full_name }} + stainless-api-key: ${{ secrets.STAINLESS_API_KEY }} + + - name: Install Rye + if: ${{ steps.release.outputs.releases_created }} + run: | + curl -sSf https://rye.astral.sh/get | bash + echo "$HOME/.rye/shims" >> $GITHUB_PATH + env: + RYE_VERSION: '0.44.0' + RYE_INSTALL_OPTION: '--yes' + + - name: Publish to PyPI + if: ${{ steps.release.outputs.releases_created }} + run: | + bash ./bin/publish-pypi + env: + PYPI_TOKEN: ${{ secrets.OPENAI_PYPI_TOKEN || secrets.PYPI_TOKEN }} diff --git a/.release-please-manifest.json b/.release-please-manifest.json index dac37ce406..e567f9cb13 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.66.4" + ".": "1.66.5" } \ No newline at end of file diff --git a/.stats.yml b/.stats.yml index 53c73037d5..b032562238 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 81 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-c8579861bc21d4d2155a5b9e8e7d54faee8083730673c4d32cbbe573d7fb4116.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-f3bce04386c4fcfd5037e0477fbaa39010003fd1558eb5185fe4a71dd6a05fdd.yml diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ed70082c7..d8fb019fc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,19 @@ # Changelog +## 1.66.5 (2025-03-18) + +Full Changelog: [v1.66.4...v1.66.5](https://github.com/openai/openai-python/compare/v1.66.4...v1.66.5) + +### Bug Fixes + +* **types:** improve responses type names ([#2224](https://github.com/openai/openai-python/issues/2224)) ([5f7beb8](https://github.com/openai/openai-python/commit/5f7beb873af5ccef2551f34ab3ef098e099ce9c6)) + + +### Chores + +* **internal:** add back releases workflow ([c71d4c9](https://github.com/openai/openai-python/commit/c71d4c918eab3532b36ea944b0c4069db6ac2d38)) +* **internal:** codegen related update ([#2222](https://github.com/openai/openai-python/issues/2222)) ([f570d91](https://github.com/openai/openai-python/commit/f570d914a16cb5092533e32dfd863027d378c0b5)) + ## 1.66.4 (2025-03-17) Full Changelog: [v1.66.3...v1.66.4](https://github.com/openai/openai-python/compare/v1.66.3...v1.66.4) diff --git a/api.md b/api.md index e760fe69c1..6e7f48a645 100644 --- a/api.md +++ b/api.md @@ -605,6 +605,8 @@ from openai.types.responses import ( ResponseCodeInterpreterToolCall, ResponseCompletedEvent, ResponseComputerToolCall, + ResponseComputerToolCallOutputItem, + ResponseComputerToolCallOutputScreenshot, ResponseContent, ResponseContentPartAddedEvent, ResponseContentPartDoneEvent, @@ -621,6 +623,8 @@ from openai.types.responses import ( ResponseFunctionCallArgumentsDeltaEvent, ResponseFunctionCallArgumentsDoneEvent, ResponseFunctionToolCall, + ResponseFunctionToolCallItem, + ResponseFunctionToolCallOutputItem, ResponseFunctionWebSearch, ResponseInProgressEvent, ResponseIncludable, @@ -632,7 +636,9 @@ from openai.types.responses import ( ResponseInputImage, ResponseInputItem, ResponseInputMessageContentList, + ResponseInputMessageItem, ResponseInputText, + ResponseItem, ResponseOutputAudio, ResponseOutputItem, ResponseOutputItemAddedEvent, @@ -677,4 +683,4 @@ from openai.types.responses import ResponseItemList Methods: -- client.responses.input_items.list(response_id, \*\*params) -> SyncCursorPage[Data] +- client.responses.input_items.list(response_id, \*\*params) -> SyncCursorPage[ResponseItem] diff --git a/pyproject.toml b/pyproject.toml index 8247861185..5fdf2a836d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.66.4" +version = "1.66.5" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index df2f60a7dc..dbefc6ec32 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.66.4" # x-release-please-version +__version__ = "1.66.5" # x-release-please-version diff --git a/src/openai/resources/batches.py b/src/openai/resources/batches.py index 7e7ec19ec2..b7a299be12 100644 --- a/src/openai/resources/batches.py +++ b/src/openai/resources/batches.py @@ -49,7 +49,7 @@ def create( self, *, completion_window: Literal["24h"], - endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"], + endpoint: Literal["/v1/responses", "/v1/chat/completions", "/v1/embeddings", "/v1/completions"], input_file_id: str, metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -67,9 +67,9 @@ def create( is supported. endpoint: The endpoint to be used for all requests in the batch. Currently - `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` are supported. - Note that `/v1/embeddings` batches are also restricted to a maximum of 50,000 - embedding inputs across all requests in the batch. + `/v1/responses`, `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` + are supported. Note that `/v1/embeddings` batches are also restricted to a + maximum of 50,000 embedding inputs across all requests in the batch. input_file_id: The ID of an uploaded file that contains requests for the new batch. @@ -259,7 +259,7 @@ async def create( self, *, completion_window: Literal["24h"], - endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"], + endpoint: Literal["/v1/responses", "/v1/chat/completions", "/v1/embeddings", "/v1/completions"], input_file_id: str, metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -277,9 +277,9 @@ async def create( is supported. endpoint: The endpoint to be used for all requests in the batch. Currently - `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` are supported. - Note that `/v1/embeddings` batches are also restricted to a maximum of 50,000 - embedding inputs across all requests in the batch. + `/v1/responses`, `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` + are supported. Note that `/v1/embeddings` batches are also restricted to a + maximum of 50,000 embedding inputs across all requests in the batch. input_file_id: The ID of an uploaded file that contains requests for the new batch. diff --git a/src/openai/resources/responses/input_items.py b/src/openai/resources/responses/input_items.py index 10e7d545dc..e341393cd1 100644 --- a/src/openai/resources/responses/input_items.py +++ b/src/openai/resources/responses/input_items.py @@ -16,7 +16,7 @@ from ...pagination import SyncCursorPage, AsyncCursorPage from ..._base_client import AsyncPaginator, make_request_options from ...types.responses import input_item_list_params -from ...types.responses.response_item_list import Data +from ...types.responses.response_item import ResponseItem __all__ = ["InputItems", "AsyncInputItems"] @@ -55,7 +55,7 @@ def list( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> SyncCursorPage[Data]: + ) -> SyncCursorPage[ResponseItem]: """ Returns a list of input items for a given response. @@ -84,7 +84,7 @@ def list( raise ValueError(f"Expected a non-empty value for `response_id` but received {response_id!r}") return self._get_api_list( f"/responses/{response_id}/input_items", - page=SyncCursorPage[Data], + page=SyncCursorPage[ResponseItem], options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, @@ -100,7 +100,7 @@ def list( input_item_list_params.InputItemListParams, ), ), - model=cast(Any, Data), # Union types cannot be passed in as arguments in the type system + model=cast(Any, ResponseItem), # Union types cannot be passed in as arguments in the type system ) @@ -138,7 +138,7 @@ def list( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> AsyncPaginator[Data, AsyncCursorPage[Data]]: + ) -> AsyncPaginator[ResponseItem, AsyncCursorPage[ResponseItem]]: """ Returns a list of input items for a given response. @@ -167,7 +167,7 @@ def list( raise ValueError(f"Expected a non-empty value for `response_id` but received {response_id!r}") return self._get_api_list( f"/responses/{response_id}/input_items", - page=AsyncCursorPage[Data], + page=AsyncCursorPage[ResponseItem], options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, @@ -183,7 +183,7 @@ def list( input_item_list_params.InputItemListParams, ), ), - model=cast(Any, Data), # Union types cannot be passed in as arguments in the type system + model=cast(Any, ResponseItem), # Union types cannot be passed in as arguments in the type system ) diff --git a/src/openai/types/batch_create_params.py b/src/openai/types/batch_create_params.py index e5be1d2bac..cc95afd3ba 100644 --- a/src/openai/types/batch_create_params.py +++ b/src/openai/types/batch_create_params.py @@ -17,12 +17,13 @@ class BatchCreateParams(TypedDict, total=False): Currently only `24h` is supported. """ - endpoint: Required[Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"]] + endpoint: Required[Literal["/v1/responses", "/v1/chat/completions", "/v1/embeddings", "/v1/completions"]] """The endpoint to be used for all requests in the batch. - Currently `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` are - supported. Note that `/v1/embeddings` batches are also restricted to a maximum - of 50,000 embedding inputs across all requests in the batch. + Currently `/v1/responses`, `/v1/chat/completions`, `/v1/embeddings`, and + `/v1/completions` are supported. Note that `/v1/embeddings` batches are also + restricted to a maximum of 50,000 embedding inputs across all requests in the + batch. """ input_file_id: Required[str] diff --git a/src/openai/types/chat/chat_completion_chunk.py b/src/openai/types/chat/chat_completion_chunk.py index dede513f1e..31b9cb5456 100644 --- a/src/openai/types/chat/chat_completion_chunk.py +++ b/src/openai/types/chat/chat_completion_chunk.py @@ -142,6 +142,9 @@ class ChatCompletionChunk(BaseModel): """ An optional field that will only be present when you set `stream_options: {"include_usage": true}` in your request. When present, it - contains a null value except for the last chunk which contains the token usage - statistics for the entire request. + contains a null value **except for the last chunk** which contains the token + usage statistics for the entire request. + + **NOTE:** If the stream is interrupted or cancelled, you may not receive the + final usage chunk which contains the total token usage for the request. """ diff --git a/src/openai/types/chat/chat_completion_content_part_param.py b/src/openai/types/chat/chat_completion_content_part_param.py index 1293c54312..cbedc853ba 100644 --- a/src/openai/types/chat/chat_completion_content_part_param.py +++ b/src/openai/types/chat/chat_completion_content_part_param.py @@ -22,7 +22,7 @@ class FileFile(TypedDict, total=False): file_id: str """The ID of an uploaded file to use as input.""" - file_name: str + filename: str """The name of the file, used when passing the file to the model as a string.""" diff --git a/src/openai/types/chat/chat_completion_stream_options_param.py b/src/openai/types/chat/chat_completion_stream_options_param.py index fbf7291821..471e0eba98 100644 --- a/src/openai/types/chat/chat_completion_stream_options_param.py +++ b/src/openai/types/chat/chat_completion_stream_options_param.py @@ -12,6 +12,9 @@ class ChatCompletionStreamOptionsParam(TypedDict, total=False): """If set, an additional chunk will be streamed before the `data: [DONE]` message. The `usage` field on this chunk shows the token usage statistics for the entire - request, and the `choices` field will always be an empty array. All other chunks - will also include a `usage` field, but with a null value. + request, and the `choices` field will always be an empty array. + + All other chunks will also include a `usage` field, but with a null value. + **NOTE:** If the stream is interrupted, you may not receive the final usage + chunk which contains the total token usage for the request. """ diff --git a/src/openai/types/responses/__init__.py b/src/openai/types/responses/__init__.py index 7c0cf9e3f2..4f07a3d097 100644 --- a/src/openai/types/responses/__init__.py +++ b/src/openai/types/responses/__init__.py @@ -7,6 +7,7 @@ from .tool_param import ToolParam as ToolParam from .computer_tool import ComputerTool as ComputerTool from .function_tool import FunctionTool as FunctionTool +from .response_item import ResponseItem as ResponseItem from .response_error import ResponseError as ResponseError from .response_usage import ResponseUsage as ResponseUsage from .parsed_response import ( @@ -66,6 +67,7 @@ from .response_computer_tool_call import ResponseComputerToolCall as ResponseComputerToolCall from .response_format_text_config import ResponseFormatTextConfig as ResponseFormatTextConfig from .response_function_tool_call import ResponseFunctionToolCall as ResponseFunctionToolCall +from .response_input_message_item import ResponseInputMessageItem as ResponseInputMessageItem from .response_refusal_done_event import ResponseRefusalDoneEvent as ResponseRefusalDoneEvent from .response_function_web_search import ResponseFunctionWebSearch as ResponseFunctionWebSearch from .response_input_content_param import ResponseInputContentParam as ResponseInputContentParam @@ -76,6 +78,7 @@ from .response_file_search_tool_call import ResponseFileSearchToolCall as ResponseFileSearchToolCall from .response_output_item_done_event import ResponseOutputItemDoneEvent as ResponseOutputItemDoneEvent from .response_content_part_done_event import ResponseContentPartDoneEvent as ResponseContentPartDoneEvent +from .response_function_tool_call_item import ResponseFunctionToolCallItem as ResponseFunctionToolCallItem from .response_output_item_added_event import ResponseOutputItemAddedEvent as ResponseOutputItemAddedEvent from .response_computer_tool_call_param import ResponseComputerToolCallParam as ResponseComputerToolCallParam from .response_content_part_added_event import ResponseContentPartAddedEvent as ResponseContentPartAddedEvent @@ -90,9 +93,15 @@ from .response_audio_transcript_delta_event import ( ResponseAudioTranscriptDeltaEvent as ResponseAudioTranscriptDeltaEvent, ) +from .response_computer_tool_call_output_item import ( + ResponseComputerToolCallOutputItem as ResponseComputerToolCallOutputItem, +) from .response_format_text_json_schema_config import ( ResponseFormatTextJSONSchemaConfig as ResponseFormatTextJSONSchemaConfig, ) +from .response_function_tool_call_output_item import ( + ResponseFunctionToolCallOutputItem as ResponseFunctionToolCallOutputItem, +) from .response_web_search_call_completed_event import ( ResponseWebSearchCallCompletedEvent as ResponseWebSearchCallCompletedEvent, ) @@ -120,6 +129,9 @@ from .response_function_call_arguments_delta_event import ( ResponseFunctionCallArgumentsDeltaEvent as ResponseFunctionCallArgumentsDeltaEvent, ) +from .response_computer_tool_call_output_screenshot import ( + ResponseComputerToolCallOutputScreenshot as ResponseComputerToolCallOutputScreenshot, +) from .response_format_text_json_schema_config_param import ( ResponseFormatTextJSONSchemaConfigParam as ResponseFormatTextJSONSchemaConfigParam, ) @@ -138,3 +150,6 @@ from .response_code_interpreter_call_interpreting_event import ( ResponseCodeInterpreterCallInterpretingEvent as ResponseCodeInterpreterCallInterpretingEvent, ) +from .response_computer_tool_call_output_screenshot_param import ( + ResponseComputerToolCallOutputScreenshotParam as ResponseComputerToolCallOutputScreenshotParam, +) diff --git a/src/openai/types/responses/response_computer_tool_call_output_item.py b/src/openai/types/responses/response_computer_tool_call_output_item.py new file mode 100644 index 0000000000..a2dd68f579 --- /dev/null +++ b/src/openai/types/responses/response_computer_tool_call_output_item.py @@ -0,0 +1,47 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from ..._models import BaseModel +from .response_computer_tool_call_output_screenshot import ResponseComputerToolCallOutputScreenshot + +__all__ = ["ResponseComputerToolCallOutputItem", "AcknowledgedSafetyCheck"] + + +class AcknowledgedSafetyCheck(BaseModel): + id: str + """The ID of the pending safety check.""" + + code: str + """The type of the pending safety check.""" + + message: str + """Details about the pending safety check.""" + + +class ResponseComputerToolCallOutputItem(BaseModel): + id: str + """The unique ID of the computer call tool output.""" + + call_id: str + """The ID of the computer tool call that produced the output.""" + + output: ResponseComputerToolCallOutputScreenshot + """A computer screenshot image used with the computer use tool.""" + + type: Literal["computer_call_output"] + """The type of the computer tool call output. Always `computer_call_output`.""" + + acknowledged_safety_checks: Optional[List[AcknowledgedSafetyCheck]] = None + """ + The safety checks reported by the API that have been acknowledged by the + developer. + """ + + status: Optional[Literal["in_progress", "completed", "incomplete"]] = None + """The status of the message input. + + One of `in_progress`, `completed`, or `incomplete`. Populated when input items + are returned via API. + """ diff --git a/src/openai/types/responses/response_computer_tool_call_output_screenshot.py b/src/openai/types/responses/response_computer_tool_call_output_screenshot.py new file mode 100644 index 0000000000..a500da85c1 --- /dev/null +++ b/src/openai/types/responses/response_computer_tool_call_output_screenshot.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseComputerToolCallOutputScreenshot"] + + +class ResponseComputerToolCallOutputScreenshot(BaseModel): + type: Literal["computer_screenshot"] + """Specifies the event type. + + For a computer screenshot, this property is always set to `computer_screenshot`. + """ + + file_id: Optional[str] = None + """The identifier of an uploaded file that contains the screenshot.""" + + image_url: Optional[str] = None + """The URL of the screenshot image.""" diff --git a/src/openai/types/responses/response_computer_tool_call_output_screenshot_param.py b/src/openai/types/responses/response_computer_tool_call_output_screenshot_param.py new file mode 100644 index 0000000000..efc2028aa4 --- /dev/null +++ b/src/openai/types/responses/response_computer_tool_call_output_screenshot_param.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ResponseComputerToolCallOutputScreenshotParam"] + + +class ResponseComputerToolCallOutputScreenshotParam(TypedDict, total=False): + type: Required[Literal["computer_screenshot"]] + """Specifies the event type. + + For a computer screenshot, this property is always set to `computer_screenshot`. + """ + + file_id: str + """The identifier of an uploaded file that contains the screenshot.""" + + image_url: str + """The URL of the screenshot image.""" diff --git a/src/openai/types/responses/response_function_tool_call.py b/src/openai/types/responses/response_function_tool_call.py index 5d82906cb7..2a8482204e 100644 --- a/src/openai/types/responses/response_function_tool_call.py +++ b/src/openai/types/responses/response_function_tool_call.py @@ -9,9 +9,6 @@ class ResponseFunctionToolCall(BaseModel): - id: str - """The unique ID of the function tool call.""" - arguments: str """A JSON string of the arguments to pass to the function.""" @@ -24,6 +21,9 @@ class ResponseFunctionToolCall(BaseModel): type: Literal["function_call"] """The type of the function tool call. Always `function_call`.""" + id: Optional[str] = None + """The unique ID of the function tool call.""" + status: Optional[Literal["in_progress", "completed", "incomplete"]] = None """The status of the item. diff --git a/src/openai/types/responses/response_function_tool_call_item.py b/src/openai/types/responses/response_function_tool_call_item.py new file mode 100644 index 0000000000..477e9b70aa --- /dev/null +++ b/src/openai/types/responses/response_function_tool_call_item.py @@ -0,0 +1,11 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +from .response_function_tool_call import ResponseFunctionToolCall + +__all__ = ["ResponseFunctionToolCallItem"] + + +class ResponseFunctionToolCallItem(ResponseFunctionToolCall): + id: str # type: ignore + """The unique ID of the function call tool output.""" diff --git a/src/openai/types/responses/response_function_tool_call_output_item.py b/src/openai/types/responses/response_function_tool_call_output_item.py new file mode 100644 index 0000000000..4c8c41a6fe --- /dev/null +++ b/src/openai/types/responses/response_function_tool_call_output_item.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseFunctionToolCallOutputItem"] + + +class ResponseFunctionToolCallOutputItem(BaseModel): + id: str + """The unique ID of the function call tool output.""" + + call_id: str + """The unique ID of the function tool call generated by the model.""" + + output: str + """A JSON string of the output of the function tool call.""" + + type: Literal["function_call_output"] + """The type of the function tool call output. Always `function_call_output`.""" + + status: Optional[Literal["in_progress", "completed", "incomplete"]] = None + """The status of the item. + + One of `in_progress`, `completed`, or `incomplete`. Populated when items are + returned via API. + """ diff --git a/src/openai/types/responses/response_function_tool_call_param.py b/src/openai/types/responses/response_function_tool_call_param.py index 51b947a764..eaa263cf67 100644 --- a/src/openai/types/responses/response_function_tool_call_param.py +++ b/src/openai/types/responses/response_function_tool_call_param.py @@ -8,9 +8,6 @@ class ResponseFunctionToolCallParam(TypedDict, total=False): - id: Required[str] - """The unique ID of the function tool call.""" - arguments: Required[str] """A JSON string of the arguments to pass to the function.""" @@ -23,6 +20,9 @@ class ResponseFunctionToolCallParam(TypedDict, total=False): type: Required[Literal["function_call"]] """The type of the function tool call. Always `function_call`.""" + id: str + """The unique ID of the function tool call.""" + status: Literal["in_progress", "completed", "incomplete"] """The status of the item. diff --git a/src/openai/types/responses/response_input_item_param.py b/src/openai/types/responses/response_input_item_param.py index 32ac13cabb..2505f7c0b5 100644 --- a/src/openai/types/responses/response_input_item_param.py +++ b/src/openai/types/responses/response_input_item_param.py @@ -13,12 +13,12 @@ from .response_function_web_search_param import ResponseFunctionWebSearchParam from .response_file_search_tool_call_param import ResponseFileSearchToolCallParam from .response_input_message_content_list_param import ResponseInputMessageContentListParam +from .response_computer_tool_call_output_screenshot_param import ResponseComputerToolCallOutputScreenshotParam __all__ = [ "ResponseInputItemParam", "Message", "ComputerCallOutput", - "ComputerCallOutputOutput", "ComputerCallOutputAcknowledgedSafetyCheck", "FunctionCallOutput", "ItemReference", @@ -46,20 +46,6 @@ class Message(TypedDict, total=False): """The type of the message input. Always set to `message`.""" -class ComputerCallOutputOutput(TypedDict, total=False): - type: Required[Literal["computer_screenshot"]] - """Specifies the event type. - - For a computer screenshot, this property is always set to `computer_screenshot`. - """ - - file_id: str - """The identifier of an uploaded file that contains the screenshot.""" - - image_url: str - """The URL of the screenshot image.""" - - class ComputerCallOutputAcknowledgedSafetyCheck(TypedDict, total=False): id: Required[str] """The ID of the pending safety check.""" @@ -75,7 +61,7 @@ class ComputerCallOutput(TypedDict, total=False): call_id: Required[str] """The ID of the computer tool call that produced the output.""" - output: Required[ComputerCallOutputOutput] + output: Required[ResponseComputerToolCallOutputScreenshotParam] """A computer screenshot image used with the computer use tool.""" type: Required[Literal["computer_call_output"]] diff --git a/src/openai/types/responses/response_input_message_item.py b/src/openai/types/responses/response_input_message_item.py new file mode 100644 index 0000000000..6a788e7fa4 --- /dev/null +++ b/src/openai/types/responses/response_input_message_item.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel +from .response_input_message_content_list import ResponseInputMessageContentList + +__all__ = ["ResponseInputMessageItem"] + + +class ResponseInputMessageItem(BaseModel): + id: str + """The unique ID of the message input.""" + + content: ResponseInputMessageContentList + """ + A list of one or many input items to the model, containing different content + types. + """ + + role: Literal["user", "system", "developer"] + """The role of the message input. One of `user`, `system`, or `developer`.""" + + status: Optional[Literal["in_progress", "completed", "incomplete"]] = None + """The status of item. + + One of `in_progress`, `completed`, or `incomplete`. Populated when items are + returned via API. + """ + + type: Optional[Literal["message"]] = None + """The type of the message input. Always set to `message`.""" diff --git a/src/openai/types/responses/response_input_param.py b/src/openai/types/responses/response_input_param.py index b942f4868a..84a80eb7c2 100644 --- a/src/openai/types/responses/response_input_param.py +++ b/src/openai/types/responses/response_input_param.py @@ -13,13 +13,13 @@ from .response_function_web_search_param import ResponseFunctionWebSearchParam from .response_file_search_tool_call_param import ResponseFileSearchToolCallParam from .response_input_message_content_list_param import ResponseInputMessageContentListParam +from .response_computer_tool_call_output_screenshot_param import ResponseComputerToolCallOutputScreenshotParam __all__ = [ "ResponseInputParam", "ResponseInputItemParam", "Message", "ComputerCallOutput", - "ComputerCallOutputOutput", "ComputerCallOutputAcknowledgedSafetyCheck", "FunctionCallOutput", "ItemReference", @@ -47,20 +47,6 @@ class Message(TypedDict, total=False): """The type of the message input. Always set to `message`.""" -class ComputerCallOutputOutput(TypedDict, total=False): - type: Required[Literal["computer_screenshot"]] - """Specifies the event type. - - For a computer screenshot, this property is always set to `computer_screenshot`. - """ - - file_id: str - """The identifier of an uploaded file that contains the screenshot.""" - - image_url: str - """The URL of the screenshot image.""" - - class ComputerCallOutputAcknowledgedSafetyCheck(TypedDict, total=False): id: Required[str] """The ID of the pending safety check.""" @@ -76,7 +62,7 @@ class ComputerCallOutput(TypedDict, total=False): call_id: Required[str] """The ID of the computer tool call that produced the output.""" - output: Required[ComputerCallOutputOutput] + output: Required[ResponseComputerToolCallOutputScreenshotParam] """A computer screenshot image used with the computer use tool.""" type: Required[Literal["computer_call_output"]] diff --git a/src/openai/types/responses/response_item.py b/src/openai/types/responses/response_item.py new file mode 100644 index 0000000000..dc8d67d0f2 --- /dev/null +++ b/src/openai/types/responses/response_item.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Annotated, TypeAlias + +from ..._utils import PropertyInfo +from .response_output_message import ResponseOutputMessage +from .response_computer_tool_call import ResponseComputerToolCall +from .response_input_message_item import ResponseInputMessageItem +from .response_function_web_search import ResponseFunctionWebSearch +from .response_file_search_tool_call import ResponseFileSearchToolCall +from .response_function_tool_call_item import ResponseFunctionToolCallItem +from .response_computer_tool_call_output_item import ResponseComputerToolCallOutputItem +from .response_function_tool_call_output_item import ResponseFunctionToolCallOutputItem + +__all__ = ["ResponseItem"] + +ResponseItem: TypeAlias = Annotated[ + Union[ + ResponseInputMessageItem, + ResponseOutputMessage, + ResponseFileSearchToolCall, + ResponseComputerToolCall, + ResponseComputerToolCallOutputItem, + ResponseFunctionWebSearch, + ResponseFunctionToolCallItem, + ResponseFunctionToolCallOutputItem, + ], + PropertyInfo(discriminator="type"), +] diff --git a/src/openai/types/responses/response_item_list.py b/src/openai/types/responses/response_item_list.py index 7c3e4d7f82..b43eacdb51 100644 --- a/src/openai/types/responses/response_item_list.py +++ b/src/openai/types/responses/response_item_list.py @@ -1,142 +1,16 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing import List, Union, Optional -from typing_extensions import Literal, Annotated, TypeAlias +from typing import List +from typing_extensions import Literal -from ..._utils import PropertyInfo from ..._models import BaseModel -from .response_output_message import ResponseOutputMessage -from .response_computer_tool_call import ResponseComputerToolCall -from .response_function_tool_call import ResponseFunctionToolCall -from .response_function_web_search import ResponseFunctionWebSearch -from .response_file_search_tool_call import ResponseFileSearchToolCall -from .response_input_message_content_list import ResponseInputMessageContentList +from .response_item import ResponseItem -__all__ = [ - "ResponseItemList", - "Data", - "DataMessage", - "DataComputerCallOutput", - "DataComputerCallOutputOutput", - "DataComputerCallOutputAcknowledgedSafetyCheck", - "DataFunctionCallOutput", -] - - -class DataMessage(BaseModel): - id: str - """The unique ID of the message input.""" - - content: ResponseInputMessageContentList - """ - A list of one or many input items to the model, containing different content - types. - """ - - role: Literal["user", "system", "developer"] - """The role of the message input. One of `user`, `system`, or `developer`.""" - - status: Optional[Literal["in_progress", "completed", "incomplete"]] = None - """The status of item. - - One of `in_progress`, `completed`, or `incomplete`. Populated when items are - returned via API. - """ - - type: Optional[Literal["message"]] = None - """The type of the message input. Always set to `message`.""" - - -class DataComputerCallOutputOutput(BaseModel): - type: Literal["computer_screenshot"] - """Specifies the event type. - - For a computer screenshot, this property is always set to `computer_screenshot`. - """ - - file_id: Optional[str] = None - """The identifier of an uploaded file that contains the screenshot.""" - - image_url: Optional[str] = None - """The URL of the screenshot image.""" - - -class DataComputerCallOutputAcknowledgedSafetyCheck(BaseModel): - id: str - """The ID of the pending safety check.""" - - code: str - """The type of the pending safety check.""" - - message: str - """Details about the pending safety check.""" - - -class DataComputerCallOutput(BaseModel): - id: str - """The unique ID of the computer call tool output.""" - - call_id: str - """The ID of the computer tool call that produced the output.""" - - output: DataComputerCallOutputOutput - """A computer screenshot image used with the computer use tool.""" - - type: Literal["computer_call_output"] - """The type of the computer tool call output. Always `computer_call_output`.""" - - acknowledged_safety_checks: Optional[List[DataComputerCallOutputAcknowledgedSafetyCheck]] = None - """ - The safety checks reported by the API that have been acknowledged by the - developer. - """ - - status: Optional[Literal["in_progress", "completed", "incomplete"]] = None - """The status of the message input. - - One of `in_progress`, `completed`, or `incomplete`. Populated when input items - are returned via API. - """ - - -class DataFunctionCallOutput(BaseModel): - id: str - """The unique ID of the function call tool output.""" - - call_id: str - """The unique ID of the function tool call generated by the model.""" - - output: str - """A JSON string of the output of the function tool call.""" - - type: Literal["function_call_output"] - """The type of the function tool call output. Always `function_call_output`.""" - - status: Optional[Literal["in_progress", "completed", "incomplete"]] = None - """The status of the item. - - One of `in_progress`, `completed`, or `incomplete`. Populated when items are - returned via API. - """ - - -Data: TypeAlias = Annotated[ - Union[ - DataMessage, - ResponseOutputMessage, - ResponseFileSearchToolCall, - ResponseComputerToolCall, - DataComputerCallOutput, - ResponseFunctionWebSearch, - ResponseFunctionToolCall, - DataFunctionCallOutput, - ], - PropertyInfo(discriminator="type"), -] +__all__ = ["ResponseItemList"] class ResponseItemList(BaseModel): - data: List[Data] + data: List[ResponseItem] """A list of items used to generate this response.""" first_id: str diff --git a/src/openai/types/responses/response_usage.py b/src/openai/types/responses/response_usage.py index ef631c5882..9ad36bd326 100644 --- a/src/openai/types/responses/response_usage.py +++ b/src/openai/types/responses/response_usage.py @@ -3,7 +3,15 @@ from ..._models import BaseModel -__all__ = ["ResponseUsage", "OutputTokensDetails"] +__all__ = ["ResponseUsage", "InputTokensDetails", "OutputTokensDetails"] + + +class InputTokensDetails(BaseModel): + cached_tokens: int + """The number of tokens that were retrieved from the cache. + + [More on prompt caching](https://platform.openai.com/docs/guides/prompt-caching). + """ class OutputTokensDetails(BaseModel): @@ -15,6 +23,9 @@ class ResponseUsage(BaseModel): input_tokens: int """The number of input tokens.""" + input_tokens_details: InputTokensDetails + """A detailed breakdown of the input tokens.""" + output_tokens: int """The number of output tokens.""" diff --git a/src/openai/types/shared/reasoning.py b/src/openai/types/shared/reasoning.py index 50821a1727..78a396d738 100644 --- a/src/openai/types/shared/reasoning.py +++ b/src/openai/types/shared/reasoning.py @@ -20,7 +20,7 @@ class Reasoning(BaseModel): """ generate_summary: Optional[Literal["concise", "detailed"]] = None - """**o-series models only** + """**computer_use_preview only** A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of `concise` or diff --git a/src/openai/types/shared_params/reasoning.py b/src/openai/types/shared_params/reasoning.py index f2b5c5963a..2953b895c4 100644 --- a/src/openai/types/shared_params/reasoning.py +++ b/src/openai/types/shared_params/reasoning.py @@ -3,7 +3,7 @@ from __future__ import annotations from typing import Optional -from typing_extensions import Literal, Required, TypedDict +from typing_extensions import Literal, TypedDict from ..shared.reasoning_effort import ReasoningEffort @@ -11,7 +11,7 @@ class Reasoning(TypedDict, total=False): - effort: Required[Optional[ReasoningEffort]] + effort: Optional[ReasoningEffort] """**o-series models only** Constrains effort on reasoning for @@ -21,7 +21,7 @@ class Reasoning(TypedDict, total=False): """ generate_summary: Optional[Literal["concise", "detailed"]] - """**o-series models only** + """**computer_use_preview only** A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. One of `concise` or diff --git a/tests/api_resources/responses/test_input_items.py b/tests/api_resources/responses/test_input_items.py index 28c5e8ca1f..77a156b5ac 100644 --- a/tests/api_resources/responses/test_input_items.py +++ b/tests/api_resources/responses/test_input_items.py @@ -10,7 +10,7 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.responses.response_item_list import Data +from openai.types.responses import ResponseItem base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") @@ -23,7 +23,7 @@ def test_method_list(self, client: OpenAI) -> None: input_item = client.responses.input_items.list( response_id="response_id", ) - assert_matches_type(SyncCursorPage[Data], input_item, path=["response"]) + assert_matches_type(SyncCursorPage[ResponseItem], input_item, path=["response"]) @parametrize def test_method_list_with_all_params(self, client: OpenAI) -> None: @@ -34,7 +34,7 @@ def test_method_list_with_all_params(self, client: OpenAI) -> None: limit=0, order="asc", ) - assert_matches_type(SyncCursorPage[Data], input_item, path=["response"]) + assert_matches_type(SyncCursorPage[ResponseItem], input_item, path=["response"]) @parametrize def test_raw_response_list(self, client: OpenAI) -> None: @@ -45,7 +45,7 @@ def test_raw_response_list(self, client: OpenAI) -> None: assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" input_item = response.parse() - assert_matches_type(SyncCursorPage[Data], input_item, path=["response"]) + assert_matches_type(SyncCursorPage[ResponseItem], input_item, path=["response"]) @parametrize def test_streaming_response_list(self, client: OpenAI) -> None: @@ -56,7 +56,7 @@ def test_streaming_response_list(self, client: OpenAI) -> None: assert response.http_request.headers.get("X-Stainless-Lang") == "python" input_item = response.parse() - assert_matches_type(SyncCursorPage[Data], input_item, path=["response"]) + assert_matches_type(SyncCursorPage[ResponseItem], input_item, path=["response"]) assert cast(Any, response.is_closed) is True @@ -76,7 +76,7 @@ async def test_method_list(self, async_client: AsyncOpenAI) -> None: input_item = await async_client.responses.input_items.list( response_id="response_id", ) - assert_matches_type(AsyncCursorPage[Data], input_item, path=["response"]) + assert_matches_type(AsyncCursorPage[ResponseItem], input_item, path=["response"]) @parametrize async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: @@ -87,7 +87,7 @@ async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> N limit=0, order="asc", ) - assert_matches_type(AsyncCursorPage[Data], input_item, path=["response"]) + assert_matches_type(AsyncCursorPage[ResponseItem], input_item, path=["response"]) @parametrize async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: @@ -98,7 +98,7 @@ async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" input_item = response.parse() - assert_matches_type(AsyncCursorPage[Data], input_item, path=["response"]) + assert_matches_type(AsyncCursorPage[ResponseItem], input_item, path=["response"]) @parametrize async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: @@ -109,7 +109,7 @@ async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: assert response.http_request.headers.get("X-Stainless-Lang") == "python" input_item = await response.parse() - assert_matches_type(AsyncCursorPage[Data], input_item, path=["response"]) + assert_matches_type(AsyncCursorPage[ResponseItem], input_item, path=["response"]) assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/test_batches.py b/tests/api_resources/test_batches.py index 6f9b598e61..a2f8fb48a3 100644 --- a/tests/api_resources/test_batches.py +++ b/tests/api_resources/test_batches.py @@ -22,7 +22,7 @@ class TestBatches: def test_method_create(self, client: OpenAI) -> None: batch = client.batches.create( completion_window="24h", - endpoint="/v1/chat/completions", + endpoint="/v1/responses", input_file_id="string", ) assert_matches_type(Batch, batch, path=["response"]) @@ -31,7 +31,7 @@ def test_method_create(self, client: OpenAI) -> None: def test_method_create_with_all_params(self, client: OpenAI) -> None: batch = client.batches.create( completion_window="24h", - endpoint="/v1/chat/completions", + endpoint="/v1/responses", input_file_id="string", metadata={"foo": "string"}, ) @@ -41,7 +41,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: def test_raw_response_create(self, client: OpenAI) -> None: response = client.batches.with_raw_response.create( completion_window="24h", - endpoint="/v1/chat/completions", + endpoint="/v1/responses", input_file_id="string", ) @@ -54,7 +54,7 @@ def test_raw_response_create(self, client: OpenAI) -> None: def test_streaming_response_create(self, client: OpenAI) -> None: with client.batches.with_streaming_response.create( completion_window="24h", - endpoint="/v1/chat/completions", + endpoint="/v1/responses", input_file_id="string", ) as response: assert not response.is_closed @@ -182,7 +182,7 @@ class TestAsyncBatches: async def test_method_create(self, async_client: AsyncOpenAI) -> None: batch = await async_client.batches.create( completion_window="24h", - endpoint="/v1/chat/completions", + endpoint="/v1/responses", input_file_id="string", ) assert_matches_type(Batch, batch, path=["response"]) @@ -191,7 +191,7 @@ async def test_method_create(self, async_client: AsyncOpenAI) -> None: async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: batch = await async_client.batches.create( completion_window="24h", - endpoint="/v1/chat/completions", + endpoint="/v1/responses", input_file_id="string", metadata={"foo": "string"}, ) @@ -201,7 +201,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: response = await async_client.batches.with_raw_response.create( completion_window="24h", - endpoint="/v1/chat/completions", + endpoint="/v1/responses", input_file_id="string", ) @@ -214,7 +214,7 @@ async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: async with async_client.batches.with_streaming_response.create( completion_window="24h", - endpoint="/v1/chat/completions", + endpoint="/v1/responses", input_file_id="string", ) as response: assert not response.is_closed From 653dfec4c0abf67c4f90f25044c57bc6acbae77a Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 19 Mar 2025 20:39:23 +0000 Subject: [PATCH 732/816] feat(api): o1-pro now available through the API (#2228) --- .stats.yml | 2 +- api.md | 2 + src/openai/resources/responses/responses.py | 17 +- .../resources/responses/responses.py.orig | 1796 +++++++++++++++++ src/openai/types/__init__.py | 2 + src/openai/types/responses/response.py | 4 +- .../types/responses/response_create_params.py | 4 +- .../response_function_tool_call_item.py | 2 +- src/openai/types/shared/__init__.py | 2 + src/openai/types/shared/all_models.py | 16 + src/openai/types/shared/chat_model.py | 9 +- src/openai/types/shared/responses_model.py | 12 + src/openai/types/shared_params/__init__.py | 1 + src/openai/types/shared_params/chat_model.py | 9 +- .../types/shared_params/responses_model.py | 14 + 15 files changed, 1868 insertions(+), 24 deletions(-) create mode 100644 src/openai/resources/responses/responses.py.orig create mode 100644 src/openai/types/shared/all_models.py create mode 100644 src/openai/types/shared/responses_model.py create mode 100644 src/openai/types/shared_params/responses_model.py diff --git a/.stats.yml b/.stats.yml index b032562238..e0b06dc22a 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 81 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-f3bce04386c4fcfd5037e0477fbaa39010003fd1558eb5185fe4a71dd6a05fdd.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-b26121d5df6eb5d3032a45a267473798b15fcfec76dd44a3256cf1238be05fa4.yml diff --git a/api.md b/api.md index 6e7f48a645..7f3a9392a2 100644 --- a/api.md +++ b/api.md @@ -2,6 +2,7 @@ ```python from openai.types import ( + AllModels, ChatModel, ComparisonFilter, CompoundFilter, @@ -14,6 +15,7 @@ from openai.types import ( ResponseFormatJSONObject, ResponseFormatJSONSchema, ResponseFormatText, + ResponsesModel, ) ``` diff --git a/src/openai/resources/responses/responses.py b/src/openai/resources/responses/responses.py index 0c70a2ef22..668f4db80a 100644 --- a/src/openai/resources/responses/responses.py +++ b/src/openai/resources/responses/responses.py @@ -44,6 +44,7 @@ from ...types.responses.parsed_response import ParsedResponse from ...lib.streaming.responses._responses import ResponseStreamManager, AsyncResponseStreamManager from ...types.responses.response_includable import ResponseIncludable +from ...types.shared_params.responses_model import ResponsesModel from ...types.responses.response_input_param import ResponseInputParam from ...types.responses.response_stream_event import ResponseStreamEvent from ...types.responses.response_text_config_param import ResponseTextConfigParam @@ -80,7 +81,7 @@ def create( self, *, input: Union[str, ResponseInputParam], - model: Union[str, ChatModel], + model: ResponsesModel, include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -245,7 +246,7 @@ def create( self, *, input: Union[str, ResponseInputParam], - model: Union[str, ChatModel], + model: ResponsesModel, stream: Literal[True], include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, @@ -410,7 +411,7 @@ def create( self, *, input: Union[str, ResponseInputParam], - model: Union[str, ChatModel], + model: ResponsesModel, stream: bool, include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, @@ -575,7 +576,7 @@ def create( self, *, input: Union[str, ResponseInputParam], - model: Union[str, ChatModel], + model: ResponsesModel, include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -892,7 +893,7 @@ async def create( self, *, input: Union[str, ResponseInputParam], - model: Union[str, ChatModel], + model: ResponsesModel, include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, @@ -1057,7 +1058,7 @@ async def create( self, *, input: Union[str, ResponseInputParam], - model: Union[str, ChatModel], + model: ResponsesModel, stream: Literal[True], include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, @@ -1222,7 +1223,7 @@ async def create( self, *, input: Union[str, ResponseInputParam], - model: Union[str, ChatModel], + model: ResponsesModel, stream: bool, include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, @@ -1387,7 +1388,7 @@ async def create( self, *, input: Union[str, ResponseInputParam], - model: Union[str, ChatModel], + model: ResponsesModel, include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, instructions: Optional[str] | NotGiven = NOT_GIVEN, max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, diff --git a/src/openai/resources/responses/responses.py.orig b/src/openai/resources/responses/responses.py.orig new file mode 100644 index 0000000000..dec4c19367 --- /dev/null +++ b/src/openai/resources/responses/responses.py.orig @@ -0,0 +1,1796 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Any, List, Type, Union, Iterable, Optional, cast +from functools import partial +from typing_extensions import Literal, overload + +import httpx + +from ... import _legacy_response +from ..._types import NOT_GIVEN, Body, Query, Headers, NoneType, NotGiven +from ..._utils import ( + is_given, + required_args, + maybe_transform, + async_maybe_transform, +) +from ..._compat import cached_property +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from .input_items import ( + InputItems, + AsyncInputItems, + InputItemsWithRawResponse, + AsyncInputItemsWithRawResponse, + InputItemsWithStreamingResponse, + AsyncInputItemsWithStreamingResponse, +) +from ..._streaming import Stream, AsyncStream +from ...lib._tools import PydanticFunctionTool, ResponsesPydanticFunctionTool +from ..._base_client import make_request_options +from ...types.responses import response_create_params, response_retrieve_params +<<<<<<< HEAD +from ...lib._parsing._responses import ( + TextFormatT, + parse_response, + type_to_text_format_param as _type_to_text_format_param, +) +from ...types.shared.chat_model import ChatModel +||||||| parent of 001707b8 (feat(api): o1-pro now available through the API (#2228)) +from ...types.shared.chat_model import ChatModel +======= +>>>>>>> 001707b8 (feat(api): o1-pro now available through the API (#2228)) +from ...types.responses.response import Response +from ...types.responses.tool_param import ToolParam, ParseableToolParam +from ...types.shared_params.metadata import Metadata +from ...types.shared_params.reasoning import Reasoning +from ...types.responses.parsed_response import ParsedResponse +from ...lib.streaming.responses._responses import ResponseStreamManager, AsyncResponseStreamManager +from ...types.responses.response_includable import ResponseIncludable +from ...types.shared_params.responses_model import ResponsesModel +from ...types.responses.response_input_param import ResponseInputParam +from ...types.responses.response_stream_event import ResponseStreamEvent +from ...types.responses.response_text_config_param import ResponseTextConfigParam + +__all__ = ["Responses", "AsyncResponses"] + + +class Responses(SyncAPIResource): + @cached_property + def input_items(self) -> InputItems: + return InputItems(self._client) + + @cached_property + def with_raw_response(self) -> ResponsesWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return ResponsesWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> ResponsesWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return ResponsesWithStreamingResponse(self) + + @overload + def create( + self, + *, + input: Union[str, ResponseInputParam], + model: ResponsesModel, + include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, + previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, + reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, + tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, + tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Response: + """Creates a model response. + + Provide + [text](https://platform.openai.com/docs/guides/text) or + [image](https://platform.openai.com/docs/guides/images) inputs to generate + [text](https://platform.openai.com/docs/guides/text) or + [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have + the model call your own + [custom code](https://platform.openai.com/docs/guides/function-calling) or use + built-in [tools](https://platform.openai.com/docs/guides/tools) like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search) to use + your own data as input for the model's response. + + Args: + input: Text, image, or file inputs to the model, used to generate a response. + + Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Image inputs](https://platform.openai.com/docs/guides/images) + - [File inputs](https://platform.openai.com/docs/guides/pdf-files) + - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) + - [Function calling](https://platform.openai.com/docs/guides/function-calling) + + model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + wide range of models with different capabilities, performance characteristics, + and price points. Refer to the + [model guide](https://platform.openai.com/docs/models) to browse and compare + available models. + + include: Specify additional output data to include in the model response. Currently + supported values are: + + - `file_search_call.results`: Include the search results of the file search tool + call. + - `message.input_image.image_url`: Include image urls from the input message. + - `computer_call_output.output.image_url`: Include image urls from the computer + call output. + + instructions: Inserts a system (or developer) message as the first item in the model's + context. + + When using along with `previous_response_id`, the instructions from a previous + response will be not be carried over to the next response. This makes it simple + to swap out system (or developer) messages in new responses. + + max_output_tokens: An upper bound for the number of tokens that can be generated for a response, + including visible output tokens and + [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + + parallel_tool_calls: Whether to allow the model to run tool calls in parallel. + + previous_response_id: The unique ID of the previous response to the model. Use this to create + multi-turn conversations. Learn more about + [conversation state](https://platform.openai.com/docs/guides/conversation-state). + + reasoning: **o-series models only** + + Configuration options for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). + + store: Whether to store the generated model response for later retrieval via API. + + stream: If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) + for more information. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. We generally recommend altering this or `top_p` but + not both. + + text: Configuration options for a text response from the model. Can be plain text or + structured JSON data. Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + + tool_choice: How the model should select which tool (or tools) to use when generating a + response. See the `tools` parameter to see how to specify which tools the model + can call. + + tools: An array of tools the model may call while generating a response. You can + specify which tool to use by setting the `tool_choice` parameter. + + The two categories of tools you can provide the model are: + + - **Built-in tools**: Tools that are provided by OpenAI that extend the model's + capabilities, like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search). + Learn more about + [built-in tools](https://platform.openai.com/docs/guides/tools). + - **Function calls (custom tools)**: Functions that are defined by you, enabling + the model to call your own code. Learn more about + [function calling](https://platform.openai.com/docs/guides/function-calling). + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + truncation: The truncation strategy to use for the model response. + + - `auto`: If the context of this response and previous ones exceeds the model's + context window size, the model will truncate the response to fit the context + window by dropping input items in the middle of the conversation. + - `disabled` (default): If a model response will exceed the context window size + for a model, the request will fail with a 400 error. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + def create( + self, + *, + input: Union[str, ResponseInputParam], + model: ResponsesModel, + stream: Literal[True], + include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, + previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, + reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, + tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, + tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Stream[ResponseStreamEvent]: + """Creates a model response. + + Provide + [text](https://platform.openai.com/docs/guides/text) or + [image](https://platform.openai.com/docs/guides/images) inputs to generate + [text](https://platform.openai.com/docs/guides/text) or + [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have + the model call your own + [custom code](https://platform.openai.com/docs/guides/function-calling) or use + built-in [tools](https://platform.openai.com/docs/guides/tools) like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search) to use + your own data as input for the model's response. + + Args: + input: Text, image, or file inputs to the model, used to generate a response. + + Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Image inputs](https://platform.openai.com/docs/guides/images) + - [File inputs](https://platform.openai.com/docs/guides/pdf-files) + - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) + - [Function calling](https://platform.openai.com/docs/guides/function-calling) + + model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + wide range of models with different capabilities, performance characteristics, + and price points. Refer to the + [model guide](https://platform.openai.com/docs/models) to browse and compare + available models. + + stream: If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) + for more information. + + include: Specify additional output data to include in the model response. Currently + supported values are: + + - `file_search_call.results`: Include the search results of the file search tool + call. + - `message.input_image.image_url`: Include image urls from the input message. + - `computer_call_output.output.image_url`: Include image urls from the computer + call output. + + instructions: Inserts a system (or developer) message as the first item in the model's + context. + + When using along with `previous_response_id`, the instructions from a previous + response will be not be carried over to the next response. This makes it simple + to swap out system (or developer) messages in new responses. + + max_output_tokens: An upper bound for the number of tokens that can be generated for a response, + including visible output tokens and + [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + + parallel_tool_calls: Whether to allow the model to run tool calls in parallel. + + previous_response_id: The unique ID of the previous response to the model. Use this to create + multi-turn conversations. Learn more about + [conversation state](https://platform.openai.com/docs/guides/conversation-state). + + reasoning: **o-series models only** + + Configuration options for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). + + store: Whether to store the generated model response for later retrieval via API. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. We generally recommend altering this or `top_p` but + not both. + + text: Configuration options for a text response from the model. Can be plain text or + structured JSON data. Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + + tool_choice: How the model should select which tool (or tools) to use when generating a + response. See the `tools` parameter to see how to specify which tools the model + can call. + + tools: An array of tools the model may call while generating a response. You can + specify which tool to use by setting the `tool_choice` parameter. + + The two categories of tools you can provide the model are: + + - **Built-in tools**: Tools that are provided by OpenAI that extend the model's + capabilities, like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search). + Learn more about + [built-in tools](https://platform.openai.com/docs/guides/tools). + - **Function calls (custom tools)**: Functions that are defined by you, enabling + the model to call your own code. Learn more about + [function calling](https://platform.openai.com/docs/guides/function-calling). + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + truncation: The truncation strategy to use for the model response. + + - `auto`: If the context of this response and previous ones exceeds the model's + context window size, the model will truncate the response to fit the context + window by dropping input items in the middle of the conversation. + - `disabled` (default): If a model response will exceed the context window size + for a model, the request will fail with a 400 error. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + def create( + self, + *, + input: Union[str, ResponseInputParam], + model: ResponsesModel, + stream: bool, + include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, + previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, + reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, + tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, + tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Response | Stream[ResponseStreamEvent]: + """Creates a model response. + + Provide + [text](https://platform.openai.com/docs/guides/text) or + [image](https://platform.openai.com/docs/guides/images) inputs to generate + [text](https://platform.openai.com/docs/guides/text) or + [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have + the model call your own + [custom code](https://platform.openai.com/docs/guides/function-calling) or use + built-in [tools](https://platform.openai.com/docs/guides/tools) like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search) to use + your own data as input for the model's response. + + Args: + input: Text, image, or file inputs to the model, used to generate a response. + + Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Image inputs](https://platform.openai.com/docs/guides/images) + - [File inputs](https://platform.openai.com/docs/guides/pdf-files) + - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) + - [Function calling](https://platform.openai.com/docs/guides/function-calling) + + model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + wide range of models with different capabilities, performance characteristics, + and price points. Refer to the + [model guide](https://platform.openai.com/docs/models) to browse and compare + available models. + + stream: If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) + for more information. + + include: Specify additional output data to include in the model response. Currently + supported values are: + + - `file_search_call.results`: Include the search results of the file search tool + call. + - `message.input_image.image_url`: Include image urls from the input message. + - `computer_call_output.output.image_url`: Include image urls from the computer + call output. + + instructions: Inserts a system (or developer) message as the first item in the model's + context. + + When using along with `previous_response_id`, the instructions from a previous + response will be not be carried over to the next response. This makes it simple + to swap out system (or developer) messages in new responses. + + max_output_tokens: An upper bound for the number of tokens that can be generated for a response, + including visible output tokens and + [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + + parallel_tool_calls: Whether to allow the model to run tool calls in parallel. + + previous_response_id: The unique ID of the previous response to the model. Use this to create + multi-turn conversations. Learn more about + [conversation state](https://platform.openai.com/docs/guides/conversation-state). + + reasoning: **o-series models only** + + Configuration options for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). + + store: Whether to store the generated model response for later retrieval via API. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. We generally recommend altering this or `top_p` but + not both. + + text: Configuration options for a text response from the model. Can be plain text or + structured JSON data. Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + + tool_choice: How the model should select which tool (or tools) to use when generating a + response. See the `tools` parameter to see how to specify which tools the model + can call. + + tools: An array of tools the model may call while generating a response. You can + specify which tool to use by setting the `tool_choice` parameter. + + The two categories of tools you can provide the model are: + + - **Built-in tools**: Tools that are provided by OpenAI that extend the model's + capabilities, like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search). + Learn more about + [built-in tools](https://platform.openai.com/docs/guides/tools). + - **Function calls (custom tools)**: Functions that are defined by you, enabling + the model to call your own code. Learn more about + [function calling](https://platform.openai.com/docs/guides/function-calling). + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + truncation: The truncation strategy to use for the model response. + + - `auto`: If the context of this response and previous ones exceeds the model's + context window size, the model will truncate the response to fit the context + window by dropping input items in the middle of the conversation. + - `disabled` (default): If a model response will exceed the context window size + for a model, the request will fail with a 400 error. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @required_args(["input", "model"], ["input", "model", "stream"]) + def create( + self, + *, + input: Union[str, ResponseInputParam], + model: ResponsesModel, + include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, + previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, + reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, + tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, + tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Response | Stream[ResponseStreamEvent]: + return self._post( + "/responses", + body=maybe_transform( + { + "input": input, + "model": model, + "include": include, + "instructions": instructions, + "max_output_tokens": max_output_tokens, + "metadata": metadata, + "parallel_tool_calls": parallel_tool_calls, + "previous_response_id": previous_response_id, + "reasoning": reasoning, + "store": store, + "stream": stream, + "temperature": temperature, + "text": text, + "tool_choice": tool_choice, + "tools": tools, + "top_p": top_p, + "truncation": truncation, + "user": user, + }, + response_create_params.ResponseCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Response, + stream=stream or False, + stream_cls=Stream[ResponseStreamEvent], + ) + + def stream( + self, + *, + input: Union[str, ResponseInputParam], + model: Union[str, ChatModel], + text_format: type[TextFormatT] | NotGiven = NOT_GIVEN, + tools: Iterable[ParseableToolParam] | NotGiven = NOT_GIVEN, + include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, + previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, + reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, + tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> ResponseStreamManager[TextFormatT]: + if is_given(text_format): + if not text: + text = {} + + if "format" in text: + raise TypeError("Cannot mix and match text.format with text_format") + + text["format"] = _type_to_text_format_param(text_format) + + tools = _make_tools(tools) + + api_request: partial[Stream[ResponseStreamEvent]] = partial( + self.create, + input=input, + model=model, + tools=tools, + include=include, + instructions=instructions, + max_output_tokens=max_output_tokens, + metadata=metadata, + parallel_tool_calls=parallel_tool_calls, + previous_response_id=previous_response_id, + store=store, + stream=True, + temperature=temperature, + text=text, + tool_choice=tool_choice, + reasoning=reasoning, + top_p=top_p, + truncation=truncation, + user=user, + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + ) + + return ResponseStreamManager( + api_request, + text_format=text_format, + input_tools=tools, + ) + + def parse( + self, + *, + input: Union[str, ResponseInputParam], + model: Union[str, ChatModel], + text_format: type[TextFormatT] | NotGiven = NOT_GIVEN, + tools: Iterable[ParseableToolParam] | NotGiven = NOT_GIVEN, + include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, + previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, + reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, + tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> ParsedResponse[TextFormatT]: + if is_given(text_format): + if not text: + text = {} + + if "format" in text: + raise TypeError("Cannot mix and match text.format with text_format") + + text["format"] = _type_to_text_format_param(text_format) + + tools = _make_tools(tools) + + def parser(raw_response: Response) -> ParsedResponse[TextFormatT]: + return parse_response( + input_tools=tools, + text_format=text_format, + response=raw_response, + ) + + return self._post( + "/responses", + body=maybe_transform( + { + "input": input, + "model": model, + "include": include, + "instructions": instructions, + "max_output_tokens": max_output_tokens, + "metadata": metadata, + "parallel_tool_calls": parallel_tool_calls, + "previous_response_id": previous_response_id, + "reasoning": reasoning, + "store": store, + "stream": stream, + "temperature": temperature, + "text": text, + "tool_choice": tool_choice, + "tools": tools, + "top_p": top_p, + "truncation": truncation, + "user": user, + }, + response_create_params.ResponseCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + post_parser=parser, + ), + # we turn the `Response` instance into a `ParsedResponse` + # in the `parser` function above + cast_to=cast(Type[ParsedResponse[TextFormatT]], Response), + ) + + def retrieve( + self, + response_id: str, + *, + include: List[ResponseIncludable] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Response: + """ + Retrieves a model response with the given ID. + + Args: + include: Additional fields to include in the response. See the `include` parameter for + Response creation above for more information. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not response_id: + raise ValueError(f"Expected a non-empty value for `response_id` but received {response_id!r}") + return self._get( + f"/responses/{response_id}", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform({"include": include}, response_retrieve_params.ResponseRetrieveParams), + ), + cast_to=Response, + ) + + def delete( + self, + response_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> None: + """ + Deletes a model response with the given ID. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not response_id: + raise ValueError(f"Expected a non-empty value for `response_id` but received {response_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return self._delete( + f"/responses/{response_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class AsyncResponses(AsyncAPIResource): + @cached_property + def input_items(self) -> AsyncInputItems: + return AsyncInputItems(self._client) + + @cached_property + def with_raw_response(self) -> AsyncResponsesWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return AsyncResponsesWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncResponsesWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return AsyncResponsesWithStreamingResponse(self) + + @overload + async def create( + self, + *, + input: Union[str, ResponseInputParam], + model: ResponsesModel, + include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, + previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, + reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, + tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, + tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Response: + """Creates a model response. + + Provide + [text](https://platform.openai.com/docs/guides/text) or + [image](https://platform.openai.com/docs/guides/images) inputs to generate + [text](https://platform.openai.com/docs/guides/text) or + [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have + the model call your own + [custom code](https://platform.openai.com/docs/guides/function-calling) or use + built-in [tools](https://platform.openai.com/docs/guides/tools) like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search) to use + your own data as input for the model's response. + + Args: + input: Text, image, or file inputs to the model, used to generate a response. + + Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Image inputs](https://platform.openai.com/docs/guides/images) + - [File inputs](https://platform.openai.com/docs/guides/pdf-files) + - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) + - [Function calling](https://platform.openai.com/docs/guides/function-calling) + + model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + wide range of models with different capabilities, performance characteristics, + and price points. Refer to the + [model guide](https://platform.openai.com/docs/models) to browse and compare + available models. + + include: Specify additional output data to include in the model response. Currently + supported values are: + + - `file_search_call.results`: Include the search results of the file search tool + call. + - `message.input_image.image_url`: Include image urls from the input message. + - `computer_call_output.output.image_url`: Include image urls from the computer + call output. + + instructions: Inserts a system (or developer) message as the first item in the model's + context. + + When using along with `previous_response_id`, the instructions from a previous + response will be not be carried over to the next response. This makes it simple + to swap out system (or developer) messages in new responses. + + max_output_tokens: An upper bound for the number of tokens that can be generated for a response, + including visible output tokens and + [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + + parallel_tool_calls: Whether to allow the model to run tool calls in parallel. + + previous_response_id: The unique ID of the previous response to the model. Use this to create + multi-turn conversations. Learn more about + [conversation state](https://platform.openai.com/docs/guides/conversation-state). + + reasoning: **o-series models only** + + Configuration options for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). + + store: Whether to store the generated model response for later retrieval via API. + + stream: If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) + for more information. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. We generally recommend altering this or `top_p` but + not both. + + text: Configuration options for a text response from the model. Can be plain text or + structured JSON data. Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + + tool_choice: How the model should select which tool (or tools) to use when generating a + response. See the `tools` parameter to see how to specify which tools the model + can call. + + tools: An array of tools the model may call while generating a response. You can + specify which tool to use by setting the `tool_choice` parameter. + + The two categories of tools you can provide the model are: + + - **Built-in tools**: Tools that are provided by OpenAI that extend the model's + capabilities, like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search). + Learn more about + [built-in tools](https://platform.openai.com/docs/guides/tools). + - **Function calls (custom tools)**: Functions that are defined by you, enabling + the model to call your own code. Learn more about + [function calling](https://platform.openai.com/docs/guides/function-calling). + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + truncation: The truncation strategy to use for the model response. + + - `auto`: If the context of this response and previous ones exceeds the model's + context window size, the model will truncate the response to fit the context + window by dropping input items in the middle of the conversation. + - `disabled` (default): If a model response will exceed the context window size + for a model, the request will fail with a 400 error. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + async def create( + self, + *, + input: Union[str, ResponseInputParam], + model: ResponsesModel, + stream: Literal[True], + include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, + previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, + reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, + tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, + tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncStream[ResponseStreamEvent]: + """Creates a model response. + + Provide + [text](https://platform.openai.com/docs/guides/text) or + [image](https://platform.openai.com/docs/guides/images) inputs to generate + [text](https://platform.openai.com/docs/guides/text) or + [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have + the model call your own + [custom code](https://platform.openai.com/docs/guides/function-calling) or use + built-in [tools](https://platform.openai.com/docs/guides/tools) like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search) to use + your own data as input for the model's response. + + Args: + input: Text, image, or file inputs to the model, used to generate a response. + + Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Image inputs](https://platform.openai.com/docs/guides/images) + - [File inputs](https://platform.openai.com/docs/guides/pdf-files) + - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) + - [Function calling](https://platform.openai.com/docs/guides/function-calling) + + model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + wide range of models with different capabilities, performance characteristics, + and price points. Refer to the + [model guide](https://platform.openai.com/docs/models) to browse and compare + available models. + + stream: If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) + for more information. + + include: Specify additional output data to include in the model response. Currently + supported values are: + + - `file_search_call.results`: Include the search results of the file search tool + call. + - `message.input_image.image_url`: Include image urls from the input message. + - `computer_call_output.output.image_url`: Include image urls from the computer + call output. + + instructions: Inserts a system (or developer) message as the first item in the model's + context. + + When using along with `previous_response_id`, the instructions from a previous + response will be not be carried over to the next response. This makes it simple + to swap out system (or developer) messages in new responses. + + max_output_tokens: An upper bound for the number of tokens that can be generated for a response, + including visible output tokens and + [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + + parallel_tool_calls: Whether to allow the model to run tool calls in parallel. + + previous_response_id: The unique ID of the previous response to the model. Use this to create + multi-turn conversations. Learn more about + [conversation state](https://platform.openai.com/docs/guides/conversation-state). + + reasoning: **o-series models only** + + Configuration options for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). + + store: Whether to store the generated model response for later retrieval via API. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. We generally recommend altering this or `top_p` but + not both. + + text: Configuration options for a text response from the model. Can be plain text or + structured JSON data. Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + + tool_choice: How the model should select which tool (or tools) to use when generating a + response. See the `tools` parameter to see how to specify which tools the model + can call. + + tools: An array of tools the model may call while generating a response. You can + specify which tool to use by setting the `tool_choice` parameter. + + The two categories of tools you can provide the model are: + + - **Built-in tools**: Tools that are provided by OpenAI that extend the model's + capabilities, like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search). + Learn more about + [built-in tools](https://platform.openai.com/docs/guides/tools). + - **Function calls (custom tools)**: Functions that are defined by you, enabling + the model to call your own code. Learn more about + [function calling](https://platform.openai.com/docs/guides/function-calling). + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + truncation: The truncation strategy to use for the model response. + + - `auto`: If the context of this response and previous ones exceeds the model's + context window size, the model will truncate the response to fit the context + window by dropping input items in the middle of the conversation. + - `disabled` (default): If a model response will exceed the context window size + for a model, the request will fail with a 400 error. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload + async def create( + self, + *, + input: Union[str, ResponseInputParam], + model: ResponsesModel, + stream: bool, + include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, + previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, + reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, + tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, + tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Response | AsyncStream[ResponseStreamEvent]: + """Creates a model response. + + Provide + [text](https://platform.openai.com/docs/guides/text) or + [image](https://platform.openai.com/docs/guides/images) inputs to generate + [text](https://platform.openai.com/docs/guides/text) or + [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have + the model call your own + [custom code](https://platform.openai.com/docs/guides/function-calling) or use + built-in [tools](https://platform.openai.com/docs/guides/tools) like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search) to use + your own data as input for the model's response. + + Args: + input: Text, image, or file inputs to the model, used to generate a response. + + Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Image inputs](https://platform.openai.com/docs/guides/images) + - [File inputs](https://platform.openai.com/docs/guides/pdf-files) + - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) + - [Function calling](https://platform.openai.com/docs/guides/function-calling) + + model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + wide range of models with different capabilities, performance characteristics, + and price points. Refer to the + [model guide](https://platform.openai.com/docs/models) to browse and compare + available models. + + stream: If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) + for more information. + + include: Specify additional output data to include in the model response. Currently + supported values are: + + - `file_search_call.results`: Include the search results of the file search tool + call. + - `message.input_image.image_url`: Include image urls from the input message. + - `computer_call_output.output.image_url`: Include image urls from the computer + call output. + + instructions: Inserts a system (or developer) message as the first item in the model's + context. + + When using along with `previous_response_id`, the instructions from a previous + response will be not be carried over to the next response. This makes it simple + to swap out system (or developer) messages in new responses. + + max_output_tokens: An upper bound for the number of tokens that can be generated for a response, + including visible output tokens and + [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + + parallel_tool_calls: Whether to allow the model to run tool calls in parallel. + + previous_response_id: The unique ID of the previous response to the model. Use this to create + multi-turn conversations. Learn more about + [conversation state](https://platform.openai.com/docs/guides/conversation-state). + + reasoning: **o-series models only** + + Configuration options for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). + + store: Whether to store the generated model response for later retrieval via API. + + temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will + make the output more random, while lower values like 0.2 will make it more + focused and deterministic. We generally recommend altering this or `top_p` but + not both. + + text: Configuration options for a text response from the model. Can be plain text or + structured JSON data. Learn more: + + - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) + - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) + + tool_choice: How the model should select which tool (or tools) to use when generating a + response. See the `tools` parameter to see how to specify which tools the model + can call. + + tools: An array of tools the model may call while generating a response. You can + specify which tool to use by setting the `tool_choice` parameter. + + The two categories of tools you can provide the model are: + + - **Built-in tools**: Tools that are provided by OpenAI that extend the model's + capabilities, like + [web search](https://platform.openai.com/docs/guides/tools-web-search) or + [file search](https://platform.openai.com/docs/guides/tools-file-search). + Learn more about + [built-in tools](https://platform.openai.com/docs/guides/tools). + - **Function calls (custom tools)**: Functions that are defined by you, enabling + the model to call your own code. Learn more about + [function calling](https://platform.openai.com/docs/guides/function-calling). + + top_p: An alternative to sampling with temperature, called nucleus sampling, where the + model considers the results of the tokens with top_p probability mass. So 0.1 + means only the tokens comprising the top 10% probability mass are considered. + + We generally recommend altering this or `temperature` but not both. + + truncation: The truncation strategy to use for the model response. + + - `auto`: If the context of this response and previous ones exceeds the model's + context window size, the model will truncate the response to fit the context + window by dropping input items in the middle of the conversation. + - `disabled` (default): If a model response will exceed the context window size + for a model, the request will fail with a 400 error. + + user: A unique identifier representing your end-user, which can help OpenAI to monitor + and detect abuse. + [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @required_args(["input", "model"], ["input", "model", "stream"]) + async def create( + self, + *, + input: Union[str, ResponseInputParam], + model: ResponsesModel, + include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, + previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, + reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, + tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, + tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Response | AsyncStream[ResponseStreamEvent]: + return await self._post( + "/responses", + body=await async_maybe_transform( + { + "input": input, + "model": model, + "include": include, + "instructions": instructions, + "max_output_tokens": max_output_tokens, + "metadata": metadata, + "parallel_tool_calls": parallel_tool_calls, + "previous_response_id": previous_response_id, + "reasoning": reasoning, + "store": store, + "stream": stream, + "temperature": temperature, + "text": text, + "tool_choice": tool_choice, + "tools": tools, + "top_p": top_p, + "truncation": truncation, + "user": user, + }, + response_create_params.ResponseCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=Response, + stream=stream or False, + stream_cls=AsyncStream[ResponseStreamEvent], + ) + + def stream( + self, + *, + input: Union[str, ResponseInputParam], + model: Union[str, ChatModel], + text_format: type[TextFormatT] | NotGiven = NOT_GIVEN, + tools: Iterable[ParseableToolParam] | NotGiven = NOT_GIVEN, + include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, + previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, + reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, + tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncResponseStreamManager[TextFormatT]: + if is_given(text_format): + if not text: + text = {} + + if "format" in text: + raise TypeError("Cannot mix and match text.format with text_format") + + text["format"] = _type_to_text_format_param(text_format) + + tools = _make_tools(tools) + + api_request = self.create( + input=input, + model=model, + tools=tools, + include=include, + instructions=instructions, + max_output_tokens=max_output_tokens, + metadata=metadata, + parallel_tool_calls=parallel_tool_calls, + previous_response_id=previous_response_id, + store=store, + stream=True, + temperature=temperature, + text=text, + tool_choice=tool_choice, + reasoning=reasoning, + top_p=top_p, + truncation=truncation, + user=user, + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + ) + + return AsyncResponseStreamManager( + api_request, + text_format=text_format, + input_tools=tools, + ) + + async def parse( + self, + *, + input: Union[str, ResponseInputParam], + model: Union[str, ChatModel], + text_format: type[TextFormatT] | NotGiven = NOT_GIVEN, + tools: Iterable[ParseableToolParam] | NotGiven = NOT_GIVEN, + include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, + instructions: Optional[str] | NotGiven = NOT_GIVEN, + max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, + previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, + reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + store: Optional[bool] | NotGiven = NOT_GIVEN, + stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + temperature: Optional[float] | NotGiven = NOT_GIVEN, + text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, + tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, + top_p: Optional[float] | NotGiven = NOT_GIVEN, + truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, + user: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> ParsedResponse[TextFormatT]: + if is_given(text_format): + if not text: + text = {} + + if "format" in text: + raise TypeError("Cannot mix and match text.format with text_format") + + text["format"] = _type_to_text_format_param(text_format) + + tools = _make_tools(tools) + + def parser(raw_response: Response) -> ParsedResponse[TextFormatT]: + return parse_response( + input_tools=tools, + text_format=text_format, + response=raw_response, + ) + + return await self._post( + "/responses", + body=maybe_transform( + { + "input": input, + "model": model, + "include": include, + "instructions": instructions, + "max_output_tokens": max_output_tokens, + "metadata": metadata, + "parallel_tool_calls": parallel_tool_calls, + "previous_response_id": previous_response_id, + "reasoning": reasoning, + "store": store, + "stream": stream, + "temperature": temperature, + "text": text, + "tool_choice": tool_choice, + "tools": tools, + "top_p": top_p, + "truncation": truncation, + "user": user, + }, + response_create_params.ResponseCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + post_parser=parser, + ), + # we turn the `Response` instance into a `ParsedResponse` + # in the `parser` function above + cast_to=cast(Type[ParsedResponse[TextFormatT]], Response), + ) + + async def retrieve( + self, + response_id: str, + *, + include: List[ResponseIncludable] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Response: + """ + Retrieves a model response with the given ID. + + Args: + include: Additional fields to include in the response. See the `include` parameter for + Response creation above for more information. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not response_id: + raise ValueError(f"Expected a non-empty value for `response_id` but received {response_id!r}") + return await self._get( + f"/responses/{response_id}", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + {"include": include}, response_retrieve_params.ResponseRetrieveParams + ), + ), + cast_to=Response, + ) + + async def delete( + self, + response_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> None: + """ + Deletes a model response with the given ID. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not response_id: + raise ValueError(f"Expected a non-empty value for `response_id` but received {response_id!r}") + extra_headers = {"Accept": "*/*", **(extra_headers or {})} + return await self._delete( + f"/responses/{response_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=NoneType, + ) + + +class ResponsesWithRawResponse: + def __init__(self, responses: Responses) -> None: + self._responses = responses + + self.create = _legacy_response.to_raw_response_wrapper( + responses.create, + ) + self.retrieve = _legacy_response.to_raw_response_wrapper( + responses.retrieve, + ) + self.delete = _legacy_response.to_raw_response_wrapper( + responses.delete, + ) + + @cached_property + def input_items(self) -> InputItemsWithRawResponse: + return InputItemsWithRawResponse(self._responses.input_items) + + +class AsyncResponsesWithRawResponse: + def __init__(self, responses: AsyncResponses) -> None: + self._responses = responses + + self.create = _legacy_response.async_to_raw_response_wrapper( + responses.create, + ) + self.retrieve = _legacy_response.async_to_raw_response_wrapper( + responses.retrieve, + ) + self.delete = _legacy_response.async_to_raw_response_wrapper( + responses.delete, + ) + + @cached_property + def input_items(self) -> AsyncInputItemsWithRawResponse: + return AsyncInputItemsWithRawResponse(self._responses.input_items) + + +class ResponsesWithStreamingResponse: + def __init__(self, responses: Responses) -> None: + self._responses = responses + + self.create = to_streamed_response_wrapper( + responses.create, + ) + self.retrieve = to_streamed_response_wrapper( + responses.retrieve, + ) + self.delete = to_streamed_response_wrapper( + responses.delete, + ) + + @cached_property + def input_items(self) -> InputItemsWithStreamingResponse: + return InputItemsWithStreamingResponse(self._responses.input_items) + + +class AsyncResponsesWithStreamingResponse: + def __init__(self, responses: AsyncResponses) -> None: + self._responses = responses + + self.create = async_to_streamed_response_wrapper( + responses.create, + ) + self.retrieve = async_to_streamed_response_wrapper( + responses.retrieve, + ) + self.delete = async_to_streamed_response_wrapper( + responses.delete, + ) + + @cached_property + def input_items(self) -> AsyncInputItemsWithStreamingResponse: + return AsyncInputItemsWithStreamingResponse(self._responses.input_items) + + +def _make_tools(tools: Iterable[ParseableToolParam] | NotGiven) -> List[ToolParam] | NotGiven: + if not is_given(tools): + return NOT_GIVEN + + converted_tools: List[ToolParam] = [] + for tool in tools: + if tool["type"] != "function": + converted_tools.append(tool) + continue + + if "function" not in tool: + # standard Responses API case + converted_tools.append(tool) + continue + + function = cast(Any, tool)["function"] # pyright: ignore[reportUnnecessaryCast] + if not isinstance(function, PydanticFunctionTool): + raise Exception( + "Expected Chat Completions function tool shape to be created using `openai.pydantic_function_tool()`" + ) + + assert "parameters" in function + new_tool = ResponsesPydanticFunctionTool( + { + "type": "function", + "name": function["name"], + "description": function.get("description"), + "parameters": function["parameters"], + "strict": function.get("strict") or False, + }, + function.model, + ) + + converted_tools.append(new_tool.cast()) + + return converted_tools diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index 4c337d41c7..11761534c9 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -7,10 +7,12 @@ from .model import Model as Model from .shared import ( Metadata as Metadata, + AllModels as AllModels, ChatModel as ChatModel, Reasoning as Reasoning, ErrorObject as ErrorObject, CompoundFilter as CompoundFilter, + ResponsesModel as ResponsesModel, ReasoningEffort as ReasoningEffort, ComparisonFilter as ComparisonFilter, FunctionDefinition as FunctionDefinition, diff --git a/src/openai/types/responses/response.py b/src/openai/types/responses/response.py index 66887ae9b5..1bedf80889 100644 --- a/src/openai/types/responses/response.py +++ b/src/openai/types/responses/response.py @@ -11,11 +11,11 @@ from ..shared.metadata import Metadata from ..shared.reasoning import Reasoning from .tool_choice_types import ToolChoiceTypes -from ..shared.chat_model import ChatModel from .tool_choice_options import ToolChoiceOptions from .response_output_item import ResponseOutputItem from .response_text_config import ResponseTextConfig from .tool_choice_function import ToolChoiceFunction +from ..shared.responses_model import ResponsesModel __all__ = ["Response", "IncompleteDetails", "ToolChoice"] @@ -61,7 +61,7 @@ class Response(BaseModel): a maximum length of 512 characters. """ - model: Union[str, ChatModel] + model: ResponsesModel """Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a wide range of models with different capabilities, performance diff --git a/src/openai/types/responses/response_create_params.py b/src/openai/types/responses/response_create_params.py index d5b2fdeb1a..651050c50d 100644 --- a/src/openai/types/responses/response_create_params.py +++ b/src/openai/types/responses/response_create_params.py @@ -6,7 +6,6 @@ from typing_extensions import Literal, Required, TypeAlias, TypedDict from .tool_param import ToolParam -from ..shared.chat_model import ChatModel from .response_includable import ResponseIncludable from .tool_choice_options import ToolChoiceOptions from .response_input_param import ResponseInputParam @@ -15,6 +14,7 @@ from ..shared_params.reasoning import Reasoning from .response_text_config_param import ResponseTextConfigParam from .tool_choice_function_param import ToolChoiceFunctionParam +from ..shared_params.responses_model import ResponsesModel __all__ = [ "ResponseCreateParamsBase", @@ -37,7 +37,7 @@ class ResponseCreateParamsBase(TypedDict, total=False): - [Function calling](https://platform.openai.com/docs/guides/function-calling) """ - model: Required[Union[str, ChatModel]] + model: Required[ResponsesModel] """Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a wide range of models with different capabilities, performance diff --git a/src/openai/types/responses/response_function_tool_call_item.py b/src/openai/types/responses/response_function_tool_call_item.py index 477e9b70aa..25984f9451 100644 --- a/src/openai/types/responses/response_function_tool_call_item.py +++ b/src/openai/types/responses/response_function_tool_call_item.py @@ -8,4 +8,4 @@ class ResponseFunctionToolCallItem(ResponseFunctionToolCall): id: str # type: ignore - """The unique ID of the function call tool output.""" + """The unique ID of the function tool call.""" diff --git a/src/openai/types/shared/__init__.py b/src/openai/types/shared/__init__.py index 6ccc2313cc..6ad0ed5e01 100644 --- a/src/openai/types/shared/__init__.py +++ b/src/openai/types/shared/__init__.py @@ -2,9 +2,11 @@ from .metadata import Metadata as Metadata from .reasoning import Reasoning as Reasoning +from .all_models import AllModels as AllModels from .chat_model import ChatModel as ChatModel from .error_object import ErrorObject as ErrorObject from .compound_filter import CompoundFilter as CompoundFilter +from .responses_model import ResponsesModel as ResponsesModel from .reasoning_effort import ReasoningEffort as ReasoningEffort from .comparison_filter import ComparisonFilter as ComparisonFilter from .function_definition import FunctionDefinition as FunctionDefinition diff --git a/src/openai/types/shared/all_models.py b/src/openai/types/shared/all_models.py new file mode 100644 index 0000000000..c4635e2140 --- /dev/null +++ b/src/openai/types/shared/all_models.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Literal, TypeAlias + +from .chat_model import ChatModel + +__all__ = ["AllModels"] + +AllModels: TypeAlias = Union[ + str, + ChatModel, + str, + ChatModel, + Literal["o1-pro", "o1-pro-2025-03-19", "computer-use-preview", "computer-use-preview-2025-03-11"], +] diff --git a/src/openai/types/shared/chat_model.py b/src/openai/types/shared/chat_model.py index 31d7104e6e..b19375725d 100644 --- a/src/openai/types/shared/chat_model.py +++ b/src/openai/types/shared/chat_model.py @@ -13,11 +13,6 @@ "o1-preview-2024-09-12", "o1-mini", "o1-mini-2024-09-12", - "computer-use-preview", - "computer-use-preview-2025-02-04", - "computer-use-preview-2025-03-11", - "gpt-4.5-preview", - "gpt-4.5-preview-2025-02-27", "gpt-4o", "gpt-4o-2024-11-20", "gpt-4o-2024-08-06", @@ -27,6 +22,10 @@ "gpt-4o-audio-preview-2024-12-17", "gpt-4o-mini-audio-preview", "gpt-4o-mini-audio-preview-2024-12-17", + "gpt-4o-search-preview", + "gpt-4o-mini-search-preview", + "gpt-4o-search-preview-2025-03-11", + "gpt-4o-mini-search-preview-2025-03-11", "chatgpt-4o-latest", "gpt-4o-mini", "gpt-4o-mini-2024-07-18", diff --git a/src/openai/types/shared/responses_model.py b/src/openai/types/shared/responses_model.py new file mode 100644 index 0000000000..85f154fd84 --- /dev/null +++ b/src/openai/types/shared/responses_model.py @@ -0,0 +1,12 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Literal, TypeAlias + +from .chat_model import ChatModel + +__all__ = ["ResponsesModel"] + +ResponsesModel: TypeAlias = Union[ + str, ChatModel, Literal["o1-pro", "o1-pro-2025-03-19", "computer-use-preview", "computer-use-preview-2025-03-11"] +] diff --git a/src/openai/types/shared_params/__init__.py b/src/openai/types/shared_params/__init__.py index 4a4a8cdf1e..8894710807 100644 --- a/src/openai/types/shared_params/__init__.py +++ b/src/openai/types/shared_params/__init__.py @@ -4,6 +4,7 @@ from .reasoning import Reasoning as Reasoning from .chat_model import ChatModel as ChatModel from .compound_filter import CompoundFilter as CompoundFilter +from .responses_model import ResponsesModel as ResponsesModel from .reasoning_effort import ReasoningEffort as ReasoningEffort from .comparison_filter import ComparisonFilter as ComparisonFilter from .function_definition import FunctionDefinition as FunctionDefinition diff --git a/src/openai/types/shared_params/chat_model.py b/src/openai/types/shared_params/chat_model.py index 55649876eb..ff81b07ac3 100644 --- a/src/openai/types/shared_params/chat_model.py +++ b/src/openai/types/shared_params/chat_model.py @@ -15,11 +15,6 @@ "o1-preview-2024-09-12", "o1-mini", "o1-mini-2024-09-12", - "computer-use-preview", - "computer-use-preview-2025-02-04", - "computer-use-preview-2025-03-11", - "gpt-4.5-preview", - "gpt-4.5-preview-2025-02-27", "gpt-4o", "gpt-4o-2024-11-20", "gpt-4o-2024-08-06", @@ -29,6 +24,10 @@ "gpt-4o-audio-preview-2024-12-17", "gpt-4o-mini-audio-preview", "gpt-4o-mini-audio-preview-2024-12-17", + "gpt-4o-search-preview", + "gpt-4o-mini-search-preview", + "gpt-4o-search-preview-2025-03-11", + "gpt-4o-mini-search-preview-2025-03-11", "chatgpt-4o-latest", "gpt-4o-mini", "gpt-4o-mini-2024-07-18", diff --git a/src/openai/types/shared_params/responses_model.py b/src/openai/types/shared_params/responses_model.py new file mode 100644 index 0000000000..3bf0e13731 --- /dev/null +++ b/src/openai/types/shared_params/responses_model.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, TypeAlias + +from ..shared.chat_model import ChatModel + +__all__ = ["ResponsesModel"] + +ResponsesModel: TypeAlias = Union[ + str, ChatModel, Literal["o1-pro", "o1-pro-2025-03-19", "computer-use-preview", "computer-use-preview-2025-03-11"] +] From e9f971a71f7820c624d53c4927590dba67b2f71b Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 19 Mar 2025 21:02:54 +0000 Subject: [PATCH 733/816] release: 1.67.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index e567f9cb13..4556676715 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.66.5" + ".": "1.67.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index d8fb019fc8..ddd8b945c6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.67.0 (2025-03-19) + +Full Changelog: [v1.66.5...v1.67.0](https://github.com/openai/openai-python/compare/v1.66.5...v1.67.0) + +### Features + +* **api:** o1-pro now available through the API ([#2228](https://github.com/openai/openai-python/issues/2228)) ([40a19d8](https://github.com/openai/openai-python/commit/40a19d8592c1767d6318230fc93e37c360d1bcd1)) + ## 1.66.5 (2025-03-18) Full Changelog: [v1.66.4...v1.66.5](https://github.com/openai/openai-python/compare/v1.66.4...v1.66.5) diff --git a/pyproject.toml b/pyproject.toml index 5fdf2a836d..a0a7eba2f5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.66.5" +version = "1.67.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index dbefc6ec32..b63e6ad189 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.66.5" # x-release-please-version +__version__ = "1.67.0" # x-release-please-version From 2b4bc759b49504580cabc5e90b9cd79be4267207 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 20 Mar 2025 16:25:10 +0000 Subject: [PATCH 734/816] feat(api): new models for TTS, STT, + new audio features for Realtime (#2232) --- .stats.yml | 4 +- api.md | 20 ++ src/openai/resources/audio/speech.py | 14 +- src/openai/resources/audio/transcriptions.py | 285 +++++++++++++++- src/openai/resources/audio/translations.py | 3 +- .../resources/beta/realtime/__init__.py | 14 + .../resources/beta/realtime/realtime.py | 312 ++++++++++++------ .../resources/beta/realtime/sessions.py | 64 +++- .../beta/realtime/transcription_sessions.py | 277 ++++++++++++++++ src/openai/types/audio/__init__.py | 4 + .../types/audio/speech_create_params.py | 8 +- src/openai/types/audio/speech_model.py | 2 +- src/openai/types/audio/transcription.py | 21 +- .../audio/transcription_create_params.py | 58 +++- .../types/audio/transcription_include.py | 7 + .../types/audio/transcription_stream_event.py | 14 + .../audio/transcription_text_delta_event.py | 35 ++ .../audio/transcription_text_done_event.py | 35 ++ .../types/audio/translation_create_params.py | 5 +- src/openai/types/audio_model.py | 2 +- src/openai/types/beta/realtime/__init__.py | 12 + ...put_audio_transcription_completed_event.py | 17 +- ...m_input_audio_transcription_delta_event.py | 39 +++ .../conversation_item_retrieve_event.py | 19 ++ .../conversation_item_retrieve_event_param.py | 18 + .../beta/realtime/realtime_client_event.py | 16 +- .../realtime/realtime_client_event_param.py | 16 +- .../beta/realtime/realtime_server_event.py | 57 ++-- src/openai/types/beta/realtime/session.py | 112 +++++-- .../beta/realtime/session_create_params.py | 97 ++++-- .../beta/realtime/session_update_event.py | 106 ++++-- .../realtime/session_update_event_param.py | 98 ++++-- .../beta/realtime/transcription_session.py | 100 ++++++ .../transcription_session_create_params.py | 143 ++++++++ .../realtime/transcription_session_update.py | 160 +++++++++ .../transcription_session_update_param.py | 160 +++++++++ .../transcription_session_updated_event.py | 24 ++ tests/api_resources/audio/test_speech.py | 2 + .../audio/test_transcriptions.py | 146 ++++++-- .../beta/realtime/test_sessions.py | 8 +- .../realtime/test_transcription_sessions.py | 120 +++++++ tests/lib/test_audio.py | 4 +- 42 files changed, 2333 insertions(+), 325 deletions(-) create mode 100644 src/openai/resources/beta/realtime/transcription_sessions.py create mode 100644 src/openai/types/audio/transcription_include.py create mode 100644 src/openai/types/audio/transcription_stream_event.py create mode 100644 src/openai/types/audio/transcription_text_delta_event.py create mode 100644 src/openai/types/audio/transcription_text_done_event.py create mode 100644 src/openai/types/beta/realtime/conversation_item_input_audio_transcription_delta_event.py create mode 100644 src/openai/types/beta/realtime/conversation_item_retrieve_event.py create mode 100644 src/openai/types/beta/realtime/conversation_item_retrieve_event_param.py create mode 100644 src/openai/types/beta/realtime/transcription_session.py create mode 100644 src/openai/types/beta/realtime/transcription_session_create_params.py create mode 100644 src/openai/types/beta/realtime/transcription_session_update.py create mode 100644 src/openai/types/beta/realtime/transcription_session_update_param.py create mode 100644 src/openai/types/beta/realtime/transcription_session_updated_event.py create mode 100644 tests/api_resources/beta/realtime/test_transcription_sessions.py diff --git a/.stats.yml b/.stats.yml index e0b06dc22a..abb9371314 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ -configured_endpoints: 81 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-b26121d5df6eb5d3032a45a267473798b15fcfec76dd44a3256cf1238be05fa4.yml +configured_endpoints: 82 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-c22f59c66aec7914b6ee653d3098d1c1c8c16c180d2a158e819c8ddbf476f74b.yml diff --git a/api.md b/api.md index 7f3a9392a2..a5f81c624c 100644 --- a/api.md +++ b/api.md @@ -151,7 +151,11 @@ Types: ```python from openai.types.audio import ( Transcription, + TranscriptionInclude, TranscriptionSegment, + TranscriptionStreamEvent, + TranscriptionTextDeltaEvent, + TranscriptionTextDoneEvent, TranscriptionVerbose, TranscriptionWord, TranscriptionCreateResponse, @@ -338,7 +342,9 @@ from openai.types.beta.realtime import ( ConversationItemDeleteEvent, ConversationItemDeletedEvent, ConversationItemInputAudioTranscriptionCompletedEvent, + ConversationItemInputAudioTranscriptionDeltaEvent, ConversationItemInputAudioTranscriptionFailedEvent, + ConversationItemRetrieveEvent, ConversationItemTruncateEvent, ConversationItemTruncatedEvent, ConversationItemWithReference, @@ -375,6 +381,8 @@ from openai.types.beta.realtime import ( SessionCreatedEvent, SessionUpdateEvent, SessionUpdatedEvent, + TranscriptionSessionUpdate, + TranscriptionSessionUpdatedEvent, ) ``` @@ -390,6 +398,18 @@ Methods: - client.beta.realtime.sessions.create(\*\*params) -> SessionCreateResponse +### TranscriptionSessions + +Types: + +```python +from openai.types.beta.realtime import TranscriptionSession +``` + +Methods: + +- client.beta.realtime.transcription_sessions.create(\*\*params) -> TranscriptionSession + ## Assistants Types: diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index ad01118161..529e3a47ea 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -54,6 +54,7 @@ def create( input: str, model: Union[str, SpeechModel], voice: Literal["alloy", "ash", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer"], + instructions: str | NotGiven = NOT_GIVEN, response_format: Literal["mp3", "opus", "aac", "flac", "wav", "pcm"] | NotGiven = NOT_GIVEN, speed: float | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -71,13 +72,16 @@ def create( model: One of the available [TTS models](https://platform.openai.com/docs/models#tts): - `tts-1` or `tts-1-hd` + `tts-1`, `tts-1-hd` or `gpt-4o-mini-tts`. voice: The voice to use when generating the audio. Supported voices are `alloy`, `ash`, `coral`, `echo`, `fable`, `onyx`, `nova`, `sage` and `shimmer`. Previews of the voices are available in the [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech#voice-options). + instructions: Control the voice of your generated audio with additional instructions. Does not + work with `tts-1` or `tts-1-hd`. + response_format: The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, `wav`, and `pcm`. @@ -100,6 +104,7 @@ def create( "input": input, "model": model, "voice": voice, + "instructions": instructions, "response_format": response_format, "speed": speed, }, @@ -138,6 +143,7 @@ async def create( input: str, model: Union[str, SpeechModel], voice: Literal["alloy", "ash", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer"], + instructions: str | NotGiven = NOT_GIVEN, response_format: Literal["mp3", "opus", "aac", "flac", "wav", "pcm"] | NotGiven = NOT_GIVEN, speed: float | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -155,13 +161,16 @@ async def create( model: One of the available [TTS models](https://platform.openai.com/docs/models#tts): - `tts-1` or `tts-1-hd` + `tts-1`, `tts-1-hd` or `gpt-4o-mini-tts`. voice: The voice to use when generating the audio. Supported voices are `alloy`, `ash`, `coral`, `echo`, `fable`, `onyx`, `nova`, `sage` and `shimmer`. Previews of the voices are available in the [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech#voice-options). + instructions: Control the voice of your generated audio with additional instructions. Does not + work with `tts-1` or `tts-1-hd`. + response_format: The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, `wav`, and `pcm`. @@ -184,6 +193,7 @@ async def create( "input": input, "model": model, "voice": voice, + "instructions": instructions, "response_format": response_format, "speed": speed, }, diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index f338ad067d..2a77f91d69 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -3,7 +3,7 @@ from __future__ import annotations import logging -from typing import TYPE_CHECKING, List, Union, Mapping, cast +from typing import TYPE_CHECKING, List, Union, Mapping, Optional, cast from typing_extensions import Literal, overload, assert_never import httpx @@ -13,6 +13,7 @@ from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from ..._utils import ( extract_files, + required_args, maybe_transform, deepcopy_minimal, async_maybe_transform, @@ -20,12 +21,16 @@ from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ..._streaming import Stream, AsyncStream from ...types.audio import transcription_create_params from ..._base_client import make_request_options from ...types.audio_model import AudioModel from ...types.audio.transcription import Transcription from ...types.audio_response_format import AudioResponseFormat +from ...types.audio.transcription_include import TranscriptionInclude from ...types.audio.transcription_verbose import TranscriptionVerbose +from ...types.audio.transcription_stream_event import TranscriptionStreamEvent +from ...types.audio.transcription_create_response import TranscriptionCreateResponse __all__ = ["Transcriptions", "AsyncTranscriptions"] @@ -58,6 +63,7 @@ def create( *, file: FileTypes, model: Union[str, AudioModel], + include: List[TranscriptionInclude] | NotGiven = NOT_GIVEN, response_format: Union[Literal["json"], NotGiven] = NOT_GIVEN, language: str | NotGiven = NOT_GIVEN, prompt: str | NotGiven = NOT_GIVEN, @@ -77,6 +83,7 @@ def create( *, file: FileTypes, model: Union[str, AudioModel], + include: List[TranscriptionInclude] | NotGiven = NOT_GIVEN, response_format: Literal["verbose_json"], language: str | NotGiven = NOT_GIVEN, prompt: str | NotGiven = NOT_GIVEN, @@ -97,6 +104,7 @@ def create( file: FileTypes, model: Union[str, AudioModel], response_format: Literal["text", "srt", "vtt"], + include: List[TranscriptionInclude] | NotGiven = NOT_GIVEN, language: str | NotGiven = NOT_GIVEN, prompt: str | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, @@ -109,11 +117,96 @@ def create( timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> str: ... + @overload + def create( + self, + *, + file: FileTypes, + model: Union[str, AudioModel], + stream: Literal[True], + include: List[TranscriptionInclude] | NotGiven = NOT_GIVEN, + language: str | NotGiven = NOT_GIVEN, + prompt: str | NotGiven = NOT_GIVEN, + response_format: Union[AudioResponseFormat, NotGiven] = NOT_GIVEN, + temperature: float | NotGiven = NOT_GIVEN, + timestamp_granularities: List[Literal["word", "segment"]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Stream[TranscriptionStreamEvent]: + """ + Transcribes audio into the input language. + + Args: + file: + The audio file object (not file name) to transcribe, in one of these formats: + flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. + + model: ID of the model to use. The options are `gpt-4o-transcribe`, + `gpt-4o-mini-transcribe`, and `whisper-1` (which is powered by our open source + Whisper V2 model). + + stream: If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section of the Speech-to-Text guide](https://platform.openai.com/docs/guides/speech-to-text?lang=curl#streaming-transcriptions) + for more information. + + Note: Streaming is not supported for the `whisper-1` model and will be ignored. + + include: Additional information to include in the transcription response. `logprobs` will + return the log probabilities of the tokens in the response to understand the + model's confidence in the transcription. `logprobs` only works with + response_format set to `json` and only with the models `gpt-4o-transcribe` and + `gpt-4o-mini-transcribe`. + + language: The language of the input audio. Supplying the input language in + [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) + format will improve accuracy and latency. + + prompt: An optional text to guide the model's style or continue a previous audio + segment. The + [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) + should match the audio language. + + response_format: The format of the output, in one of these options: `json`, `text`, `srt`, + `verbose_json`, or `vtt`. For `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`, + the only supported format is `json`. + + temperature: The sampling temperature, between 0 and 1. Higher values like 0.8 will make the + output more random, while lower values like 0.2 will make it more focused and + deterministic. If set to 0, the model will use + [log probability](https://en.wikipedia.org/wiki/Log_probability) to + automatically increase the temperature until certain thresholds are hit. + + timestamp_granularities: The timestamp granularities to populate for this transcription. + `response_format` must be set `verbose_json` to use timestamp granularities. + Either or both of these options are supported: `word`, or `segment`. Note: There + is no additional latency for segment timestamps, but generating word timestamps + incurs additional latency. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload def create( self, *, file: FileTypes, model: Union[str, AudioModel], + stream: bool, + include: List[TranscriptionInclude] | NotGiven = NOT_GIVEN, language: str | NotGiven = NOT_GIVEN, prompt: str | NotGiven = NOT_GIVEN, response_format: Union[AudioResponseFormat, NotGiven] = NOT_GIVEN, @@ -125,7 +218,7 @@ def create( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> Transcription | TranscriptionVerbose | str: + ) -> TranscriptionCreateResponse | Stream[TranscriptionStreamEvent]: """ Transcribes audio into the input language. @@ -134,8 +227,24 @@ def create( The audio file object (not file name) to transcribe, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. - model: ID of the model to use. Only `whisper-1` (which is powered by our open source - Whisper V2 model) is currently available. + model: ID of the model to use. The options are `gpt-4o-transcribe`, + `gpt-4o-mini-transcribe`, and `whisper-1` (which is powered by our open source + Whisper V2 model). + + stream: If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section of the Speech-to-Text guide](https://platform.openai.com/docs/guides/speech-to-text?lang=curl#streaming-transcriptions) + for more information. + + Note: Streaming is not supported for the `whisper-1` model and will be ignored. + + include: Additional information to include in the transcription response. `logprobs` will + return the log probabilities of the tokens in the response to understand the + model's confidence in the transcription. `logprobs` only works with + response_format set to `json` and only with the models `gpt-4o-transcribe` and + `gpt-4o-mini-transcribe`. language: The language of the input audio. Supplying the input language in [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) @@ -147,7 +256,8 @@ def create( should match the audio language. response_format: The format of the output, in one of these options: `json`, `text`, `srt`, - `verbose_json`, or `vtt`. + `verbose_json`, or `vtt`. For `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`, + the only supported format is `json`. temperature: The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and @@ -169,13 +279,37 @@ def create( timeout: Override the client-level default timeout for this request, in seconds """ + ... + + @required_args(["file", "model"], ["file", "model", "stream"]) + def create( + self, + *, + file: FileTypes, + model: Union[str, AudioModel], + include: List[TranscriptionInclude] | NotGiven = NOT_GIVEN, + language: str | NotGiven = NOT_GIVEN, + prompt: str | NotGiven = NOT_GIVEN, + response_format: Union[AudioResponseFormat, NotGiven] = NOT_GIVEN, + stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + temperature: float | NotGiven = NOT_GIVEN, + timestamp_granularities: List[Literal["word", "segment"]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> str | Transcription | TranscriptionVerbose | Stream[TranscriptionStreamEvent]: body = deepcopy_minimal( { "file": file, "model": model, + "include": include, "language": language, "prompt": prompt, "response_format": response_format, + "stream": stream, "temperature": temperature, "timestamp_granularities": timestamp_granularities, } @@ -193,6 +327,8 @@ def create( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=_get_response_format_type(response_format), + stream=stream or False, + stream_cls=Stream[TranscriptionStreamEvent], ) @@ -226,6 +362,7 @@ async def create( language: str | NotGiven = NOT_GIVEN, prompt: str | NotGiven = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, + include: List[TranscriptionInclude] | NotGiven = NOT_GIVEN, timestamp_granularities: List[Literal["word", "segment"]] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -241,6 +378,7 @@ async def create( *, file: FileTypes, model: Union[str, AudioModel], + include: List[TranscriptionInclude] | NotGiven = NOT_GIVEN, response_format: Literal["verbose_json"], language: str | NotGiven = NOT_GIVEN, prompt: str | NotGiven = NOT_GIVEN, @@ -260,6 +398,7 @@ async def create( *, file: FileTypes, model: Union[str, AudioModel], + include: List[TranscriptionInclude] | NotGiven = NOT_GIVEN, response_format: Literal["text", "srt", "vtt"], language: str | NotGiven = NOT_GIVEN, prompt: str | NotGiven = NOT_GIVEN, @@ -273,11 +412,96 @@ async def create( timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> str: ... + @overload + async def create( + self, + *, + file: FileTypes, + model: Union[str, AudioModel], + stream: Literal[True], + include: List[TranscriptionInclude] | NotGiven = NOT_GIVEN, + language: str | NotGiven = NOT_GIVEN, + prompt: str | NotGiven = NOT_GIVEN, + response_format: Union[AudioResponseFormat, NotGiven] = NOT_GIVEN, + temperature: float | NotGiven = NOT_GIVEN, + timestamp_granularities: List[Literal["word", "segment"]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncStream[TranscriptionStreamEvent]: + """ + Transcribes audio into the input language. + + Args: + file: + The audio file object (not file name) to transcribe, in one of these formats: + flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. + + model: ID of the model to use. The options are `gpt-4o-transcribe`, + `gpt-4o-mini-transcribe`, and `whisper-1` (which is powered by our open source + Whisper V2 model). + + stream: If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section of the Speech-to-Text guide](https://platform.openai.com/docs/guides/speech-to-text?lang=curl#streaming-transcriptions) + for more information. + + Note: Streaming is not supported for the `whisper-1` model and will be ignored. + + include: Additional information to include in the transcription response. `logprobs` will + return the log probabilities of the tokens in the response to understand the + model's confidence in the transcription. `logprobs` only works with + response_format set to `json` and only with the models `gpt-4o-transcribe` and + `gpt-4o-mini-transcribe`. + + language: The language of the input audio. Supplying the input language in + [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) + format will improve accuracy and latency. + + prompt: An optional text to guide the model's style or continue a previous audio + segment. The + [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) + should match the audio language. + + response_format: The format of the output, in one of these options: `json`, `text`, `srt`, + `verbose_json`, or `vtt`. For `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`, + the only supported format is `json`. + + temperature: The sampling temperature, between 0 and 1. Higher values like 0.8 will make the + output more random, while lower values like 0.2 will make it more focused and + deterministic. If set to 0, the model will use + [log probability](https://en.wikipedia.org/wiki/Log_probability) to + automatically increase the temperature until certain thresholds are hit. + + timestamp_granularities: The timestamp granularities to populate for this transcription. + `response_format` must be set `verbose_json` to use timestamp granularities. + Either or both of these options are supported: `word`, or `segment`. Note: There + is no additional latency for segment timestamps, but generating word timestamps + incurs additional latency. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + ... + + @overload async def create( self, *, file: FileTypes, model: Union[str, AudioModel], + stream: bool, + include: List[TranscriptionInclude] | NotGiven = NOT_GIVEN, language: str | NotGiven = NOT_GIVEN, prompt: str | NotGiven = NOT_GIVEN, response_format: Union[AudioResponseFormat, NotGiven] = NOT_GIVEN, @@ -289,7 +513,7 @@ async def create( extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> Transcription | TranscriptionVerbose | str: + ) -> TranscriptionCreateResponse | AsyncStream[TranscriptionStreamEvent]: """ Transcribes audio into the input language. @@ -298,8 +522,24 @@ async def create( The audio file object (not file name) to transcribe, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. - model: ID of the model to use. Only `whisper-1` (which is powered by our open source - Whisper V2 model) is currently available. + model: ID of the model to use. The options are `gpt-4o-transcribe`, + `gpt-4o-mini-transcribe`, and `whisper-1` (which is powered by our open source + Whisper V2 model). + + stream: If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section of the Speech-to-Text guide](https://platform.openai.com/docs/guides/speech-to-text?lang=curl#streaming-transcriptions) + for more information. + + Note: Streaming is not supported for the `whisper-1` model and will be ignored. + + include: Additional information to include in the transcription response. `logprobs` will + return the log probabilities of the tokens in the response to understand the + model's confidence in the transcription. `logprobs` only works with + response_format set to `json` and only with the models `gpt-4o-transcribe` and + `gpt-4o-mini-transcribe`. language: The language of the input audio. Supplying the input language in [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) @@ -311,7 +551,8 @@ async def create( should match the audio language. response_format: The format of the output, in one of these options: `json`, `text`, `srt`, - `verbose_json`, or `vtt`. + `verbose_json`, or `vtt`. For `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`, + the only supported format is `json`. temperature: The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and @@ -333,13 +574,37 @@ async def create( timeout: Override the client-level default timeout for this request, in seconds """ + ... + + @required_args(["file", "model"], ["file", "model", "stream"]) + async def create( + self, + *, + file: FileTypes, + model: Union[str, AudioModel], + include: List[TranscriptionInclude] | NotGiven = NOT_GIVEN, + language: str | NotGiven = NOT_GIVEN, + prompt: str | NotGiven = NOT_GIVEN, + response_format: Union[AudioResponseFormat, NotGiven] = NOT_GIVEN, + stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, + temperature: float | NotGiven = NOT_GIVEN, + timestamp_granularities: List[Literal["word", "segment"]] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> Transcription | TranscriptionVerbose | str | AsyncStream[TranscriptionStreamEvent]: body = deepcopy_minimal( { "file": file, "model": model, + "include": include, "language": language, "prompt": prompt, "response_format": response_format, + "stream": stream, "temperature": temperature, "timestamp_granularities": timestamp_granularities, } @@ -357,6 +622,8 @@ async def create( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=_get_response_format_type(response_format), + stream=stream or False, + stream_cls=AsyncStream[TranscriptionStreamEvent], ) diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index cd3132dc57..f55dbd0ee5 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -9,7 +9,6 @@ import httpx from ... import _legacy_response -from ...types import AudioResponseFormat from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from ..._utils import ( extract_files, @@ -109,7 +108,7 @@ def create( file: FileTypes, model: Union[str, AudioModel], prompt: str | NotGiven = NOT_GIVEN, - response_format: Union[AudioResponseFormat, NotGiven] = NOT_GIVEN, + response_format: Union[Literal["json", "text", "srt", "verbose_json", "vtt"], NotGiven] = NOT_GIVEN, temperature: float | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. diff --git a/src/openai/resources/beta/realtime/__init__.py b/src/openai/resources/beta/realtime/__init__.py index 474434e6e1..7ab3d9931c 100644 --- a/src/openai/resources/beta/realtime/__init__.py +++ b/src/openai/resources/beta/realtime/__init__.py @@ -16,6 +16,14 @@ SessionsWithStreamingResponse, AsyncSessionsWithStreamingResponse, ) +from .transcription_sessions import ( + TranscriptionSessions, + AsyncTranscriptionSessions, + TranscriptionSessionsWithRawResponse, + AsyncTranscriptionSessionsWithRawResponse, + TranscriptionSessionsWithStreamingResponse, + AsyncTranscriptionSessionsWithStreamingResponse, +) __all__ = [ "Sessions", @@ -24,6 +32,12 @@ "AsyncSessionsWithRawResponse", "SessionsWithStreamingResponse", "AsyncSessionsWithStreamingResponse", + "TranscriptionSessions", + "AsyncTranscriptionSessions", + "TranscriptionSessionsWithRawResponse", + "AsyncTranscriptionSessionsWithRawResponse", + "TranscriptionSessionsWithStreamingResponse", + "AsyncTranscriptionSessionsWithStreamingResponse", "Realtime", "AsyncRealtime", "RealtimeWithRawResponse", diff --git a/src/openai/resources/beta/realtime/realtime.py b/src/openai/resources/beta/realtime/realtime.py index cd610d9089..76e57f8cb7 100644 --- a/src/openai/resources/beta/realtime/realtime.py +++ b/src/openai/resources/beta/realtime/realtime.py @@ -32,7 +32,19 @@ from ...._resource import SyncAPIResource, AsyncAPIResource from ...._exceptions import OpenAIError from ...._base_client import _merge_mappings -from ....types.beta.realtime import session_update_event_param, response_create_event_param +from ....types.beta.realtime import ( + session_update_event_param, + response_create_event_param, + transcription_session_update_param, +) +from .transcription_sessions import ( + TranscriptionSessions, + AsyncTranscriptionSessions, + TranscriptionSessionsWithRawResponse, + AsyncTranscriptionSessionsWithRawResponse, + TranscriptionSessionsWithStreamingResponse, + AsyncTranscriptionSessionsWithStreamingResponse, +) from ....types.websocket_connection_options import WebsocketConnectionOptions from ....types.beta.realtime.realtime_client_event import RealtimeClientEvent from ....types.beta.realtime.realtime_server_event import RealtimeServerEvent @@ -55,6 +67,10 @@ class Realtime(SyncAPIResource): def sessions(self) -> Sessions: return Sessions(self._client) + @cached_property + def transcription_sessions(self) -> TranscriptionSessions: + return TranscriptionSessions(self._client) + @cached_property def with_raw_response(self) -> RealtimeWithRawResponse: """ @@ -107,6 +123,10 @@ class AsyncRealtime(AsyncAPIResource): def sessions(self) -> AsyncSessions: return AsyncSessions(self._client) + @cached_property + def transcription_sessions(self) -> AsyncTranscriptionSessions: + return AsyncTranscriptionSessions(self._client) + @cached_property def with_raw_response(self) -> AsyncRealtimeWithRawResponse: """ @@ -162,6 +182,10 @@ def __init__(self, realtime: Realtime) -> None: def sessions(self) -> SessionsWithRawResponse: return SessionsWithRawResponse(self._realtime.sessions) + @cached_property + def transcription_sessions(self) -> TranscriptionSessionsWithRawResponse: + return TranscriptionSessionsWithRawResponse(self._realtime.transcription_sessions) + class AsyncRealtimeWithRawResponse: def __init__(self, realtime: AsyncRealtime) -> None: @@ -171,6 +195,10 @@ def __init__(self, realtime: AsyncRealtime) -> None: def sessions(self) -> AsyncSessionsWithRawResponse: return AsyncSessionsWithRawResponse(self._realtime.sessions) + @cached_property + def transcription_sessions(self) -> AsyncTranscriptionSessionsWithRawResponse: + return AsyncTranscriptionSessionsWithRawResponse(self._realtime.transcription_sessions) + class RealtimeWithStreamingResponse: def __init__(self, realtime: Realtime) -> None: @@ -180,6 +208,10 @@ def __init__(self, realtime: Realtime) -> None: def sessions(self) -> SessionsWithStreamingResponse: return SessionsWithStreamingResponse(self._realtime.sessions) + @cached_property + def transcription_sessions(self) -> TranscriptionSessionsWithStreamingResponse: + return TranscriptionSessionsWithStreamingResponse(self._realtime.transcription_sessions) + class AsyncRealtimeWithStreamingResponse: def __init__(self, realtime: AsyncRealtime) -> None: @@ -189,14 +221,19 @@ def __init__(self, realtime: AsyncRealtime) -> None: def sessions(self) -> AsyncSessionsWithStreamingResponse: return AsyncSessionsWithStreamingResponse(self._realtime.sessions) + @cached_property + def transcription_sessions(self) -> AsyncTranscriptionSessionsWithStreamingResponse: + return AsyncTranscriptionSessionsWithStreamingResponse(self._realtime.transcription_sessions) + class AsyncRealtimeConnection: """Represents a live websocket connection to the Realtime API""" session: AsyncRealtimeSessionResource response: AsyncRealtimeResponseResource - conversation: AsyncRealtimeConversationResource input_audio_buffer: AsyncRealtimeInputAudioBufferResource + conversation: AsyncRealtimeConversationResource + transcription_session: AsyncRealtimeTranscriptionSessionResource _connection: AsyncWebsocketConnection @@ -205,8 +242,9 @@ def __init__(self, connection: AsyncWebsocketConnection) -> None: self.session = AsyncRealtimeSessionResource(self) self.response = AsyncRealtimeResponseResource(self) - self.conversation = AsyncRealtimeConversationResource(self) self.input_audio_buffer = AsyncRealtimeInputAudioBufferResource(self) + self.conversation = AsyncRealtimeConversationResource(self) + self.transcription_session = AsyncRealtimeTranscriptionSessionResource(self) async def __aiter__(self) -> AsyncIterator[RealtimeServerEvent]: """ @@ -377,8 +415,9 @@ class RealtimeConnection: session: RealtimeSessionResource response: RealtimeResponseResource - conversation: RealtimeConversationResource input_audio_buffer: RealtimeInputAudioBufferResource + conversation: RealtimeConversationResource + transcription_session: RealtimeTranscriptionSessionResource _connection: WebsocketConnection @@ -387,8 +426,9 @@ def __init__(self, connection: WebsocketConnection) -> None: self.session = RealtimeSessionResource(self) self.response = RealtimeResponseResource(self) - self.conversation = RealtimeConversationResource(self) self.input_audio_buffer = RealtimeInputAudioBufferResource(self) + self.conversation = RealtimeConversationResource(self) + self.transcription_session = RealtimeTranscriptionSessionResource(self) def __iter__(self) -> Iterator[RealtimeServerEvent]: """ @@ -582,20 +622,6 @@ def update(self, *, session: session_update_event_param.Session, event_id: str | class RealtimeResponseResource(BaseRealtimeConnectionResource): - def cancel(self, *, event_id: str | NotGiven = NOT_GIVEN, response_id: str | NotGiven = NOT_GIVEN) -> None: - """Send this event to cancel an in-progress response. - - The server will respond - with a `response.cancelled` event or an error if there is no response to - cancel. - """ - self._connection.send( - cast( - RealtimeClientEventParam, - strip_not_given({"type": "response.cancel", "event_id": event_id, "response_id": response_id}), - ) - ) - def create( self, *, @@ -626,6 +652,70 @@ def create( ) ) + def cancel(self, *, event_id: str | NotGiven = NOT_GIVEN, response_id: str | NotGiven = NOT_GIVEN) -> None: + """Send this event to cancel an in-progress response. + + The server will respond + with a `response.cancelled` event or an error if there is no response to + cancel. + """ + self._connection.send( + cast( + RealtimeClientEventParam, + strip_not_given({"type": "response.cancel", "event_id": event_id, "response_id": response_id}), + ) + ) + + +class RealtimeInputAudioBufferResource(BaseRealtimeConnectionResource): + def clear(self, *, event_id: str | NotGiven = NOT_GIVEN) -> None: + """Send this event to clear the audio bytes in the buffer. + + The server will + respond with an `input_audio_buffer.cleared` event. + """ + self._connection.send( + cast(RealtimeClientEventParam, strip_not_given({"type": "input_audio_buffer.clear", "event_id": event_id})) + ) + + def commit(self, *, event_id: str | NotGiven = NOT_GIVEN) -> None: + """ + Send this event to commit the user input audio buffer, which will create a + new user message item in the conversation. This event will produce an error + if the input audio buffer is empty. When in Server VAD mode, the client does + not need to send this event, the server will commit the audio buffer + automatically. + + Committing the input audio buffer will trigger input audio transcription + (if enabled in session configuration), but it will not create a response + from the model. The server will respond with an `input_audio_buffer.committed` + event. + """ + self._connection.send( + cast(RealtimeClientEventParam, strip_not_given({"type": "input_audio_buffer.commit", "event_id": event_id})) + ) + + def append(self, *, audio: str, event_id: str | NotGiven = NOT_GIVEN) -> None: + """Send this event to append audio bytes to the input audio buffer. + + The audio + buffer is temporary storage you can write to and later commit. In Server VAD + mode, the audio buffer is used to detect speech and the server will decide + when to commit. When Server VAD is disabled, you must commit the audio buffer + manually. + + The client may choose how much audio to place in each event up to a maximum + of 15 MiB, for example streaming smaller chunks from the client may allow the + VAD to be more responsive. Unlike made other client events, the server will + not send a confirmation response to this event. + """ + self._connection.send( + cast( + RealtimeClientEventParam, + strip_not_given({"type": "input_audio_buffer.append", "audio": audio, "event_id": event_id}), + ) + ) + class RealtimeConversationResource(BaseRealtimeConnectionResource): @cached_property @@ -711,53 +801,30 @@ def truncate( ) ) - -class RealtimeInputAudioBufferResource(BaseRealtimeConnectionResource): - def clear(self, *, event_id: str | NotGiven = NOT_GIVEN) -> None: - """Send this event to clear the audio bytes in the buffer. - - The server will - respond with an `input_audio_buffer.cleared` event. + def retrieve(self, *, item_id: str, event_id: str | NotGiven = NOT_GIVEN) -> None: """ - self._connection.send( - cast(RealtimeClientEventParam, strip_not_given({"type": "input_audio_buffer.clear", "event_id": event_id})) - ) - - def commit(self, *, event_id: str | NotGiven = NOT_GIVEN) -> None: - """ - Send this event to commit the user input audio buffer, which will create a - new user message item in the conversation. This event will produce an error - if the input audio buffer is empty. When in Server VAD mode, the client does - not need to send this event, the server will commit the audio buffer - automatically. - - Committing the input audio buffer will trigger input audio transcription - (if enabled in session configuration), but it will not create a response - from the model. The server will respond with an `input_audio_buffer.committed` - event. + Send this event when you want to retrieve the server's representation of a specific item in the conversation history. This is useful, for example, to inspect user audio after noise cancellation and VAD. + The server will respond with a `conversation.item.retrieved` event, + unless the item does not exist in the conversation history, in which case the + server will respond with an error. """ self._connection.send( - cast(RealtimeClientEventParam, strip_not_given({"type": "input_audio_buffer.commit", "event_id": event_id})) + cast( + RealtimeClientEventParam, + strip_not_given({"type": "conversation.item.retrieve", "item_id": item_id, "event_id": event_id}), + ) ) - def append(self, *, audio: str, event_id: str | NotGiven = NOT_GIVEN) -> None: - """Send this event to append audio bytes to the input audio buffer. - The audio - buffer is temporary storage you can write to and later commit. In Server VAD - mode, the audio buffer is used to detect speech and the server will decide - when to commit. When Server VAD is disabled, you must commit the audio buffer - manually. - - The client may choose how much audio to place in each event up to a maximum - of 15 MiB, for example streaming smaller chunks from the client may allow the - VAD to be more responsive. Unlike made other client events, the server will - not send a confirmation response to this event. - """ +class RealtimeTranscriptionSessionResource(BaseRealtimeConnectionResource): + def update( + self, *, session: transcription_session_update_param.Session, event_id: str | NotGiven = NOT_GIVEN + ) -> None: + """Send this event to update a transcription session.""" self._connection.send( cast( RealtimeClientEventParam, - strip_not_given({"type": "input_audio_buffer.append", "audio": audio, "event_id": event_id}), + strip_not_given({"type": "transcription_session.update", "session": session, "event_id": event_id}), ) ) @@ -792,20 +859,6 @@ async def update( class AsyncRealtimeResponseResource(BaseAsyncRealtimeConnectionResource): - async def cancel(self, *, event_id: str | NotGiven = NOT_GIVEN, response_id: str | NotGiven = NOT_GIVEN) -> None: - """Send this event to cancel an in-progress response. - - The server will respond - with a `response.cancelled` event or an error if there is no response to - cancel. - """ - await self._connection.send( - cast( - RealtimeClientEventParam, - strip_not_given({"type": "response.cancel", "event_id": event_id, "response_id": response_id}), - ) - ) - async def create( self, *, @@ -836,6 +889,70 @@ async def create( ) ) + async def cancel(self, *, event_id: str | NotGiven = NOT_GIVEN, response_id: str | NotGiven = NOT_GIVEN) -> None: + """Send this event to cancel an in-progress response. + + The server will respond + with a `response.cancelled` event or an error if there is no response to + cancel. + """ + await self._connection.send( + cast( + RealtimeClientEventParam, + strip_not_given({"type": "response.cancel", "event_id": event_id, "response_id": response_id}), + ) + ) + + +class AsyncRealtimeInputAudioBufferResource(BaseAsyncRealtimeConnectionResource): + async def clear(self, *, event_id: str | NotGiven = NOT_GIVEN) -> None: + """Send this event to clear the audio bytes in the buffer. + + The server will + respond with an `input_audio_buffer.cleared` event. + """ + await self._connection.send( + cast(RealtimeClientEventParam, strip_not_given({"type": "input_audio_buffer.clear", "event_id": event_id})) + ) + + async def commit(self, *, event_id: str | NotGiven = NOT_GIVEN) -> None: + """ + Send this event to commit the user input audio buffer, which will create a + new user message item in the conversation. This event will produce an error + if the input audio buffer is empty. When in Server VAD mode, the client does + not need to send this event, the server will commit the audio buffer + automatically. + + Committing the input audio buffer will trigger input audio transcription + (if enabled in session configuration), but it will not create a response + from the model. The server will respond with an `input_audio_buffer.committed` + event. + """ + await self._connection.send( + cast(RealtimeClientEventParam, strip_not_given({"type": "input_audio_buffer.commit", "event_id": event_id})) + ) + + async def append(self, *, audio: str, event_id: str | NotGiven = NOT_GIVEN) -> None: + """Send this event to append audio bytes to the input audio buffer. + + The audio + buffer is temporary storage you can write to and later commit. In Server VAD + mode, the audio buffer is used to detect speech and the server will decide + when to commit. When Server VAD is disabled, you must commit the audio buffer + manually. + + The client may choose how much audio to place in each event up to a maximum + of 15 MiB, for example streaming smaller chunks from the client may allow the + VAD to be more responsive. Unlike made other client events, the server will + not send a confirmation response to this event. + """ + await self._connection.send( + cast( + RealtimeClientEventParam, + strip_not_given({"type": "input_audio_buffer.append", "audio": audio, "event_id": event_id}), + ) + ) + class AsyncRealtimeConversationResource(BaseAsyncRealtimeConnectionResource): @cached_property @@ -921,52 +1038,29 @@ async def truncate( ) ) - -class AsyncRealtimeInputAudioBufferResource(BaseAsyncRealtimeConnectionResource): - async def clear(self, *, event_id: str | NotGiven = NOT_GIVEN) -> None: - """Send this event to clear the audio bytes in the buffer. - - The server will - respond with an `input_audio_buffer.cleared` event. - """ - await self._connection.send( - cast(RealtimeClientEventParam, strip_not_given({"type": "input_audio_buffer.clear", "event_id": event_id})) - ) - - async def commit(self, *, event_id: str | NotGiven = NOT_GIVEN) -> None: + async def retrieve(self, *, item_id: str, event_id: str | NotGiven = NOT_GIVEN) -> None: """ - Send this event to commit the user input audio buffer, which will create a - new user message item in the conversation. This event will produce an error - if the input audio buffer is empty. When in Server VAD mode, the client does - not need to send this event, the server will commit the audio buffer - automatically. - - Committing the input audio buffer will trigger input audio transcription - (if enabled in session configuration), but it will not create a response - from the model. The server will respond with an `input_audio_buffer.committed` - event. + Send this event when you want to retrieve the server's representation of a specific item in the conversation history. This is useful, for example, to inspect user audio after noise cancellation and VAD. + The server will respond with a `conversation.item.retrieved` event, + unless the item does not exist in the conversation history, in which case the + server will respond with an error. """ await self._connection.send( - cast(RealtimeClientEventParam, strip_not_given({"type": "input_audio_buffer.commit", "event_id": event_id})) + cast( + RealtimeClientEventParam, + strip_not_given({"type": "conversation.item.retrieve", "item_id": item_id, "event_id": event_id}), + ) ) - async def append(self, *, audio: str, event_id: str | NotGiven = NOT_GIVEN) -> None: - """Send this event to append audio bytes to the input audio buffer. - - The audio - buffer is temporary storage you can write to and later commit. In Server VAD - mode, the audio buffer is used to detect speech and the server will decide - when to commit. When Server VAD is disabled, you must commit the audio buffer - manually. - The client may choose how much audio to place in each event up to a maximum - of 15 MiB, for example streaming smaller chunks from the client may allow the - VAD to be more responsive. Unlike made other client events, the server will - not send a confirmation response to this event. - """ +class AsyncRealtimeTranscriptionSessionResource(BaseAsyncRealtimeConnectionResource): + async def update( + self, *, session: transcription_session_update_param.Session, event_id: str | NotGiven = NOT_GIVEN + ) -> None: + """Send this event to update a transcription session.""" await self._connection.send( cast( RealtimeClientEventParam, - strip_not_given({"type": "input_audio_buffer.append", "audio": audio, "event_id": event_id}), + strip_not_given({"type": "transcription_session.update", "session": session, "event_id": event_id}), ) ) diff --git a/src/openai/resources/beta/realtime/sessions.py b/src/openai/resources/beta/realtime/sessions.py index 4b337b7c19..5884e54de2 100644 --- a/src/openai/resources/beta/realtime/sessions.py +++ b/src/openai/resources/beta/realtime/sessions.py @@ -47,6 +47,7 @@ def create( self, *, input_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"] | NotGiven = NOT_GIVEN, + input_audio_noise_reduction: session_create_params.InputAudioNoiseReduction | NotGiven = NOT_GIVEN, input_audio_transcription: session_create_params.InputAudioTranscription | NotGiven = NOT_GIVEN, instructions: str | NotGiven = NOT_GIVEN, max_response_output_tokens: Union[int, Literal["inf"]] | NotGiven = NOT_GIVEN, @@ -86,14 +87,20 @@ def create( `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, single channel (mono), and little-endian byte order. + input_audio_noise_reduction: Configuration for input audio noise reduction. This can be set to `null` to turn + off. Noise reduction filters audio added to the input audio buffer before it is + sent to VAD and the model. Filtering the audio can improve VAD and turn + detection accuracy (reducing false positives) and model performance by improving + perception of the input audio. + input_audio_transcription: Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs asynchronously through - [OpenAI Whisper transcription](https://platform.openai.com/docs/api-reference/audio/createTranscription) - and should be treated as rough guidance rather than the representation - understood by the model. The client can optionally set the language and prompt - for transcription, these fields will be passed to the Whisper API. + [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription) + and should be treated as guidance of input audio content rather than precisely + what the model heard. The client can optionally set the language and prompt for + transcription, these offer additional guidance to the transcription service. instructions: The default system instructions (i.e. system message) prepended to model calls. This field allows the client to guide the model on desired responses. The model @@ -119,16 +126,24 @@ def create( output_audio_format: The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For `pcm16`, output audio is sampled at a rate of 24kHz. - temperature: Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8. + temperature: Sampling temperature for the model, limited to [0.6, 1.2]. For audio models a + temperature of 0.8 is highly recommended for best performance. tool_choice: How the model chooses tools. Options are `auto`, `none`, `required`, or specify a function. tools: Tools (functions) available to the model. - turn_detection: Configuration for turn detection. Can be set to `null` to turn off. Server VAD - means that the model will detect the start and end of speech based on audio - volume and respond at the end of user speech. + turn_detection: Configuration for turn detection, ether Server VAD or Semantic VAD. This can be + set to `null` to turn off, in which case the client must manually trigger model + response. Server VAD means that the model will detect the start and end of + speech based on audio volume and respond at the end of user speech. Semantic VAD + is more advanced and uses a turn detection model (in conjuction with VAD) to + semantically estimate whether the user has finished speaking, then dynamically + sets a timeout based on this probability. For example, if user audio trails off + with "uhhm", the model will score a low probability of turn end and wait longer + for the user to continue speaking. This can be useful for more natural + conversations, but may have a higher latency. voice: The voice the model uses to respond. Voice cannot be changed during the session once the model has responded with audio at least once. Current voice options are @@ -148,6 +163,7 @@ def create( body=maybe_transform( { "input_audio_format": input_audio_format, + "input_audio_noise_reduction": input_audio_noise_reduction, "input_audio_transcription": input_audio_transcription, "instructions": instructions, "max_response_output_tokens": max_response_output_tokens, @@ -193,6 +209,7 @@ async def create( self, *, input_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"] | NotGiven = NOT_GIVEN, + input_audio_noise_reduction: session_create_params.InputAudioNoiseReduction | NotGiven = NOT_GIVEN, input_audio_transcription: session_create_params.InputAudioTranscription | NotGiven = NOT_GIVEN, instructions: str | NotGiven = NOT_GIVEN, max_response_output_tokens: Union[int, Literal["inf"]] | NotGiven = NOT_GIVEN, @@ -232,14 +249,20 @@ async def create( `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, single channel (mono), and little-endian byte order. + input_audio_noise_reduction: Configuration for input audio noise reduction. This can be set to `null` to turn + off. Noise reduction filters audio added to the input audio buffer before it is + sent to VAD and the model. Filtering the audio can improve VAD and turn + detection accuracy (reducing false positives) and model performance by improving + perception of the input audio. + input_audio_transcription: Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs asynchronously through - [OpenAI Whisper transcription](https://platform.openai.com/docs/api-reference/audio/createTranscription) - and should be treated as rough guidance rather than the representation - understood by the model. The client can optionally set the language and prompt - for transcription, these fields will be passed to the Whisper API. + [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription) + and should be treated as guidance of input audio content rather than precisely + what the model heard. The client can optionally set the language and prompt for + transcription, these offer additional guidance to the transcription service. instructions: The default system instructions (i.e. system message) prepended to model calls. This field allows the client to guide the model on desired responses. The model @@ -265,16 +288,24 @@ async def create( output_audio_format: The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For `pcm16`, output audio is sampled at a rate of 24kHz. - temperature: Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8. + temperature: Sampling temperature for the model, limited to [0.6, 1.2]. For audio models a + temperature of 0.8 is highly recommended for best performance. tool_choice: How the model chooses tools. Options are `auto`, `none`, `required`, or specify a function. tools: Tools (functions) available to the model. - turn_detection: Configuration for turn detection. Can be set to `null` to turn off. Server VAD - means that the model will detect the start and end of speech based on audio - volume and respond at the end of user speech. + turn_detection: Configuration for turn detection, ether Server VAD or Semantic VAD. This can be + set to `null` to turn off, in which case the client must manually trigger model + response. Server VAD means that the model will detect the start and end of + speech based on audio volume and respond at the end of user speech. Semantic VAD + is more advanced and uses a turn detection model (in conjuction with VAD) to + semantically estimate whether the user has finished speaking, then dynamically + sets a timeout based on this probability. For example, if user audio trails off + with "uhhm", the model will score a low probability of turn end and wait longer + for the user to continue speaking. This can be useful for more natural + conversations, but may have a higher latency. voice: The voice the model uses to respond. Voice cannot be changed during the session once the model has responded with audio at least once. Current voice options are @@ -294,6 +325,7 @@ async def create( body=await async_maybe_transform( { "input_audio_format": input_audio_format, + "input_audio_noise_reduction": input_audio_noise_reduction, "input_audio_transcription": input_audio_transcription, "instructions": instructions, "max_response_output_tokens": max_response_output_tokens, diff --git a/src/openai/resources/beta/realtime/transcription_sessions.py b/src/openai/resources/beta/realtime/transcription_sessions.py new file mode 100644 index 0000000000..0917da71fa --- /dev/null +++ b/src/openai/resources/beta/realtime/transcription_sessions.py @@ -0,0 +1,277 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List +from typing_extensions import Literal + +import httpx + +from .... import _legacy_response +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ...._utils import ( + maybe_transform, + async_maybe_transform, +) +from ...._compat import cached_property +from ...._resource import SyncAPIResource, AsyncAPIResource +from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ...._base_client import make_request_options +from ....types.beta.realtime import transcription_session_create_params +from ....types.beta.realtime.transcription_session import TranscriptionSession + +__all__ = ["TranscriptionSessions", "AsyncTranscriptionSessions"] + + +class TranscriptionSessions(SyncAPIResource): + @cached_property + def with_raw_response(self) -> TranscriptionSessionsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return TranscriptionSessionsWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> TranscriptionSessionsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return TranscriptionSessionsWithStreamingResponse(self) + + def create( + self, + *, + include: List[str] | NotGiven = NOT_GIVEN, + input_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"] | NotGiven = NOT_GIVEN, + input_audio_noise_reduction: transcription_session_create_params.InputAudioNoiseReduction + | NotGiven = NOT_GIVEN, + input_audio_transcription: transcription_session_create_params.InputAudioTranscription | NotGiven = NOT_GIVEN, + modalities: List[Literal["text", "audio"]] | NotGiven = NOT_GIVEN, + turn_detection: transcription_session_create_params.TurnDetection | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> TranscriptionSession: + """ + Create an ephemeral API token for use in client-side applications with the + Realtime API specifically for realtime transcriptions. Can be configured with + the same session parameters as the `transcription_session.update` client event. + + It responds with a session object, plus a `client_secret` key which contains a + usable ephemeral API token that can be used to authenticate browser clients for + the Realtime API. + + Args: + include: + The set of items to include in the transcription. Current available items are: + + - `item.input_audio_transcription.logprobs` + + input_audio_format: The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For + `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, single channel + (mono), and little-endian byte order. + + input_audio_noise_reduction: Configuration for input audio noise reduction. This can be set to `null` to turn + off. Noise reduction filters audio added to the input audio buffer before it is + sent to VAD and the model. Filtering the audio can improve VAD and turn + detection accuracy (reducing false positives) and model performance by improving + perception of the input audio. + + input_audio_transcription: Configuration for input audio transcription. The client can optionally set the + language and prompt for transcription, these offer additional guidance to the + transcription service. + + modalities: The set of modalities the model can respond with. To disable audio, set this to + ["text"]. + + turn_detection: Configuration for turn detection, ether Server VAD or Semantic VAD. This can be + set to `null` to turn off, in which case the client must manually trigger model + response. Server VAD means that the model will detect the start and end of + speech based on audio volume and respond at the end of user speech. Semantic VAD + is more advanced and uses a turn detection model (in conjuction with VAD) to + semantically estimate whether the user has finished speaking, then dynamically + sets a timeout based on this probability. For example, if user audio trails off + with "uhhm", the model will score a low probability of turn end and wait longer + for the user to continue speaking. This can be useful for more natural + conversations, but may have a higher latency. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return self._post( + "/realtime/transcription_sessions", + body=maybe_transform( + { + "include": include, + "input_audio_format": input_audio_format, + "input_audio_noise_reduction": input_audio_noise_reduction, + "input_audio_transcription": input_audio_transcription, + "modalities": modalities, + "turn_detection": turn_detection, + }, + transcription_session_create_params.TranscriptionSessionCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=TranscriptionSession, + ) + + +class AsyncTranscriptionSessions(AsyncAPIResource): + @cached_property + def with_raw_response(self) -> AsyncTranscriptionSessionsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return AsyncTranscriptionSessionsWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncTranscriptionSessionsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return AsyncTranscriptionSessionsWithStreamingResponse(self) + + async def create( + self, + *, + include: List[str] | NotGiven = NOT_GIVEN, + input_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"] | NotGiven = NOT_GIVEN, + input_audio_noise_reduction: transcription_session_create_params.InputAudioNoiseReduction + | NotGiven = NOT_GIVEN, + input_audio_transcription: transcription_session_create_params.InputAudioTranscription | NotGiven = NOT_GIVEN, + modalities: List[Literal["text", "audio"]] | NotGiven = NOT_GIVEN, + turn_detection: transcription_session_create_params.TurnDetection | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> TranscriptionSession: + """ + Create an ephemeral API token for use in client-side applications with the + Realtime API specifically for realtime transcriptions. Can be configured with + the same session parameters as the `transcription_session.update` client event. + + It responds with a session object, plus a `client_secret` key which contains a + usable ephemeral API token that can be used to authenticate browser clients for + the Realtime API. + + Args: + include: + The set of items to include in the transcription. Current available items are: + + - `item.input_audio_transcription.logprobs` + + input_audio_format: The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For + `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, single channel + (mono), and little-endian byte order. + + input_audio_noise_reduction: Configuration for input audio noise reduction. This can be set to `null` to turn + off. Noise reduction filters audio added to the input audio buffer before it is + sent to VAD and the model. Filtering the audio can improve VAD and turn + detection accuracy (reducing false positives) and model performance by improving + perception of the input audio. + + input_audio_transcription: Configuration for input audio transcription. The client can optionally set the + language and prompt for transcription, these offer additional guidance to the + transcription service. + + modalities: The set of modalities the model can respond with. To disable audio, set this to + ["text"]. + + turn_detection: Configuration for turn detection, ether Server VAD or Semantic VAD. This can be + set to `null` to turn off, in which case the client must manually trigger model + response. Server VAD means that the model will detect the start and end of + speech based on audio volume and respond at the end of user speech. Semantic VAD + is more advanced and uses a turn detection model (in conjuction with VAD) to + semantically estimate whether the user has finished speaking, then dynamically + sets a timeout based on this probability. For example, if user audio trails off + with "uhhm", the model will score a low probability of turn end and wait longer + for the user to continue speaking. This can be useful for more natural + conversations, but may have a higher latency. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} + return await self._post( + "/realtime/transcription_sessions", + body=await async_maybe_transform( + { + "include": include, + "input_audio_format": input_audio_format, + "input_audio_noise_reduction": input_audio_noise_reduction, + "input_audio_transcription": input_audio_transcription, + "modalities": modalities, + "turn_detection": turn_detection, + }, + transcription_session_create_params.TranscriptionSessionCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=TranscriptionSession, + ) + + +class TranscriptionSessionsWithRawResponse: + def __init__(self, transcription_sessions: TranscriptionSessions) -> None: + self._transcription_sessions = transcription_sessions + + self.create = _legacy_response.to_raw_response_wrapper( + transcription_sessions.create, + ) + + +class AsyncTranscriptionSessionsWithRawResponse: + def __init__(self, transcription_sessions: AsyncTranscriptionSessions) -> None: + self._transcription_sessions = transcription_sessions + + self.create = _legacy_response.async_to_raw_response_wrapper( + transcription_sessions.create, + ) + + +class TranscriptionSessionsWithStreamingResponse: + def __init__(self, transcription_sessions: TranscriptionSessions) -> None: + self._transcription_sessions = transcription_sessions + + self.create = to_streamed_response_wrapper( + transcription_sessions.create, + ) + + +class AsyncTranscriptionSessionsWithStreamingResponse: + def __init__(self, transcription_sessions: AsyncTranscriptionSessions) -> None: + self._transcription_sessions = transcription_sessions + + self.create = async_to_streamed_response_wrapper( + transcription_sessions.create, + ) diff --git a/src/openai/types/audio/__init__.py b/src/openai/types/audio/__init__.py index 822e0f3a8d..396944ee47 100644 --- a/src/openai/types/audio/__init__.py +++ b/src/openai/types/audio/__init__.py @@ -8,9 +8,13 @@ from .transcription_word import TranscriptionWord as TranscriptionWord from .translation_verbose import TranslationVerbose as TranslationVerbose from .speech_create_params import SpeechCreateParams as SpeechCreateParams +from .transcription_include import TranscriptionInclude as TranscriptionInclude from .transcription_segment import TranscriptionSegment as TranscriptionSegment from .transcription_verbose import TranscriptionVerbose as TranscriptionVerbose from .translation_create_params import TranslationCreateParams as TranslationCreateParams +from .transcription_stream_event import TranscriptionStreamEvent as TranscriptionStreamEvent from .transcription_create_params import TranscriptionCreateParams as TranscriptionCreateParams from .translation_create_response import TranslationCreateResponse as TranslationCreateResponse from .transcription_create_response import TranscriptionCreateResponse as TranscriptionCreateResponse +from .transcription_text_done_event import TranscriptionTextDoneEvent as TranscriptionTextDoneEvent +from .transcription_text_delta_event import TranscriptionTextDeltaEvent as TranscriptionTextDeltaEvent diff --git a/src/openai/types/audio/speech_create_params.py b/src/openai/types/audio/speech_create_params.py index ed1a1ce748..958680710b 100644 --- a/src/openai/types/audio/speech_create_params.py +++ b/src/openai/types/audio/speech_create_params.py @@ -17,7 +17,7 @@ class SpeechCreateParams(TypedDict, total=False): model: Required[Union[str, SpeechModel]] """ One of the available [TTS models](https://platform.openai.com/docs/models#tts): - `tts-1` or `tts-1-hd` + `tts-1`, `tts-1-hd` or `gpt-4o-mini-tts`. """ voice: Required[Literal["alloy", "ash", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer"]] @@ -28,6 +28,12 @@ class SpeechCreateParams(TypedDict, total=False): [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech#voice-options). """ + instructions: str + """Control the voice of your generated audio with additional instructions. + + Does not work with `tts-1` or `tts-1-hd`. + """ + response_format: Literal["mp3", "opus", "aac", "flac", "wav", "pcm"] """The format to audio in. diff --git a/src/openai/types/audio/speech_model.py b/src/openai/types/audio/speech_model.py index bd685ab34d..f004f805da 100644 --- a/src/openai/types/audio/speech_model.py +++ b/src/openai/types/audio/speech_model.py @@ -4,4 +4,4 @@ __all__ = ["SpeechModel"] -SpeechModel: TypeAlias = Literal["tts-1", "tts-1-hd"] +SpeechModel: TypeAlias = Literal["tts-1", "tts-1-hd", "gpt-4o-mini-tts"] diff --git a/src/openai/types/audio/transcription.py b/src/openai/types/audio/transcription.py index edb5f227fc..1576385404 100644 --- a/src/openai/types/audio/transcription.py +++ b/src/openai/types/audio/transcription.py @@ -1,11 +1,30 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +from typing import List, Optional from ..._models import BaseModel -__all__ = ["Transcription"] +__all__ = ["Transcription", "Logprob"] + + +class Logprob(BaseModel): + token: Optional[str] = None + """The token in the transcription.""" + + bytes: Optional[List[float]] = None + """The bytes of the token.""" + + logprob: Optional[float] = None + """The log probability of the token.""" class Transcription(BaseModel): text: str """The transcribed text.""" + + logprobs: Optional[List[Logprob]] = None + """The log probabilities of the tokens in the transcription. + + Only returned with the models `gpt-4o-transcribe` and `gpt-4o-mini-transcribe` + if `logprobs` is added to the `include` array. + """ diff --git a/src/openai/types/audio/transcription_create_params.py b/src/openai/types/audio/transcription_create_params.py index f1779c35e6..0cda4c7907 100644 --- a/src/openai/types/audio/transcription_create_params.py +++ b/src/openai/types/audio/transcription_create_params.py @@ -2,17 +2,22 @@ from __future__ import annotations -from typing import List, Union +from typing import List, Union, Optional from typing_extensions import Literal, Required, TypedDict from ..._types import FileTypes from ..audio_model import AudioModel +from .transcription_include import TranscriptionInclude from ..audio_response_format import AudioResponseFormat -__all__ = ["TranscriptionCreateParams"] +__all__ = [ + "TranscriptionCreateParamsBase", + "TranscriptionCreateParamsNonStreaming", + "TranscriptionCreateParamsStreaming", +] -class TranscriptionCreateParams(TypedDict, total=False): +class TranscriptionCreateParamsBase(TypedDict, total=False): file: Required[FileTypes] """ The audio file object (not file name) to transcribe, in one of these formats: @@ -22,8 +27,17 @@ class TranscriptionCreateParams(TypedDict, total=False): model: Required[Union[str, AudioModel]] """ID of the model to use. - Only `whisper-1` (which is powered by our open source Whisper V2 model) is - currently available. + The options are `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, and `whisper-1` + (which is powered by our open source Whisper V2 model). + """ + + include: List[TranscriptionInclude] + """Additional information to include in the transcription response. + + `logprobs` will return the log probabilities of the tokens in the response to + understand the model's confidence in the transcription. `logprobs` only works + with response_format set to `json` and only with the models `gpt-4o-transcribe` + and `gpt-4o-mini-transcribe`. """ language: str @@ -45,7 +59,8 @@ class TranscriptionCreateParams(TypedDict, total=False): response_format: AudioResponseFormat """ The format of the output, in one of these options: `json`, `text`, `srt`, - `verbose_json`, or `vtt`. + `verbose_json`, or `vtt`. For `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`, + the only supported format is `json`. """ temperature: float @@ -65,3 +80,34 @@ class TranscriptionCreateParams(TypedDict, total=False): is no additional latency for segment timestamps, but generating word timestamps incurs additional latency. """ + + +class TranscriptionCreateParamsNonStreaming(TranscriptionCreateParamsBase, total=False): + stream: Optional[Literal[False]] + """ + If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section of the Speech-to-Text guide](https://platform.openai.com/docs/guides/speech-to-text?lang=curl#streaming-transcriptions) + for more information. + + Note: Streaming is not supported for the `whisper-1` model and will be ignored. + """ + + +class TranscriptionCreateParamsStreaming(TranscriptionCreateParamsBase): + stream: Required[Literal[True]] + """ + If set to true, the model response data will be streamed to the client as it is + generated using + [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). + See the + [Streaming section of the Speech-to-Text guide](https://platform.openai.com/docs/guides/speech-to-text?lang=curl#streaming-transcriptions) + for more information. + + Note: Streaming is not supported for the `whisper-1` model and will be ignored. + """ + + +TranscriptionCreateParams = Union[TranscriptionCreateParamsNonStreaming, TranscriptionCreateParamsStreaming] diff --git a/src/openai/types/audio/transcription_include.py b/src/openai/types/audio/transcription_include.py new file mode 100644 index 0000000000..0e464ac934 --- /dev/null +++ b/src/openai/types/audio/transcription_include.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal, TypeAlias + +__all__ = ["TranscriptionInclude"] + +TranscriptionInclude: TypeAlias = Literal["logprobs"] diff --git a/src/openai/types/audio/transcription_stream_event.py b/src/openai/types/audio/transcription_stream_event.py new file mode 100644 index 0000000000..757077a280 --- /dev/null +++ b/src/openai/types/audio/transcription_stream_event.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Annotated, TypeAlias + +from ..._utils import PropertyInfo +from .transcription_text_done_event import TranscriptionTextDoneEvent +from .transcription_text_delta_event import TranscriptionTextDeltaEvent + +__all__ = ["TranscriptionStreamEvent"] + +TranscriptionStreamEvent: TypeAlias = Annotated[ + Union[TranscriptionTextDeltaEvent, TranscriptionTextDoneEvent], PropertyInfo(discriminator="type") +] diff --git a/src/openai/types/audio/transcription_text_delta_event.py b/src/openai/types/audio/transcription_text_delta_event.py new file mode 100644 index 0000000000..f8d5355491 --- /dev/null +++ b/src/openai/types/audio/transcription_text_delta_event.py @@ -0,0 +1,35 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["TranscriptionTextDeltaEvent", "Logprob"] + + +class Logprob(BaseModel): + token: Optional[str] = None + """The token that was used to generate the log probability.""" + + bytes: Optional[List[object]] = None + """The bytes that were used to generate the log probability.""" + + logprob: Optional[float] = None + """The log probability of the token.""" + + +class TranscriptionTextDeltaEvent(BaseModel): + delta: str + """The text delta that was additionally transcribed.""" + + type: Literal["transcript.text.delta"] + """The type of the event. Always `transcript.text.delta`.""" + + logprobs: Optional[List[Logprob]] = None + """The log probabilities of the delta. + + Only included if you + [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) + with the `include[]` parameter set to `logprobs`. + """ diff --git a/src/openai/types/audio/transcription_text_done_event.py b/src/openai/types/audio/transcription_text_done_event.py new file mode 100644 index 0000000000..3f1a713a52 --- /dev/null +++ b/src/openai/types/audio/transcription_text_done_event.py @@ -0,0 +1,35 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["TranscriptionTextDoneEvent", "Logprob"] + + +class Logprob(BaseModel): + token: Optional[str] = None + """The token that was used to generate the log probability.""" + + bytes: Optional[List[object]] = None + """The bytes that were used to generate the log probability.""" + + logprob: Optional[float] = None + """The log probability of the token.""" + + +class TranscriptionTextDoneEvent(BaseModel): + text: str + """The text that was transcribed.""" + + type: Literal["transcript.text.done"] + """The type of the event. Always `transcript.text.done`.""" + + logprobs: Optional[List[Logprob]] = None + """The log probabilities of the individual tokens in the transcription. + + Only included if you + [create a transcription](https://platform.openai.com/docs/api-reference/audio/create-transcription) + with the `include[]` parameter set to `logprobs`. + """ diff --git a/src/openai/types/audio/translation_create_params.py b/src/openai/types/audio/translation_create_params.py index 62f85b8757..b23a185375 100644 --- a/src/openai/types/audio/translation_create_params.py +++ b/src/openai/types/audio/translation_create_params.py @@ -3,11 +3,10 @@ from __future__ import annotations from typing import Union -from typing_extensions import Required, TypedDict +from typing_extensions import Literal, Required, TypedDict from ..._types import FileTypes from ..audio_model import AudioModel -from ..audio_response_format import AudioResponseFormat __all__ = ["TranslationCreateParams"] @@ -34,7 +33,7 @@ class TranslationCreateParams(TypedDict, total=False): should be in English. """ - response_format: AudioResponseFormat + response_format: Literal["json", "text", "srt", "verbose_json", "vtt"] """ The format of the output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`. diff --git a/src/openai/types/audio_model.py b/src/openai/types/audio_model.py index 94ae84c015..4d14d60181 100644 --- a/src/openai/types/audio_model.py +++ b/src/openai/types/audio_model.py @@ -4,4 +4,4 @@ __all__ = ["AudioModel"] -AudioModel: TypeAlias = Literal["whisper-1"] +AudioModel: TypeAlias = Literal["whisper-1", "gpt-4o-transcribe", "gpt-4o-mini-transcribe"] diff --git a/src/openai/types/beta/realtime/__init__.py b/src/openai/types/beta/realtime/__init__.py index cd0616dcfa..0374b9b457 100644 --- a/src/openai/types/beta/realtime/__init__.py +++ b/src/openai/types/beta/realtime/__init__.py @@ -15,6 +15,7 @@ from .session_create_params import SessionCreateParams as SessionCreateParams from .session_created_event import SessionCreatedEvent as SessionCreatedEvent from .session_updated_event import SessionUpdatedEvent as SessionUpdatedEvent +from .transcription_session import TranscriptionSession as TranscriptionSession from .response_created_event import ResponseCreatedEvent as ResponseCreatedEvent from .conversation_item_param import ConversationItemParam as ConversationItemParam from .realtime_connect_params import RealtimeConnectParams as RealtimeConnectParams @@ -32,6 +33,7 @@ from .realtime_client_event_param import RealtimeClientEventParam as RealtimeClientEventParam from .response_cancel_event_param import ResponseCancelEventParam as ResponseCancelEventParam from .response_create_event_param import ResponseCreateEventParam as ResponseCreateEventParam +from .transcription_session_update import TranscriptionSessionUpdate as TranscriptionSessionUpdate from .conversation_item_create_event import ConversationItemCreateEvent as ConversationItemCreateEvent from .conversation_item_delete_event import ConversationItemDeleteEvent as ConversationItemDeleteEvent from .input_audio_buffer_clear_event import InputAudioBufferClearEvent as InputAudioBufferClearEvent @@ -41,6 +43,7 @@ from .input_audio_buffer_append_event import InputAudioBufferAppendEvent as InputAudioBufferAppendEvent from .input_audio_buffer_commit_event import InputAudioBufferCommitEvent as InputAudioBufferCommitEvent from .response_output_item_done_event import ResponseOutputItemDoneEvent as ResponseOutputItemDoneEvent +from .conversation_item_retrieve_event import ConversationItemRetrieveEvent as ConversationItemRetrieveEvent from .conversation_item_truncate_event import ConversationItemTruncateEvent as ConversationItemTruncateEvent from .conversation_item_with_reference import ConversationItemWithReference as ConversationItemWithReference from .input_audio_buffer_cleared_event import InputAudioBufferClearedEvent as InputAudioBufferClearedEvent @@ -49,6 +52,9 @@ from .conversation_item_truncated_event import ConversationItemTruncatedEvent as ConversationItemTruncatedEvent from .response_content_part_added_event import ResponseContentPartAddedEvent as ResponseContentPartAddedEvent from .input_audio_buffer_committed_event import InputAudioBufferCommittedEvent as InputAudioBufferCommittedEvent +from .transcription_session_update_param import TranscriptionSessionUpdateParam as TranscriptionSessionUpdateParam +from .transcription_session_create_params import TranscriptionSessionCreateParams as TranscriptionSessionCreateParams +from .transcription_session_updated_event import TranscriptionSessionUpdatedEvent as TranscriptionSessionUpdatedEvent from .conversation_item_create_event_param import ConversationItemCreateEventParam as ConversationItemCreateEventParam from .conversation_item_delete_event_param import ConversationItemDeleteEventParam as ConversationItemDeleteEventParam from .input_audio_buffer_clear_event_param import InputAudioBufferClearEventParam as InputAudioBufferClearEventParam @@ -58,6 +64,9 @@ from .response_audio_transcript_delta_event import ( ResponseAudioTranscriptDeltaEvent as ResponseAudioTranscriptDeltaEvent, ) +from .conversation_item_retrieve_event_param import ( + ConversationItemRetrieveEventParam as ConversationItemRetrieveEventParam, +) from .conversation_item_truncate_event_param import ( ConversationItemTruncateEventParam as ConversationItemTruncateEventParam, ) @@ -76,6 +85,9 @@ from .response_function_call_arguments_delta_event import ( ResponseFunctionCallArgumentsDeltaEvent as ResponseFunctionCallArgumentsDeltaEvent, ) +from .conversation_item_input_audio_transcription_delta_event import ( + ConversationItemInputAudioTranscriptionDeltaEvent as ConversationItemInputAudioTranscriptionDeltaEvent, +) from .conversation_item_input_audio_transcription_failed_event import ( ConversationItemInputAudioTranscriptionFailedEvent as ConversationItemInputAudioTranscriptionFailedEvent, ) diff --git a/src/openai/types/beta/realtime/conversation_item_input_audio_transcription_completed_event.py b/src/openai/types/beta/realtime/conversation_item_input_audio_transcription_completed_event.py index ded79cc0f7..469811693c 100644 --- a/src/openai/types/beta/realtime/conversation_item_input_audio_transcription_completed_event.py +++ b/src/openai/types/beta/realtime/conversation_item_input_audio_transcription_completed_event.py @@ -1,10 +1,22 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +from typing import List, Optional from typing_extensions import Literal from ...._models import BaseModel -__all__ = ["ConversationItemInputAudioTranscriptionCompletedEvent"] +__all__ = ["ConversationItemInputAudioTranscriptionCompletedEvent", "Logprob"] + + +class Logprob(BaseModel): + token: str + """The token that was used to generate the log probability.""" + + bytes: List[int] + """The bytes that were used to generate the log probability.""" + + logprob: float + """The log probability of the token.""" class ConversationItemInputAudioTranscriptionCompletedEvent(BaseModel): @@ -24,3 +36,6 @@ class ConversationItemInputAudioTranscriptionCompletedEvent(BaseModel): """ The event type, must be `conversation.item.input_audio_transcription.completed`. """ + + logprobs: Optional[List[Logprob]] = None + """The log probabilities of the transcription.""" diff --git a/src/openai/types/beta/realtime/conversation_item_input_audio_transcription_delta_event.py b/src/openai/types/beta/realtime/conversation_item_input_audio_transcription_delta_event.py new file mode 100644 index 0000000000..924d06d98a --- /dev/null +++ b/src/openai/types/beta/realtime/conversation_item_input_audio_transcription_delta_event.py @@ -0,0 +1,39 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["ConversationItemInputAudioTranscriptionDeltaEvent", "Logprob"] + + +class Logprob(BaseModel): + token: str + """The token that was used to generate the log probability.""" + + bytes: List[int] + """The bytes that were used to generate the log probability.""" + + logprob: float + """The log probability of the token.""" + + +class ConversationItemInputAudioTranscriptionDeltaEvent(BaseModel): + event_id: str + """The unique ID of the server event.""" + + item_id: str + """The ID of the item.""" + + type: Literal["conversation.item.input_audio_transcription.delta"] + """The event type, must be `conversation.item.input_audio_transcription.delta`.""" + + content_index: Optional[int] = None + """The index of the content part in the item's content array.""" + + delta: Optional[str] = None + """The text delta.""" + + logprobs: Optional[List[Logprob]] = None + """The log probabilities of the transcription.""" diff --git a/src/openai/types/beta/realtime/conversation_item_retrieve_event.py b/src/openai/types/beta/realtime/conversation_item_retrieve_event.py new file mode 100644 index 0000000000..822386055c --- /dev/null +++ b/src/openai/types/beta/realtime/conversation_item_retrieve_event.py @@ -0,0 +1,19 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["ConversationItemRetrieveEvent"] + + +class ConversationItemRetrieveEvent(BaseModel): + item_id: str + """The ID of the item to retrieve.""" + + type: Literal["conversation.item.retrieve"] + """The event type, must be `conversation.item.retrieve`.""" + + event_id: Optional[str] = None + """Optional client-generated ID used to identify this event.""" diff --git a/src/openai/types/beta/realtime/conversation_item_retrieve_event_param.py b/src/openai/types/beta/realtime/conversation_item_retrieve_event_param.py new file mode 100644 index 0000000000..71b3ffa499 --- /dev/null +++ b/src/openai/types/beta/realtime/conversation_item_retrieve_event_param.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["ConversationItemRetrieveEventParam"] + + +class ConversationItemRetrieveEventParam(TypedDict, total=False): + item_id: Required[str] + """The ID of the item to retrieve.""" + + type: Required[Literal["conversation.item.retrieve"]] + """The event type, must be `conversation.item.retrieve`.""" + + event_id: str + """Optional client-generated ID used to identify this event.""" diff --git a/src/openai/types/beta/realtime/realtime_client_event.py b/src/openai/types/beta/realtime/realtime_client_event.py index 0769184cd0..f962a505cd 100644 --- a/src/openai/types/beta/realtime/realtime_client_event.py +++ b/src/openai/types/beta/realtime/realtime_client_event.py @@ -7,26 +7,30 @@ from .session_update_event import SessionUpdateEvent from .response_cancel_event import ResponseCancelEvent from .response_create_event import ResponseCreateEvent +from .transcription_session_update import TranscriptionSessionUpdate from .conversation_item_create_event import ConversationItemCreateEvent from .conversation_item_delete_event import ConversationItemDeleteEvent from .input_audio_buffer_clear_event import InputAudioBufferClearEvent from .input_audio_buffer_append_event import InputAudioBufferAppendEvent from .input_audio_buffer_commit_event import InputAudioBufferCommitEvent +from .conversation_item_retrieve_event import ConversationItemRetrieveEvent from .conversation_item_truncate_event import ConversationItemTruncateEvent __all__ = ["RealtimeClientEvent"] RealtimeClientEvent: TypeAlias = Annotated[ Union[ - SessionUpdateEvent, - InputAudioBufferAppendEvent, - InputAudioBufferCommitEvent, - InputAudioBufferClearEvent, ConversationItemCreateEvent, - ConversationItemTruncateEvent, ConversationItemDeleteEvent, - ResponseCreateEvent, + ConversationItemRetrieveEvent, + ConversationItemTruncateEvent, + InputAudioBufferAppendEvent, + InputAudioBufferClearEvent, + InputAudioBufferCommitEvent, ResponseCancelEvent, + ResponseCreateEvent, + SessionUpdateEvent, + TranscriptionSessionUpdate, ], PropertyInfo(discriminator="type"), ] diff --git a/src/openai/types/beta/realtime/realtime_client_event_param.py b/src/openai/types/beta/realtime/realtime_client_event_param.py index 4020892c33..6fdba4b87c 100644 --- a/src/openai/types/beta/realtime/realtime_client_event_param.py +++ b/src/openai/types/beta/realtime/realtime_client_event_param.py @@ -8,23 +8,27 @@ from .session_update_event_param import SessionUpdateEventParam from .response_cancel_event_param import ResponseCancelEventParam from .response_create_event_param import ResponseCreateEventParam +from .transcription_session_update_param import TranscriptionSessionUpdateParam from .conversation_item_create_event_param import ConversationItemCreateEventParam from .conversation_item_delete_event_param import ConversationItemDeleteEventParam from .input_audio_buffer_clear_event_param import InputAudioBufferClearEventParam from .input_audio_buffer_append_event_param import InputAudioBufferAppendEventParam from .input_audio_buffer_commit_event_param import InputAudioBufferCommitEventParam +from .conversation_item_retrieve_event_param import ConversationItemRetrieveEventParam from .conversation_item_truncate_event_param import ConversationItemTruncateEventParam __all__ = ["RealtimeClientEventParam"] RealtimeClientEventParam: TypeAlias = Union[ - SessionUpdateEventParam, - InputAudioBufferAppendEventParam, - InputAudioBufferCommitEventParam, - InputAudioBufferClearEventParam, ConversationItemCreateEventParam, - ConversationItemTruncateEventParam, ConversationItemDeleteEventParam, - ResponseCreateEventParam, + ConversationItemRetrieveEventParam, + ConversationItemTruncateEventParam, + InputAudioBufferAppendEventParam, + InputAudioBufferClearEventParam, + InputAudioBufferCommitEventParam, ResponseCancelEventParam, + ResponseCreateEventParam, + SessionUpdateEventParam, + TranscriptionSessionUpdateParam, ] diff --git a/src/openai/types/beta/realtime/realtime_server_event.py b/src/openai/types/beta/realtime/realtime_server_event.py index 5f8ed55b13..ba1d324445 100644 --- a/src/openai/types/beta/realtime/realtime_server_event.py +++ b/src/openai/types/beta/realtime/realtime_server_event.py @@ -1,10 +1,12 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing import Union -from typing_extensions import Annotated, TypeAlias +from typing_extensions import Literal, Annotated, TypeAlias from ...._utils import PropertyInfo +from ...._models import BaseModel from .error_event import ErrorEvent +from .conversation_item import ConversationItem from .response_done_event import ResponseDoneEvent from .session_created_event import SessionCreatedEvent from .session_updated_event import SessionUpdatedEvent @@ -24,49 +26,66 @@ from .conversation_item_truncated_event import ConversationItemTruncatedEvent from .response_content_part_added_event import ResponseContentPartAddedEvent from .input_audio_buffer_committed_event import InputAudioBufferCommittedEvent +from .transcription_session_updated_event import TranscriptionSessionUpdatedEvent from .response_audio_transcript_done_event import ResponseAudioTranscriptDoneEvent from .response_audio_transcript_delta_event import ResponseAudioTranscriptDeltaEvent from .input_audio_buffer_speech_started_event import InputAudioBufferSpeechStartedEvent from .input_audio_buffer_speech_stopped_event import InputAudioBufferSpeechStoppedEvent from .response_function_call_arguments_done_event import ResponseFunctionCallArgumentsDoneEvent from .response_function_call_arguments_delta_event import ResponseFunctionCallArgumentsDeltaEvent +from .conversation_item_input_audio_transcription_delta_event import ConversationItemInputAudioTranscriptionDeltaEvent from .conversation_item_input_audio_transcription_failed_event import ConversationItemInputAudioTranscriptionFailedEvent from .conversation_item_input_audio_transcription_completed_event import ( ConversationItemInputAudioTranscriptionCompletedEvent, ) -__all__ = ["RealtimeServerEvent"] +__all__ = ["RealtimeServerEvent", "ConversationItemRetrieved"] + + +class ConversationItemRetrieved(BaseModel): + event_id: str + """The unique ID of the server event.""" + + item: ConversationItem + """The item to add to the conversation.""" + + type: Literal["conversation.item.retrieved"] + """The event type, must be `conversation.item.retrieved`.""" + RealtimeServerEvent: TypeAlias = Annotated[ Union[ - ErrorEvent, - SessionCreatedEvent, - SessionUpdatedEvent, ConversationCreatedEvent, - InputAudioBufferCommittedEvent, - InputAudioBufferClearedEvent, - InputAudioBufferSpeechStartedEvent, - InputAudioBufferSpeechStoppedEvent, ConversationItemCreatedEvent, + ConversationItemDeletedEvent, ConversationItemInputAudioTranscriptionCompletedEvent, + ConversationItemInputAudioTranscriptionDeltaEvent, ConversationItemInputAudioTranscriptionFailedEvent, + ConversationItemRetrieved, ConversationItemTruncatedEvent, - ConversationItemDeletedEvent, + ErrorEvent, + InputAudioBufferClearedEvent, + InputAudioBufferCommittedEvent, + InputAudioBufferSpeechStartedEvent, + InputAudioBufferSpeechStoppedEvent, + RateLimitsUpdatedEvent, + ResponseAudioDeltaEvent, + ResponseAudioDoneEvent, + ResponseAudioTranscriptDeltaEvent, + ResponseAudioTranscriptDoneEvent, + ResponseContentPartAddedEvent, + ResponseContentPartDoneEvent, ResponseCreatedEvent, ResponseDoneEvent, + ResponseFunctionCallArgumentsDeltaEvent, + ResponseFunctionCallArgumentsDoneEvent, ResponseOutputItemAddedEvent, ResponseOutputItemDoneEvent, - ResponseContentPartAddedEvent, - ResponseContentPartDoneEvent, ResponseTextDeltaEvent, ResponseTextDoneEvent, - ResponseAudioTranscriptDeltaEvent, - ResponseAudioTranscriptDoneEvent, - ResponseAudioDeltaEvent, - ResponseAudioDoneEvent, - ResponseFunctionCallArgumentsDeltaEvent, - ResponseFunctionCallArgumentsDoneEvent, - RateLimitsUpdatedEvent, + SessionCreatedEvent, + SessionUpdatedEvent, + TranscriptionSessionUpdatedEvent, ], PropertyInfo(discriminator="type"), ] diff --git a/src/openai/types/beta/realtime/session.py b/src/openai/types/beta/realtime/session.py index aee20fa906..3ed53ff5f8 100644 --- a/src/openai/types/beta/realtime/session.py +++ b/src/openai/types/beta/realtime/session.py @@ -5,14 +5,40 @@ from ...._models import BaseModel -__all__ = ["Session", "InputAudioTranscription", "Tool", "TurnDetection"] +__all__ = ["Session", "InputAudioNoiseReduction", "InputAudioTranscription", "Tool", "TurnDetection"] + + +class InputAudioNoiseReduction(BaseModel): + type: Optional[Literal["near_field", "far_field"]] = None + """Type of noise reduction. + + `near_field` is for close-talking microphones such as headphones, `far_field` is + for far-field microphones such as laptop or conference room microphones. + """ class InputAudioTranscription(BaseModel): + language: Optional[str] = None + """The language of the input audio. + + Supplying the input language in + [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) + format will improve accuracy and latency. + """ + model: Optional[str] = None """ - The model to use for transcription, `whisper-1` is the only currently supported - model. + The model to use for transcription, current options are `gpt-4o-transcribe`, + `gpt-4o-mini-transcribe`, and `whisper-1`. + """ + + prompt: Optional[str] = None + """ + An optional text to guide the model's style or continue a previous audio + segment. For `whisper-1`, the + [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting). + For `gpt-4o-transcribe` models, the prompt is a free text string, for example + "expect words related to technology". """ @@ -35,46 +61,56 @@ class Tool(BaseModel): class TurnDetection(BaseModel): create_response: Optional[bool] = None - """Whether or not to automatically generate a response when a VAD stop event + """ + Whether or not to automatically generate a response when a VAD stop event occurs. + """ + + eagerness: Optional[Literal["low", "medium", "high", "auto"]] = None + """Used only for `semantic_vad` mode. - `true` by default. + The eagerness of the model to respond. `low` will wait longer for the user to + continue speaking, `high` will respond more quickly. `auto` is the default and + is equivalent to `medium`. """ interrupt_response: Optional[bool] = None """ Whether or not to automatically interrupt any ongoing response with output to the default conversation (i.e. `conversation` of `auto`) when a VAD start event - occurs. `true` by default. + occurs. """ prefix_padding_ms: Optional[int] = None - """Amount of audio to include before the VAD detected speech (in milliseconds). + """Used only for `server_vad` mode. + Amount of audio to include before the VAD detected speech (in milliseconds). Defaults to 300ms. """ silence_duration_ms: Optional[int] = None - """Duration of silence to detect speech stop (in milliseconds). + """Used only for `server_vad` mode. - Defaults to 500ms. With shorter values the model will respond more quickly, but - may jump in on short pauses from the user. + Duration of silence to detect speech stop (in milliseconds). Defaults to 500ms. + With shorter values the model will respond more quickly, but may jump in on + short pauses from the user. """ threshold: Optional[float] = None - """Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. + """Used only for `server_vad` mode. - A higher threshold will require louder audio to activate the model, and thus - might perform better in noisy environments. + Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A higher + threshold will require louder audio to activate the model, and thus might + perform better in noisy environments. """ - type: Optional[Literal["server_vad"]] = None - """Type of turn detection, only `server_vad` is currently supported.""" + type: Optional[Literal["server_vad", "semantic_vad"]] = None + """Type of turn detection.""" class Session(BaseModel): id: Optional[str] = None - """Unique identifier for the session object.""" + """Unique identifier for the session that looks like `sess_1234567890abcdef`.""" input_audio_format: Optional[Literal["pcm16", "g711_ulaw", "g711_alaw"]] = None """The format of input audio. @@ -84,13 +120,25 @@ class Session(BaseModel): byte order. """ + input_audio_noise_reduction: Optional[InputAudioNoiseReduction] = None + """Configuration for input audio noise reduction. + + This can be set to `null` to turn off. Noise reduction filters audio added to + the input audio buffer before it is sent to VAD and the model. Filtering the + audio can improve VAD and turn detection accuracy (reducing false positives) and + model performance by improving perception of the input audio. + """ + input_audio_transcription: Optional[InputAudioTranscription] = None """ Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs - asynchronously through Whisper and should be treated as rough guidance rather - than the representation understood by the model. + asynchronously through + [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription) + and should be treated as guidance of input audio content rather than precisely + what the model heard. The client can optionally set the language and prompt for + transcription, these offer additional guidance to the transcription service. """ instructions: Optional[str] = None @@ -122,16 +170,14 @@ class Session(BaseModel): To disable audio, set this to ["text"]. """ - model: Union[ - str, + model: Optional[ Literal[ "gpt-4o-realtime-preview", "gpt-4o-realtime-preview-2024-10-01", "gpt-4o-realtime-preview-2024-12-17", "gpt-4o-mini-realtime-preview", "gpt-4o-mini-realtime-preview-2024-12-17", - ], - None, + ] ] = None """The Realtime model used for this session.""" @@ -143,7 +189,11 @@ class Session(BaseModel): """ temperature: Optional[float] = None - """Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.""" + """Sampling temperature for the model, limited to [0.6, 1.2]. + + For audio models a temperature of 0.8 is highly recommended for best + performance. + """ tool_choice: Optional[str] = None """How the model chooses tools. @@ -155,11 +205,17 @@ class Session(BaseModel): """Tools (functions) available to the model.""" turn_detection: Optional[TurnDetection] = None - """Configuration for turn detection. - - Can be set to `null` to turn off. Server VAD means that the model will detect - the start and end of speech based on audio volume and respond at the end of user - speech. + """Configuration for turn detection, ether Server VAD or Semantic VAD. + + This can be set to `null` to turn off, in which case the client must manually + trigger model response. Server VAD means that the model will detect the start + and end of speech based on audio volume and respond at the end of user speech. + Semantic VAD is more advanced and uses a turn detection model (in conjuction + with VAD) to semantically estimate whether the user has finished speaking, then + dynamically sets a timeout based on this probability. For example, if user audio + trails off with "uhhm", the model will score a low probability of turn end and + wait longer for the user to continue speaking. This can be useful for more + natural conversations, but may have a higher latency. """ voice: Optional[Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"]] = None diff --git a/src/openai/types/beta/realtime/session_create_params.py b/src/openai/types/beta/realtime/session_create_params.py index bbc86d7c7d..fe4a1c8636 100644 --- a/src/openai/types/beta/realtime/session_create_params.py +++ b/src/openai/types/beta/realtime/session_create_params.py @@ -5,7 +5,7 @@ from typing import List, Union, Iterable from typing_extensions import Literal, TypedDict -__all__ = ["SessionCreateParams", "InputAudioTranscription", "Tool", "TurnDetection"] +__all__ = ["SessionCreateParams", "InputAudioNoiseReduction", "InputAudioTranscription", "Tool", "TurnDetection"] class SessionCreateParams(TypedDict, total=False): @@ -17,16 +17,25 @@ class SessionCreateParams(TypedDict, total=False): byte order. """ + input_audio_noise_reduction: InputAudioNoiseReduction + """Configuration for input audio noise reduction. + + This can be set to `null` to turn off. Noise reduction filters audio added to + the input audio buffer before it is sent to VAD and the model. Filtering the + audio can improve VAD and turn detection accuracy (reducing false positives) and + model performance by improving perception of the input audio. + """ + input_audio_transcription: InputAudioTranscription """ Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs asynchronously through - [OpenAI Whisper transcription](https://platform.openai.com/docs/api-reference/audio/createTranscription) - and should be treated as rough guidance rather than the representation - understood by the model. The client can optionally set the language and prompt - for transcription, these fields will be passed to the Whisper API. + [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription) + and should be treated as guidance of input audio content rather than precisely + what the model heard. The client can optionally set the language and prompt for + transcription, these offer additional guidance to the transcription service. """ instructions: str @@ -75,7 +84,11 @@ class SessionCreateParams(TypedDict, total=False): """ temperature: float - """Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.""" + """Sampling temperature for the model, limited to [0.6, 1.2]. + + For audio models a temperature of 0.8 is highly recommended for best + performance. + """ tool_choice: str """How the model chooses tools. @@ -87,11 +100,17 @@ class SessionCreateParams(TypedDict, total=False): """Tools (functions) available to the model.""" turn_detection: TurnDetection - """Configuration for turn detection. + """Configuration for turn detection, ether Server VAD or Semantic VAD. - Can be set to `null` to turn off. Server VAD means that the model will detect - the start and end of speech based on audio volume and respond at the end of user - speech. + This can be set to `null` to turn off, in which case the client must manually + trigger model response. Server VAD means that the model will detect the start + and end of speech based on audio volume and respond at the end of user speech. + Semantic VAD is more advanced and uses a turn detection model (in conjuction + with VAD) to semantically estimate whether the user has finished speaking, then + dynamically sets a timeout based on this probability. For example, if user audio + trails off with "uhhm", the model will score a low probability of turn end and + wait longer for the user to continue speaking. This can be useful for more + natural conversations, but may have a higher latency. """ voice: Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"] @@ -103,6 +122,15 @@ class SessionCreateParams(TypedDict, total=False): """ +class InputAudioNoiseReduction(TypedDict, total=False): + type: Literal["near_field", "far_field"] + """Type of noise reduction. + + `near_field` is for close-talking microphones such as headphones, `far_field` is + for far-field microphones such as laptop or conference room microphones. + """ + + class InputAudioTranscription(TypedDict, total=False): language: str """The language of the input audio. @@ -114,16 +142,17 @@ class InputAudioTranscription(TypedDict, total=False): model: str """ - The model to use for transcription, `whisper-1` is the only currently supported - model. + The model to use for transcription, current options are `gpt-4o-transcribe`, + `gpt-4o-mini-transcribe`, and `whisper-1`. """ prompt: str - """An optional text to guide the model's style or continue a previous audio - segment. - - The [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) - should match the audio language. + """ + An optional text to guide the model's style or continue a previous audio + segment. For `whisper-1`, the + [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting). + For `gpt-4o-transcribe` models, the prompt is a free text string, for example + "expect words related to technology". """ @@ -146,38 +175,48 @@ class Tool(TypedDict, total=False): class TurnDetection(TypedDict, total=False): create_response: bool - """Whether or not to automatically generate a response when a VAD stop event + """ + Whether or not to automatically generate a response when a VAD stop event occurs. + """ + + eagerness: Literal["low", "medium", "high", "auto"] + """Used only for `semantic_vad` mode. - `true` by default. + The eagerness of the model to respond. `low` will wait longer for the user to + continue speaking, `high` will respond more quickly. `auto` is the default and + is equivalent to `medium`. """ interrupt_response: bool """ Whether or not to automatically interrupt any ongoing response with output to the default conversation (i.e. `conversation` of `auto`) when a VAD start event - occurs. `true` by default. + occurs. """ prefix_padding_ms: int - """Amount of audio to include before the VAD detected speech (in milliseconds). + """Used only for `server_vad` mode. + Amount of audio to include before the VAD detected speech (in milliseconds). Defaults to 300ms. """ silence_duration_ms: int - """Duration of silence to detect speech stop (in milliseconds). + """Used only for `server_vad` mode. - Defaults to 500ms. With shorter values the model will respond more quickly, but - may jump in on short pauses from the user. + Duration of silence to detect speech stop (in milliseconds). Defaults to 500ms. + With shorter values the model will respond more quickly, but may jump in on + short pauses from the user. """ threshold: float - """Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. + """Used only for `server_vad` mode. - A higher threshold will require louder audio to activate the model, and thus - might perform better in noisy environments. + Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A higher + threshold will require louder audio to activate the model, and thus might + perform better in noisy environments. """ - type: str - """Type of turn detection, only `server_vad` is currently supported.""" + type: Literal["server_vad", "semantic_vad"] + """Type of turn detection.""" diff --git a/src/openai/types/beta/realtime/session_update_event.py b/src/openai/types/beta/realtime/session_update_event.py index 999cd8d660..00180f593d 100644 --- a/src/openai/types/beta/realtime/session_update_event.py +++ b/src/openai/types/beta/realtime/session_update_event.py @@ -5,7 +5,23 @@ from ...._models import BaseModel -__all__ = ["SessionUpdateEvent", "Session", "SessionInputAudioTranscription", "SessionTool", "SessionTurnDetection"] +__all__ = [ + "SessionUpdateEvent", + "Session", + "SessionInputAudioNoiseReduction", + "SessionInputAudioTranscription", + "SessionTool", + "SessionTurnDetection", +] + + +class SessionInputAudioNoiseReduction(BaseModel): + type: Optional[Literal["near_field", "far_field"]] = None + """Type of noise reduction. + + `near_field` is for close-talking microphones such as headphones, `far_field` is + for far-field microphones such as laptop or conference room microphones. + """ class SessionInputAudioTranscription(BaseModel): @@ -19,16 +35,17 @@ class SessionInputAudioTranscription(BaseModel): model: Optional[str] = None """ - The model to use for transcription, `whisper-1` is the only currently supported - model. + The model to use for transcription, current options are `gpt-4o-transcribe`, + `gpt-4o-mini-transcribe`, and `whisper-1`. """ prompt: Optional[str] = None - """An optional text to guide the model's style or continue a previous audio - segment. - - The [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) - should match the audio language. + """ + An optional text to guide the model's style or continue a previous audio + segment. For `whisper-1`, the + [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting). + For `gpt-4o-transcribe` models, the prompt is a free text string, for example + "expect words related to technology". """ @@ -51,41 +68,51 @@ class SessionTool(BaseModel): class SessionTurnDetection(BaseModel): create_response: Optional[bool] = None - """Whether or not to automatically generate a response when a VAD stop event + """ + Whether or not to automatically generate a response when a VAD stop event occurs. + """ - `true` by default. + eagerness: Optional[Literal["low", "medium", "high", "auto"]] = None + """Used only for `semantic_vad` mode. + + The eagerness of the model to respond. `low` will wait longer for the user to + continue speaking, `high` will respond more quickly. `auto` is the default and + is equivalent to `medium`. """ interrupt_response: Optional[bool] = None """ Whether or not to automatically interrupt any ongoing response with output to the default conversation (i.e. `conversation` of `auto`) when a VAD start event - occurs. `true` by default. + occurs. """ prefix_padding_ms: Optional[int] = None - """Amount of audio to include before the VAD detected speech (in milliseconds). + """Used only for `server_vad` mode. + Amount of audio to include before the VAD detected speech (in milliseconds). Defaults to 300ms. """ silence_duration_ms: Optional[int] = None - """Duration of silence to detect speech stop (in milliseconds). + """Used only for `server_vad` mode. - Defaults to 500ms. With shorter values the model will respond more quickly, but - may jump in on short pauses from the user. + Duration of silence to detect speech stop (in milliseconds). Defaults to 500ms. + With shorter values the model will respond more quickly, but may jump in on + short pauses from the user. """ threshold: Optional[float] = None - """Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. + """Used only for `server_vad` mode. - A higher threshold will require louder audio to activate the model, and thus - might perform better in noisy environments. + Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A higher + threshold will require louder audio to activate the model, and thus might + perform better in noisy environments. """ - type: Optional[str] = None - """Type of turn detection, only `server_vad` is currently supported.""" + type: Optional[Literal["server_vad", "semantic_vad"]] = None + """Type of turn detection.""" class Session(BaseModel): @@ -97,16 +124,25 @@ class Session(BaseModel): byte order. """ + input_audio_noise_reduction: Optional[SessionInputAudioNoiseReduction] = None + """Configuration for input audio noise reduction. + + This can be set to `null` to turn off. Noise reduction filters audio added to + the input audio buffer before it is sent to VAD and the model. Filtering the + audio can improve VAD and turn detection accuracy (reducing false positives) and + model performance by improving perception of the input audio. + """ + input_audio_transcription: Optional[SessionInputAudioTranscription] = None """ Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs asynchronously through - [OpenAI Whisper transcription](https://platform.openai.com/docs/api-reference/audio/createTranscription) - and should be treated as rough guidance rather than the representation - understood by the model. The client can optionally set the language and prompt - for transcription, these fields will be passed to the Whisper API. + [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription) + and should be treated as guidance of input audio content rather than precisely + what the model heard. The client can optionally set the language and prompt for + transcription, these offer additional guidance to the transcription service. """ instructions: Optional[str] = None @@ -157,7 +193,11 @@ class Session(BaseModel): """ temperature: Optional[float] = None - """Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.""" + """Sampling temperature for the model, limited to [0.6, 1.2]. + + For audio models a temperature of 0.8 is highly recommended for best + performance. + """ tool_choice: Optional[str] = None """How the model chooses tools. @@ -169,11 +209,17 @@ class Session(BaseModel): """Tools (functions) available to the model.""" turn_detection: Optional[SessionTurnDetection] = None - """Configuration for turn detection. - - Can be set to `null` to turn off. Server VAD means that the model will detect - the start and end of speech based on audio volume and respond at the end of user - speech. + """Configuration for turn detection, ether Server VAD or Semantic VAD. + + This can be set to `null` to turn off, in which case the client must manually + trigger model response. Server VAD means that the model will detect the start + and end of speech based on audio volume and respond at the end of user speech. + Semantic VAD is more advanced and uses a turn detection model (in conjuction + with VAD) to semantically estimate whether the user has finished speaking, then + dynamically sets a timeout based on this probability. For example, if user audio + trails off with "uhhm", the model will score a low probability of turn end and + wait longer for the user to continue speaking. This can be useful for more + natural conversations, but may have a higher latency. """ voice: Optional[Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"]] = None diff --git a/src/openai/types/beta/realtime/session_update_event_param.py b/src/openai/types/beta/realtime/session_update_event_param.py index 07fdba9d85..b8bce8fbd0 100644 --- a/src/openai/types/beta/realtime/session_update_event_param.py +++ b/src/openai/types/beta/realtime/session_update_event_param.py @@ -8,12 +8,22 @@ __all__ = [ "SessionUpdateEventParam", "Session", + "SessionInputAudioNoiseReduction", "SessionInputAudioTranscription", "SessionTool", "SessionTurnDetection", ] +class SessionInputAudioNoiseReduction(TypedDict, total=False): + type: Literal["near_field", "far_field"] + """Type of noise reduction. + + `near_field` is for close-talking microphones such as headphones, `far_field` is + for far-field microphones such as laptop or conference room microphones. + """ + + class SessionInputAudioTranscription(TypedDict, total=False): language: str """The language of the input audio. @@ -25,16 +35,17 @@ class SessionInputAudioTranscription(TypedDict, total=False): model: str """ - The model to use for transcription, `whisper-1` is the only currently supported - model. + The model to use for transcription, current options are `gpt-4o-transcribe`, + `gpt-4o-mini-transcribe`, and `whisper-1`. """ prompt: str - """An optional text to guide the model's style or continue a previous audio - segment. - - The [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) - should match the audio language. + """ + An optional text to guide the model's style or continue a previous audio + segment. For `whisper-1`, the + [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting). + For `gpt-4o-transcribe` models, the prompt is a free text string, for example + "expect words related to technology". """ @@ -57,41 +68,51 @@ class SessionTool(TypedDict, total=False): class SessionTurnDetection(TypedDict, total=False): create_response: bool - """Whether or not to automatically generate a response when a VAD stop event + """ + Whether or not to automatically generate a response when a VAD stop event occurs. + """ - `true` by default. + eagerness: Literal["low", "medium", "high", "auto"] + """Used only for `semantic_vad` mode. + + The eagerness of the model to respond. `low` will wait longer for the user to + continue speaking, `high` will respond more quickly. `auto` is the default and + is equivalent to `medium`. """ interrupt_response: bool """ Whether or not to automatically interrupt any ongoing response with output to the default conversation (i.e. `conversation` of `auto`) when a VAD start event - occurs. `true` by default. + occurs. """ prefix_padding_ms: int - """Amount of audio to include before the VAD detected speech (in milliseconds). + """Used only for `server_vad` mode. + Amount of audio to include before the VAD detected speech (in milliseconds). Defaults to 300ms. """ silence_duration_ms: int - """Duration of silence to detect speech stop (in milliseconds). + """Used only for `server_vad` mode. - Defaults to 500ms. With shorter values the model will respond more quickly, but - may jump in on short pauses from the user. + Duration of silence to detect speech stop (in milliseconds). Defaults to 500ms. + With shorter values the model will respond more quickly, but may jump in on + short pauses from the user. """ threshold: float - """Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. + """Used only for `server_vad` mode. - A higher threshold will require louder audio to activate the model, and thus - might perform better in noisy environments. + Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A higher + threshold will require louder audio to activate the model, and thus might + perform better in noisy environments. """ - type: str - """Type of turn detection, only `server_vad` is currently supported.""" + type: Literal["server_vad", "semantic_vad"] + """Type of turn detection.""" class Session(TypedDict, total=False): @@ -103,16 +124,25 @@ class Session(TypedDict, total=False): byte order. """ + input_audio_noise_reduction: SessionInputAudioNoiseReduction + """Configuration for input audio noise reduction. + + This can be set to `null` to turn off. Noise reduction filters audio added to + the input audio buffer before it is sent to VAD and the model. Filtering the + audio can improve VAD and turn detection accuracy (reducing false positives) and + model performance by improving perception of the input audio. + """ + input_audio_transcription: SessionInputAudioTranscription """ Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs asynchronously through - [OpenAI Whisper transcription](https://platform.openai.com/docs/api-reference/audio/createTranscription) - and should be treated as rough guidance rather than the representation - understood by the model. The client can optionally set the language and prompt - for transcription, these fields will be passed to the Whisper API. + [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription) + and should be treated as guidance of input audio content rather than precisely + what the model heard. The client can optionally set the language and prompt for + transcription, these offer additional guidance to the transcription service. """ instructions: str @@ -161,7 +191,11 @@ class Session(TypedDict, total=False): """ temperature: float - """Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.""" + """Sampling temperature for the model, limited to [0.6, 1.2]. + + For audio models a temperature of 0.8 is highly recommended for best + performance. + """ tool_choice: str """How the model chooses tools. @@ -173,11 +207,17 @@ class Session(TypedDict, total=False): """Tools (functions) available to the model.""" turn_detection: SessionTurnDetection - """Configuration for turn detection. - - Can be set to `null` to turn off. Server VAD means that the model will detect - the start and end of speech based on audio volume and respond at the end of user - speech. + """Configuration for turn detection, ether Server VAD or Semantic VAD. + + This can be set to `null` to turn off, in which case the client must manually + trigger model response. Server VAD means that the model will detect the start + and end of speech based on audio volume and respond at the end of user speech. + Semantic VAD is more advanced and uses a turn detection model (in conjuction + with VAD) to semantically estimate whether the user has finished speaking, then + dynamically sets a timeout based on this probability. For example, if user audio + trails off with "uhhm", the model will score a low probability of turn end and + wait longer for the user to continue speaking. This can be useful for more + natural conversations, but may have a higher latency. """ voice: Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"] diff --git a/src/openai/types/beta/realtime/transcription_session.py b/src/openai/types/beta/realtime/transcription_session.py new file mode 100644 index 0000000000..7c7abf37b6 --- /dev/null +++ b/src/openai/types/beta/realtime/transcription_session.py @@ -0,0 +1,100 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["TranscriptionSession", "ClientSecret", "InputAudioTranscription", "TurnDetection"] + + +class ClientSecret(BaseModel): + expires_at: int + """Timestamp for when the token expires. + + Currently, all tokens expire after one minute. + """ + + value: str + """ + Ephemeral key usable in client environments to authenticate connections to the + Realtime API. Use this in client-side environments rather than a standard API + token, which should only be used server-side. + """ + + +class InputAudioTranscription(BaseModel): + language: Optional[str] = None + """The language of the input audio. + + Supplying the input language in + [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) + format will improve accuracy and latency. + """ + + model: Optional[Literal["gpt-4o-transcribe", "gpt-4o-mini-transcribe", "whisper-1"]] = None + """The model to use for transcription. + + Can be `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, or `whisper-1`. + """ + + prompt: Optional[str] = None + """An optional text to guide the model's style or continue a previous audio + segment. + + The [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) + should match the audio language. + """ + + +class TurnDetection(BaseModel): + prefix_padding_ms: Optional[int] = None + """Amount of audio to include before the VAD detected speech (in milliseconds). + + Defaults to 300ms. + """ + + silence_duration_ms: Optional[int] = None + """Duration of silence to detect speech stop (in milliseconds). + + Defaults to 500ms. With shorter values the model will respond more quickly, but + may jump in on short pauses from the user. + """ + + threshold: Optional[float] = None + """Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. + + A higher threshold will require louder audio to activate the model, and thus + might perform better in noisy environments. + """ + + type: Optional[str] = None + """Type of turn detection, only `server_vad` is currently supported.""" + + +class TranscriptionSession(BaseModel): + client_secret: ClientSecret + """Ephemeral key returned by the API. + + Only present when the session is created on the server via REST API. + """ + + input_audio_format: Optional[str] = None + """The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.""" + + input_audio_transcription: Optional[InputAudioTranscription] = None + """Configuration of the transcription model.""" + + modalities: Optional[List[Literal["text", "audio"]]] = None + """The set of modalities the model can respond with. + + To disable audio, set this to ["text"]. + """ + + turn_detection: Optional[TurnDetection] = None + """Configuration for turn detection. + + Can be set to `null` to turn off. Server VAD means that the model will detect + the start and end of speech based on audio volume and respond at the end of user + speech. + """ diff --git a/src/openai/types/beta/realtime/transcription_session_create_params.py b/src/openai/types/beta/realtime/transcription_session_create_params.py new file mode 100644 index 0000000000..4066dc4c5d --- /dev/null +++ b/src/openai/types/beta/realtime/transcription_session_create_params.py @@ -0,0 +1,143 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List +from typing_extensions import Literal, TypedDict + +__all__ = ["TranscriptionSessionCreateParams", "InputAudioNoiseReduction", "InputAudioTranscription", "TurnDetection"] + + +class TranscriptionSessionCreateParams(TypedDict, total=False): + include: List[str] + """The set of items to include in the transcription. Current available items are: + + - `item.input_audio_transcription.logprobs` + """ + + input_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"] + """The format of input audio. + + Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For `pcm16`, input audio must + be 16-bit PCM at a 24kHz sample rate, single channel (mono), and little-endian + byte order. + """ + + input_audio_noise_reduction: InputAudioNoiseReduction + """Configuration for input audio noise reduction. + + This can be set to `null` to turn off. Noise reduction filters audio added to + the input audio buffer before it is sent to VAD and the model. Filtering the + audio can improve VAD and turn detection accuracy (reducing false positives) and + model performance by improving perception of the input audio. + """ + + input_audio_transcription: InputAudioTranscription + """Configuration for input audio transcription. + + The client can optionally set the language and prompt for transcription, these + offer additional guidance to the transcription service. + """ + + modalities: List[Literal["text", "audio"]] + """The set of modalities the model can respond with. + + To disable audio, set this to ["text"]. + """ + + turn_detection: TurnDetection + """Configuration for turn detection, ether Server VAD or Semantic VAD. + + This can be set to `null` to turn off, in which case the client must manually + trigger model response. Server VAD means that the model will detect the start + and end of speech based on audio volume and respond at the end of user speech. + Semantic VAD is more advanced and uses a turn detection model (in conjuction + with VAD) to semantically estimate whether the user has finished speaking, then + dynamically sets a timeout based on this probability. For example, if user audio + trails off with "uhhm", the model will score a low probability of turn end and + wait longer for the user to continue speaking. This can be useful for more + natural conversations, but may have a higher latency. + """ + + +class InputAudioNoiseReduction(TypedDict, total=False): + type: Literal["near_field", "far_field"] + """Type of noise reduction. + + `near_field` is for close-talking microphones such as headphones, `far_field` is + for far-field microphones such as laptop or conference room microphones. + """ + + +class InputAudioTranscription(TypedDict, total=False): + language: str + """The language of the input audio. + + Supplying the input language in + [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) + format will improve accuracy and latency. + """ + + model: Literal["gpt-4o-transcribe", "gpt-4o-mini-transcribe", "whisper-1"] + """ + The model to use for transcription, current options are `gpt-4o-transcribe`, + `gpt-4o-mini-transcribe`, and `whisper-1`. + """ + + prompt: str + """ + An optional text to guide the model's style or continue a previous audio + segment. For `whisper-1`, the + [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting). + For `gpt-4o-transcribe` models, the prompt is a free text string, for example + "expect words related to technology". + """ + + +class TurnDetection(TypedDict, total=False): + create_response: bool + """ + Whether or not to automatically generate a response when a VAD stop event + occurs. + """ + + eagerness: Literal["low", "medium", "high", "auto"] + """Used only for `semantic_vad` mode. + + The eagerness of the model to respond. `low` will wait longer for the user to + continue speaking, `high` will respond more quickly. `auto` is the default and + is equivalent to `medium`. + """ + + interrupt_response: bool + """ + Whether or not to automatically interrupt any ongoing response with output to + the default conversation (i.e. `conversation` of `auto`) when a VAD start event + occurs. + """ + + prefix_padding_ms: int + """Used only for `server_vad` mode. + + Amount of audio to include before the VAD detected speech (in milliseconds). + Defaults to 300ms. + """ + + silence_duration_ms: int + """Used only for `server_vad` mode. + + Duration of silence to detect speech stop (in milliseconds). Defaults to 500ms. + With shorter values the model will respond more quickly, but may jump in on + short pauses from the user. + """ + + threshold: float + """Used only for `server_vad` mode. + + Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A higher + threshold will require louder audio to activate the model, and thus might + perform better in noisy environments. + """ + + type: Literal["server_vad", "semantic_vad"] + """Type of turn detection.""" diff --git a/src/openai/types/beta/realtime/transcription_session_update.py b/src/openai/types/beta/realtime/transcription_session_update.py new file mode 100644 index 0000000000..043ac02e07 --- /dev/null +++ b/src/openai/types/beta/realtime/transcription_session_update.py @@ -0,0 +1,160 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = [ + "TranscriptionSessionUpdate", + "Session", + "SessionInputAudioNoiseReduction", + "SessionInputAudioTranscription", + "SessionTurnDetection", +] + + +class SessionInputAudioNoiseReduction(BaseModel): + type: Optional[Literal["near_field", "far_field"]] = None + """Type of noise reduction. + + `near_field` is for close-talking microphones such as headphones, `far_field` is + for far-field microphones such as laptop or conference room microphones. + """ + + +class SessionInputAudioTranscription(BaseModel): + language: Optional[str] = None + """The language of the input audio. + + Supplying the input language in + [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) + format will improve accuracy and latency. + """ + + model: Optional[Literal["gpt-4o-transcribe", "gpt-4o-mini-transcribe", "whisper-1"]] = None + """ + The model to use for transcription, current options are `gpt-4o-transcribe`, + `gpt-4o-mini-transcribe`, and `whisper-1`. + """ + + prompt: Optional[str] = None + """ + An optional text to guide the model's style or continue a previous audio + segment. For `whisper-1`, the + [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting). + For `gpt-4o-transcribe` models, the prompt is a free text string, for example + "expect words related to technology". + """ + + +class SessionTurnDetection(BaseModel): + create_response: Optional[bool] = None + """ + Whether or not to automatically generate a response when a VAD stop event + occurs. + """ + + eagerness: Optional[Literal["low", "medium", "high", "auto"]] = None + """Used only for `semantic_vad` mode. + + The eagerness of the model to respond. `low` will wait longer for the user to + continue speaking, `high` will respond more quickly. `auto` is the default and + is equivalent to `medium`. + """ + + interrupt_response: Optional[bool] = None + """ + Whether or not to automatically interrupt any ongoing response with output to + the default conversation (i.e. `conversation` of `auto`) when a VAD start event + occurs. + """ + + prefix_padding_ms: Optional[int] = None + """Used only for `server_vad` mode. + + Amount of audio to include before the VAD detected speech (in milliseconds). + Defaults to 300ms. + """ + + silence_duration_ms: Optional[int] = None + """Used only for `server_vad` mode. + + Duration of silence to detect speech stop (in milliseconds). Defaults to 500ms. + With shorter values the model will respond more quickly, but may jump in on + short pauses from the user. + """ + + threshold: Optional[float] = None + """Used only for `server_vad` mode. + + Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A higher + threshold will require louder audio to activate the model, and thus might + perform better in noisy environments. + """ + + type: Optional[Literal["server_vad", "semantic_vad"]] = None + """Type of turn detection.""" + + +class Session(BaseModel): + include: Optional[List[str]] = None + """The set of items to include in the transcription. Current available items are: + + - `item.input_audio_transcription.logprobs` + """ + + input_audio_format: Optional[Literal["pcm16", "g711_ulaw", "g711_alaw"]] = None + """The format of input audio. + + Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For `pcm16`, input audio must + be 16-bit PCM at a 24kHz sample rate, single channel (mono), and little-endian + byte order. + """ + + input_audio_noise_reduction: Optional[SessionInputAudioNoiseReduction] = None + """Configuration for input audio noise reduction. + + This can be set to `null` to turn off. Noise reduction filters audio added to + the input audio buffer before it is sent to VAD and the model. Filtering the + audio can improve VAD and turn detection accuracy (reducing false positives) and + model performance by improving perception of the input audio. + """ + + input_audio_transcription: Optional[SessionInputAudioTranscription] = None + """Configuration for input audio transcription. + + The client can optionally set the language and prompt for transcription, these + offer additional guidance to the transcription service. + """ + + modalities: Optional[List[Literal["text", "audio"]]] = None + """The set of modalities the model can respond with. + + To disable audio, set this to ["text"]. + """ + + turn_detection: Optional[SessionTurnDetection] = None + """Configuration for turn detection, ether Server VAD or Semantic VAD. + + This can be set to `null` to turn off, in which case the client must manually + trigger model response. Server VAD means that the model will detect the start + and end of speech based on audio volume and respond at the end of user speech. + Semantic VAD is more advanced and uses a turn detection model (in conjuction + with VAD) to semantically estimate whether the user has finished speaking, then + dynamically sets a timeout based on this probability. For example, if user audio + trails off with "uhhm", the model will score a low probability of turn end and + wait longer for the user to continue speaking. This can be useful for more + natural conversations, but may have a higher latency. + """ + + +class TranscriptionSessionUpdate(BaseModel): + session: Session + """Realtime transcription session object configuration.""" + + type: Literal["transcription_session.update"] + """The event type, must be `transcription_session.update`.""" + + event_id: Optional[str] = None + """Optional client-generated ID used to identify this event.""" diff --git a/src/openai/types/beta/realtime/transcription_session_update_param.py b/src/openai/types/beta/realtime/transcription_session_update_param.py new file mode 100644 index 0000000000..997a36d77b --- /dev/null +++ b/src/openai/types/beta/realtime/transcription_session_update_param.py @@ -0,0 +1,160 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List +from typing_extensions import Literal, Required, TypedDict + +__all__ = [ + "TranscriptionSessionUpdateParam", + "Session", + "SessionInputAudioNoiseReduction", + "SessionInputAudioTranscription", + "SessionTurnDetection", +] + + +class SessionInputAudioNoiseReduction(TypedDict, total=False): + type: Literal["near_field", "far_field"] + """Type of noise reduction. + + `near_field` is for close-talking microphones such as headphones, `far_field` is + for far-field microphones such as laptop or conference room microphones. + """ + + +class SessionInputAudioTranscription(TypedDict, total=False): + language: str + """The language of the input audio. + + Supplying the input language in + [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) + format will improve accuracy and latency. + """ + + model: Literal["gpt-4o-transcribe", "gpt-4o-mini-transcribe", "whisper-1"] + """ + The model to use for transcription, current options are `gpt-4o-transcribe`, + `gpt-4o-mini-transcribe`, and `whisper-1`. + """ + + prompt: str + """ + An optional text to guide the model's style or continue a previous audio + segment. For `whisper-1`, the + [prompt is a list of keywords](https://platform.openai.com/docs/guides/speech-to-text#prompting). + For `gpt-4o-transcribe` models, the prompt is a free text string, for example + "expect words related to technology". + """ + + +class SessionTurnDetection(TypedDict, total=False): + create_response: bool + """ + Whether or not to automatically generate a response when a VAD stop event + occurs. + """ + + eagerness: Literal["low", "medium", "high", "auto"] + """Used only for `semantic_vad` mode. + + The eagerness of the model to respond. `low` will wait longer for the user to + continue speaking, `high` will respond more quickly. `auto` is the default and + is equivalent to `medium`. + """ + + interrupt_response: bool + """ + Whether or not to automatically interrupt any ongoing response with output to + the default conversation (i.e. `conversation` of `auto`) when a VAD start event + occurs. + """ + + prefix_padding_ms: int + """Used only for `server_vad` mode. + + Amount of audio to include before the VAD detected speech (in milliseconds). + Defaults to 300ms. + """ + + silence_duration_ms: int + """Used only for `server_vad` mode. + + Duration of silence to detect speech stop (in milliseconds). Defaults to 500ms. + With shorter values the model will respond more quickly, but may jump in on + short pauses from the user. + """ + + threshold: float + """Used only for `server_vad` mode. + + Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A higher + threshold will require louder audio to activate the model, and thus might + perform better in noisy environments. + """ + + type: Literal["server_vad", "semantic_vad"] + """Type of turn detection.""" + + +class Session(TypedDict, total=False): + include: List[str] + """The set of items to include in the transcription. Current available items are: + + - `item.input_audio_transcription.logprobs` + """ + + input_audio_format: Literal["pcm16", "g711_ulaw", "g711_alaw"] + """The format of input audio. + + Options are `pcm16`, `g711_ulaw`, or `g711_alaw`. For `pcm16`, input audio must + be 16-bit PCM at a 24kHz sample rate, single channel (mono), and little-endian + byte order. + """ + + input_audio_noise_reduction: SessionInputAudioNoiseReduction + """Configuration for input audio noise reduction. + + This can be set to `null` to turn off. Noise reduction filters audio added to + the input audio buffer before it is sent to VAD and the model. Filtering the + audio can improve VAD and turn detection accuracy (reducing false positives) and + model performance by improving perception of the input audio. + """ + + input_audio_transcription: SessionInputAudioTranscription + """Configuration for input audio transcription. + + The client can optionally set the language and prompt for transcription, these + offer additional guidance to the transcription service. + """ + + modalities: List[Literal["text", "audio"]] + """The set of modalities the model can respond with. + + To disable audio, set this to ["text"]. + """ + + turn_detection: SessionTurnDetection + """Configuration for turn detection, ether Server VAD or Semantic VAD. + + This can be set to `null` to turn off, in which case the client must manually + trigger model response. Server VAD means that the model will detect the start + and end of speech based on audio volume and respond at the end of user speech. + Semantic VAD is more advanced and uses a turn detection model (in conjuction + with VAD) to semantically estimate whether the user has finished speaking, then + dynamically sets a timeout based on this probability. For example, if user audio + trails off with "uhhm", the model will score a low probability of turn end and + wait longer for the user to continue speaking. This can be useful for more + natural conversations, but may have a higher latency. + """ + + +class TranscriptionSessionUpdateParam(TypedDict, total=False): + session: Required[Session] + """Realtime transcription session object configuration.""" + + type: Required[Literal["transcription_session.update"]] + """The event type, must be `transcription_session.update`.""" + + event_id: str + """Optional client-generated ID used to identify this event.""" diff --git a/src/openai/types/beta/realtime/transcription_session_updated_event.py b/src/openai/types/beta/realtime/transcription_session_updated_event.py new file mode 100644 index 0000000000..ffc100bcc2 --- /dev/null +++ b/src/openai/types/beta/realtime/transcription_session_updated_event.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel +from .transcription_session import TranscriptionSession + +__all__ = ["TranscriptionSessionUpdatedEvent"] + + +class TranscriptionSessionUpdatedEvent(BaseModel): + event_id: str + """The unique ID of the server event.""" + + session: TranscriptionSession + """A new Realtime transcription session configuration. + + When a session is created on the server via REST API, the session object also + contains an ephemeral key. Default TTL for keys is one minute. This property is + not present when a session is updated via the WebSocket API. + """ + + type: Literal["transcription_session.updated"] + """The event type, must be `transcription_session.updated`.""" diff --git a/tests/api_resources/audio/test_speech.py b/tests/api_resources/audio/test_speech.py index 781ebeceb9..808f6ef66c 100644 --- a/tests/api_resources/audio/test_speech.py +++ b/tests/api_resources/audio/test_speech.py @@ -41,6 +41,7 @@ def test_method_create_with_all_params(self, client: OpenAI, respx_mock: MockRou input="string", model="string", voice="alloy", + instructions="instructions", response_format="mp3", speed=0.25, ) @@ -104,6 +105,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI, re input="string", model="string", voice="alloy", + instructions="instructions", response_format="mp3", speed=0.25, ) diff --git a/tests/api_resources/audio/test_transcriptions.py b/tests/api_resources/audio/test_transcriptions.py index bdb7e0dfb6..19215e11df 100644 --- a/tests/api_resources/audio/test_transcriptions.py +++ b/tests/api_resources/audio/test_transcriptions.py @@ -18,31 +18,33 @@ class TestTranscriptions: parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize - def test_method_create(self, client: OpenAI) -> None: + def test_method_create_overload_1(self, client: OpenAI) -> None: transcription = client.audio.transcriptions.create( file=b"raw file contents", - model="whisper-1", + model="gpt-4o-transcribe", ) assert_matches_type(TranscriptionCreateResponse, transcription, path=["response"]) @parametrize - def test_method_create_with_all_params(self, client: OpenAI) -> None: + def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: transcription = client.audio.transcriptions.create( file=b"raw file contents", - model="whisper-1", - language="string", - prompt="string", + model="gpt-4o-transcribe", + include=["logprobs"], + language="language", + prompt="prompt", response_format="json", + stream=False, temperature=0, timestamp_granularities=["word"], ) assert_matches_type(TranscriptionCreateResponse, transcription, path=["response"]) @parametrize - def test_raw_response_create(self, client: OpenAI) -> None: + def test_raw_response_create_overload_1(self, client: OpenAI) -> None: response = client.audio.transcriptions.with_raw_response.create( file=b"raw file contents", - model="whisper-1", + model="gpt-4o-transcribe", ) assert response.is_closed is True @@ -51,10 +53,10 @@ def test_raw_response_create(self, client: OpenAI) -> None: assert_matches_type(TranscriptionCreateResponse, transcription, path=["response"]) @parametrize - def test_streaming_response_create(self, client: OpenAI) -> None: + def test_streaming_response_create_overload_1(self, client: OpenAI) -> None: with client.audio.transcriptions.with_streaming_response.create( file=b"raw file contents", - model="whisper-1", + model="gpt-4o-transcribe", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -64,36 +66,89 @@ def test_streaming_response_create(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @parametrize + def test_method_create_overload_2(self, client: OpenAI) -> None: + transcription_stream = client.audio.transcriptions.create( + file=b"raw file contents", + model="gpt-4o-transcribe", + stream=True, + ) + transcription_stream.response.close() + + @parametrize + def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: + transcription_stream = client.audio.transcriptions.create( + file=b"raw file contents", + model="gpt-4o-transcribe", + stream=True, + include=["logprobs"], + language="language", + prompt="prompt", + response_format="json", + temperature=0, + timestamp_granularities=["word"], + ) + transcription_stream.response.close() + + @parametrize + def test_raw_response_create_overload_2(self, client: OpenAI) -> None: + response = client.audio.transcriptions.with_raw_response.create( + file=b"raw file contents", + model="gpt-4o-transcribe", + stream=True, + ) + + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + stream = response.parse() + stream.close() + + @parametrize + def test_streaming_response_create_overload_2(self, client: OpenAI) -> None: + with client.audio.transcriptions.with_streaming_response.create( + file=b"raw file contents", + model="gpt-4o-transcribe", + stream=True, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + stream = response.parse() + stream.close() + + assert cast(Any, response.is_closed) is True + class TestAsyncTranscriptions: parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) @parametrize - async def test_method_create(self, async_client: AsyncOpenAI) -> None: + async def test_method_create_overload_1(self, async_client: AsyncOpenAI) -> None: transcription = await async_client.audio.transcriptions.create( file=b"raw file contents", - model="whisper-1", + model="gpt-4o-transcribe", ) assert_matches_type(TranscriptionCreateResponse, transcription, path=["response"]) @parametrize - async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: + async def test_method_create_with_all_params_overload_1(self, async_client: AsyncOpenAI) -> None: transcription = await async_client.audio.transcriptions.create( file=b"raw file contents", - model="whisper-1", - language="string", - prompt="string", + model="gpt-4o-transcribe", + include=["logprobs"], + language="language", + prompt="prompt", response_format="json", + stream=False, temperature=0, timestamp_granularities=["word"], ) assert_matches_type(TranscriptionCreateResponse, transcription, path=["response"]) @parametrize - async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: + async def test_raw_response_create_overload_1(self, async_client: AsyncOpenAI) -> None: response = await async_client.audio.transcriptions.with_raw_response.create( file=b"raw file contents", - model="whisper-1", + model="gpt-4o-transcribe", ) assert response.is_closed is True @@ -102,10 +157,10 @@ async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: assert_matches_type(TranscriptionCreateResponse, transcription, path=["response"]) @parametrize - async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: + async def test_streaming_response_create_overload_1(self, async_client: AsyncOpenAI) -> None: async with async_client.audio.transcriptions.with_streaming_response.create( file=b"raw file contents", - model="whisper-1", + model="gpt-4o-transcribe", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -114,3 +169,54 @@ async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> Non assert_matches_type(TranscriptionCreateResponse, transcription, path=["response"]) assert cast(Any, response.is_closed) is True + + @parametrize + async def test_method_create_overload_2(self, async_client: AsyncOpenAI) -> None: + transcription_stream = await async_client.audio.transcriptions.create( + file=b"raw file contents", + model="gpt-4o-transcribe", + stream=True, + ) + await transcription_stream.response.aclose() + + @parametrize + async def test_method_create_with_all_params_overload_2(self, async_client: AsyncOpenAI) -> None: + transcription_stream = await async_client.audio.transcriptions.create( + file=b"raw file contents", + model="gpt-4o-transcribe", + stream=True, + include=["logprobs"], + language="language", + prompt="prompt", + response_format="json", + temperature=0, + timestamp_granularities=["word"], + ) + await transcription_stream.response.aclose() + + @parametrize + async def test_raw_response_create_overload_2(self, async_client: AsyncOpenAI) -> None: + response = await async_client.audio.transcriptions.with_raw_response.create( + file=b"raw file contents", + model="gpt-4o-transcribe", + stream=True, + ) + + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + stream = response.parse() + await stream.close() + + @parametrize + async def test_streaming_response_create_overload_2(self, async_client: AsyncOpenAI) -> None: + async with async_client.audio.transcriptions.with_streaming_response.create( + file=b"raw file contents", + model="gpt-4o-transcribe", + stream=True, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + stream = await response.parse() + await stream.close() + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/beta/realtime/test_sessions.py b/tests/api_resources/beta/realtime/test_sessions.py index 5ea308ca0d..c0a426a417 100644 --- a/tests/api_resources/beta/realtime/test_sessions.py +++ b/tests/api_resources/beta/realtime/test_sessions.py @@ -26,6 +26,7 @@ def test_method_create(self, client: OpenAI) -> None: def test_method_create_with_all_params(self, client: OpenAI) -> None: session = client.beta.realtime.sessions.create( input_audio_format="pcm16", + input_audio_noise_reduction={"type": "near_field"}, input_audio_transcription={ "language": "language", "model": "model", @@ -48,11 +49,12 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: ], turn_detection={ "create_response": True, + "eagerness": "low", "interrupt_response": True, "prefix_padding_ms": 0, "silence_duration_ms": 0, "threshold": 0, - "type": "type", + "type": "server_vad", }, voice="alloy", ) @@ -91,6 +93,7 @@ async def test_method_create(self, async_client: AsyncOpenAI) -> None: async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: session = await async_client.beta.realtime.sessions.create( input_audio_format="pcm16", + input_audio_noise_reduction={"type": "near_field"}, input_audio_transcription={ "language": "language", "model": "model", @@ -113,11 +116,12 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> ], turn_detection={ "create_response": True, + "eagerness": "low", "interrupt_response": True, "prefix_padding_ms": 0, "silence_duration_ms": 0, "threshold": 0, - "type": "type", + "type": "server_vad", }, voice="alloy", ) diff --git a/tests/api_resources/beta/realtime/test_transcription_sessions.py b/tests/api_resources/beta/realtime/test_transcription_sessions.py new file mode 100644 index 0000000000..4826185bea --- /dev/null +++ b/tests/api_resources/beta/realtime/test_transcription_sessions.py @@ -0,0 +1,120 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai.types.beta.realtime import TranscriptionSession + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") + + +class TestTranscriptionSessions: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + def test_method_create(self, client: OpenAI) -> None: + transcription_session = client.beta.realtime.transcription_sessions.create() + assert_matches_type(TranscriptionSession, transcription_session, path=["response"]) + + @parametrize + def test_method_create_with_all_params(self, client: OpenAI) -> None: + transcription_session = client.beta.realtime.transcription_sessions.create( + include=["string"], + input_audio_format="pcm16", + input_audio_noise_reduction={"type": "near_field"}, + input_audio_transcription={ + "language": "language", + "model": "gpt-4o-transcribe", + "prompt": "prompt", + }, + modalities=["text"], + turn_detection={ + "create_response": True, + "eagerness": "low", + "interrupt_response": True, + "prefix_padding_ms": 0, + "silence_duration_ms": 0, + "threshold": 0, + "type": "server_vad", + }, + ) + assert_matches_type(TranscriptionSession, transcription_session, path=["response"]) + + @parametrize + def test_raw_response_create(self, client: OpenAI) -> None: + response = client.beta.realtime.transcription_sessions.with_raw_response.create() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + transcription_session = response.parse() + assert_matches_type(TranscriptionSession, transcription_session, path=["response"]) + + @parametrize + def test_streaming_response_create(self, client: OpenAI) -> None: + with client.beta.realtime.transcription_sessions.with_streaming_response.create() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + transcription_session = response.parse() + assert_matches_type(TranscriptionSession, transcription_session, path=["response"]) + + assert cast(Any, response.is_closed) is True + + +class TestAsyncTranscriptionSessions: + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + async def test_method_create(self, async_client: AsyncOpenAI) -> None: + transcription_session = await async_client.beta.realtime.transcription_sessions.create() + assert_matches_type(TranscriptionSession, transcription_session, path=["response"]) + + @parametrize + async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: + transcription_session = await async_client.beta.realtime.transcription_sessions.create( + include=["string"], + input_audio_format="pcm16", + input_audio_noise_reduction={"type": "near_field"}, + input_audio_transcription={ + "language": "language", + "model": "gpt-4o-transcribe", + "prompt": "prompt", + }, + modalities=["text"], + turn_detection={ + "create_response": True, + "eagerness": "low", + "interrupt_response": True, + "prefix_padding_ms": 0, + "silence_duration_ms": 0, + "threshold": 0, + "type": "server_vad", + }, + ) + assert_matches_type(TranscriptionSession, transcription_session, path=["response"]) + + @parametrize + async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: + response = await async_client.beta.realtime.transcription_sessions.with_raw_response.create() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + transcription_session = response.parse() + assert_matches_type(TranscriptionSession, transcription_session, path=["response"]) + + @parametrize + async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: + async with async_client.beta.realtime.transcription_sessions.with_streaming_response.create() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + transcription_session = await response.parse() + assert_matches_type(TranscriptionSession, transcription_session, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/lib/test_audio.py b/tests/lib/test_audio.py index 0f53b316ba..ff8dba4714 100644 --- a/tests/lib/test_audio.py +++ b/tests/lib/test_audio.py @@ -26,7 +26,7 @@ def test_translation_create_overloads_in_sync(sync: bool, client: OpenAI, async_ assert_signatures_in_sync( fn, overload, - exclude_params={"response_format"}, + exclude_params={"response_format", "stream"}, description=f" for overload {i}", ) @@ -60,7 +60,7 @@ def test_transcription_create_overloads_in_sync(sync: bool, client: OpenAI, asyn assert_signatures_in_sync( fn, overload, - exclude_params={"response_format"}, + exclude_params={"response_format", "stream"}, description=f" for overload {i}", ) From 8136a21637df5d79442efcb26459d2dd6154db77 Mon Sep 17 00:00:00 2001 From: Kevin Whinnery Date: Thu, 20 Mar 2025 11:31:58 -0500 Subject: [PATCH 735/816] feat: add audio helpers * add audio helpers * update ignore, lockfile, add execute * fix examples, lint errors * lint and export errors * temp: ignore type errors --- .gitignore | 4 + examples/audio.py | 26 ---- examples/speech_to_text.py | 25 ++++ examples/text_to_speech.py | 31 +++++ pyproject.toml | 2 + requirements-dev.lock | 7 +- requirements.lock | 6 + src/openai/helpers.py | 4 + src/openai/helpers/__init__.py | 4 + src/openai/helpers/local_audio_player.py | 162 +++++++++++++++++++++++ src/openai/helpers/microphone.py | 98 ++++++++++++++ 11 files changed, 341 insertions(+), 28 deletions(-) create mode 100755 examples/speech_to_text.py create mode 100755 examples/text_to_speech.py create mode 100644 src/openai/helpers.py create mode 100644 src/openai/helpers/__init__.py create mode 100644 src/openai/helpers/local_audio_player.py create mode 100644 src/openai/helpers/microphone.py diff --git a/.gitignore b/.gitignore index 8779740800..70815df7f6 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,7 @@ dist .envrc codegen.log Brewfile.lock.json + +.DS_Store + +examples/*.mp3 diff --git a/examples/audio.py b/examples/audio.py index 85f47bfb06..af41fe601b 100755 --- a/examples/audio.py +++ b/examples/audio.py @@ -1,6 +1,5 @@ #!/usr/bin/env rye run python -import time from pathlib import Path from openai import OpenAI @@ -12,8 +11,6 @@ def main() -> None: - stream_to_speakers() - # Create text-to-speech audio file with openai.audio.speech.with_streaming_response.create( model="tts-1", @@ -37,28 +34,5 @@ def main() -> None: print(translation.text) -def stream_to_speakers() -> None: - import pyaudio - - player_stream = pyaudio.PyAudio().open(format=pyaudio.paInt16, channels=1, rate=24000, output=True) - - start_time = time.time() - - with openai.audio.speech.with_streaming_response.create( - model="tts-1", - voice="alloy", - response_format="pcm", # similar to WAV, but without a header chunk at the start. - input="""I see skies of blue and clouds of white - The bright blessed days, the dark sacred nights - And I think to myself - What a wonderful world""", - ) as response: - print(f"Time to first byte: {int((time.time() - start_time) * 1000)}ms") - for chunk in response.iter_bytes(chunk_size=1024): - player_stream.write(chunk) - - print(f"Done in {int((time.time() - start_time) * 1000)}ms.") - - if __name__ == "__main__": main() diff --git a/examples/speech_to_text.py b/examples/speech_to_text.py new file mode 100755 index 0000000000..cc3f56b424 --- /dev/null +++ b/examples/speech_to_text.py @@ -0,0 +1,25 @@ +#!/usr/bin/env rye run python + +import asyncio + +from openai import AsyncOpenAI +from openai.helpers import Microphone + +# gets OPENAI_API_KEY from your environment variables +openai = AsyncOpenAI() + + +async def main() -> None: + print("Recording for the next 10 seconds...") + recording = await Microphone(timeout=10).record() + print("Recording complete") + transcription = await openai.audio.transcriptions.create( + model="whisper-1", + file=recording, + ) + + print(transcription.text) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/examples/text_to_speech.py b/examples/text_to_speech.py new file mode 100755 index 0000000000..ac8b12b0ab --- /dev/null +++ b/examples/text_to_speech.py @@ -0,0 +1,31 @@ +#!/usr/bin/env rye run python + +import time +import asyncio + +from openai import AsyncOpenAI +from openai.helpers import LocalAudioPlayer + +# gets OPENAI_API_KEY from your environment variables +openai = AsyncOpenAI() + + +async def main() -> None: + start_time = time.time() + + async with openai.audio.speech.with_streaming_response.create( + model="tts-1", + voice="alloy", + response_format="pcm", # similar to WAV, but without a header chunk at the start. + input="""I see skies of blue and clouds of white + The bright blessed days, the dark sacred nights + And I think to myself + What a wonderful world""", + ) as response: + print(f"Time to first byte: {int((time.time() - start_time) * 1000)}ms") + await LocalAudioPlayer().play(response) + print(f"Time to play: {int((time.time() - start_time) * 1000)}ms") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/pyproject.toml b/pyproject.toml index a0a7eba2f5..dcec9ad3c4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -16,6 +16,8 @@ dependencies = [ "sniffio", "tqdm > 4", "jiter>=0.4.0, <1", + "sounddevice>=0.5.1", + "numpy>=2.0.2", ] requires-python = ">= 3.8" classifiers = [ diff --git a/requirements-dev.lock b/requirements-dev.lock index 48e49f926c..0755ddb3c5 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -33,6 +33,7 @@ certifi==2023.7.22 # via requests cffi==1.16.0 # via cryptography + # via sounddevice charset-normalizer==3.3.2 # via requests click==8.1.7 @@ -92,7 +93,7 @@ nest-asyncio==1.6.0 nodeenv==1.8.0 # via pyright nox==2023.4.22 -numpy==1.26.3 +numpy==2.0.2 # via openai # via pandas # via pandas-stubs @@ -102,7 +103,7 @@ packaging==23.2 # via black # via nox # via pytest -pandas==2.1.4 +pandas==2.2.3 # via openai pandas-stubs==2.1.4.231227 # via openai @@ -154,6 +155,8 @@ sniffio==1.3.0 # via trio sortedcontainers==2.4.0 # via trio +sounddevice==0.5.1 + # via openai time-machine==2.9.0 toml==0.10.2 # via inline-snapshot diff --git a/requirements.lock b/requirements.lock index b935c0ee59..fa88e26c0f 100644 --- a/requirements.lock +++ b/requirements.lock @@ -18,6 +18,8 @@ anyio==4.1.0 certifi==2023.7.22 # via httpcore # via httpx +cffi==1.17.1 + # via sounddevice distro==1.8.0 # via openai exceptiongroup==1.2.2 @@ -41,6 +43,8 @@ pandas==2.2.3 # via openai pandas-stubs==2.2.2.240807 # via openai +pycparser==2.22 + # via cffi pydantic==2.10.3 # via openai pydantic-core==2.27.1 @@ -54,6 +58,8 @@ six==1.16.0 sniffio==1.3.0 # via anyio # via openai +sounddevice==0.5.1 + # via openai tqdm==4.66.5 # via openai types-pytz==2024.2.0.20241003 diff --git a/src/openai/helpers.py b/src/openai/helpers.py new file mode 100644 index 0000000000..1a10168a96 --- /dev/null +++ b/src/openai/helpers.py @@ -0,0 +1,4 @@ +from .helpers.microphone import Microphone +from .helpers.local_audio_player import LocalAudioPlayer + +__all__ = ["LocalAudioPlayer", "Microphone"] diff --git a/src/openai/helpers/__init__.py b/src/openai/helpers/__init__.py new file mode 100644 index 0000000000..ab3044da59 --- /dev/null +++ b/src/openai/helpers/__init__.py @@ -0,0 +1,4 @@ +from .microphone import Microphone +from .local_audio_player import LocalAudioPlayer + +__all__ = ["Microphone", "LocalAudioPlayer"] diff --git a/src/openai/helpers/local_audio_player.py b/src/openai/helpers/local_audio_player.py new file mode 100644 index 0000000000..46a16ce6bb --- /dev/null +++ b/src/openai/helpers/local_audio_player.py @@ -0,0 +1,162 @@ +# mypy: ignore-errors +import queue +import asyncio +from typing import Any, Union, Callable, AsyncGenerator, cast + +import numpy as np +import sounddevice as sd # type: ignore +import numpy.typing as npt + +from .. import _legacy_response +from .._response import StreamedBinaryAPIResponse, AsyncStreamedBinaryAPIResponse + +SAMPLE_RATE = 24000 + + +class LocalAudioPlayer: + def __init__( + self, + should_stop: Union[Callable[[], bool], None] = None, + ): + self.channels = 1 + self.dtype = np.float32 + self.should_stop = should_stop + + async def _tts_response_to_buffer( + self, + response: Union[ + _legacy_response.HttpxBinaryResponseContent, + AsyncStreamedBinaryAPIResponse, + StreamedBinaryAPIResponse, + ], + ) -> npt.NDArray[np.float32]: + chunks: list[bytes] = [] + if isinstance(response, _legacy_response.HttpxBinaryResponseContent) or isinstance( + response, StreamedBinaryAPIResponse + ): + for chunk in response.iter_bytes(chunk_size=1024): + if chunk: + chunks.append(chunk) + else: + async for chunk in response.iter_bytes(chunk_size=1024): + if chunk: + chunks.append(chunk) + + audio_bytes = b"".join(chunks) + audio_np = np.frombuffer(audio_bytes, dtype=np.int16).astype(np.float32) / 32767.0 + audio_np = audio_np.reshape(-1, 1) + return audio_np + + async def play( + self, + input: Union[ + npt.NDArray[np.int16], + npt.NDArray[np.float32], + _legacy_response.HttpxBinaryResponseContent, + AsyncStreamedBinaryAPIResponse, + StreamedBinaryAPIResponse, + ], + ) -> None: + audio_content: npt.NDArray[np.float32] + if isinstance(input, np.ndarray): + if input.dtype == np.int16 and self.dtype == np.float32: + audio_content = (input.astype(np.float32) / 32767.0).reshape(-1, self.channels) + elif input.dtype == np.float32: + audio_content = cast(npt.NDArray[np.float32], input) + else: + raise ValueError(f"Unsupported dtype: {input.dtype}") + else: + audio_content = await self._tts_response_to_buffer(input) + + loop = asyncio.get_event_loop() + event = asyncio.Event() + idx = 0 + + def callback( + outdata: npt.NDArray[np.float32], + frame_count: int, + _time_info: Any, + _status: Any, + ): + nonlocal idx + + remainder = len(audio_content) - idx + if remainder == 0 or (callable(self.should_stop) and self.should_stop()): + loop.call_soon_threadsafe(event.set) + raise sd.CallbackStop + valid_frames = frame_count if remainder >= frame_count else remainder + outdata[:valid_frames] = audio_content[idx : idx + valid_frames] + outdata[valid_frames:] = 0 + idx += valid_frames + + stream = sd.OutputStream( + samplerate=SAMPLE_RATE, + callback=callback, + dtype=audio_content.dtype, + channels=audio_content.shape[1], + ) + with stream: + await event.wait() + + async def play_stream( + self, + buffer_stream: AsyncGenerator[Union[npt.NDArray[np.float32], npt.NDArray[np.int16], None], None], + ) -> None: + loop = asyncio.get_event_loop() + event = asyncio.Event() + buffer_queue: queue.Queue[Union[npt.NDArray[np.float32], npt.NDArray[np.int16], None]] = queue.Queue(maxsize=50) + + async def buffer_producer(): + async for buffer in buffer_stream: + if buffer is None: + break + await loop.run_in_executor(None, buffer_queue.put, buffer) + await loop.run_in_executor(None, buffer_queue.put, None) # Signal completion + + def callback( + outdata: npt.NDArray[np.float32], + frame_count: int, + _time_info: Any, + _status: Any, + ): + nonlocal current_buffer, buffer_pos + + frames_written = 0 + while frames_written < frame_count: + if current_buffer is None or buffer_pos >= len(current_buffer): + try: + current_buffer = buffer_queue.get(timeout=0.1) + if current_buffer is None: + loop.call_soon_threadsafe(event.set) + raise sd.CallbackStop + buffer_pos = 0 + + if current_buffer.dtype == np.int16 and self.dtype == np.float32: + current_buffer = (current_buffer.astype(np.float32) / 32767.0).reshape(-1, self.channels) + + except queue.Empty: + outdata[frames_written:] = 0 + return + + remaining_frames = len(current_buffer) - buffer_pos + frames_to_write = min(frame_count - frames_written, remaining_frames) + outdata[frames_written : frames_written + frames_to_write] = current_buffer[ + buffer_pos : buffer_pos + frames_to_write + ] + buffer_pos += frames_to_write + frames_written += frames_to_write + + current_buffer = None + buffer_pos = 0 + + producer_task = asyncio.create_task(buffer_producer()) + + with sd.OutputStream( + samplerate=SAMPLE_RATE, + channels=self.channels, + dtype=self.dtype, + callback=callback, + ): + await event.wait() + + await producer_task diff --git a/src/openai/helpers/microphone.py b/src/openai/helpers/microphone.py new file mode 100644 index 0000000000..18650909aa --- /dev/null +++ b/src/openai/helpers/microphone.py @@ -0,0 +1,98 @@ +# mypy: ignore-errors +import io +import time +import wave +import asyncio +from typing import Any, Type, Union, Generic, TypeVar, Callable, overload +from typing_extensions import Literal + +import numpy as np +import sounddevice as sd # type: ignore +import numpy.typing as npt + +from openai._types import FileTypes, FileContent + +SAMPLE_RATE = 24000 + +DType = TypeVar("DType", bound=np.generic) + + +class Microphone(Generic[DType]): + def __init__( + self, + channels: int = 1, + dtype: Type[DType] = np.int16, + should_record: Union[Callable[[], bool], None] = None, + timeout: Union[float, None] = None, + ): + self.channels = channels + self.dtype = dtype + self.should_record = should_record + self.buffer_chunks = [] + self.timeout = timeout + self.has_record_function = callable(should_record) + + def _ndarray_to_wav(self, audio_data: npt.NDArray[DType]) -> FileTypes: + buffer: FileContent = io.BytesIO() + with wave.open(buffer, "w") as wav_file: + wav_file.setnchannels(self.channels) + wav_file.setsampwidth(np.dtype(self.dtype).itemsize) + wav_file.setframerate(SAMPLE_RATE) + wav_file.writeframes(audio_data.tobytes()) + buffer.seek(0) + return ("audio.wav", buffer, "audio/wav") + + @overload + async def record(self, return_ndarray: Literal[True]) -> npt.NDArray[DType]: ... + + @overload + async def record(self, return_ndarray: Literal[False]) -> FileTypes: ... + + @overload + async def record(self, return_ndarray: None = ...) -> FileTypes: ... + + async def record(self, return_ndarray: Union[bool, None] = False) -> Union[npt.NDArray[DType], FileTypes]: + loop = asyncio.get_event_loop() + event = asyncio.Event() + self.buffer_chunks: list[npt.NDArray[DType]] = [] + start_time = time.perf_counter() + + def callback( + indata: npt.NDArray[DType], + _frame_count: int, + _time_info: Any, + _status: Any, + ): + execution_time = time.perf_counter() - start_time + reached_recording_timeout = execution_time > self.timeout if self.timeout is not None else False + if reached_recording_timeout: + loop.call_soon_threadsafe(event.set) + raise sd.CallbackStop + + should_be_recording = self.should_record() if callable(self.should_record) else True + if not should_be_recording: + loop.call_soon_threadsafe(event.set) + raise sd.CallbackStop + + self.buffer_chunks.append(indata.copy()) + + stream = sd.InputStream( + callback=callback, + dtype=self.dtype, + samplerate=SAMPLE_RATE, + channels=self.channels, + ) + with stream: + await event.wait() + + # Concatenate all chunks into a single buffer, handle empty case + concatenated_chunks: npt.NDArray[DType] = ( + np.concatenate(self.buffer_chunks, axis=0) + if len(self.buffer_chunks) > 0 + else np.array([], dtype=self.dtype) + ) + + if return_ndarray: + return concatenated_chunks + else: + return self._ndarray_to_wav(concatenated_chunks) From 6d0ecdd8ecbface903cf93c7571398b90b803b0b Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 20 Mar 2025 16:32:31 +0000 Subject: [PATCH 736/816] release: 1.68.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 9 +++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 4556676715..42bc7e250e 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.67.0" + ".": "1.68.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index ddd8b945c6..78ae21f27f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 1.68.0 (2025-03-20) + +Full Changelog: [v1.67.0...v1.68.0](https://github.com/openai/openai-python/compare/v1.67.0...v1.68.0) + +### Features + +* add audio helpers ([423655c](https://github.com/openai/openai-python/commit/423655ca9077cfd258f1e52f6eb386fc8307fa5f)) +* **api:** new models for TTS, STT, + new audio features for Realtime ([#2232](https://github.com/openai/openai-python/issues/2232)) ([ab5192d](https://github.com/openai/openai-python/commit/ab5192d0a7b417ade622ec94dd48f86beb90692c)) + ## 1.67.0 (2025-03-19) Full Changelog: [v1.66.5...v1.67.0](https://github.com/openai/openai-python/compare/v1.66.5...v1.67.0) diff --git a/pyproject.toml b/pyproject.toml index dcec9ad3c4..5ee7157038 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.67.0" +version = "1.68.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index b63e6ad189..23e4e7ffb7 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.67.0" # x-release-please-version +__version__ = "1.68.0" # x-release-please-version From 916641e801d2b0bf0ec7a6ea1d171c2a1931fdef Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 20 Mar 2025 17:58:42 +0000 Subject: [PATCH 737/816] fix(client): remove duplicate types (#2235) --- src/openai/types/shared/all_models.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/openai/types/shared/all_models.py b/src/openai/types/shared/all_models.py index c4635e2140..db8410773e 100644 --- a/src/openai/types/shared/all_models.py +++ b/src/openai/types/shared/all_models.py @@ -8,9 +8,5 @@ __all__ = ["AllModels"] AllModels: TypeAlias = Union[ - str, - ChatModel, - str, - ChatModel, - Literal["o1-pro", "o1-pro-2025-03-19", "computer-use-preview", "computer-use-preview-2025-03-11"], + str, ChatModel, Literal["o1-pro", "o1-pro-2025-03-19", "computer-use-preview", "computer-use-preview-2025-03-11"] ] From 35e0e11d85038d7c5350afe534e8c7f0f46b4f05 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 20 Mar 2025 18:06:44 -0400 Subject: [PATCH 738/816] codegen metadata --- .stats.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index abb9371314..2df281d34f 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,2 @@ configured_endpoints: 82 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-c22f59c66aec7914b6ee653d3098d1c1c8c16c180d2a158e819c8ddbf476f74b.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-5ad6884898c07591750dde560118baf7074a59aecd1f367f930c5e42b04e848a.yml From dbf975c84b02ffdd13de183f6af9a88890a367b3 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Fri, 21 Mar 2025 13:32:27 +0000 Subject: [PATCH 739/816] fix(package): make sounddevice and numpy optional dependencies --- pyproject.toml | 3 +-- src/openai/_extras/__init__.py | 1 + src/openai/_extras/numpy_proxy.py | 2 +- src/openai/_extras/sounddevice_proxy.py | 28 ++++++++++++++++++++++++ src/openai/helpers/local_audio_player.py | 13 ++++++----- src/openai/helpers/microphone.py | 12 +++++----- 6 files changed, 46 insertions(+), 13 deletions(-) create mode 100644 src/openai/_extras/sounddevice_proxy.py diff --git a/pyproject.toml b/pyproject.toml index 5ee7157038..f34bf6bfa3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -16,8 +16,6 @@ dependencies = [ "sniffio", "tqdm > 4", "jiter>=0.4.0, <1", - "sounddevice>=0.5.1", - "numpy>=2.0.2", ] requires-python = ">= 3.8" classifiers = [ @@ -47,6 +45,7 @@ openai = "openai.cli:main" [project.optional-dependencies] realtime = ["websockets >= 13, < 15"] datalib = ["numpy >= 1", "pandas >= 1.2.3", "pandas-stubs >= 1.1.0.11"] +audio = ["sounddevice>=0.5.1", "numpy>=2.0.2"] [tool.rye] managed = true diff --git a/src/openai/_extras/__init__.py b/src/openai/_extras/__init__.py index 864dac4171..692de248c0 100644 --- a/src/openai/_extras/__init__.py +++ b/src/openai/_extras/__init__.py @@ -1,2 +1,3 @@ from .numpy_proxy import numpy as numpy, has_numpy as has_numpy from .pandas_proxy import pandas as pandas +from .sounddevice_proxy import sounddevice as sounddevice diff --git a/src/openai/_extras/numpy_proxy.py b/src/openai/_extras/numpy_proxy.py index 27880bf132..8412965e44 100644 --- a/src/openai/_extras/numpy_proxy.py +++ b/src/openai/_extras/numpy_proxy.py @@ -10,7 +10,7 @@ import numpy as numpy -NUMPY_INSTRUCTIONS = format_instructions(library="numpy", extra="datalib") +NUMPY_INSTRUCTIONS = format_instructions(library="numpy", extra="audio") class NumpyProxy(LazyProxy[Any]): diff --git a/src/openai/_extras/sounddevice_proxy.py b/src/openai/_extras/sounddevice_proxy.py new file mode 100644 index 0000000000..0894782bd5 --- /dev/null +++ b/src/openai/_extras/sounddevice_proxy.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any +from typing_extensions import override + +from .._utils import LazyProxy +from ._common import MissingDependencyError, format_instructions + +if TYPE_CHECKING: + import sounddevice as sounddevice # type: ignore + + +SOUNDDEVICE_INSTRUCTIONS = format_instructions(library="sounddevice", extra="audio") + + +class SounddeviceProxy(LazyProxy[Any]): + @override + def __load__(self) -> Any: + try: + import sounddevice # type: ignore + except ImportError as err: + raise MissingDependencyError(SOUNDDEVICE_INSTRUCTIONS) from err + + return sounddevice + + +if not TYPE_CHECKING: + sounddevice = SounddeviceProxy() diff --git a/src/openai/helpers/local_audio_player.py b/src/openai/helpers/local_audio_player.py index 46a16ce6bb..eed68aa21d 100644 --- a/src/openai/helpers/local_audio_player.py +++ b/src/openai/helpers/local_audio_player.py @@ -1,15 +1,18 @@ # mypy: ignore-errors +from __future__ import annotations + import queue import asyncio from typing import Any, Union, Callable, AsyncGenerator, cast - -import numpy as np -import sounddevice as sd # type: ignore -import numpy.typing as npt +from typing_extensions import TYPE_CHECKING from .. import _legacy_response +from .._extras import numpy as np, sounddevice as sd from .._response import StreamedBinaryAPIResponse, AsyncStreamedBinaryAPIResponse +if TYPE_CHECKING: + import numpy.typing as npt + SAMPLE_RATE = 24000 @@ -62,7 +65,7 @@ async def play( if input.dtype == np.int16 and self.dtype == np.float32: audio_content = (input.astype(np.float32) / 32767.0).reshape(-1, self.channels) elif input.dtype == np.float32: - audio_content = cast(npt.NDArray[np.float32], input) + audio_content = cast('npt.NDArray[np.float32]', input) else: raise ValueError(f"Unsupported dtype: {input.dtype}") else: diff --git a/src/openai/helpers/microphone.py b/src/openai/helpers/microphone.py index 18650909aa..62a6d8d8a9 100644 --- a/src/openai/helpers/microphone.py +++ b/src/openai/helpers/microphone.py @@ -1,16 +1,18 @@ # mypy: ignore-errors +from __future__ import annotations + import io import time import wave import asyncio from typing import Any, Type, Union, Generic, TypeVar, Callable, overload -from typing_extensions import Literal +from typing_extensions import TYPE_CHECKING, Literal -import numpy as np -import sounddevice as sd # type: ignore -import numpy.typing as npt +from .._types import FileTypes, FileContent +from .._extras import numpy as np, sounddevice as sd -from openai._types import FileTypes, FileContent +if TYPE_CHECKING: + import numpy.typing as npt SAMPLE_RATE = 24000 From 751d739eb3dd6c759537c809d61e789f57bef4bf Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Fri, 21 Mar 2025 13:33:45 +0000 Subject: [PATCH 740/816] chore(ci): run workflows on next too --- .github/workflows/ci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 06eb10c5f0..d86fc0ea53 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,6 +6,7 @@ on: pull_request: branches: - main + - next jobs: lint: From 044f192e41831f4b01fe47944a2248a554cfdd34 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Fri, 21 Mar 2025 13:41:53 +0000 Subject: [PATCH 741/816] fix(helpers/audio): remove duplicative module --- src/openai/helpers.py | 4 ---- 1 file changed, 4 deletions(-) delete mode 100644 src/openai/helpers.py diff --git a/src/openai/helpers.py b/src/openai/helpers.py deleted file mode 100644 index 1a10168a96..0000000000 --- a/src/openai/helpers.py +++ /dev/null @@ -1,4 +0,0 @@ -from .helpers.microphone import Microphone -from .helpers.local_audio_player import LocalAudioPlayer - -__all__ = ["LocalAudioPlayer", "Microphone"] From d55062a3c474dfa2aa5964e997304aac080a4dd1 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 21 Mar 2025 13:42:29 +0000 Subject: [PATCH 742/816] release: 1.68.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 15 +++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 18 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 42bc7e250e..2ec6ee54df 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.68.0" + ".": "1.68.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 78ae21f27f..d26a769784 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## 1.68.1 (2025-03-21) + +Full Changelog: [v1.68.0...v1.68.1](https://github.com/openai/openai-python/compare/v1.68.0...v1.68.1) + +### Bug Fixes + +* **client:** remove duplicate types ([#2235](https://github.com/openai/openai-python/issues/2235)) ([063f7d0](https://github.com/openai/openai-python/commit/063f7d0684c350ca9d766e2cb150233a22a623c8)) +* **helpers/audio:** remove duplicative module ([f253d04](https://github.com/openai/openai-python/commit/f253d0415145f2c4904ea2e7b389d31d94e45a54)) +* **package:** make sounddevice and numpy optional dependencies ([8b04453](https://github.com/openai/openai-python/commit/8b04453f0483736c13f0209a9f8f3618bc0e86c9)) + + +### Chores + +* **ci:** run workflows on next too ([67f89d4](https://github.com/openai/openai-python/commit/67f89d478aab780d1481c9bf6682c6633e431137)) + ## 1.68.0 (2025-03-20) Full Changelog: [v1.67.0...v1.68.0](https://github.com/openai/openai-python/compare/v1.67.0...v1.68.0) diff --git a/pyproject.toml b/pyproject.toml index f34bf6bfa3..57871a46fe 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.68.0" +version = "1.68.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 23e4e7ffb7..1f00359eb1 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.68.0" # x-release-please-version +__version__ = "1.68.1" # x-release-please-version From 257152bb1bbbce965ef37b9d349a0027742525f5 Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Fri, 21 Mar 2025 14:41:50 +0000 Subject: [PATCH 743/816] refactor(package): rename audio extra to voice_helpers --- pyproject.toml | 2 +- src/openai/_extras/numpy_proxy.py | 2 +- src/openai/_extras/sounddevice_proxy.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 57871a46fe..e40060400a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -45,7 +45,7 @@ openai = "openai.cli:main" [project.optional-dependencies] realtime = ["websockets >= 13, < 15"] datalib = ["numpy >= 1", "pandas >= 1.2.3", "pandas-stubs >= 1.1.0.11"] -audio = ["sounddevice>=0.5.1", "numpy>=2.0.2"] +voice_helpers = ["sounddevice>=0.5.1", "numpy>=2.0.2"] [tool.rye] managed = true diff --git a/src/openai/_extras/numpy_proxy.py b/src/openai/_extras/numpy_proxy.py index 8412965e44..2b0669576e 100644 --- a/src/openai/_extras/numpy_proxy.py +++ b/src/openai/_extras/numpy_proxy.py @@ -10,7 +10,7 @@ import numpy as numpy -NUMPY_INSTRUCTIONS = format_instructions(library="numpy", extra="audio") +NUMPY_INSTRUCTIONS = format_instructions(library="numpy", extra="voice_helpers") class NumpyProxy(LazyProxy[Any]): diff --git a/src/openai/_extras/sounddevice_proxy.py b/src/openai/_extras/sounddevice_proxy.py index 0894782bd5..482d4c6874 100644 --- a/src/openai/_extras/sounddevice_proxy.py +++ b/src/openai/_extras/sounddevice_proxy.py @@ -10,7 +10,7 @@ import sounddevice as sounddevice # type: ignore -SOUNDDEVICE_INSTRUCTIONS = format_instructions(library="sounddevice", extra="audio") +SOUNDDEVICE_INSTRUCTIONS = format_instructions(library="sounddevice", extra="voice_helpers") class SounddeviceProxy(LazyProxy[Any]): From f66d2e6fdc51c4528c99bb25a8fbca6f9b9b872d Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 21 Mar 2025 14:42:25 +0000 Subject: [PATCH 744/816] release: 1.68.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 2ec6ee54df..e280020f03 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.68.1" + ".": "1.68.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index d26a769784..ee22cfe7fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.68.2 (2025-03-21) + +Full Changelog: [v1.68.1...v1.68.2](https://github.com/openai/openai-python/compare/v1.68.1...v1.68.2) + +### Refactors + +* **package:** rename audio extra to voice_helpers ([2dd6cb8](https://github.com/openai/openai-python/commit/2dd6cb87489fe12c5e45128f44d985c3f49aba1d)) + ## 1.68.1 (2025-03-21) Full Changelog: [v1.68.0...v1.68.1](https://github.com/openai/openai-python/compare/v1.68.0...v1.68.1) diff --git a/pyproject.toml b/pyproject.toml index e40060400a..b1917922cd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.68.1" +version = "1.68.2" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 1f00359eb1..a29ce4e818 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.68.1" # x-release-please-version +__version__ = "1.68.2" # x-release-please-version From 2706bdd779d3fca61b68ebd956ecd8eb1db421ae Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 26 Mar 2025 16:35:37 +0000 Subject: [PATCH 745/816] chore: fix typos (#2259) --- src/openai/_models.py | 2 +- src/openai/_utils/_transform.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/openai/_models.py b/src/openai/_models.py index ff7c1f3392..fc4f201e4e 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -721,7 +721,7 @@ def add_request_id(obj: BaseModel, request_id: str | None) -> None: cast(Any, obj).__exclude_fields__ = {*(exclude_fields or {}), "_request_id", "__exclude_fields__"} -# our use of subclasssing here causes weirdness for type checkers, +# our use of subclassing here causes weirdness for type checkers, # so we just pretend that we don't subclass if TYPE_CHECKING: GenericModel = BaseModel diff --git a/src/openai/_utils/_transform.py b/src/openai/_utils/_transform.py index 18afd9d8bd..7ac2e17fbb 100644 --- a/src/openai/_utils/_transform.py +++ b/src/openai/_utils/_transform.py @@ -126,7 +126,7 @@ def _get_annotated_type(type_: type) -> type | None: def _maybe_transform_key(key: str, type_: type) -> str: """Transform the given `data` based on the annotations provided in `type_`. - Note: this function only looks at `Annotated` types that contain `PropertInfo` metadata. + Note: this function only looks at `Annotated` types that contain `PropertyInfo` metadata. """ annotated_type = _get_annotated_type(type_) if annotated_type is None: From a4b9f4075ebcf54a97489bc55995e308ccb62a1b Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 26 Mar 2025 17:32:51 +0000 Subject: [PATCH 746/816] chore: add hash of OpenAPI spec/config inputs to .stats.yml --- .stats.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.stats.yml b/.stats.yml index 2df281d34f..fe93204292 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,2 +1,4 @@ configured_endpoints: 82 openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-5ad6884898c07591750dde560118baf7074a59aecd1f367f930c5e42b04e848a.yml +openapi_spec_hash: 0c255269b89767eae26f4d4dc22d3cbd +config_hash: d36e491b0afc4f79e3afad4b3c9bec70 From 2e73b5291ba6256714daea346c935dd01dbb6bb2 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 26 Mar 2025 20:32:36 +0000 Subject: [PATCH 747/816] chore(api): updates to supported Voice IDs (#2261) --- .stats.yml | 4 ++-- src/openai/resources/audio/speech.py | 16 ++++++++----- .../resources/beta/realtime/sessions.py | 16 +++++++++---- src/openai/resources/responses/input_items.py | 13 +++++++++- src/openai/resources/responses/responses.py | 24 +++++++++---------- .../types/audio/speech_create_params.py | 11 ++++++--- .../types/beta/realtime/realtime_response.py | 9 +++++-- .../beta/realtime/response_create_event.py | 8 +++++-- .../realtime/response_create_event_param.py | 6 +++-- src/openai/types/beta/realtime/session.py | 6 ++++- .../beta/realtime/session_create_params.py | 6 +++-- .../beta/realtime/session_create_response.py | 6 ++++- .../beta/realtime/session_update_event.py | 8 +++++-- .../realtime/session_update_event_param.py | 6 +++-- .../transcription_session_create_params.py | 7 +++--- .../realtime/transcription_session_update.py | 7 +++--- .../transcription_session_update_param.py | 7 +++--- .../types/chat/chat_completion_audio_param.py | 7 +++++- .../types/responses/input_item_list_params.py | 9 +++++++ src/openai/types/responses/response.py | 4 ++-- .../types/responses/response_create_params.py | 4 ++-- ...response_format_text_json_schema_config.py | 14 +++++------ ...se_format_text_json_schema_config_param.py | 14 +++++------ tests/api_resources/audio/test_speech.py | 16 ++++++------- .../beta/realtime/test_sessions.py | 4 ++-- tests/api_resources/chat/test_completions.py | 8 +++---- .../responses/test_input_items.py | 2 ++ 27 files changed, 158 insertions(+), 84 deletions(-) diff --git a/.stats.yml b/.stats.yml index fe93204292..4d1276a5e6 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 82 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-5ad6884898c07591750dde560118baf7074a59aecd1f367f930c5e42b04e848a.yml -openapi_spec_hash: 0c255269b89767eae26f4d4dc22d3cbd +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-6663c59193eb95b201e492de17dcbd5e126ba03d18ce66287a3e2c632ca56fe7.yml +openapi_spec_hash: 7996d2c34cc44fe2ce9ffe93c0ab774e config_hash: d36e491b0afc4f79e3afad4b3c9bec70 diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index 529e3a47ea..1ee53db9d5 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -53,7 +53,9 @@ def create( *, input: str, model: Union[str, SpeechModel], - voice: Literal["alloy", "ash", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer"], + voice: Union[ + str, Literal["alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer", "verse"] + ], instructions: str | NotGiven = NOT_GIVEN, response_format: Literal["mp3", "opus", "aac", "flac", "wav", "pcm"] | NotGiven = NOT_GIVEN, speed: float | NotGiven = NOT_GIVEN, @@ -75,8 +77,8 @@ def create( `tts-1`, `tts-1-hd` or `gpt-4o-mini-tts`. voice: The voice to use when generating the audio. Supported voices are `alloy`, `ash`, - `coral`, `echo`, `fable`, `onyx`, `nova`, `sage` and `shimmer`. Previews of the - voices are available in the + `ballad`, `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`, `shimmer`, and + `verse`. Previews of the voices are available in the [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech#voice-options). instructions: Control the voice of your generated audio with additional instructions. Does not @@ -142,7 +144,9 @@ async def create( *, input: str, model: Union[str, SpeechModel], - voice: Literal["alloy", "ash", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer"], + voice: Union[ + str, Literal["alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer", "verse"] + ], instructions: str | NotGiven = NOT_GIVEN, response_format: Literal["mp3", "opus", "aac", "flac", "wav", "pcm"] | NotGiven = NOT_GIVEN, speed: float | NotGiven = NOT_GIVEN, @@ -164,8 +168,8 @@ async def create( `tts-1`, `tts-1-hd` or `gpt-4o-mini-tts`. voice: The voice to use when generating the audio. Supported voices are `alloy`, `ash`, - `coral`, `echo`, `fable`, `onyx`, `nova`, `sage` and `shimmer`. Previews of the - voices are available in the + `ballad`, `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`, `shimmer`, and + `verse`. Previews of the voices are available in the [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech#voice-options). instructions: Control the voice of your generated audio with additional instructions. Does not diff --git a/src/openai/resources/beta/realtime/sessions.py b/src/openai/resources/beta/realtime/sessions.py index 5884e54de2..3e1c956fe4 100644 --- a/src/openai/resources/beta/realtime/sessions.py +++ b/src/openai/resources/beta/realtime/sessions.py @@ -65,7 +65,10 @@ def create( tool_choice: str | NotGiven = NOT_GIVEN, tools: Iterable[session_create_params.Tool] | NotGiven = NOT_GIVEN, turn_detection: session_create_params.TurnDetection | NotGiven = NOT_GIVEN, - voice: Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"] | NotGiven = NOT_GIVEN, + voice: Union[ + str, Literal["alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer", "verse"] + ] + | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -147,7 +150,8 @@ def create( voice: The voice the model uses to respond. Voice cannot be changed during the session once the model has responded with audio at least once. Current voice options are - `alloy`, `ash`, `ballad`, `coral`, `echo` `sage`, `shimmer` and `verse`. + `alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`, + `shimmer`, and `verse`. extra_headers: Send extra headers @@ -227,7 +231,10 @@ async def create( tool_choice: str | NotGiven = NOT_GIVEN, tools: Iterable[session_create_params.Tool] | NotGiven = NOT_GIVEN, turn_detection: session_create_params.TurnDetection | NotGiven = NOT_GIVEN, - voice: Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"] | NotGiven = NOT_GIVEN, + voice: Union[ + str, Literal["alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer", "verse"] + ] + | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -309,7 +316,8 @@ async def create( voice: The voice the model uses to respond. Voice cannot be changed during the session once the model has responded with audio at least once. Current voice options are - `alloy`, `ash`, `ballad`, `coral`, `echo` `sage`, `shimmer` and `verse`. + `alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`, + `shimmer`, and `verse`. extra_headers: Send extra headers diff --git a/src/openai/resources/responses/input_items.py b/src/openai/resources/responses/input_items.py index e341393cd1..ee0e628169 100644 --- a/src/openai/resources/responses/input_items.py +++ b/src/openai/resources/responses/input_items.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Any, cast +from typing import Any, List, cast from typing_extensions import Literal import httpx @@ -17,6 +17,7 @@ from ..._base_client import AsyncPaginator, make_request_options from ...types.responses import input_item_list_params from ...types.responses.response_item import ResponseItem +from ...types.responses.response_includable import ResponseIncludable __all__ = ["InputItems", "AsyncInputItems"] @@ -47,6 +48,7 @@ def list( *, after: str | NotGiven = NOT_GIVEN, before: str | NotGiven = NOT_GIVEN, + include: List[ResponseIncludable] | NotGiven = NOT_GIVEN, limit: int | NotGiven = NOT_GIVEN, order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -64,6 +66,9 @@ def list( before: An item ID to list items before, used in pagination. + include: Additional fields to include in the response. See the `include` parameter for + Response creation above for more information. + limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. @@ -94,6 +99,7 @@ def list( { "after": after, "before": before, + "include": include, "limit": limit, "order": order, }, @@ -130,6 +136,7 @@ def list( *, after: str | NotGiven = NOT_GIVEN, before: str | NotGiven = NOT_GIVEN, + include: List[ResponseIncludable] | NotGiven = NOT_GIVEN, limit: int | NotGiven = NOT_GIVEN, order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -147,6 +154,9 @@ def list( before: An item ID to list items before, used in pagination. + include: Additional fields to include in the response. See the `include` parameter for + Response creation above for more information. + limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. @@ -177,6 +187,7 @@ def list( { "after": after, "before": before, + "include": include, "limit": limit, "order": order, }, diff --git a/src/openai/resources/responses/responses.py b/src/openai/resources/responses/responses.py index 668f4db80a..29ed3de42a 100644 --- a/src/openai/resources/responses/responses.py +++ b/src/openai/resources/responses/responses.py @@ -149,8 +149,8 @@ def create( context. When using along with `previous_response_id`, the instructions from a previous - response will be not be carried over to the next response. This makes it simple - to swap out system (or developer) messages in new responses. + response will not be carried over to the next response. This makes it simple to + swap out system (or developer) messages in new responses. max_output_tokens: An upper bound for the number of tokens that can be generated for a response, including visible output tokens and @@ -321,8 +321,8 @@ def create( context. When using along with `previous_response_id`, the instructions from a previous - response will be not be carried over to the next response. This makes it simple - to swap out system (or developer) messages in new responses. + response will not be carried over to the next response. This makes it simple to + swap out system (or developer) messages in new responses. max_output_tokens: An upper bound for the number of tokens that can be generated for a response, including visible output tokens and @@ -486,8 +486,8 @@ def create( context. When using along with `previous_response_id`, the instructions from a previous - response will be not be carried over to the next response. This makes it simple - to swap out system (or developer) messages in new responses. + response will not be carried over to the next response. This makes it simple to + swap out system (or developer) messages in new responses. max_output_tokens: An upper bound for the number of tokens that can be generated for a response, including visible output tokens and @@ -961,8 +961,8 @@ async def create( context. When using along with `previous_response_id`, the instructions from a previous - response will be not be carried over to the next response. This makes it simple - to swap out system (or developer) messages in new responses. + response will not be carried over to the next response. This makes it simple to + swap out system (or developer) messages in new responses. max_output_tokens: An upper bound for the number of tokens that can be generated for a response, including visible output tokens and @@ -1133,8 +1133,8 @@ async def create( context. When using along with `previous_response_id`, the instructions from a previous - response will be not be carried over to the next response. This makes it simple - to swap out system (or developer) messages in new responses. + response will not be carried over to the next response. This makes it simple to + swap out system (or developer) messages in new responses. max_output_tokens: An upper bound for the number of tokens that can be generated for a response, including visible output tokens and @@ -1298,8 +1298,8 @@ async def create( context. When using along with `previous_response_id`, the instructions from a previous - response will be not be carried over to the next response. This makes it simple - to swap out system (or developer) messages in new responses. + response will not be carried over to the next response. This makes it simple to + swap out system (or developer) messages in new responses. max_output_tokens: An upper bound for the number of tokens that can be generated for a response, including visible output tokens and diff --git a/src/openai/types/audio/speech_create_params.py b/src/openai/types/audio/speech_create_params.py index 958680710b..a4fc020532 100644 --- a/src/openai/types/audio/speech_create_params.py +++ b/src/openai/types/audio/speech_create_params.py @@ -20,11 +20,16 @@ class SpeechCreateParams(TypedDict, total=False): `tts-1`, `tts-1-hd` or `gpt-4o-mini-tts`. """ - voice: Required[Literal["alloy", "ash", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer"]] + voice: Required[ + Union[ + str, Literal["alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer", "verse"] + ] + ] """The voice to use when generating the audio. - Supported voices are `alloy`, `ash`, `coral`, `echo`, `fable`, `onyx`, `nova`, - `sage` and `shimmer`. Previews of the voices are available in the + Supported voices are `alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `onyx`, + `nova`, `sage`, `shimmer`, and `verse`. Previews of the voices are available in + the [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech#voice-options). """ diff --git a/src/openai/types/beta/realtime/realtime_response.py b/src/openai/types/beta/realtime/realtime_response.py index 4c3c83d666..8ecfb91c31 100644 --- a/src/openai/types/beta/realtime/realtime_response.py +++ b/src/openai/types/beta/realtime/realtime_response.py @@ -80,8 +80,13 @@ class RealtimeResponse(BaseModel): will become the input for later turns. """ - voice: Optional[Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"]] = None + voice: Union[ + str, + Literal["alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer", "verse"], + None, + ] = None """ The voice the model used to respond. Current voice options are `alloy`, `ash`, - `ballad`, `coral`, `echo` `sage`, `shimmer` and `verse`. + `ballad`, `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`, `shimmer`, and + `verse`. """ diff --git a/src/openai/types/beta/realtime/response_create_event.py b/src/openai/types/beta/realtime/response_create_event.py index d6c5fda926..3b8a6de8df 100644 --- a/src/openai/types/beta/realtime/response_create_event.py +++ b/src/openai/types/beta/realtime/response_create_event.py @@ -101,12 +101,16 @@ class Response(BaseModel): tools: Optional[List[ResponseTool]] = None """Tools (functions) available to the model.""" - voice: Optional[Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"]] = None + voice: Union[ + str, + Literal["alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer", "verse"], + None, + ] = None """The voice the model uses to respond. Voice cannot be changed during the session once the model has responded with audio at least once. Current voice options are `alloy`, `ash`, `ballad`, - `coral`, `echo` `sage`, `shimmer` and `verse`. + `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`, `shimmer`, and `verse`. """ diff --git a/src/openai/types/beta/realtime/response_create_event_param.py b/src/openai/types/beta/realtime/response_create_event_param.py index c02fe1b34e..c569d507a0 100644 --- a/src/openai/types/beta/realtime/response_create_event_param.py +++ b/src/openai/types/beta/realtime/response_create_event_param.py @@ -102,12 +102,14 @@ class Response(TypedDict, total=False): tools: Iterable[ResponseTool] """Tools (functions) available to the model.""" - voice: Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"] + voice: Union[ + str, Literal["alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer", "verse"] + ] """The voice the model uses to respond. Voice cannot be changed during the session once the model has responded with audio at least once. Current voice options are `alloy`, `ash`, `ballad`, - `coral`, `echo` `sage`, `shimmer` and `verse`. + `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`, `shimmer`, and `verse`. """ diff --git a/src/openai/types/beta/realtime/session.py b/src/openai/types/beta/realtime/session.py index 3ed53ff5f8..6acde57f09 100644 --- a/src/openai/types/beta/realtime/session.py +++ b/src/openai/types/beta/realtime/session.py @@ -218,7 +218,11 @@ class Session(BaseModel): natural conversations, but may have a higher latency. """ - voice: Optional[Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"]] = None + voice: Union[ + str, + Literal["alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer", "verse"], + None, + ] = None """The voice the model uses to respond. Voice cannot be changed during the session once the model has responded with diff --git a/src/openai/types/beta/realtime/session_create_params.py b/src/openai/types/beta/realtime/session_create_params.py index fe4a1c8636..eadee29b28 100644 --- a/src/openai/types/beta/realtime/session_create_params.py +++ b/src/openai/types/beta/realtime/session_create_params.py @@ -113,12 +113,14 @@ class SessionCreateParams(TypedDict, total=False): natural conversations, but may have a higher latency. """ - voice: Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"] + voice: Union[ + str, Literal["alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer", "verse"] + ] """The voice the model uses to respond. Voice cannot be changed during the session once the model has responded with audio at least once. Current voice options are `alloy`, `ash`, `ballad`, - `coral`, `echo` `sage`, `shimmer` and `verse`. + `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`, `shimmer`, and `verse`. """ diff --git a/src/openai/types/beta/realtime/session_create_response.py b/src/openai/types/beta/realtime/session_create_response.py index c26e62bef1..3cc8ca15ce 100644 --- a/src/openai/types/beta/realtime/session_create_response.py +++ b/src/openai/types/beta/realtime/session_create_response.py @@ -141,7 +141,11 @@ class SessionCreateResponse(BaseModel): speech. """ - voice: Optional[Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"]] = None + voice: Union[ + str, + Literal["alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer", "verse"], + None, + ] = None """The voice the model uses to respond. Voice cannot be changed during the session once the model has responded with diff --git a/src/openai/types/beta/realtime/session_update_event.py b/src/openai/types/beta/realtime/session_update_event.py index 00180f593d..ba34b0260b 100644 --- a/src/openai/types/beta/realtime/session_update_event.py +++ b/src/openai/types/beta/realtime/session_update_event.py @@ -222,12 +222,16 @@ class Session(BaseModel): natural conversations, but may have a higher latency. """ - voice: Optional[Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"]] = None + voice: Union[ + str, + Literal["alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer", "verse"], + None, + ] = None """The voice the model uses to respond. Voice cannot be changed during the session once the model has responded with audio at least once. Current voice options are `alloy`, `ash`, `ballad`, - `coral`, `echo` `sage`, `shimmer` and `verse`. + `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`, `shimmer`, and `verse`. """ diff --git a/src/openai/types/beta/realtime/session_update_event_param.py b/src/openai/types/beta/realtime/session_update_event_param.py index b8bce8fbd0..0984d39e91 100644 --- a/src/openai/types/beta/realtime/session_update_event_param.py +++ b/src/openai/types/beta/realtime/session_update_event_param.py @@ -220,12 +220,14 @@ class Session(TypedDict, total=False): natural conversations, but may have a higher latency. """ - voice: Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"] + voice: Union[ + str, Literal["alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer", "verse"] + ] """The voice the model uses to respond. Voice cannot be changed during the session once the model has responded with audio at least once. Current voice options are `alloy`, `ash`, `ballad`, - `coral`, `echo` `sage`, `shimmer` and `verse`. + `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`, `shimmer`, and `verse`. """ diff --git a/src/openai/types/beta/realtime/transcription_session_create_params.py b/src/openai/types/beta/realtime/transcription_session_create_params.py index 4066dc4c5d..1cf511f0b5 100644 --- a/src/openai/types/beta/realtime/transcription_session_create_params.py +++ b/src/openai/types/beta/realtime/transcription_session_create_params.py @@ -96,9 +96,10 @@ class InputAudioTranscription(TypedDict, total=False): class TurnDetection(TypedDict, total=False): create_response: bool - """ - Whether or not to automatically generate a response when a VAD stop event + """Whether or not to automatically generate a response when a VAD stop event occurs. + + Not available for transcription sessions. """ eagerness: Literal["low", "medium", "high", "auto"] @@ -113,7 +114,7 @@ class TurnDetection(TypedDict, total=False): """ Whether or not to automatically interrupt any ongoing response with output to the default conversation (i.e. `conversation` of `auto`) when a VAD start event - occurs. + occurs. Not available for transcription sessions. """ prefix_padding_ms: int diff --git a/src/openai/types/beta/realtime/transcription_session_update.py b/src/openai/types/beta/realtime/transcription_session_update.py index 043ac02e07..c3e8f011c8 100644 --- a/src/openai/types/beta/realtime/transcription_session_update.py +++ b/src/openai/types/beta/realtime/transcription_session_update.py @@ -50,9 +50,10 @@ class SessionInputAudioTranscription(BaseModel): class SessionTurnDetection(BaseModel): create_response: Optional[bool] = None - """ - Whether or not to automatically generate a response when a VAD stop event + """Whether or not to automatically generate a response when a VAD stop event occurs. + + Not available for transcription sessions. """ eagerness: Optional[Literal["low", "medium", "high", "auto"]] = None @@ -67,7 +68,7 @@ class SessionTurnDetection(BaseModel): """ Whether or not to automatically interrupt any ongoing response with output to the default conversation (i.e. `conversation` of `auto`) when a VAD start event - occurs. + occurs. Not available for transcription sessions. """ prefix_padding_ms: Optional[int] = None diff --git a/src/openai/types/beta/realtime/transcription_session_update_param.py b/src/openai/types/beta/realtime/transcription_session_update_param.py index 997a36d77b..549c49011b 100644 --- a/src/openai/types/beta/realtime/transcription_session_update_param.py +++ b/src/openai/types/beta/realtime/transcription_session_update_param.py @@ -50,9 +50,10 @@ class SessionInputAudioTranscription(TypedDict, total=False): class SessionTurnDetection(TypedDict, total=False): create_response: bool - """ - Whether or not to automatically generate a response when a VAD stop event + """Whether or not to automatically generate a response when a VAD stop event occurs. + + Not available for transcription sessions. """ eagerness: Literal["low", "medium", "high", "auto"] @@ -67,7 +68,7 @@ class SessionTurnDetection(TypedDict, total=False): """ Whether or not to automatically interrupt any ongoing response with output to the default conversation (i.e. `conversation` of `auto`) when a VAD start event - occurs. + occurs. Not available for transcription sessions. """ prefix_padding_ms: int diff --git a/src/openai/types/chat/chat_completion_audio_param.py b/src/openai/types/chat/chat_completion_audio_param.py index 6321417826..b902f2667f 100644 --- a/src/openai/types/chat/chat_completion_audio_param.py +++ b/src/openai/types/chat/chat_completion_audio_param.py @@ -2,6 +2,7 @@ from __future__ import annotations +from typing import Union from typing_extensions import Literal, Required, TypedDict __all__ = ["ChatCompletionAudioParam"] @@ -14,7 +15,11 @@ class ChatCompletionAudioParam(TypedDict, total=False): Must be one of `wav`, `mp3`, `flac`, `opus`, or `pcm16`. """ - voice: Required[Literal["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"]] + voice: Required[ + Union[ + str, Literal["alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer", "verse"] + ] + ] """The voice the model uses to respond. Supported voices are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, and diff --git a/src/openai/types/responses/input_item_list_params.py b/src/openai/types/responses/input_item_list_params.py index e0b71f1ac5..6555d26788 100644 --- a/src/openai/types/responses/input_item_list_params.py +++ b/src/openai/types/responses/input_item_list_params.py @@ -2,8 +2,11 @@ from __future__ import annotations +from typing import List from typing_extensions import Literal, TypedDict +from .response_includable import ResponseIncludable + __all__ = ["InputItemListParams"] @@ -14,6 +17,12 @@ class InputItemListParams(TypedDict, total=False): before: str """An item ID to list items before, used in pagination.""" + include: List[ResponseIncludable] + """Additional fields to include in the response. + + See the `include` parameter for Response creation above for more information. + """ + limit: int """A limit on the number of objects to be returned. diff --git a/src/openai/types/responses/response.py b/src/openai/types/responses/response.py index 1bedf80889..8cd1e01144 100644 --- a/src/openai/types/responses/response.py +++ b/src/openai/types/responses/response.py @@ -47,8 +47,8 @@ class Response(BaseModel): context. When using along with `previous_response_id`, the instructions from a previous - response will be not be carried over to the next response. This makes it simple - to swap out system (or developer) messages in new responses. + response will not be carried over to the next response. This makes it simple to + swap out system (or developer) messages in new responses. """ metadata: Optional[Metadata] = None diff --git a/src/openai/types/responses/response_create_params.py b/src/openai/types/responses/response_create_params.py index 651050c50d..ed82e678e5 100644 --- a/src/openai/types/responses/response_create_params.py +++ b/src/openai/types/responses/response_create_params.py @@ -64,8 +64,8 @@ class ResponseCreateParamsBase(TypedDict, total=False): context. When using along with `previous_response_id`, the instructions from a previous - response will be not be carried over to the next response. This makes it simple - to swap out system (or developer) messages in new responses. + response will not be carried over to the next response. This makes it simple to + swap out system (or developer) messages in new responses. """ max_output_tokens: Optional[int] diff --git a/src/openai/types/responses/response_format_text_json_schema_config.py b/src/openai/types/responses/response_format_text_json_schema_config.py index 3cf066370f..001fcf5bab 100644 --- a/src/openai/types/responses/response_format_text_json_schema_config.py +++ b/src/openai/types/responses/response_format_text_json_schema_config.py @@ -11,6 +11,13 @@ class ResponseFormatTextJSONSchemaConfig(BaseModel): + name: str + """The name of the response format. + + Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length + of 64. + """ + schema_: Dict[str, object] = FieldInfo(alias="schema") """ The schema for the response format, described as a JSON Schema object. Learn how @@ -26,13 +33,6 @@ class ResponseFormatTextJSONSchemaConfig(BaseModel): how to respond in the format. """ - name: Optional[str] = None - """The name of the response format. - - Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length - of 64. - """ - strict: Optional[bool] = None """ Whether to enable strict schema adherence when generating the output. If set to diff --git a/src/openai/types/responses/response_format_text_json_schema_config_param.py b/src/openai/types/responses/response_format_text_json_schema_config_param.py index 211c5d1eff..f293a80c5a 100644 --- a/src/openai/types/responses/response_format_text_json_schema_config_param.py +++ b/src/openai/types/responses/response_format_text_json_schema_config_param.py @@ -9,6 +9,13 @@ class ResponseFormatTextJSONSchemaConfigParam(TypedDict, total=False): + name: Required[str] + """The name of the response format. + + Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length + of 64. + """ + schema: Required[Dict[str, object]] """ The schema for the response format, described as a JSON Schema object. Learn how @@ -24,13 +31,6 @@ class ResponseFormatTextJSONSchemaConfigParam(TypedDict, total=False): how to respond in the format. """ - name: str - """The name of the response format. - - Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length - of 64. - """ - strict: Optional[bool] """ Whether to enable strict schema adherence when generating the output. If set to diff --git a/tests/api_resources/audio/test_speech.py b/tests/api_resources/audio/test_speech.py index 808f6ef66c..ce9ed59ce3 100644 --- a/tests/api_resources/audio/test_speech.py +++ b/tests/api_resources/audio/test_speech.py @@ -28,7 +28,7 @@ def test_method_create(self, client: OpenAI, respx_mock: MockRouter) -> None: speech = client.audio.speech.create( input="string", model="string", - voice="alloy", + voice="ash", ) assert isinstance(speech, _legacy_response.HttpxBinaryResponseContent) assert speech.json() == {"foo": "bar"} @@ -40,7 +40,7 @@ def test_method_create_with_all_params(self, client: OpenAI, respx_mock: MockRou speech = client.audio.speech.create( input="string", model="string", - voice="alloy", + voice="ash", instructions="instructions", response_format="mp3", speed=0.25, @@ -56,7 +56,7 @@ def test_raw_response_create(self, client: OpenAI, respx_mock: MockRouter) -> No response = client.audio.speech.with_raw_response.create( input="string", model="string", - voice="alloy", + voice="ash", ) assert response.is_closed is True @@ -71,7 +71,7 @@ def test_streaming_response_create(self, client: OpenAI, respx_mock: MockRouter) with client.audio.speech.with_streaming_response.create( input="string", model="string", - voice="alloy", + voice="ash", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -92,7 +92,7 @@ async def test_method_create(self, async_client: AsyncOpenAI, respx_mock: MockRo speech = await async_client.audio.speech.create( input="string", model="string", - voice="alloy", + voice="ash", ) assert isinstance(speech, _legacy_response.HttpxBinaryResponseContent) assert speech.json() == {"foo": "bar"} @@ -104,7 +104,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI, re speech = await async_client.audio.speech.create( input="string", model="string", - voice="alloy", + voice="ash", instructions="instructions", response_format="mp3", speed=0.25, @@ -120,7 +120,7 @@ async def test_raw_response_create(self, async_client: AsyncOpenAI, respx_mock: response = await async_client.audio.speech.with_raw_response.create( input="string", model="string", - voice="alloy", + voice="ash", ) assert response.is_closed is True @@ -135,7 +135,7 @@ async def test_streaming_response_create(self, async_client: AsyncOpenAI, respx_ async with async_client.audio.speech.with_streaming_response.create( input="string", model="string", - voice="alloy", + voice="ash", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" diff --git a/tests/api_resources/beta/realtime/test_sessions.py b/tests/api_resources/beta/realtime/test_sessions.py index c0a426a417..f432b7d277 100644 --- a/tests/api_resources/beta/realtime/test_sessions.py +++ b/tests/api_resources/beta/realtime/test_sessions.py @@ -56,7 +56,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "threshold": 0, "type": "server_vad", }, - voice="alloy", + voice="ash", ) assert_matches_type(SessionCreateResponse, session, path=["response"]) @@ -123,7 +123,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "threshold": 0, "type": "server_vad", }, - voice="alloy", + voice="ash", ) assert_matches_type(SessionCreateResponse, session, path=["response"]) diff --git a/tests/api_resources/chat/test_completions.py b/tests/api_resources/chat/test_completions.py index d4ccc494dd..aaef82e8c5 100644 --- a/tests/api_resources/chat/test_completions.py +++ b/tests/api_resources/chat/test_completions.py @@ -48,7 +48,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: model="gpt-4o", audio={ "format": "wav", - "voice": "alloy", + "voice": "ash", }, frequency_penalty=-2, function_call="none", @@ -175,7 +175,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: stream=True, audio={ "format": "wav", - "voice": "alloy", + "voice": "ash", }, frequency_penalty=-2, function_call="none", @@ -475,7 +475,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn model="gpt-4o", audio={ "format": "wav", - "voice": "alloy", + "voice": "ash", }, frequency_penalty=-2, function_call="none", @@ -602,7 +602,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn stream=True, audio={ "format": "wav", - "voice": "alloy", + "voice": "ash", }, frequency_penalty=-2, function_call="none", diff --git a/tests/api_resources/responses/test_input_items.py b/tests/api_resources/responses/test_input_items.py index 77a156b5ac..2528943c06 100644 --- a/tests/api_resources/responses/test_input_items.py +++ b/tests/api_resources/responses/test_input_items.py @@ -31,6 +31,7 @@ def test_method_list_with_all_params(self, client: OpenAI) -> None: response_id="response_id", after="after", before="before", + include=["file_search_call.results"], limit=0, order="asc", ) @@ -84,6 +85,7 @@ async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> N response_id="response_id", after="after", before="before", + include=["file_search_call.results"], limit=0, order="asc", ) From 8677d3ca5350c7ad07a66dcde78152bccb1655c0 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 27 Mar 2025 16:07:22 +0000 Subject: [PATCH 748/816] feat(api): add `get /chat/completions` endpoint --- .stats.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index 4d1276a5e6..1e1104a062 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 82 openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-6663c59193eb95b201e492de17dcbd5e126ba03d18ce66287a3e2c632ca56fe7.yml openapi_spec_hash: 7996d2c34cc44fe2ce9ffe93c0ab774e -config_hash: d36e491b0afc4f79e3afad4b3c9bec70 +config_hash: 9351ea829c2b41da3b48a38c934c92ee From a6393219a6d4bd1fbcafdabfe757de093a87e2af Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Thu, 27 Mar 2025 17:21:23 +0000 Subject: [PATCH 749/816] fix(audio): correctly parse transcription stream events --- src/openai/_streaming.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/openai/_streaming.py b/src/openai/_streaming.py index 9cb72ffe17..641c3a7a72 100644 --- a/src/openai/_streaming.py +++ b/src/openai/_streaming.py @@ -59,7 +59,7 @@ def __stream__(self) -> Iterator[_T]: if sse.data.startswith("[DONE]"): break - if sse.event is None or sse.event.startswith("response."): + if sse.event is None or sse.event.startswith("response.") or sse.event.startswith('transcript.'): data = sse.json() if is_mapping(data) and data.get("error"): message = None @@ -161,7 +161,7 @@ async def __stream__(self) -> AsyncIterator[_T]: if sse.data.startswith("[DONE]"): break - if sse.event is None or sse.event.startswith("response."): + if sse.event is None or sse.event.startswith("response.") or sse.event.startswith('transcript.'): data = sse.json() if is_mapping(data) and data.get("error"): message = None From 46ed48e793ff9f5a088918ce9b1ad7bef13b9b37 Mon Sep 17 00:00:00 2001 From: Lucas Grzegorczyk Date: Thu, 27 Mar 2025 18:30:19 +0100 Subject: [PATCH 750/816] Remove stray responses.py.orig file (#2258) --- .../resources/responses/responses.py.orig | 1796 ----------------- 1 file changed, 1796 deletions(-) delete mode 100644 src/openai/resources/responses/responses.py.orig diff --git a/src/openai/resources/responses/responses.py.orig b/src/openai/resources/responses/responses.py.orig deleted file mode 100644 index dec4c19367..0000000000 --- a/src/openai/resources/responses/responses.py.orig +++ /dev/null @@ -1,1796 +0,0 @@ -# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -from __future__ import annotations - -from typing import Any, List, Type, Union, Iterable, Optional, cast -from functools import partial -from typing_extensions import Literal, overload - -import httpx - -from ... import _legacy_response -from ..._types import NOT_GIVEN, Body, Query, Headers, NoneType, NotGiven -from ..._utils import ( - is_given, - required_args, - maybe_transform, - async_maybe_transform, -) -from ..._compat import cached_property -from ..._resource import SyncAPIResource, AsyncAPIResource -from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper -from .input_items import ( - InputItems, - AsyncInputItems, - InputItemsWithRawResponse, - AsyncInputItemsWithRawResponse, - InputItemsWithStreamingResponse, - AsyncInputItemsWithStreamingResponse, -) -from ..._streaming import Stream, AsyncStream -from ...lib._tools import PydanticFunctionTool, ResponsesPydanticFunctionTool -from ..._base_client import make_request_options -from ...types.responses import response_create_params, response_retrieve_params -<<<<<<< HEAD -from ...lib._parsing._responses import ( - TextFormatT, - parse_response, - type_to_text_format_param as _type_to_text_format_param, -) -from ...types.shared.chat_model import ChatModel -||||||| parent of 001707b8 (feat(api): o1-pro now available through the API (#2228)) -from ...types.shared.chat_model import ChatModel -======= ->>>>>>> 001707b8 (feat(api): o1-pro now available through the API (#2228)) -from ...types.responses.response import Response -from ...types.responses.tool_param import ToolParam, ParseableToolParam -from ...types.shared_params.metadata import Metadata -from ...types.shared_params.reasoning import Reasoning -from ...types.responses.parsed_response import ParsedResponse -from ...lib.streaming.responses._responses import ResponseStreamManager, AsyncResponseStreamManager -from ...types.responses.response_includable import ResponseIncludable -from ...types.shared_params.responses_model import ResponsesModel -from ...types.responses.response_input_param import ResponseInputParam -from ...types.responses.response_stream_event import ResponseStreamEvent -from ...types.responses.response_text_config_param import ResponseTextConfigParam - -__all__ = ["Responses", "AsyncResponses"] - - -class Responses(SyncAPIResource): - @cached_property - def input_items(self) -> InputItems: - return InputItems(self._client) - - @cached_property - def with_raw_response(self) -> ResponsesWithRawResponse: - """ - This property can be used as a prefix for any HTTP method call to return - the raw response object instead of the parsed content. - - For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers - """ - return ResponsesWithRawResponse(self) - - @cached_property - def with_streaming_response(self) -> ResponsesWithStreamingResponse: - """ - An alternative to `.with_raw_response` that doesn't eagerly read the response body. - - For more information, see https://www.github.com/openai/openai-python#with_streaming_response - """ - return ResponsesWithStreamingResponse(self) - - @overload - def create( - self, - *, - input: Union[str, ResponseInputParam], - model: ResponsesModel, - include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, - instructions: Optional[str] | NotGiven = NOT_GIVEN, - max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, - previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, - reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, - store: Optional[bool] | NotGiven = NOT_GIVEN, - stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, - temperature: Optional[float] | NotGiven = NOT_GIVEN, - text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, - tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, - tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, - top_p: Optional[float] | NotGiven = NOT_GIVEN, - truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, - user: str | NotGiven = NOT_GIVEN, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> Response: - """Creates a model response. - - Provide - [text](https://platform.openai.com/docs/guides/text) or - [image](https://platform.openai.com/docs/guides/images) inputs to generate - [text](https://platform.openai.com/docs/guides/text) or - [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have - the model call your own - [custom code](https://platform.openai.com/docs/guides/function-calling) or use - built-in [tools](https://platform.openai.com/docs/guides/tools) like - [web search](https://platform.openai.com/docs/guides/tools-web-search) or - [file search](https://platform.openai.com/docs/guides/tools-file-search) to use - your own data as input for the model's response. - - Args: - input: Text, image, or file inputs to the model, used to generate a response. - - Learn more: - - - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) - - [Image inputs](https://platform.openai.com/docs/guides/images) - - [File inputs](https://platform.openai.com/docs/guides/pdf-files) - - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) - - [Function calling](https://platform.openai.com/docs/guides/function-calling) - - model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a - wide range of models with different capabilities, performance characteristics, - and price points. Refer to the - [model guide](https://platform.openai.com/docs/models) to browse and compare - available models. - - include: Specify additional output data to include in the model response. Currently - supported values are: - - - `file_search_call.results`: Include the search results of the file search tool - call. - - `message.input_image.image_url`: Include image urls from the input message. - - `computer_call_output.output.image_url`: Include image urls from the computer - call output. - - instructions: Inserts a system (or developer) message as the first item in the model's - context. - - When using along with `previous_response_id`, the instructions from a previous - response will be not be carried over to the next response. This makes it simple - to swap out system (or developer) messages in new responses. - - max_output_tokens: An upper bound for the number of tokens that can be generated for a response, - including visible output tokens and - [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). - - metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format, and - querying for objects via API or the dashboard. - - Keys are strings with a maximum length of 64 characters. Values are strings with - a maximum length of 512 characters. - - parallel_tool_calls: Whether to allow the model to run tool calls in parallel. - - previous_response_id: The unique ID of the previous response to the model. Use this to create - multi-turn conversations. Learn more about - [conversation state](https://platform.openai.com/docs/guides/conversation-state). - - reasoning: **o-series models only** - - Configuration options for - [reasoning models](https://platform.openai.com/docs/guides/reasoning). - - store: Whether to store the generated model response for later retrieval via API. - - stream: If set to true, the model response data will be streamed to the client as it is - generated using - [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). - See the - [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) - for more information. - - temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will - make the output more random, while lower values like 0.2 will make it more - focused and deterministic. We generally recommend altering this or `top_p` but - not both. - - text: Configuration options for a text response from the model. Can be plain text or - structured JSON data. Learn more: - - - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) - - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) - - tool_choice: How the model should select which tool (or tools) to use when generating a - response. See the `tools` parameter to see how to specify which tools the model - can call. - - tools: An array of tools the model may call while generating a response. You can - specify which tool to use by setting the `tool_choice` parameter. - - The two categories of tools you can provide the model are: - - - **Built-in tools**: Tools that are provided by OpenAI that extend the model's - capabilities, like - [web search](https://platform.openai.com/docs/guides/tools-web-search) or - [file search](https://platform.openai.com/docs/guides/tools-file-search). - Learn more about - [built-in tools](https://platform.openai.com/docs/guides/tools). - - **Function calls (custom tools)**: Functions that are defined by you, enabling - the model to call your own code. Learn more about - [function calling](https://platform.openai.com/docs/guides/function-calling). - - top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. So 0.1 - means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or `temperature` but not both. - - truncation: The truncation strategy to use for the model response. - - - `auto`: If the context of this response and previous ones exceeds the model's - context window size, the model will truncate the response to fit the context - window by dropping input items in the middle of the conversation. - - `disabled` (default): If a model response will exceed the context window size - for a model, the request will fail with a 400 error. - - user: A unique identifier representing your end-user, which can help OpenAI to monitor - and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). - - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - ... - - @overload - def create( - self, - *, - input: Union[str, ResponseInputParam], - model: ResponsesModel, - stream: Literal[True], - include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, - instructions: Optional[str] | NotGiven = NOT_GIVEN, - max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, - previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, - reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, - store: Optional[bool] | NotGiven = NOT_GIVEN, - temperature: Optional[float] | NotGiven = NOT_GIVEN, - text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, - tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, - tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, - top_p: Optional[float] | NotGiven = NOT_GIVEN, - truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, - user: str | NotGiven = NOT_GIVEN, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> Stream[ResponseStreamEvent]: - """Creates a model response. - - Provide - [text](https://platform.openai.com/docs/guides/text) or - [image](https://platform.openai.com/docs/guides/images) inputs to generate - [text](https://platform.openai.com/docs/guides/text) or - [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have - the model call your own - [custom code](https://platform.openai.com/docs/guides/function-calling) or use - built-in [tools](https://platform.openai.com/docs/guides/tools) like - [web search](https://platform.openai.com/docs/guides/tools-web-search) or - [file search](https://platform.openai.com/docs/guides/tools-file-search) to use - your own data as input for the model's response. - - Args: - input: Text, image, or file inputs to the model, used to generate a response. - - Learn more: - - - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) - - [Image inputs](https://platform.openai.com/docs/guides/images) - - [File inputs](https://platform.openai.com/docs/guides/pdf-files) - - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) - - [Function calling](https://platform.openai.com/docs/guides/function-calling) - - model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a - wide range of models with different capabilities, performance characteristics, - and price points. Refer to the - [model guide](https://platform.openai.com/docs/models) to browse and compare - available models. - - stream: If set to true, the model response data will be streamed to the client as it is - generated using - [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). - See the - [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) - for more information. - - include: Specify additional output data to include in the model response. Currently - supported values are: - - - `file_search_call.results`: Include the search results of the file search tool - call. - - `message.input_image.image_url`: Include image urls from the input message. - - `computer_call_output.output.image_url`: Include image urls from the computer - call output. - - instructions: Inserts a system (or developer) message as the first item in the model's - context. - - When using along with `previous_response_id`, the instructions from a previous - response will be not be carried over to the next response. This makes it simple - to swap out system (or developer) messages in new responses. - - max_output_tokens: An upper bound for the number of tokens that can be generated for a response, - including visible output tokens and - [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). - - metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format, and - querying for objects via API or the dashboard. - - Keys are strings with a maximum length of 64 characters. Values are strings with - a maximum length of 512 characters. - - parallel_tool_calls: Whether to allow the model to run tool calls in parallel. - - previous_response_id: The unique ID of the previous response to the model. Use this to create - multi-turn conversations. Learn more about - [conversation state](https://platform.openai.com/docs/guides/conversation-state). - - reasoning: **o-series models only** - - Configuration options for - [reasoning models](https://platform.openai.com/docs/guides/reasoning). - - store: Whether to store the generated model response for later retrieval via API. - - temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will - make the output more random, while lower values like 0.2 will make it more - focused and deterministic. We generally recommend altering this or `top_p` but - not both. - - text: Configuration options for a text response from the model. Can be plain text or - structured JSON data. Learn more: - - - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) - - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) - - tool_choice: How the model should select which tool (or tools) to use when generating a - response. See the `tools` parameter to see how to specify which tools the model - can call. - - tools: An array of tools the model may call while generating a response. You can - specify which tool to use by setting the `tool_choice` parameter. - - The two categories of tools you can provide the model are: - - - **Built-in tools**: Tools that are provided by OpenAI that extend the model's - capabilities, like - [web search](https://platform.openai.com/docs/guides/tools-web-search) or - [file search](https://platform.openai.com/docs/guides/tools-file-search). - Learn more about - [built-in tools](https://platform.openai.com/docs/guides/tools). - - **Function calls (custom tools)**: Functions that are defined by you, enabling - the model to call your own code. Learn more about - [function calling](https://platform.openai.com/docs/guides/function-calling). - - top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. So 0.1 - means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or `temperature` but not both. - - truncation: The truncation strategy to use for the model response. - - - `auto`: If the context of this response and previous ones exceeds the model's - context window size, the model will truncate the response to fit the context - window by dropping input items in the middle of the conversation. - - `disabled` (default): If a model response will exceed the context window size - for a model, the request will fail with a 400 error. - - user: A unique identifier representing your end-user, which can help OpenAI to monitor - and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). - - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - ... - - @overload - def create( - self, - *, - input: Union[str, ResponseInputParam], - model: ResponsesModel, - stream: bool, - include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, - instructions: Optional[str] | NotGiven = NOT_GIVEN, - max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, - previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, - reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, - store: Optional[bool] | NotGiven = NOT_GIVEN, - temperature: Optional[float] | NotGiven = NOT_GIVEN, - text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, - tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, - tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, - top_p: Optional[float] | NotGiven = NOT_GIVEN, - truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, - user: str | NotGiven = NOT_GIVEN, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> Response | Stream[ResponseStreamEvent]: - """Creates a model response. - - Provide - [text](https://platform.openai.com/docs/guides/text) or - [image](https://platform.openai.com/docs/guides/images) inputs to generate - [text](https://platform.openai.com/docs/guides/text) or - [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have - the model call your own - [custom code](https://platform.openai.com/docs/guides/function-calling) or use - built-in [tools](https://platform.openai.com/docs/guides/tools) like - [web search](https://platform.openai.com/docs/guides/tools-web-search) or - [file search](https://platform.openai.com/docs/guides/tools-file-search) to use - your own data as input for the model's response. - - Args: - input: Text, image, or file inputs to the model, used to generate a response. - - Learn more: - - - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) - - [Image inputs](https://platform.openai.com/docs/guides/images) - - [File inputs](https://platform.openai.com/docs/guides/pdf-files) - - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) - - [Function calling](https://platform.openai.com/docs/guides/function-calling) - - model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a - wide range of models with different capabilities, performance characteristics, - and price points. Refer to the - [model guide](https://platform.openai.com/docs/models) to browse and compare - available models. - - stream: If set to true, the model response data will be streamed to the client as it is - generated using - [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). - See the - [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) - for more information. - - include: Specify additional output data to include in the model response. Currently - supported values are: - - - `file_search_call.results`: Include the search results of the file search tool - call. - - `message.input_image.image_url`: Include image urls from the input message. - - `computer_call_output.output.image_url`: Include image urls from the computer - call output. - - instructions: Inserts a system (or developer) message as the first item in the model's - context. - - When using along with `previous_response_id`, the instructions from a previous - response will be not be carried over to the next response. This makes it simple - to swap out system (or developer) messages in new responses. - - max_output_tokens: An upper bound for the number of tokens that can be generated for a response, - including visible output tokens and - [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). - - metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format, and - querying for objects via API or the dashboard. - - Keys are strings with a maximum length of 64 characters. Values are strings with - a maximum length of 512 characters. - - parallel_tool_calls: Whether to allow the model to run tool calls in parallel. - - previous_response_id: The unique ID of the previous response to the model. Use this to create - multi-turn conversations. Learn more about - [conversation state](https://platform.openai.com/docs/guides/conversation-state). - - reasoning: **o-series models only** - - Configuration options for - [reasoning models](https://platform.openai.com/docs/guides/reasoning). - - store: Whether to store the generated model response for later retrieval via API. - - temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will - make the output more random, while lower values like 0.2 will make it more - focused and deterministic. We generally recommend altering this or `top_p` but - not both. - - text: Configuration options for a text response from the model. Can be plain text or - structured JSON data. Learn more: - - - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) - - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) - - tool_choice: How the model should select which tool (or tools) to use when generating a - response. See the `tools` parameter to see how to specify which tools the model - can call. - - tools: An array of tools the model may call while generating a response. You can - specify which tool to use by setting the `tool_choice` parameter. - - The two categories of tools you can provide the model are: - - - **Built-in tools**: Tools that are provided by OpenAI that extend the model's - capabilities, like - [web search](https://platform.openai.com/docs/guides/tools-web-search) or - [file search](https://platform.openai.com/docs/guides/tools-file-search). - Learn more about - [built-in tools](https://platform.openai.com/docs/guides/tools). - - **Function calls (custom tools)**: Functions that are defined by you, enabling - the model to call your own code. Learn more about - [function calling](https://platform.openai.com/docs/guides/function-calling). - - top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. So 0.1 - means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or `temperature` but not both. - - truncation: The truncation strategy to use for the model response. - - - `auto`: If the context of this response and previous ones exceeds the model's - context window size, the model will truncate the response to fit the context - window by dropping input items in the middle of the conversation. - - `disabled` (default): If a model response will exceed the context window size - for a model, the request will fail with a 400 error. - - user: A unique identifier representing your end-user, which can help OpenAI to monitor - and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). - - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - ... - - @required_args(["input", "model"], ["input", "model", "stream"]) - def create( - self, - *, - input: Union[str, ResponseInputParam], - model: ResponsesModel, - include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, - instructions: Optional[str] | NotGiven = NOT_GIVEN, - max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, - previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, - reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, - store: Optional[bool] | NotGiven = NOT_GIVEN, - stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, - temperature: Optional[float] | NotGiven = NOT_GIVEN, - text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, - tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, - tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, - top_p: Optional[float] | NotGiven = NOT_GIVEN, - truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, - user: str | NotGiven = NOT_GIVEN, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> Response | Stream[ResponseStreamEvent]: - return self._post( - "/responses", - body=maybe_transform( - { - "input": input, - "model": model, - "include": include, - "instructions": instructions, - "max_output_tokens": max_output_tokens, - "metadata": metadata, - "parallel_tool_calls": parallel_tool_calls, - "previous_response_id": previous_response_id, - "reasoning": reasoning, - "store": store, - "stream": stream, - "temperature": temperature, - "text": text, - "tool_choice": tool_choice, - "tools": tools, - "top_p": top_p, - "truncation": truncation, - "user": user, - }, - response_create_params.ResponseCreateParams, - ), - options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout - ), - cast_to=Response, - stream=stream or False, - stream_cls=Stream[ResponseStreamEvent], - ) - - def stream( - self, - *, - input: Union[str, ResponseInputParam], - model: Union[str, ChatModel], - text_format: type[TextFormatT] | NotGiven = NOT_GIVEN, - tools: Iterable[ParseableToolParam] | NotGiven = NOT_GIVEN, - include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, - instructions: Optional[str] | NotGiven = NOT_GIVEN, - max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, - previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, - reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, - store: Optional[bool] | NotGiven = NOT_GIVEN, - temperature: Optional[float] | NotGiven = NOT_GIVEN, - text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, - tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, - top_p: Optional[float] | NotGiven = NOT_GIVEN, - truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, - user: str | NotGiven = NOT_GIVEN, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> ResponseStreamManager[TextFormatT]: - if is_given(text_format): - if not text: - text = {} - - if "format" in text: - raise TypeError("Cannot mix and match text.format with text_format") - - text["format"] = _type_to_text_format_param(text_format) - - tools = _make_tools(tools) - - api_request: partial[Stream[ResponseStreamEvent]] = partial( - self.create, - input=input, - model=model, - tools=tools, - include=include, - instructions=instructions, - max_output_tokens=max_output_tokens, - metadata=metadata, - parallel_tool_calls=parallel_tool_calls, - previous_response_id=previous_response_id, - store=store, - stream=True, - temperature=temperature, - text=text, - tool_choice=tool_choice, - reasoning=reasoning, - top_p=top_p, - truncation=truncation, - user=user, - extra_headers=extra_headers, - extra_query=extra_query, - extra_body=extra_body, - timeout=timeout, - ) - - return ResponseStreamManager( - api_request, - text_format=text_format, - input_tools=tools, - ) - - def parse( - self, - *, - input: Union[str, ResponseInputParam], - model: Union[str, ChatModel], - text_format: type[TextFormatT] | NotGiven = NOT_GIVEN, - tools: Iterable[ParseableToolParam] | NotGiven = NOT_GIVEN, - include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, - instructions: Optional[str] | NotGiven = NOT_GIVEN, - max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, - previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, - reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, - store: Optional[bool] | NotGiven = NOT_GIVEN, - stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, - temperature: Optional[float] | NotGiven = NOT_GIVEN, - text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, - tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, - top_p: Optional[float] | NotGiven = NOT_GIVEN, - truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, - user: str | NotGiven = NOT_GIVEN, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> ParsedResponse[TextFormatT]: - if is_given(text_format): - if not text: - text = {} - - if "format" in text: - raise TypeError("Cannot mix and match text.format with text_format") - - text["format"] = _type_to_text_format_param(text_format) - - tools = _make_tools(tools) - - def parser(raw_response: Response) -> ParsedResponse[TextFormatT]: - return parse_response( - input_tools=tools, - text_format=text_format, - response=raw_response, - ) - - return self._post( - "/responses", - body=maybe_transform( - { - "input": input, - "model": model, - "include": include, - "instructions": instructions, - "max_output_tokens": max_output_tokens, - "metadata": metadata, - "parallel_tool_calls": parallel_tool_calls, - "previous_response_id": previous_response_id, - "reasoning": reasoning, - "store": store, - "stream": stream, - "temperature": temperature, - "text": text, - "tool_choice": tool_choice, - "tools": tools, - "top_p": top_p, - "truncation": truncation, - "user": user, - }, - response_create_params.ResponseCreateParams, - ), - options=make_request_options( - extra_headers=extra_headers, - extra_query=extra_query, - extra_body=extra_body, - timeout=timeout, - post_parser=parser, - ), - # we turn the `Response` instance into a `ParsedResponse` - # in the `parser` function above - cast_to=cast(Type[ParsedResponse[TextFormatT]], Response), - ) - - def retrieve( - self, - response_id: str, - *, - include: List[ResponseIncludable] | NotGiven = NOT_GIVEN, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> Response: - """ - Retrieves a model response with the given ID. - - Args: - include: Additional fields to include in the response. See the `include` parameter for - Response creation above for more information. - - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - if not response_id: - raise ValueError(f"Expected a non-empty value for `response_id` but received {response_id!r}") - return self._get( - f"/responses/{response_id}", - options=make_request_options( - extra_headers=extra_headers, - extra_query=extra_query, - extra_body=extra_body, - timeout=timeout, - query=maybe_transform({"include": include}, response_retrieve_params.ResponseRetrieveParams), - ), - cast_to=Response, - ) - - def delete( - self, - response_id: str, - *, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> None: - """ - Deletes a model response with the given ID. - - Args: - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - if not response_id: - raise ValueError(f"Expected a non-empty value for `response_id` but received {response_id!r}") - extra_headers = {"Accept": "*/*", **(extra_headers or {})} - return self._delete( - f"/responses/{response_id}", - options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout - ), - cast_to=NoneType, - ) - - -class AsyncResponses(AsyncAPIResource): - @cached_property - def input_items(self) -> AsyncInputItems: - return AsyncInputItems(self._client) - - @cached_property - def with_raw_response(self) -> AsyncResponsesWithRawResponse: - """ - This property can be used as a prefix for any HTTP method call to return - the raw response object instead of the parsed content. - - For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers - """ - return AsyncResponsesWithRawResponse(self) - - @cached_property - def with_streaming_response(self) -> AsyncResponsesWithStreamingResponse: - """ - An alternative to `.with_raw_response` that doesn't eagerly read the response body. - - For more information, see https://www.github.com/openai/openai-python#with_streaming_response - """ - return AsyncResponsesWithStreamingResponse(self) - - @overload - async def create( - self, - *, - input: Union[str, ResponseInputParam], - model: ResponsesModel, - include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, - instructions: Optional[str] | NotGiven = NOT_GIVEN, - max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, - previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, - reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, - store: Optional[bool] | NotGiven = NOT_GIVEN, - stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, - temperature: Optional[float] | NotGiven = NOT_GIVEN, - text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, - tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, - tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, - top_p: Optional[float] | NotGiven = NOT_GIVEN, - truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, - user: str | NotGiven = NOT_GIVEN, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> Response: - """Creates a model response. - - Provide - [text](https://platform.openai.com/docs/guides/text) or - [image](https://platform.openai.com/docs/guides/images) inputs to generate - [text](https://platform.openai.com/docs/guides/text) or - [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have - the model call your own - [custom code](https://platform.openai.com/docs/guides/function-calling) or use - built-in [tools](https://platform.openai.com/docs/guides/tools) like - [web search](https://platform.openai.com/docs/guides/tools-web-search) or - [file search](https://platform.openai.com/docs/guides/tools-file-search) to use - your own data as input for the model's response. - - Args: - input: Text, image, or file inputs to the model, used to generate a response. - - Learn more: - - - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) - - [Image inputs](https://platform.openai.com/docs/guides/images) - - [File inputs](https://platform.openai.com/docs/guides/pdf-files) - - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) - - [Function calling](https://platform.openai.com/docs/guides/function-calling) - - model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a - wide range of models with different capabilities, performance characteristics, - and price points. Refer to the - [model guide](https://platform.openai.com/docs/models) to browse and compare - available models. - - include: Specify additional output data to include in the model response. Currently - supported values are: - - - `file_search_call.results`: Include the search results of the file search tool - call. - - `message.input_image.image_url`: Include image urls from the input message. - - `computer_call_output.output.image_url`: Include image urls from the computer - call output. - - instructions: Inserts a system (or developer) message as the first item in the model's - context. - - When using along with `previous_response_id`, the instructions from a previous - response will be not be carried over to the next response. This makes it simple - to swap out system (or developer) messages in new responses. - - max_output_tokens: An upper bound for the number of tokens that can be generated for a response, - including visible output tokens and - [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). - - metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format, and - querying for objects via API or the dashboard. - - Keys are strings with a maximum length of 64 characters. Values are strings with - a maximum length of 512 characters. - - parallel_tool_calls: Whether to allow the model to run tool calls in parallel. - - previous_response_id: The unique ID of the previous response to the model. Use this to create - multi-turn conversations. Learn more about - [conversation state](https://platform.openai.com/docs/guides/conversation-state). - - reasoning: **o-series models only** - - Configuration options for - [reasoning models](https://platform.openai.com/docs/guides/reasoning). - - store: Whether to store the generated model response for later retrieval via API. - - stream: If set to true, the model response data will be streamed to the client as it is - generated using - [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). - See the - [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) - for more information. - - temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will - make the output more random, while lower values like 0.2 will make it more - focused and deterministic. We generally recommend altering this or `top_p` but - not both. - - text: Configuration options for a text response from the model. Can be plain text or - structured JSON data. Learn more: - - - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) - - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) - - tool_choice: How the model should select which tool (or tools) to use when generating a - response. See the `tools` parameter to see how to specify which tools the model - can call. - - tools: An array of tools the model may call while generating a response. You can - specify which tool to use by setting the `tool_choice` parameter. - - The two categories of tools you can provide the model are: - - - **Built-in tools**: Tools that are provided by OpenAI that extend the model's - capabilities, like - [web search](https://platform.openai.com/docs/guides/tools-web-search) or - [file search](https://platform.openai.com/docs/guides/tools-file-search). - Learn more about - [built-in tools](https://platform.openai.com/docs/guides/tools). - - **Function calls (custom tools)**: Functions that are defined by you, enabling - the model to call your own code. Learn more about - [function calling](https://platform.openai.com/docs/guides/function-calling). - - top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. So 0.1 - means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or `temperature` but not both. - - truncation: The truncation strategy to use for the model response. - - - `auto`: If the context of this response and previous ones exceeds the model's - context window size, the model will truncate the response to fit the context - window by dropping input items in the middle of the conversation. - - `disabled` (default): If a model response will exceed the context window size - for a model, the request will fail with a 400 error. - - user: A unique identifier representing your end-user, which can help OpenAI to monitor - and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). - - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - ... - - @overload - async def create( - self, - *, - input: Union[str, ResponseInputParam], - model: ResponsesModel, - stream: Literal[True], - include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, - instructions: Optional[str] | NotGiven = NOT_GIVEN, - max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, - previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, - reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, - store: Optional[bool] | NotGiven = NOT_GIVEN, - temperature: Optional[float] | NotGiven = NOT_GIVEN, - text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, - tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, - tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, - top_p: Optional[float] | NotGiven = NOT_GIVEN, - truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, - user: str | NotGiven = NOT_GIVEN, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> AsyncStream[ResponseStreamEvent]: - """Creates a model response. - - Provide - [text](https://platform.openai.com/docs/guides/text) or - [image](https://platform.openai.com/docs/guides/images) inputs to generate - [text](https://platform.openai.com/docs/guides/text) or - [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have - the model call your own - [custom code](https://platform.openai.com/docs/guides/function-calling) or use - built-in [tools](https://platform.openai.com/docs/guides/tools) like - [web search](https://platform.openai.com/docs/guides/tools-web-search) or - [file search](https://platform.openai.com/docs/guides/tools-file-search) to use - your own data as input for the model's response. - - Args: - input: Text, image, or file inputs to the model, used to generate a response. - - Learn more: - - - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) - - [Image inputs](https://platform.openai.com/docs/guides/images) - - [File inputs](https://platform.openai.com/docs/guides/pdf-files) - - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) - - [Function calling](https://platform.openai.com/docs/guides/function-calling) - - model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a - wide range of models with different capabilities, performance characteristics, - and price points. Refer to the - [model guide](https://platform.openai.com/docs/models) to browse and compare - available models. - - stream: If set to true, the model response data will be streamed to the client as it is - generated using - [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). - See the - [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) - for more information. - - include: Specify additional output data to include in the model response. Currently - supported values are: - - - `file_search_call.results`: Include the search results of the file search tool - call. - - `message.input_image.image_url`: Include image urls from the input message. - - `computer_call_output.output.image_url`: Include image urls from the computer - call output. - - instructions: Inserts a system (or developer) message as the first item in the model's - context. - - When using along with `previous_response_id`, the instructions from a previous - response will be not be carried over to the next response. This makes it simple - to swap out system (or developer) messages in new responses. - - max_output_tokens: An upper bound for the number of tokens that can be generated for a response, - including visible output tokens and - [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). - - metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format, and - querying for objects via API or the dashboard. - - Keys are strings with a maximum length of 64 characters. Values are strings with - a maximum length of 512 characters. - - parallel_tool_calls: Whether to allow the model to run tool calls in parallel. - - previous_response_id: The unique ID of the previous response to the model. Use this to create - multi-turn conversations. Learn more about - [conversation state](https://platform.openai.com/docs/guides/conversation-state). - - reasoning: **o-series models only** - - Configuration options for - [reasoning models](https://platform.openai.com/docs/guides/reasoning). - - store: Whether to store the generated model response for later retrieval via API. - - temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will - make the output more random, while lower values like 0.2 will make it more - focused and deterministic. We generally recommend altering this or `top_p` but - not both. - - text: Configuration options for a text response from the model. Can be plain text or - structured JSON data. Learn more: - - - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) - - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) - - tool_choice: How the model should select which tool (or tools) to use when generating a - response. See the `tools` parameter to see how to specify which tools the model - can call. - - tools: An array of tools the model may call while generating a response. You can - specify which tool to use by setting the `tool_choice` parameter. - - The two categories of tools you can provide the model are: - - - **Built-in tools**: Tools that are provided by OpenAI that extend the model's - capabilities, like - [web search](https://platform.openai.com/docs/guides/tools-web-search) or - [file search](https://platform.openai.com/docs/guides/tools-file-search). - Learn more about - [built-in tools](https://platform.openai.com/docs/guides/tools). - - **Function calls (custom tools)**: Functions that are defined by you, enabling - the model to call your own code. Learn more about - [function calling](https://platform.openai.com/docs/guides/function-calling). - - top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. So 0.1 - means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or `temperature` but not both. - - truncation: The truncation strategy to use for the model response. - - - `auto`: If the context of this response and previous ones exceeds the model's - context window size, the model will truncate the response to fit the context - window by dropping input items in the middle of the conversation. - - `disabled` (default): If a model response will exceed the context window size - for a model, the request will fail with a 400 error. - - user: A unique identifier representing your end-user, which can help OpenAI to monitor - and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). - - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - ... - - @overload - async def create( - self, - *, - input: Union[str, ResponseInputParam], - model: ResponsesModel, - stream: bool, - include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, - instructions: Optional[str] | NotGiven = NOT_GIVEN, - max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, - previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, - reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, - store: Optional[bool] | NotGiven = NOT_GIVEN, - temperature: Optional[float] | NotGiven = NOT_GIVEN, - text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, - tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, - tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, - top_p: Optional[float] | NotGiven = NOT_GIVEN, - truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, - user: str | NotGiven = NOT_GIVEN, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> Response | AsyncStream[ResponseStreamEvent]: - """Creates a model response. - - Provide - [text](https://platform.openai.com/docs/guides/text) or - [image](https://platform.openai.com/docs/guides/images) inputs to generate - [text](https://platform.openai.com/docs/guides/text) or - [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have - the model call your own - [custom code](https://platform.openai.com/docs/guides/function-calling) or use - built-in [tools](https://platform.openai.com/docs/guides/tools) like - [web search](https://platform.openai.com/docs/guides/tools-web-search) or - [file search](https://platform.openai.com/docs/guides/tools-file-search) to use - your own data as input for the model's response. - - Args: - input: Text, image, or file inputs to the model, used to generate a response. - - Learn more: - - - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) - - [Image inputs](https://platform.openai.com/docs/guides/images) - - [File inputs](https://platform.openai.com/docs/guides/pdf-files) - - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) - - [Function calling](https://platform.openai.com/docs/guides/function-calling) - - model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a - wide range of models with different capabilities, performance characteristics, - and price points. Refer to the - [model guide](https://platform.openai.com/docs/models) to browse and compare - available models. - - stream: If set to true, the model response data will be streamed to the client as it is - generated using - [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). - See the - [Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming) - for more information. - - include: Specify additional output data to include in the model response. Currently - supported values are: - - - `file_search_call.results`: Include the search results of the file search tool - call. - - `message.input_image.image_url`: Include image urls from the input message. - - `computer_call_output.output.image_url`: Include image urls from the computer - call output. - - instructions: Inserts a system (or developer) message as the first item in the model's - context. - - When using along with `previous_response_id`, the instructions from a previous - response will be not be carried over to the next response. This makes it simple - to swap out system (or developer) messages in new responses. - - max_output_tokens: An upper bound for the number of tokens that can be generated for a response, - including visible output tokens and - [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). - - metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful - for storing additional information about the object in a structured format, and - querying for objects via API or the dashboard. - - Keys are strings with a maximum length of 64 characters. Values are strings with - a maximum length of 512 characters. - - parallel_tool_calls: Whether to allow the model to run tool calls in parallel. - - previous_response_id: The unique ID of the previous response to the model. Use this to create - multi-turn conversations. Learn more about - [conversation state](https://platform.openai.com/docs/guides/conversation-state). - - reasoning: **o-series models only** - - Configuration options for - [reasoning models](https://platform.openai.com/docs/guides/reasoning). - - store: Whether to store the generated model response for later retrieval via API. - - temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will - make the output more random, while lower values like 0.2 will make it more - focused and deterministic. We generally recommend altering this or `top_p` but - not both. - - text: Configuration options for a text response from the model. Can be plain text or - structured JSON data. Learn more: - - - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) - - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) - - tool_choice: How the model should select which tool (or tools) to use when generating a - response. See the `tools` parameter to see how to specify which tools the model - can call. - - tools: An array of tools the model may call while generating a response. You can - specify which tool to use by setting the `tool_choice` parameter. - - The two categories of tools you can provide the model are: - - - **Built-in tools**: Tools that are provided by OpenAI that extend the model's - capabilities, like - [web search](https://platform.openai.com/docs/guides/tools-web-search) or - [file search](https://platform.openai.com/docs/guides/tools-file-search). - Learn more about - [built-in tools](https://platform.openai.com/docs/guides/tools). - - **Function calls (custom tools)**: Functions that are defined by you, enabling - the model to call your own code. Learn more about - [function calling](https://platform.openai.com/docs/guides/function-calling). - - top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. So 0.1 - means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or `temperature` but not both. - - truncation: The truncation strategy to use for the model response. - - - `auto`: If the context of this response and previous ones exceeds the model's - context window size, the model will truncate the response to fit the context - window by dropping input items in the middle of the conversation. - - `disabled` (default): If a model response will exceed the context window size - for a model, the request will fail with a 400 error. - - user: A unique identifier representing your end-user, which can help OpenAI to monitor - and detect abuse. - [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). - - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - ... - - @required_args(["input", "model"], ["input", "model", "stream"]) - async def create( - self, - *, - input: Union[str, ResponseInputParam], - model: ResponsesModel, - include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, - instructions: Optional[str] | NotGiven = NOT_GIVEN, - max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, - previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, - reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, - store: Optional[bool] | NotGiven = NOT_GIVEN, - stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, - temperature: Optional[float] | NotGiven = NOT_GIVEN, - text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, - tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, - tools: Iterable[ToolParam] | NotGiven = NOT_GIVEN, - top_p: Optional[float] | NotGiven = NOT_GIVEN, - truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, - user: str | NotGiven = NOT_GIVEN, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> Response | AsyncStream[ResponseStreamEvent]: - return await self._post( - "/responses", - body=await async_maybe_transform( - { - "input": input, - "model": model, - "include": include, - "instructions": instructions, - "max_output_tokens": max_output_tokens, - "metadata": metadata, - "parallel_tool_calls": parallel_tool_calls, - "previous_response_id": previous_response_id, - "reasoning": reasoning, - "store": store, - "stream": stream, - "temperature": temperature, - "text": text, - "tool_choice": tool_choice, - "tools": tools, - "top_p": top_p, - "truncation": truncation, - "user": user, - }, - response_create_params.ResponseCreateParams, - ), - options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout - ), - cast_to=Response, - stream=stream or False, - stream_cls=AsyncStream[ResponseStreamEvent], - ) - - def stream( - self, - *, - input: Union[str, ResponseInputParam], - model: Union[str, ChatModel], - text_format: type[TextFormatT] | NotGiven = NOT_GIVEN, - tools: Iterable[ParseableToolParam] | NotGiven = NOT_GIVEN, - include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, - instructions: Optional[str] | NotGiven = NOT_GIVEN, - max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, - previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, - reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, - store: Optional[bool] | NotGiven = NOT_GIVEN, - temperature: Optional[float] | NotGiven = NOT_GIVEN, - text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, - tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, - top_p: Optional[float] | NotGiven = NOT_GIVEN, - truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, - user: str | NotGiven = NOT_GIVEN, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> AsyncResponseStreamManager[TextFormatT]: - if is_given(text_format): - if not text: - text = {} - - if "format" in text: - raise TypeError("Cannot mix and match text.format with text_format") - - text["format"] = _type_to_text_format_param(text_format) - - tools = _make_tools(tools) - - api_request = self.create( - input=input, - model=model, - tools=tools, - include=include, - instructions=instructions, - max_output_tokens=max_output_tokens, - metadata=metadata, - parallel_tool_calls=parallel_tool_calls, - previous_response_id=previous_response_id, - store=store, - stream=True, - temperature=temperature, - text=text, - tool_choice=tool_choice, - reasoning=reasoning, - top_p=top_p, - truncation=truncation, - user=user, - extra_headers=extra_headers, - extra_query=extra_query, - extra_body=extra_body, - timeout=timeout, - ) - - return AsyncResponseStreamManager( - api_request, - text_format=text_format, - input_tools=tools, - ) - - async def parse( - self, - *, - input: Union[str, ResponseInputParam], - model: Union[str, ChatModel], - text_format: type[TextFormatT] | NotGiven = NOT_GIVEN, - tools: Iterable[ParseableToolParam] | NotGiven = NOT_GIVEN, - include: Optional[List[ResponseIncludable]] | NotGiven = NOT_GIVEN, - instructions: Optional[str] | NotGiven = NOT_GIVEN, - max_output_tokens: Optional[int] | NotGiven = NOT_GIVEN, - metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, - parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, - previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, - reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, - store: Optional[bool] | NotGiven = NOT_GIVEN, - stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, - temperature: Optional[float] | NotGiven = NOT_GIVEN, - text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, - tool_choice: response_create_params.ToolChoice | NotGiven = NOT_GIVEN, - top_p: Optional[float] | NotGiven = NOT_GIVEN, - truncation: Optional[Literal["auto", "disabled"]] | NotGiven = NOT_GIVEN, - user: str | NotGiven = NOT_GIVEN, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> ParsedResponse[TextFormatT]: - if is_given(text_format): - if not text: - text = {} - - if "format" in text: - raise TypeError("Cannot mix and match text.format with text_format") - - text["format"] = _type_to_text_format_param(text_format) - - tools = _make_tools(tools) - - def parser(raw_response: Response) -> ParsedResponse[TextFormatT]: - return parse_response( - input_tools=tools, - text_format=text_format, - response=raw_response, - ) - - return await self._post( - "/responses", - body=maybe_transform( - { - "input": input, - "model": model, - "include": include, - "instructions": instructions, - "max_output_tokens": max_output_tokens, - "metadata": metadata, - "parallel_tool_calls": parallel_tool_calls, - "previous_response_id": previous_response_id, - "reasoning": reasoning, - "store": store, - "stream": stream, - "temperature": temperature, - "text": text, - "tool_choice": tool_choice, - "tools": tools, - "top_p": top_p, - "truncation": truncation, - "user": user, - }, - response_create_params.ResponseCreateParams, - ), - options=make_request_options( - extra_headers=extra_headers, - extra_query=extra_query, - extra_body=extra_body, - timeout=timeout, - post_parser=parser, - ), - # we turn the `Response` instance into a `ParsedResponse` - # in the `parser` function above - cast_to=cast(Type[ParsedResponse[TextFormatT]], Response), - ) - - async def retrieve( - self, - response_id: str, - *, - include: List[ResponseIncludable] | NotGiven = NOT_GIVEN, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> Response: - """ - Retrieves a model response with the given ID. - - Args: - include: Additional fields to include in the response. See the `include` parameter for - Response creation above for more information. - - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - if not response_id: - raise ValueError(f"Expected a non-empty value for `response_id` but received {response_id!r}") - return await self._get( - f"/responses/{response_id}", - options=make_request_options( - extra_headers=extra_headers, - extra_query=extra_query, - extra_body=extra_body, - timeout=timeout, - query=await async_maybe_transform( - {"include": include}, response_retrieve_params.ResponseRetrieveParams - ), - ), - cast_to=Response, - ) - - async def delete( - self, - response_id: str, - *, - # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. - # The extra values given here take precedence over values defined on the client or passed to this method. - extra_headers: Headers | None = None, - extra_query: Query | None = None, - extra_body: Body | None = None, - timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, - ) -> None: - """ - Deletes a model response with the given ID. - - Args: - extra_headers: Send extra headers - - extra_query: Add additional query parameters to the request - - extra_body: Add additional JSON properties to the request - - timeout: Override the client-level default timeout for this request, in seconds - """ - if not response_id: - raise ValueError(f"Expected a non-empty value for `response_id` but received {response_id!r}") - extra_headers = {"Accept": "*/*", **(extra_headers or {})} - return await self._delete( - f"/responses/{response_id}", - options=make_request_options( - extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout - ), - cast_to=NoneType, - ) - - -class ResponsesWithRawResponse: - def __init__(self, responses: Responses) -> None: - self._responses = responses - - self.create = _legacy_response.to_raw_response_wrapper( - responses.create, - ) - self.retrieve = _legacy_response.to_raw_response_wrapper( - responses.retrieve, - ) - self.delete = _legacy_response.to_raw_response_wrapper( - responses.delete, - ) - - @cached_property - def input_items(self) -> InputItemsWithRawResponse: - return InputItemsWithRawResponse(self._responses.input_items) - - -class AsyncResponsesWithRawResponse: - def __init__(self, responses: AsyncResponses) -> None: - self._responses = responses - - self.create = _legacy_response.async_to_raw_response_wrapper( - responses.create, - ) - self.retrieve = _legacy_response.async_to_raw_response_wrapper( - responses.retrieve, - ) - self.delete = _legacy_response.async_to_raw_response_wrapper( - responses.delete, - ) - - @cached_property - def input_items(self) -> AsyncInputItemsWithRawResponse: - return AsyncInputItemsWithRawResponse(self._responses.input_items) - - -class ResponsesWithStreamingResponse: - def __init__(self, responses: Responses) -> None: - self._responses = responses - - self.create = to_streamed_response_wrapper( - responses.create, - ) - self.retrieve = to_streamed_response_wrapper( - responses.retrieve, - ) - self.delete = to_streamed_response_wrapper( - responses.delete, - ) - - @cached_property - def input_items(self) -> InputItemsWithStreamingResponse: - return InputItemsWithStreamingResponse(self._responses.input_items) - - -class AsyncResponsesWithStreamingResponse: - def __init__(self, responses: AsyncResponses) -> None: - self._responses = responses - - self.create = async_to_streamed_response_wrapper( - responses.create, - ) - self.retrieve = async_to_streamed_response_wrapper( - responses.retrieve, - ) - self.delete = async_to_streamed_response_wrapper( - responses.delete, - ) - - @cached_property - def input_items(self) -> AsyncInputItemsWithStreamingResponse: - return AsyncInputItemsWithStreamingResponse(self._responses.input_items) - - -def _make_tools(tools: Iterable[ParseableToolParam] | NotGiven) -> List[ToolParam] | NotGiven: - if not is_given(tools): - return NOT_GIVEN - - converted_tools: List[ToolParam] = [] - for tool in tools: - if tool["type"] != "function": - converted_tools.append(tool) - continue - - if "function" not in tool: - # standard Responses API case - converted_tools.append(tool) - continue - - function = cast(Any, tool)["function"] # pyright: ignore[reportUnnecessaryCast] - if not isinstance(function, PydanticFunctionTool): - raise Exception( - "Expected Chat Completions function tool shape to be created using `openai.pydantic_function_tool()`" - ) - - assert "parameters" in function - new_tool = ResponsesPydanticFunctionTool( - { - "type": "function", - "name": function["name"], - "description": function.get("description"), - "parameters": function["parameters"], - "strict": function.get("strict") or False, - }, - function.model, - ) - - converted_tools.append(new_tool.cast()) - - return converted_tools From a8fa0def5cd999044dae39b6cdff7a54db25c627 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 27 Mar 2025 17:30:46 +0000 Subject: [PATCH 751/816] release: 1.69.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 20 ++++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 23 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index e280020f03..5df3c6496b 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.68.2" + ".": "1.69.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index ee22cfe7fb..773c20d2af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,25 @@ # Changelog +## 1.69.0 (2025-03-27) + +Full Changelog: [v1.68.2...v1.69.0](https://github.com/openai/openai-python/compare/v1.68.2...v1.69.0) + +### Features + +* **api:** add `get /chat/completions` endpoint ([e6b8a42](https://github.com/openai/openai-python/commit/e6b8a42fc4286656cc86c2acd83692b170e77b68)) + + +### Bug Fixes + +* **audio:** correctly parse transcription stream events ([16a3a19](https://github.com/openai/openai-python/commit/16a3a195ff31f099fbe46043a12d2380c2c01f83)) + + +### Chores + +* add hash of OpenAPI spec/config inputs to .stats.yml ([515e1cd](https://github.com/openai/openai-python/commit/515e1cdd4a3109e5b29618df813656e17f22b52a)) +* **api:** updates to supported Voice IDs ([#2261](https://github.com/openai/openai-python/issues/2261)) ([64956f9](https://github.com/openai/openai-python/commit/64956f9d9889b04380c7f5eb926509d1efd523e6)) +* fix typos ([#2259](https://github.com/openai/openai-python/issues/2259)) ([6160de3](https://github.com/openai/openai-python/commit/6160de3e099f09c2d6ee5eeee4cbcc55b67a8f87)) + ## 1.68.2 (2025-03-21) Full Changelog: [v1.68.1...v1.68.2](https://github.com/openai/openai-python/compare/v1.68.1...v1.68.2) diff --git a/pyproject.toml b/pyproject.toml index b1917922cd..e50c5d6c1f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.68.2" +version = "1.69.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index a29ce4e818..50c0e42d78 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.68.2" # x-release-please-version +__version__ = "1.69.0" # x-release-please-version From 972753a5d38f78149f33b9e768fb426e21456b9d Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 27 Mar 2025 19:41:51 +0000 Subject: [PATCH 752/816] feat(api): add `get /responses/{response_id}/input_items` endpoint --- .stats.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index 1e1104a062..f6a90d2438 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 82 openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-6663c59193eb95b201e492de17dcbd5e126ba03d18ce66287a3e2c632ca56fe7.yml openapi_spec_hash: 7996d2c34cc44fe2ce9ffe93c0ab774e -config_hash: 9351ea829c2b41da3b48a38c934c92ee +config_hash: e25e31d8446b6bc0e3ef7103b6993cce From 384e6b23ce0366d6b2f31cc98d35525da5b22c10 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 31 Mar 2025 05:03:58 +0000 Subject: [PATCH 753/816] release: 1.70.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 5df3c6496b..ba5cbfb627 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.69.0" + ".": "1.70.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 773c20d2af..8954d86571 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.70.0 (2025-03-31) + +Full Changelog: [v1.69.0...v1.70.0](https://github.com/openai/openai-python/compare/v1.69.0...v1.70.0) + +### Features + +* **api:** add `get /responses/{response_id}/input_items` endpoint ([4c6a35d](https://github.com/openai/openai-python/commit/4c6a35dec65362a6a738c3387dae57bf8cbfcbb2)) + ## 1.69.0 (2025-03-27) Full Changelog: [v1.68.2...v1.69.0](https://github.com/openai/openai-python/compare/v1.68.2...v1.69.0) diff --git a/pyproject.toml b/pyproject.toml index e50c5d6c1f..296d02e40b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.69.0" +version = "1.70.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 50c0e42d78..6b4385ec3c 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.69.0" # x-release-please-version +__version__ = "1.70.0" # x-release-please-version From a718999f751b2fb4574ebfdc1d66d6234334367c Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 1 Apr 2025 00:26:24 +0000 Subject: [PATCH 754/816] chore: Remove deprecated/unused remote spec feature --- .stats.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index f6a90d2438..2ccfd3411d 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 82 openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-6663c59193eb95b201e492de17dcbd5e126ba03d18ce66287a3e2c632ca56fe7.yml openapi_spec_hash: 7996d2c34cc44fe2ce9ffe93c0ab774e -config_hash: e25e31d8446b6bc0e3ef7103b6993cce +config_hash: 2daae06cc598821ccf87201de0861e40 From 7feb73e3ef2759d4c1dc9169b21fa3d51e694d00 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 1 Apr 2025 23:12:33 +0000 Subject: [PATCH 755/816] feat(api): manual updates --- .stats.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.stats.yml b/.stats.yml index 2ccfd3411d..71ac95541b 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 82 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-6663c59193eb95b201e492de17dcbd5e126ba03d18ce66287a3e2c632ca56fe7.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-4bce8217a697c729ac98046d4caf2c9e826b54c427fb0ab4f98e549a2e0ce31c.yml openapi_spec_hash: 7996d2c34cc44fe2ce9ffe93c0ab774e -config_hash: 2daae06cc598821ccf87201de0861e40 +config_hash: 31a12443afeef2933b34e2de23c40954 From 6747d4276a994e02e9c09cf87f620aadc7182fc6 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 1 Apr 2025 23:18:34 +0000 Subject: [PATCH 756/816] feat(api): manual updates --- .stats.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index 71ac95541b..baad2afc1b 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 82 openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-4bce8217a697c729ac98046d4caf2c9e826b54c427fb0ab4f98e549a2e0ce31c.yml openapi_spec_hash: 7996d2c34cc44fe2ce9ffe93c0ab774e -config_hash: 31a12443afeef2933b34e2de23c40954 +config_hash: 178ba1bfb1237bf6b94abb3408072aa7 From c87b46135f9351147d80b5a65e61108c26cd0405 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 2 Apr 2025 14:49:55 +0000 Subject: [PATCH 757/816] feat(api): manual updates --- .stats.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index baad2afc1b..675edb075a 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 82 openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-4bce8217a697c729ac98046d4caf2c9e826b54c427fb0ab4f98e549a2e0ce31c.yml openapi_spec_hash: 7996d2c34cc44fe2ce9ffe93c0ab774e -config_hash: 178ba1bfb1237bf6b94abb3408072aa7 +config_hash: 578c5bff4208d560c0c280f13324409f From fb69e674f3caaf451ad55ad92d430d0a50e7c0a4 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 3 Apr 2025 15:55:21 +0000 Subject: [PATCH 758/816] chore(internal): remove trailing character (#2277) --- tests/test_client.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_client.py b/tests/test_client.py index 62654afe1e..616255af3c 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1797,7 +1797,7 @@ def test_get_platform(self) -> None: import threading from openai._utils import asyncify - from openai._base_client import get_platform + from openai._base_client import get_platform async def test_main() -> None: result = await asyncify(get_platform)() From 41e74d45396659b4883fee6353c7abc88870f1f5 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 3 Apr 2025 18:37:53 +0000 Subject: [PATCH 759/816] feat(api): manual updates --- .stats.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index 675edb075a..aebb90c8cf 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 82 openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-4bce8217a697c729ac98046d4caf2c9e826b54c427fb0ab4f98e549a2e0ce31c.yml openapi_spec_hash: 7996d2c34cc44fe2ce9ffe93c0ab774e -config_hash: 578c5bff4208d560c0c280f13324409f +config_hash: bcd2cacdcb9fae9938f273cd167f613c From f24c9820397bd5a42980986ac04706625bba78ce Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 7 Apr 2025 13:29:13 +0000 Subject: [PATCH 760/816] chore(deps): allow websockets v15 (#2281) --- pyproject.toml | 2 +- requirements-dev.lock | 2 +- requirements.lock | 2 +- src/openai/resources/beta/realtime/realtime.py | 8 -------- 4 files changed, 3 insertions(+), 11 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 296d02e40b..0b7d1d41b4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,7 +43,7 @@ Repository = "https://github.com/openai/openai-python" openai = "openai.cli:main" [project.optional-dependencies] -realtime = ["websockets >= 13, < 15"] +realtime = ["websockets >= 13, < 16"] datalib = ["numpy >= 1", "pandas >= 1.2.3", "pandas-stubs >= 1.1.0.11"] voice_helpers = ["sounddevice>=0.5.1", "numpy>=2.0.2"] diff --git a/requirements-dev.lock b/requirements-dev.lock index 0755ddb3c5..11bb5c1b30 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -188,7 +188,7 @@ urllib3==2.2.1 # via requests virtualenv==20.24.5 # via nox -websockets==14.2 +websockets==15.0.1 # via openai zipp==3.17.0 # via importlib-metadata diff --git a/requirements.lock b/requirements.lock index fa88e26c0f..467abc6e90 100644 --- a/requirements.lock +++ b/requirements.lock @@ -70,5 +70,5 @@ typing-extensions==4.12.2 # via pydantic-core tzdata==2024.1 # via pandas -websockets==14.2 +websockets==15.0.1 # via openai diff --git a/src/openai/resources/beta/realtime/realtime.py b/src/openai/resources/beta/realtime/realtime.py index 76e57f8cb7..5cafce1322 100644 --- a/src/openai/resources/beta/realtime/realtime.py +++ b/src/openai/resources/beta/realtime/realtime.py @@ -277,10 +277,6 @@ async def recv_bytes(self) -> bytes: """ message = await self._connection.recv(decode=False) log.debug(f"Received websocket message: %s", message) - if not isinstance(message, bytes): - # passing `decode=False` should always result in us getting `bytes` back - raise TypeError(f"Expected `.recv(decode=False)` to return `bytes` but got {type(message)}") - return message async def send(self, event: RealtimeClientEvent | RealtimeClientEventParam) -> None: @@ -461,10 +457,6 @@ def recv_bytes(self) -> bytes: """ message = self._connection.recv(decode=False) log.debug(f"Received websocket message: %s", message) - if not isinstance(message, bytes): - # passing `decode=False` should always result in us getting `bytes` back - raise TypeError(f"Expected `.recv(decode=False)` to return `bytes` but got {type(message)}") - return message def send(self, event: RealtimeClientEvent | RealtimeClientEventParam) -> None: From a764253788df8a57fd05759aafd42c3c722d361c Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 7 Apr 2025 14:51:50 +0000 Subject: [PATCH 761/816] chore(internal): only run examples workflow in main repo (#2282) --- .github/workflows/ci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d86fc0ea53..6d2699cca8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -54,6 +54,7 @@ jobs: examples: name: examples runs-on: ubuntu-latest + if: github.repository == 'openai/openai-python' steps: - uses: actions/checkout@v4 From 692fd082b41047529b55a9c7e2047bdcbc2cccdd Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 7 Apr 2025 14:52:31 +0000 Subject: [PATCH 762/816] release: 1.71.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 19 +++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 22 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index ba5cbfb627..c7704ce953 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.70.0" + ".": "1.71.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 8954d86571..e8f2e22cb8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,24 @@ # Changelog +## 1.71.0 (2025-04-07) + +Full Changelog: [v1.70.0...v1.71.0](https://github.com/openai/openai-python/compare/v1.70.0...v1.71.0) + +### Features + +* **api:** manual updates ([bf8b4b6](https://github.com/openai/openai-python/commit/bf8b4b69906bfaea622c9c644270e985d92e2df2)) +* **api:** manual updates ([3e37aa3](https://github.com/openai/openai-python/commit/3e37aa3e151d9738625a1daf75d6243d6fdbe8f2)) +* **api:** manual updates ([dba9b65](https://github.com/openai/openai-python/commit/dba9b656fa5955b6eba8f6910da836a34de8d59d)) +* **api:** manual updates ([f0c463b](https://github.com/openai/openai-python/commit/f0c463b47836666d091b5f616871f1b94646d346)) + + +### Chores + +* **deps:** allow websockets v15 ([#2281](https://github.com/openai/openai-python/issues/2281)) ([19c619e](https://github.com/openai/openai-python/commit/19c619ea95839129a86c19d5b60133e1ed9f2746)) +* **internal:** only run examples workflow in main repo ([#2282](https://github.com/openai/openai-python/issues/2282)) ([c3e0927](https://github.com/openai/openai-python/commit/c3e0927d3fbbb9f753ba12adfa682a4235ba530a)) +* **internal:** remove trailing character ([#2277](https://github.com/openai/openai-python/issues/2277)) ([5a21a2d](https://github.com/openai/openai-python/commit/5a21a2d7994e39bb0c86271eeb807983a9ae874a)) +* Remove deprecated/unused remote spec feature ([23f76eb](https://github.com/openai/openai-python/commit/23f76eb0b9ddf12bcb04a6ad3f3ec5e956d2863f)) + ## 1.70.0 (2025-03-31) Full Changelog: [v1.69.0...v1.70.0](https://github.com/openai/openai-python/compare/v1.69.0...v1.70.0) diff --git a/pyproject.toml b/pyproject.toml index 0b7d1d41b4..4583a5531f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.70.0" +version = "1.71.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 6b4385ec3c..12e9d20bb1 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.70.0" # x-release-please-version +__version__ = "1.71.0" # x-release-please-version From 039b1bf54a2fe34c2ff2d669ee23515dae52d743 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 8 Apr 2025 12:09:51 +0000 Subject: [PATCH 763/816] chore(internal): slight transform perf improvement (#2284) --- src/openai/_utils/_transform.py | 22 ++++++++++++++++++++++ tests/test_transform.py | 12 ++++++++++++ 2 files changed, 34 insertions(+) diff --git a/src/openai/_utils/_transform.py b/src/openai/_utils/_transform.py index 7ac2e17fbb..3ec620818c 100644 --- a/src/openai/_utils/_transform.py +++ b/src/openai/_utils/_transform.py @@ -142,6 +142,10 @@ def _maybe_transform_key(key: str, type_: type) -> str: return key +def _no_transform_needed(annotation: type) -> bool: + return annotation == float or annotation == int + + def _transform_recursive( data: object, *, @@ -184,6 +188,15 @@ def _transform_recursive( return cast(object, data) inner_type = extract_type_arg(stripped_type, 0) + if _no_transform_needed(inner_type): + # for some types there is no need to transform anything, so we can get a small + # perf boost from skipping that work. + # + # but we still need to convert to a list to ensure the data is json-serializable + if is_list(data): + return data + return list(data) + return [_transform_recursive(d, annotation=annotation, inner_type=inner_type) for d in data] if is_union_type(stripped_type): @@ -332,6 +345,15 @@ async def _async_transform_recursive( return cast(object, data) inner_type = extract_type_arg(stripped_type, 0) + if _no_transform_needed(inner_type): + # for some types there is no need to transform anything, so we can get a small + # perf boost from skipping that work. + # + # but we still need to convert to a list to ensure the data is json-serializable + if is_list(data): + return data + return list(data) + return [await _async_transform_recursive(d, annotation=annotation, inner_type=inner_type) for d in data] if is_union_type(stripped_type): diff --git a/tests/test_transform.py b/tests/test_transform.py index 385fbe2b2c..cd584756d7 100644 --- a/tests/test_transform.py +++ b/tests/test_transform.py @@ -432,3 +432,15 @@ async def test_base64_file_input(use_async: bool) -> None: assert await transform({"foo": io.BytesIO(b"Hello, world!")}, TypedDictBase64Input, use_async) == { "foo": "SGVsbG8sIHdvcmxkIQ==" } # type: ignore[comparison-overlap] + + +@parametrize +@pytest.mark.asyncio +async def test_transform_skipping(use_async: bool) -> None: + # lists of ints are left as-is + data = [1, 2, 3] + assert await transform(data, List[int], use_async) is data + + # iterables of ints are converted to a list + data = iter([1, 2, 3]) + assert await transform(data, Iterable[int], use_async) == [1, 2, 3] From 48c200ac0d732b030a87012575c1843957e98718 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 8 Apr 2025 14:25:27 +0000 Subject: [PATCH 764/816] chore(tests): improve enum examples (#2286) --- tests/api_resources/test_images.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/api_resources/test_images.py b/tests/api_resources/test_images.py index 9bc9719bc5..2e31f3354a 100644 --- a/tests/api_resources/test_images.py +++ b/tests/api_resources/test_images.py @@ -31,7 +31,7 @@ def test_method_create_variation_with_all_params(self, client: OpenAI) -> None: model="dall-e-2", n=1, response_format="url", - size="256x256", + size="1024x1024", user="user-1234", ) assert_matches_type(ImagesResponse, image, path=["response"]) @@ -77,7 +77,7 @@ def test_method_edit_with_all_params(self, client: OpenAI) -> None: model="dall-e-2", n=1, response_format="url", - size="256x256", + size="1024x1024", user="user-1234", ) assert_matches_type(ImagesResponse, image, path=["response"]) @@ -123,7 +123,7 @@ def test_method_generate_with_all_params(self, client: OpenAI) -> None: n=1, quality="standard", response_format="url", - size="256x256", + size="1024x1024", style="vivid", user="user-1234", ) @@ -171,7 +171,7 @@ async def test_method_create_variation_with_all_params(self, async_client: Async model="dall-e-2", n=1, response_format="url", - size="256x256", + size="1024x1024", user="user-1234", ) assert_matches_type(ImagesResponse, image, path=["response"]) @@ -217,7 +217,7 @@ async def test_method_edit_with_all_params(self, async_client: AsyncOpenAI) -> N model="dall-e-2", n=1, response_format="url", - size="256x256", + size="1024x1024", user="user-1234", ) assert_matches_type(ImagesResponse, image, path=["response"]) @@ -263,7 +263,7 @@ async def test_method_generate_with_all_params(self, async_client: AsyncOpenAI) n=1, quality="standard", response_format="url", - size="256x256", + size="1024x1024", style="vivid", user="user-1234", ) From 8da9f46bedc954cb4ceba2eb5acf5f9d3c22df57 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 8 Apr 2025 18:50:02 +0000 Subject: [PATCH 765/816] feat(api): Add evalapi to sdk (#2287) Adding the evalsapi to the sdk. --- .stats.yml | 8 +- api.md | 85 + src/openai/__init__.py | 1 + src/openai/_client.py | 9 + src/openai/_module_client.py | 7 + src/openai/resources/__init__.py | 14 + src/openai/resources/evals/__init__.py | 33 + src/openai/resources/evals/evals.py | 663 +++++++ src/openai/resources/evals/runs/__init__.py | 33 + .../resources/evals/runs/output_items.py | 315 +++ src/openai/resources/evals/runs/runs.py | 635 ++++++ src/openai/resources/fine_tuning/__init__.py | 14 + .../fine_tuning/checkpoints/__init__.py | 33 + .../fine_tuning/checkpoints/checkpoints.py | 102 + .../fine_tuning/checkpoints/permissions.py | 416 ++++ .../resources/fine_tuning/fine_tuning.py | 32 + src/openai/types/__init__.py | 17 + src/openai/types/eval_create_params.py | 153 ++ src/openai/types/eval_create_response.py | 56 + .../types/eval_custom_data_source_config.py | 21 + src/openai/types/eval_delete_response.py | 14 + src/openai/types/eval_label_model_grader.py | 74 + src/openai/types/eval_list_params.py | 27 + src/openai/types/eval_list_response.py | 56 + src/openai/types/eval_retrieve_response.py | 56 + ...l_stored_completions_data_source_config.py | 32 + src/openai/types/eval_string_check_grader.py | 24 + .../types/eval_string_check_grader_param.py | 24 + .../types/eval_text_similarity_grader.py | 44 + .../eval_text_similarity_grader_param.py | 45 + src/openai/types/eval_update_params.py | 25 + src/openai/types/eval_update_response.py | 56 + src/openai/types/evals/__init__.py | 22 + ...create_eval_completions_run_data_source.py | 185 ++ ..._eval_completions_run_data_source_param.py | 181 ++ .../create_eval_jsonl_run_data_source.py | 41 + ...create_eval_jsonl_run_data_source_param.py | 46 + src/openai/types/evals/eval_api_error.py | 14 + src/openai/types/evals/run_cancel_response.py | 115 ++ src/openai/types/evals/run_create_params.py | 33 + src/openai/types/evals/run_create_response.py | 115 ++ src/openai/types/evals/run_delete_response.py | 15 + src/openai/types/evals/run_list_params.py | 27 + src/openai/types/evals/run_list_response.py | 115 ++ .../types/evals/run_retrieve_response.py | 115 ++ src/openai/types/evals/runs/__init__.py | 7 + .../evals/runs/output_item_list_params.py | 30 + .../evals/runs/output_item_list_response.py | 104 + .../runs/output_item_retrieve_response.py | 104 + .../types/fine_tuning/checkpoints/__init__.py | 9 + .../checkpoints/permission_create_params.py | 13 + .../checkpoints/permission_create_response.py | 21 + .../checkpoints/permission_delete_response.py | 18 + .../checkpoints/permission_retrieve_params.py | 21 + .../permission_retrieve_response.py | 34 + tests/api_resources/evals/__init__.py | 1 + tests/api_resources/evals/runs/__init__.py | 1 + .../evals/runs/test_output_items.py | 263 +++ tests/api_resources/evals/test_runs.py | 589 ++++++ .../fine_tuning/checkpoints/__init__.py | 1 + .../checkpoints/test_permissions.py | 297 +++ tests/api_resources/test_evals.py | 1701 +++++++++++++++++ 62 files changed, 7358 insertions(+), 4 deletions(-) create mode 100644 src/openai/resources/evals/__init__.py create mode 100644 src/openai/resources/evals/evals.py create mode 100644 src/openai/resources/evals/runs/__init__.py create mode 100644 src/openai/resources/evals/runs/output_items.py create mode 100644 src/openai/resources/evals/runs/runs.py create mode 100644 src/openai/resources/fine_tuning/checkpoints/__init__.py create mode 100644 src/openai/resources/fine_tuning/checkpoints/checkpoints.py create mode 100644 src/openai/resources/fine_tuning/checkpoints/permissions.py create mode 100644 src/openai/types/eval_create_params.py create mode 100644 src/openai/types/eval_create_response.py create mode 100644 src/openai/types/eval_custom_data_source_config.py create mode 100644 src/openai/types/eval_delete_response.py create mode 100644 src/openai/types/eval_label_model_grader.py create mode 100644 src/openai/types/eval_list_params.py create mode 100644 src/openai/types/eval_list_response.py create mode 100644 src/openai/types/eval_retrieve_response.py create mode 100644 src/openai/types/eval_stored_completions_data_source_config.py create mode 100644 src/openai/types/eval_string_check_grader.py create mode 100644 src/openai/types/eval_string_check_grader_param.py create mode 100644 src/openai/types/eval_text_similarity_grader.py create mode 100644 src/openai/types/eval_text_similarity_grader_param.py create mode 100644 src/openai/types/eval_update_params.py create mode 100644 src/openai/types/eval_update_response.py create mode 100644 src/openai/types/evals/__init__.py create mode 100644 src/openai/types/evals/create_eval_completions_run_data_source.py create mode 100644 src/openai/types/evals/create_eval_completions_run_data_source_param.py create mode 100644 src/openai/types/evals/create_eval_jsonl_run_data_source.py create mode 100644 src/openai/types/evals/create_eval_jsonl_run_data_source_param.py create mode 100644 src/openai/types/evals/eval_api_error.py create mode 100644 src/openai/types/evals/run_cancel_response.py create mode 100644 src/openai/types/evals/run_create_params.py create mode 100644 src/openai/types/evals/run_create_response.py create mode 100644 src/openai/types/evals/run_delete_response.py create mode 100644 src/openai/types/evals/run_list_params.py create mode 100644 src/openai/types/evals/run_list_response.py create mode 100644 src/openai/types/evals/run_retrieve_response.py create mode 100644 src/openai/types/evals/runs/__init__.py create mode 100644 src/openai/types/evals/runs/output_item_list_params.py create mode 100644 src/openai/types/evals/runs/output_item_list_response.py create mode 100644 src/openai/types/evals/runs/output_item_retrieve_response.py create mode 100644 src/openai/types/fine_tuning/checkpoints/__init__.py create mode 100644 src/openai/types/fine_tuning/checkpoints/permission_create_params.py create mode 100644 src/openai/types/fine_tuning/checkpoints/permission_create_response.py create mode 100644 src/openai/types/fine_tuning/checkpoints/permission_delete_response.py create mode 100644 src/openai/types/fine_tuning/checkpoints/permission_retrieve_params.py create mode 100644 src/openai/types/fine_tuning/checkpoints/permission_retrieve_response.py create mode 100644 tests/api_resources/evals/__init__.py create mode 100644 tests/api_resources/evals/runs/__init__.py create mode 100644 tests/api_resources/evals/runs/test_output_items.py create mode 100644 tests/api_resources/evals/test_runs.py create mode 100644 tests/api_resources/fine_tuning/checkpoints/__init__.py create mode 100644 tests/api_resources/fine_tuning/checkpoints/test_permissions.py create mode 100644 tests/api_resources/test_evals.py diff --git a/.stats.yml b/.stats.yml index aebb90c8cf..ebe07c1372 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ -configured_endpoints: 82 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-4bce8217a697c729ac98046d4caf2c9e826b54c427fb0ab4f98e549a2e0ce31c.yml -openapi_spec_hash: 7996d2c34cc44fe2ce9ffe93c0ab774e -config_hash: bcd2cacdcb9fae9938f273cd167f613c +configured_endpoints: 97 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-472fe3036ea745365257fe870c0330917fb3153705c2826f49873cd631319b0a.yml +openapi_spec_hash: ea86343b5e9858a74e85da8ab2c532f6 +config_hash: ef19d36c307306f14f2e1cd5c834a151 diff --git a/api.md b/api.md index a5f81c624c..e06f55c2cc 100644 --- a/api.md +++ b/api.md @@ -259,6 +259,26 @@ Methods: - client.fine_tuning.jobs.checkpoints.list(fine_tuning_job_id, \*\*params) -> SyncCursorPage[FineTuningJobCheckpoint] +## Checkpoints + +### Permissions + +Types: + +```python +from openai.types.fine_tuning.checkpoints import ( + PermissionCreateResponse, + PermissionRetrieveResponse, + PermissionDeleteResponse, +) +``` + +Methods: + +- client.fine_tuning.checkpoints.permissions.create(fine_tuned_model_checkpoint, \*\*params) -> SyncPage[PermissionCreateResponse] +- client.fine_tuning.checkpoints.permissions.retrieve(fine_tuned_model_checkpoint, \*\*params) -> PermissionRetrieveResponse +- client.fine_tuning.checkpoints.permissions.delete(fine_tuned_model_checkpoint) -> PermissionDeleteResponse + # VectorStores Types: @@ -706,3 +726,68 @@ from openai.types.responses import ResponseItemList Methods: - client.responses.input_items.list(response_id, \*\*params) -> SyncCursorPage[ResponseItem] + +# Evals + +Types: + +```python +from openai.types import ( + EvalCustomDataSourceConfig, + EvalLabelModelGrader, + EvalStoredCompletionsDataSourceConfig, + EvalStringCheckGrader, + EvalTextSimilarityGrader, + EvalCreateResponse, + EvalRetrieveResponse, + EvalUpdateResponse, + EvalListResponse, + EvalDeleteResponse, +) +``` + +Methods: + +- client.evals.create(\*\*params) -> EvalCreateResponse +- client.evals.retrieve(eval_id) -> EvalRetrieveResponse +- client.evals.update(eval_id, \*\*params) -> EvalUpdateResponse +- client.evals.list(\*\*params) -> SyncCursorPage[EvalListResponse] +- client.evals.delete(eval_id) -> EvalDeleteResponse + +## Runs + +Types: + +```python +from openai.types.evals import ( + CreateEvalCompletionsRunDataSource, + CreateEvalJSONLRunDataSource, + EvalAPIError, + RunCreateResponse, + RunRetrieveResponse, + RunListResponse, + RunDeleteResponse, + RunCancelResponse, +) +``` + +Methods: + +- client.evals.runs.create(eval_id, \*\*params) -> RunCreateResponse +- client.evals.runs.retrieve(run_id, \*, eval_id) -> RunRetrieveResponse +- client.evals.runs.list(eval_id, \*\*params) -> SyncCursorPage[RunListResponse] +- client.evals.runs.delete(run_id, \*, eval_id) -> RunDeleteResponse +- client.evals.runs.cancel(run_id, \*, eval_id) -> RunCancelResponse + +### OutputItems + +Types: + +```python +from openai.types.evals.runs import OutputItemRetrieveResponse, OutputItemListResponse +``` + +Methods: + +- client.evals.runs.output_items.retrieve(output_item_id, \*, eval_id, run_id) -> OutputItemRetrieveResponse +- client.evals.runs.output_items.list(run_id, \*, eval_id, \*\*params) -> SyncCursorPage[OutputItemListResponse] diff --git a/src/openai/__init__.py b/src/openai/__init__.py index 7ce6df0817..9e97098bb0 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -352,6 +352,7 @@ def _reset_client() -> None: # type: ignore[reportUnusedFunction] beta as beta, chat as chat, audio as audio, + evals as evals, files as files, images as images, models as models, diff --git a/src/openai/_client.py b/src/openai/_client.py index 18d96da9a3..3aca6cb124 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -36,6 +36,7 @@ from .resources.beta import beta from .resources.chat import chat from .resources.audio import audio +from .resources.evals import evals from .resources.uploads import uploads from .resources.responses import responses from .resources.fine_tuning import fine_tuning @@ -59,6 +60,7 @@ class OpenAI(SyncAPIClient): batches: batches.Batches uploads: uploads.Uploads responses: responses.Responses + evals: evals.Evals with_raw_response: OpenAIWithRawResponse with_streaming_response: OpenAIWithStreamedResponse @@ -158,6 +160,7 @@ def __init__( self.batches = batches.Batches(self) self.uploads = uploads.Uploads(self) self.responses = responses.Responses(self) + self.evals = evals.Evals(self) self.with_raw_response = OpenAIWithRawResponse(self) self.with_streaming_response = OpenAIWithStreamedResponse(self) @@ -290,6 +293,7 @@ class AsyncOpenAI(AsyncAPIClient): batches: batches.AsyncBatches uploads: uploads.AsyncUploads responses: responses.AsyncResponses + evals: evals.AsyncEvals with_raw_response: AsyncOpenAIWithRawResponse with_streaming_response: AsyncOpenAIWithStreamedResponse @@ -389,6 +393,7 @@ def __init__( self.batches = batches.AsyncBatches(self) self.uploads = uploads.AsyncUploads(self) self.responses = responses.AsyncResponses(self) + self.evals = evals.AsyncEvals(self) self.with_raw_response = AsyncOpenAIWithRawResponse(self) self.with_streaming_response = AsyncOpenAIWithStreamedResponse(self) @@ -522,6 +527,7 @@ def __init__(self, client: OpenAI) -> None: self.batches = batches.BatchesWithRawResponse(client.batches) self.uploads = uploads.UploadsWithRawResponse(client.uploads) self.responses = responses.ResponsesWithRawResponse(client.responses) + self.evals = evals.EvalsWithRawResponse(client.evals) class AsyncOpenAIWithRawResponse: @@ -540,6 +546,7 @@ def __init__(self, client: AsyncOpenAI) -> None: self.batches = batches.AsyncBatchesWithRawResponse(client.batches) self.uploads = uploads.AsyncUploadsWithRawResponse(client.uploads) self.responses = responses.AsyncResponsesWithRawResponse(client.responses) + self.evals = evals.AsyncEvalsWithRawResponse(client.evals) class OpenAIWithStreamedResponse: @@ -558,6 +565,7 @@ def __init__(self, client: OpenAI) -> None: self.batches = batches.BatchesWithStreamingResponse(client.batches) self.uploads = uploads.UploadsWithStreamingResponse(client.uploads) self.responses = responses.ResponsesWithStreamingResponse(client.responses) + self.evals = evals.EvalsWithStreamingResponse(client.evals) class AsyncOpenAIWithStreamedResponse: @@ -576,6 +584,7 @@ def __init__(self, client: AsyncOpenAI) -> None: self.batches = batches.AsyncBatchesWithStreamingResponse(client.batches) self.uploads = uploads.AsyncUploadsWithStreamingResponse(client.uploads) self.responses = responses.AsyncResponsesWithStreamingResponse(client.responses) + self.evals = evals.AsyncEvalsWithStreamingResponse(client.evals) Client = OpenAI diff --git a/src/openai/_module_client.py b/src/openai/_module_client.py index e7d2657860..cf12f7a31e 100644 --- a/src/openai/_module_client.py +++ b/src/openai/_module_client.py @@ -30,6 +30,12 @@ def __load__(self) -> resources.Audio: return _load_client().audio +class EvalsProxy(LazyProxy[resources.Evals]): + @override + def __load__(self) -> resources.Evals: + return _load_client().evals + + class ImagesProxy(LazyProxy[resources.Images]): @override def __load__(self) -> resources.Images: @@ -94,6 +100,7 @@ def __load__(self) -> resources.VectorStores: beta: resources.Beta = BetaProxy().__as_proxied__() files: resources.Files = FilesProxy().__as_proxied__() audio: resources.Audio = AudioProxy().__as_proxied__() +evals: resources.Evals = EvalsProxy().__as_proxied__() images: resources.Images = ImagesProxy().__as_proxied__() models: resources.Models = ModelsProxy().__as_proxied__() batches: resources.Batches = BatchesProxy().__as_proxied__() diff --git a/src/openai/resources/__init__.py b/src/openai/resources/__init__.py index d3457cf319..ab9cd73e81 100644 --- a/src/openai/resources/__init__.py +++ b/src/openai/resources/__init__.py @@ -24,6 +24,14 @@ AudioWithStreamingResponse, AsyncAudioWithStreamingResponse, ) +from .evals import ( + Evals, + AsyncEvals, + EvalsWithRawResponse, + AsyncEvalsWithRawResponse, + EvalsWithStreamingResponse, + AsyncEvalsWithStreamingResponse, +) from .files import ( Files, AsyncFiles, @@ -198,4 +206,10 @@ "AsyncResponsesWithRawResponse", "ResponsesWithStreamingResponse", "AsyncResponsesWithStreamingResponse", + "Evals", + "AsyncEvals", + "EvalsWithRawResponse", + "AsyncEvalsWithRawResponse", + "EvalsWithStreamingResponse", + "AsyncEvalsWithStreamingResponse", ] diff --git a/src/openai/resources/evals/__init__.py b/src/openai/resources/evals/__init__.py new file mode 100644 index 0000000000..84f707511d --- /dev/null +++ b/src/openai/resources/evals/__init__.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .runs import ( + Runs, + AsyncRuns, + RunsWithRawResponse, + AsyncRunsWithRawResponse, + RunsWithStreamingResponse, + AsyncRunsWithStreamingResponse, +) +from .evals import ( + Evals, + AsyncEvals, + EvalsWithRawResponse, + AsyncEvalsWithRawResponse, + EvalsWithStreamingResponse, + AsyncEvalsWithStreamingResponse, +) + +__all__ = [ + "Runs", + "AsyncRuns", + "RunsWithRawResponse", + "AsyncRunsWithRawResponse", + "RunsWithStreamingResponse", + "AsyncRunsWithStreamingResponse", + "Evals", + "AsyncEvals", + "EvalsWithRawResponse", + "AsyncEvalsWithRawResponse", + "EvalsWithStreamingResponse", + "AsyncEvalsWithStreamingResponse", +] diff --git a/src/openai/resources/evals/evals.py b/src/openai/resources/evals/evals.py new file mode 100644 index 0000000000..24a0350cfb --- /dev/null +++ b/src/openai/resources/evals/evals.py @@ -0,0 +1,663 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Iterable, Optional +from typing_extensions import Literal + +import httpx + +from ... import _legacy_response +from ...types import eval_list_params, eval_create_params, eval_update_params +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ..._utils import ( + maybe_transform, + async_maybe_transform, +) +from ..._compat import cached_property +from .runs.runs import ( + Runs, + AsyncRuns, + RunsWithRawResponse, + AsyncRunsWithRawResponse, + RunsWithStreamingResponse, + AsyncRunsWithStreamingResponse, +) +from ..._resource import SyncAPIResource, AsyncAPIResource +from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ...pagination import SyncCursorPage, AsyncCursorPage +from ..._base_client import AsyncPaginator, make_request_options +from ...types.eval_list_response import EvalListResponse +from ...types.eval_create_response import EvalCreateResponse +from ...types.eval_delete_response import EvalDeleteResponse +from ...types.eval_update_response import EvalUpdateResponse +from ...types.eval_retrieve_response import EvalRetrieveResponse +from ...types.shared_params.metadata import Metadata + +__all__ = ["Evals", "AsyncEvals"] + + +class Evals(SyncAPIResource): + @cached_property + def runs(self) -> Runs: + return Runs(self._client) + + @cached_property + def with_raw_response(self) -> EvalsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return EvalsWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> EvalsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return EvalsWithStreamingResponse(self) + + def create( + self, + *, + data_source_config: eval_create_params.DataSourceConfig, + testing_criteria: Iterable[eval_create_params.TestingCriterion], + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + name: str | NotGiven = NOT_GIVEN, + share_with_openai: bool | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> EvalCreateResponse: + """ + Create the structure of an evaluation that can be used to test a model's + performance. An evaluation is a set of testing criteria and a datasource. After + creating an evaluation, you can run it on different models and model parameters. + We support several types of graders and datasources. For more information, see + the [Evals guide](https://platform.openai.com/docs/guides/evals). + + Args: + data_source_config: The configuration for the data source used for the evaluation runs. + + testing_criteria: A list of graders for all eval runs in this group. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + + name: The name of the evaluation. + + share_with_openai: Indicates whether the evaluation is shared with OpenAI. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._post( + "/evals", + body=maybe_transform( + { + "data_source_config": data_source_config, + "testing_criteria": testing_criteria, + "metadata": metadata, + "name": name, + "share_with_openai": share_with_openai, + }, + eval_create_params.EvalCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=EvalCreateResponse, + ) + + def retrieve( + self, + eval_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> EvalRetrieveResponse: + """ + Get an evaluation by ID. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not eval_id: + raise ValueError(f"Expected a non-empty value for `eval_id` but received {eval_id!r}") + return self._get( + f"/evals/{eval_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=EvalRetrieveResponse, + ) + + def update( + self, + eval_id: str, + *, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + name: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> EvalUpdateResponse: + """ + Update certain properties of an evaluation. + + Args: + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + + name: Rename the evaluation. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not eval_id: + raise ValueError(f"Expected a non-empty value for `eval_id` but received {eval_id!r}") + return self._post( + f"/evals/{eval_id}", + body=maybe_transform( + { + "metadata": metadata, + "name": name, + }, + eval_update_params.EvalUpdateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=EvalUpdateResponse, + ) + + def list( + self, + *, + after: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + order_by: Literal["created_at", "updated_at"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> SyncCursorPage[EvalListResponse]: + """ + List evaluations for a project. + + Args: + after: Identifier for the last eval from the previous pagination request. + + limit: Number of evals to retrieve. + + order: Sort order for evals by timestamp. Use `asc` for ascending order or `desc` for + descending order. + + order_by: Evals can be ordered by creation time or last updated time. Use `created_at` for + creation time or `updated_at` for last updated time. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get_api_list( + "/evals", + page=SyncCursorPage[EvalListResponse], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "limit": limit, + "order": order, + "order_by": order_by, + }, + eval_list_params.EvalListParams, + ), + ), + model=EvalListResponse, + ) + + def delete( + self, + eval_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> EvalDeleteResponse: + """ + Delete an evaluation. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not eval_id: + raise ValueError(f"Expected a non-empty value for `eval_id` but received {eval_id!r}") + return self._delete( + f"/evals/{eval_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=EvalDeleteResponse, + ) + + +class AsyncEvals(AsyncAPIResource): + @cached_property + def runs(self) -> AsyncRuns: + return AsyncRuns(self._client) + + @cached_property + def with_raw_response(self) -> AsyncEvalsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return AsyncEvalsWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncEvalsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return AsyncEvalsWithStreamingResponse(self) + + async def create( + self, + *, + data_source_config: eval_create_params.DataSourceConfig, + testing_criteria: Iterable[eval_create_params.TestingCriterion], + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + name: str | NotGiven = NOT_GIVEN, + share_with_openai: bool | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> EvalCreateResponse: + """ + Create the structure of an evaluation that can be used to test a model's + performance. An evaluation is a set of testing criteria and a datasource. After + creating an evaluation, you can run it on different models and model parameters. + We support several types of graders and datasources. For more information, see + the [Evals guide](https://platform.openai.com/docs/guides/evals). + + Args: + data_source_config: The configuration for the data source used for the evaluation runs. + + testing_criteria: A list of graders for all eval runs in this group. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + + name: The name of the evaluation. + + share_with_openai: Indicates whether the evaluation is shared with OpenAI. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._post( + "/evals", + body=await async_maybe_transform( + { + "data_source_config": data_source_config, + "testing_criteria": testing_criteria, + "metadata": metadata, + "name": name, + "share_with_openai": share_with_openai, + }, + eval_create_params.EvalCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=EvalCreateResponse, + ) + + async def retrieve( + self, + eval_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> EvalRetrieveResponse: + """ + Get an evaluation by ID. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not eval_id: + raise ValueError(f"Expected a non-empty value for `eval_id` but received {eval_id!r}") + return await self._get( + f"/evals/{eval_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=EvalRetrieveResponse, + ) + + async def update( + self, + eval_id: str, + *, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + name: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> EvalUpdateResponse: + """ + Update certain properties of an evaluation. + + Args: + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + + name: Rename the evaluation. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not eval_id: + raise ValueError(f"Expected a non-empty value for `eval_id` but received {eval_id!r}") + return await self._post( + f"/evals/{eval_id}", + body=await async_maybe_transform( + { + "metadata": metadata, + "name": name, + }, + eval_update_params.EvalUpdateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=EvalUpdateResponse, + ) + + def list( + self, + *, + after: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + order_by: Literal["created_at", "updated_at"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncPaginator[EvalListResponse, AsyncCursorPage[EvalListResponse]]: + """ + List evaluations for a project. + + Args: + after: Identifier for the last eval from the previous pagination request. + + limit: Number of evals to retrieve. + + order: Sort order for evals by timestamp. Use `asc` for ascending order or `desc` for + descending order. + + order_by: Evals can be ordered by creation time or last updated time. Use `created_at` for + creation time or `updated_at` for last updated time. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._get_api_list( + "/evals", + page=AsyncCursorPage[EvalListResponse], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "limit": limit, + "order": order, + "order_by": order_by, + }, + eval_list_params.EvalListParams, + ), + ), + model=EvalListResponse, + ) + + async def delete( + self, + eval_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> EvalDeleteResponse: + """ + Delete an evaluation. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not eval_id: + raise ValueError(f"Expected a non-empty value for `eval_id` but received {eval_id!r}") + return await self._delete( + f"/evals/{eval_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=EvalDeleteResponse, + ) + + +class EvalsWithRawResponse: + def __init__(self, evals: Evals) -> None: + self._evals = evals + + self.create = _legacy_response.to_raw_response_wrapper( + evals.create, + ) + self.retrieve = _legacy_response.to_raw_response_wrapper( + evals.retrieve, + ) + self.update = _legacy_response.to_raw_response_wrapper( + evals.update, + ) + self.list = _legacy_response.to_raw_response_wrapper( + evals.list, + ) + self.delete = _legacy_response.to_raw_response_wrapper( + evals.delete, + ) + + @cached_property + def runs(self) -> RunsWithRawResponse: + return RunsWithRawResponse(self._evals.runs) + + +class AsyncEvalsWithRawResponse: + def __init__(self, evals: AsyncEvals) -> None: + self._evals = evals + + self.create = _legacy_response.async_to_raw_response_wrapper( + evals.create, + ) + self.retrieve = _legacy_response.async_to_raw_response_wrapper( + evals.retrieve, + ) + self.update = _legacy_response.async_to_raw_response_wrapper( + evals.update, + ) + self.list = _legacy_response.async_to_raw_response_wrapper( + evals.list, + ) + self.delete = _legacy_response.async_to_raw_response_wrapper( + evals.delete, + ) + + @cached_property + def runs(self) -> AsyncRunsWithRawResponse: + return AsyncRunsWithRawResponse(self._evals.runs) + + +class EvalsWithStreamingResponse: + def __init__(self, evals: Evals) -> None: + self._evals = evals + + self.create = to_streamed_response_wrapper( + evals.create, + ) + self.retrieve = to_streamed_response_wrapper( + evals.retrieve, + ) + self.update = to_streamed_response_wrapper( + evals.update, + ) + self.list = to_streamed_response_wrapper( + evals.list, + ) + self.delete = to_streamed_response_wrapper( + evals.delete, + ) + + @cached_property + def runs(self) -> RunsWithStreamingResponse: + return RunsWithStreamingResponse(self._evals.runs) + + +class AsyncEvalsWithStreamingResponse: + def __init__(self, evals: AsyncEvals) -> None: + self._evals = evals + + self.create = async_to_streamed_response_wrapper( + evals.create, + ) + self.retrieve = async_to_streamed_response_wrapper( + evals.retrieve, + ) + self.update = async_to_streamed_response_wrapper( + evals.update, + ) + self.list = async_to_streamed_response_wrapper( + evals.list, + ) + self.delete = async_to_streamed_response_wrapper( + evals.delete, + ) + + @cached_property + def runs(self) -> AsyncRunsWithStreamingResponse: + return AsyncRunsWithStreamingResponse(self._evals.runs) diff --git a/src/openai/resources/evals/runs/__init__.py b/src/openai/resources/evals/runs/__init__.py new file mode 100644 index 0000000000..d189f16fb7 --- /dev/null +++ b/src/openai/resources/evals/runs/__init__.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .runs import ( + Runs, + AsyncRuns, + RunsWithRawResponse, + AsyncRunsWithRawResponse, + RunsWithStreamingResponse, + AsyncRunsWithStreamingResponse, +) +from .output_items import ( + OutputItems, + AsyncOutputItems, + OutputItemsWithRawResponse, + AsyncOutputItemsWithRawResponse, + OutputItemsWithStreamingResponse, + AsyncOutputItemsWithStreamingResponse, +) + +__all__ = [ + "OutputItems", + "AsyncOutputItems", + "OutputItemsWithRawResponse", + "AsyncOutputItemsWithRawResponse", + "OutputItemsWithStreamingResponse", + "AsyncOutputItemsWithStreamingResponse", + "Runs", + "AsyncRuns", + "RunsWithRawResponse", + "AsyncRunsWithRawResponse", + "RunsWithStreamingResponse", + "AsyncRunsWithStreamingResponse", +] diff --git a/src/openai/resources/evals/runs/output_items.py b/src/openai/resources/evals/runs/output_items.py new file mode 100644 index 0000000000..8fd0fdea92 --- /dev/null +++ b/src/openai/resources/evals/runs/output_items.py @@ -0,0 +1,315 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal + +import httpx + +from .... import _legacy_response +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ...._utils import maybe_transform +from ...._compat import cached_property +from ...._resource import SyncAPIResource, AsyncAPIResource +from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ....pagination import SyncCursorPage, AsyncCursorPage +from ...._base_client import AsyncPaginator, make_request_options +from ....types.evals.runs import output_item_list_params +from ....types.evals.runs.output_item_list_response import OutputItemListResponse +from ....types.evals.runs.output_item_retrieve_response import OutputItemRetrieveResponse + +__all__ = ["OutputItems", "AsyncOutputItems"] + + +class OutputItems(SyncAPIResource): + @cached_property + def with_raw_response(self) -> OutputItemsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return OutputItemsWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> OutputItemsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return OutputItemsWithStreamingResponse(self) + + def retrieve( + self, + output_item_id: str, + *, + eval_id: str, + run_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> OutputItemRetrieveResponse: + """ + Get an evaluation run output item by ID. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not eval_id: + raise ValueError(f"Expected a non-empty value for `eval_id` but received {eval_id!r}") + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") + if not output_item_id: + raise ValueError(f"Expected a non-empty value for `output_item_id` but received {output_item_id!r}") + return self._get( + f"/evals/{eval_id}/runs/{run_id}/output_items/{output_item_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=OutputItemRetrieveResponse, + ) + + def list( + self, + run_id: str, + *, + eval_id: str, + after: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + status: Literal["fail", "pass"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> SyncCursorPage[OutputItemListResponse]: + """ + Get a list of output items for an evaluation run. + + Args: + after: Identifier for the last output item from the previous pagination request. + + limit: Number of output items to retrieve. + + order: Sort order for output items by timestamp. Use `asc` for ascending order or + `desc` for descending order. Defaults to `asc`. + + status: Filter output items by status. Use `failed` to filter by failed output items or + `pass` to filter by passed output items. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not eval_id: + raise ValueError(f"Expected a non-empty value for `eval_id` but received {eval_id!r}") + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") + return self._get_api_list( + f"/evals/{eval_id}/runs/{run_id}/output_items", + page=SyncCursorPage[OutputItemListResponse], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "limit": limit, + "order": order, + "status": status, + }, + output_item_list_params.OutputItemListParams, + ), + ), + model=OutputItemListResponse, + ) + + +class AsyncOutputItems(AsyncAPIResource): + @cached_property + def with_raw_response(self) -> AsyncOutputItemsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return AsyncOutputItemsWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncOutputItemsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return AsyncOutputItemsWithStreamingResponse(self) + + async def retrieve( + self, + output_item_id: str, + *, + eval_id: str, + run_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> OutputItemRetrieveResponse: + """ + Get an evaluation run output item by ID. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not eval_id: + raise ValueError(f"Expected a non-empty value for `eval_id` but received {eval_id!r}") + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") + if not output_item_id: + raise ValueError(f"Expected a non-empty value for `output_item_id` but received {output_item_id!r}") + return await self._get( + f"/evals/{eval_id}/runs/{run_id}/output_items/{output_item_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=OutputItemRetrieveResponse, + ) + + def list( + self, + run_id: str, + *, + eval_id: str, + after: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + status: Literal["fail", "pass"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncPaginator[OutputItemListResponse, AsyncCursorPage[OutputItemListResponse]]: + """ + Get a list of output items for an evaluation run. + + Args: + after: Identifier for the last output item from the previous pagination request. + + limit: Number of output items to retrieve. + + order: Sort order for output items by timestamp. Use `asc` for ascending order or + `desc` for descending order. Defaults to `asc`. + + status: Filter output items by status. Use `failed` to filter by failed output items or + `pass` to filter by passed output items. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not eval_id: + raise ValueError(f"Expected a non-empty value for `eval_id` but received {eval_id!r}") + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") + return self._get_api_list( + f"/evals/{eval_id}/runs/{run_id}/output_items", + page=AsyncCursorPage[OutputItemListResponse], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "limit": limit, + "order": order, + "status": status, + }, + output_item_list_params.OutputItemListParams, + ), + ), + model=OutputItemListResponse, + ) + + +class OutputItemsWithRawResponse: + def __init__(self, output_items: OutputItems) -> None: + self._output_items = output_items + + self.retrieve = _legacy_response.to_raw_response_wrapper( + output_items.retrieve, + ) + self.list = _legacy_response.to_raw_response_wrapper( + output_items.list, + ) + + +class AsyncOutputItemsWithRawResponse: + def __init__(self, output_items: AsyncOutputItems) -> None: + self._output_items = output_items + + self.retrieve = _legacy_response.async_to_raw_response_wrapper( + output_items.retrieve, + ) + self.list = _legacy_response.async_to_raw_response_wrapper( + output_items.list, + ) + + +class OutputItemsWithStreamingResponse: + def __init__(self, output_items: OutputItems) -> None: + self._output_items = output_items + + self.retrieve = to_streamed_response_wrapper( + output_items.retrieve, + ) + self.list = to_streamed_response_wrapper( + output_items.list, + ) + + +class AsyncOutputItemsWithStreamingResponse: + def __init__(self, output_items: AsyncOutputItems) -> None: + self._output_items = output_items + + self.retrieve = async_to_streamed_response_wrapper( + output_items.retrieve, + ) + self.list = async_to_streamed_response_wrapper( + output_items.list, + ) diff --git a/src/openai/resources/evals/runs/runs.py b/src/openai/resources/evals/runs/runs.py new file mode 100644 index 0000000000..6df0b6d121 --- /dev/null +++ b/src/openai/resources/evals/runs/runs.py @@ -0,0 +1,635 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import Literal + +import httpx + +from .... import _legacy_response +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ...._utils import ( + maybe_transform, + async_maybe_transform, +) +from ...._compat import cached_property +from ...._resource import SyncAPIResource, AsyncAPIResource +from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from .output_items import ( + OutputItems, + AsyncOutputItems, + OutputItemsWithRawResponse, + AsyncOutputItemsWithRawResponse, + OutputItemsWithStreamingResponse, + AsyncOutputItemsWithStreamingResponse, +) +from ....pagination import SyncCursorPage, AsyncCursorPage +from ....types.evals import run_list_params, run_create_params +from ...._base_client import AsyncPaginator, make_request_options +from ....types.shared_params.metadata import Metadata +from ....types.evals.run_list_response import RunListResponse +from ....types.evals.run_cancel_response import RunCancelResponse +from ....types.evals.run_create_response import RunCreateResponse +from ....types.evals.run_delete_response import RunDeleteResponse +from ....types.evals.run_retrieve_response import RunRetrieveResponse + +__all__ = ["Runs", "AsyncRuns"] + + +class Runs(SyncAPIResource): + @cached_property + def output_items(self) -> OutputItems: + return OutputItems(self._client) + + @cached_property + def with_raw_response(self) -> RunsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return RunsWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> RunsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return RunsWithStreamingResponse(self) + + def create( + self, + eval_id: str, + *, + data_source: run_create_params.DataSource, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + name: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> RunCreateResponse: + """Create a new evaluation run. + + This is the endpoint that will kick off grading. + + Args: + data_source: Details about the run's data source. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + + name: The name of the run. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not eval_id: + raise ValueError(f"Expected a non-empty value for `eval_id` but received {eval_id!r}") + return self._post( + f"/evals/{eval_id}/runs", + body=maybe_transform( + { + "data_source": data_source, + "metadata": metadata, + "name": name, + }, + run_create_params.RunCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=RunCreateResponse, + ) + + def retrieve( + self, + run_id: str, + *, + eval_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> RunRetrieveResponse: + """ + Get an evaluation run by ID. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not eval_id: + raise ValueError(f"Expected a non-empty value for `eval_id` but received {eval_id!r}") + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") + return self._get( + f"/evals/{eval_id}/runs/{run_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=RunRetrieveResponse, + ) + + def list( + self, + eval_id: str, + *, + after: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + status: Literal["queued", "in_progress", "completed", "canceled", "failed"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> SyncCursorPage[RunListResponse]: + """ + Get a list of runs for an evaluation. + + Args: + after: Identifier for the last run from the previous pagination request. + + limit: Number of runs to retrieve. + + order: Sort order for runs by timestamp. Use `asc` for ascending order or `desc` for + descending order. Defaults to `asc`. + + status: Filter runs by status. Use "queued" | "in_progress" | "failed" | "completed" | + "canceled". + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not eval_id: + raise ValueError(f"Expected a non-empty value for `eval_id` but received {eval_id!r}") + return self._get_api_list( + f"/evals/{eval_id}/runs", + page=SyncCursorPage[RunListResponse], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "limit": limit, + "order": order, + "status": status, + }, + run_list_params.RunListParams, + ), + ), + model=RunListResponse, + ) + + def delete( + self, + run_id: str, + *, + eval_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> RunDeleteResponse: + """ + Delete an eval run. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not eval_id: + raise ValueError(f"Expected a non-empty value for `eval_id` but received {eval_id!r}") + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") + return self._delete( + f"/evals/{eval_id}/runs/{run_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=RunDeleteResponse, + ) + + def cancel( + self, + run_id: str, + *, + eval_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> RunCancelResponse: + """ + Cancel an ongoing evaluation run. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not eval_id: + raise ValueError(f"Expected a non-empty value for `eval_id` but received {eval_id!r}") + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") + return self._post( + f"/evals/{eval_id}/runs/{run_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=RunCancelResponse, + ) + + +class AsyncRuns(AsyncAPIResource): + @cached_property + def output_items(self) -> AsyncOutputItems: + return AsyncOutputItems(self._client) + + @cached_property + def with_raw_response(self) -> AsyncRunsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return AsyncRunsWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncRunsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return AsyncRunsWithStreamingResponse(self) + + async def create( + self, + eval_id: str, + *, + data_source: run_create_params.DataSource, + metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, + name: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> RunCreateResponse: + """Create a new evaluation run. + + This is the endpoint that will kick off grading. + + Args: + data_source: Details about the run's data source. + + metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful + for storing additional information about the object in a structured format, and + querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + + name: The name of the run. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not eval_id: + raise ValueError(f"Expected a non-empty value for `eval_id` but received {eval_id!r}") + return await self._post( + f"/evals/{eval_id}/runs", + body=await async_maybe_transform( + { + "data_source": data_source, + "metadata": metadata, + "name": name, + }, + run_create_params.RunCreateParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=RunCreateResponse, + ) + + async def retrieve( + self, + run_id: str, + *, + eval_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> RunRetrieveResponse: + """ + Get an evaluation run by ID. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not eval_id: + raise ValueError(f"Expected a non-empty value for `eval_id` but received {eval_id!r}") + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") + return await self._get( + f"/evals/{eval_id}/runs/{run_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=RunRetrieveResponse, + ) + + def list( + self, + eval_id: str, + *, + after: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN, + status: Literal["queued", "in_progress", "completed", "canceled", "failed"] | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncPaginator[RunListResponse, AsyncCursorPage[RunListResponse]]: + """ + Get a list of runs for an evaluation. + + Args: + after: Identifier for the last run from the previous pagination request. + + limit: Number of runs to retrieve. + + order: Sort order for runs by timestamp. Use `asc` for ascending order or `desc` for + descending order. Defaults to `asc`. + + status: Filter runs by status. Use "queued" | "in_progress" | "failed" | "completed" | + "canceled". + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not eval_id: + raise ValueError(f"Expected a non-empty value for `eval_id` but received {eval_id!r}") + return self._get_api_list( + f"/evals/{eval_id}/runs", + page=AsyncCursorPage[RunListResponse], + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "limit": limit, + "order": order, + "status": status, + }, + run_list_params.RunListParams, + ), + ), + model=RunListResponse, + ) + + async def delete( + self, + run_id: str, + *, + eval_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> RunDeleteResponse: + """ + Delete an eval run. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not eval_id: + raise ValueError(f"Expected a non-empty value for `eval_id` but received {eval_id!r}") + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") + return await self._delete( + f"/evals/{eval_id}/runs/{run_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=RunDeleteResponse, + ) + + async def cancel( + self, + run_id: str, + *, + eval_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> RunCancelResponse: + """ + Cancel an ongoing evaluation run. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not eval_id: + raise ValueError(f"Expected a non-empty value for `eval_id` but received {eval_id!r}") + if not run_id: + raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") + return await self._post( + f"/evals/{eval_id}/runs/{run_id}", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=RunCancelResponse, + ) + + +class RunsWithRawResponse: + def __init__(self, runs: Runs) -> None: + self._runs = runs + + self.create = _legacy_response.to_raw_response_wrapper( + runs.create, + ) + self.retrieve = _legacy_response.to_raw_response_wrapper( + runs.retrieve, + ) + self.list = _legacy_response.to_raw_response_wrapper( + runs.list, + ) + self.delete = _legacy_response.to_raw_response_wrapper( + runs.delete, + ) + self.cancel = _legacy_response.to_raw_response_wrapper( + runs.cancel, + ) + + @cached_property + def output_items(self) -> OutputItemsWithRawResponse: + return OutputItemsWithRawResponse(self._runs.output_items) + + +class AsyncRunsWithRawResponse: + def __init__(self, runs: AsyncRuns) -> None: + self._runs = runs + + self.create = _legacy_response.async_to_raw_response_wrapper( + runs.create, + ) + self.retrieve = _legacy_response.async_to_raw_response_wrapper( + runs.retrieve, + ) + self.list = _legacy_response.async_to_raw_response_wrapper( + runs.list, + ) + self.delete = _legacy_response.async_to_raw_response_wrapper( + runs.delete, + ) + self.cancel = _legacy_response.async_to_raw_response_wrapper( + runs.cancel, + ) + + @cached_property + def output_items(self) -> AsyncOutputItemsWithRawResponse: + return AsyncOutputItemsWithRawResponse(self._runs.output_items) + + +class RunsWithStreamingResponse: + def __init__(self, runs: Runs) -> None: + self._runs = runs + + self.create = to_streamed_response_wrapper( + runs.create, + ) + self.retrieve = to_streamed_response_wrapper( + runs.retrieve, + ) + self.list = to_streamed_response_wrapper( + runs.list, + ) + self.delete = to_streamed_response_wrapper( + runs.delete, + ) + self.cancel = to_streamed_response_wrapper( + runs.cancel, + ) + + @cached_property + def output_items(self) -> OutputItemsWithStreamingResponse: + return OutputItemsWithStreamingResponse(self._runs.output_items) + + +class AsyncRunsWithStreamingResponse: + def __init__(self, runs: AsyncRuns) -> None: + self._runs = runs + + self.create = async_to_streamed_response_wrapper( + runs.create, + ) + self.retrieve = async_to_streamed_response_wrapper( + runs.retrieve, + ) + self.list = async_to_streamed_response_wrapper( + runs.list, + ) + self.delete = async_to_streamed_response_wrapper( + runs.delete, + ) + self.cancel = async_to_streamed_response_wrapper( + runs.cancel, + ) + + @cached_property + def output_items(self) -> AsyncOutputItemsWithStreamingResponse: + return AsyncOutputItemsWithStreamingResponse(self._runs.output_items) diff --git a/src/openai/resources/fine_tuning/__init__.py b/src/openai/resources/fine_tuning/__init__.py index 7765231fee..ed7db4f4e0 100644 --- a/src/openai/resources/fine_tuning/__init__.py +++ b/src/openai/resources/fine_tuning/__init__.py @@ -8,6 +8,14 @@ JobsWithStreamingResponse, AsyncJobsWithStreamingResponse, ) +from .checkpoints import ( + Checkpoints, + AsyncCheckpoints, + CheckpointsWithRawResponse, + AsyncCheckpointsWithRawResponse, + CheckpointsWithStreamingResponse, + AsyncCheckpointsWithStreamingResponse, +) from .fine_tuning import ( FineTuning, AsyncFineTuning, @@ -24,6 +32,12 @@ "AsyncJobsWithRawResponse", "JobsWithStreamingResponse", "AsyncJobsWithStreamingResponse", + "Checkpoints", + "AsyncCheckpoints", + "CheckpointsWithRawResponse", + "AsyncCheckpointsWithRawResponse", + "CheckpointsWithStreamingResponse", + "AsyncCheckpointsWithStreamingResponse", "FineTuning", "AsyncFineTuning", "FineTuningWithRawResponse", diff --git a/src/openai/resources/fine_tuning/checkpoints/__init__.py b/src/openai/resources/fine_tuning/checkpoints/__init__.py new file mode 100644 index 0000000000..fdc37940f9 --- /dev/null +++ b/src/openai/resources/fine_tuning/checkpoints/__init__.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .checkpoints import ( + Checkpoints, + AsyncCheckpoints, + CheckpointsWithRawResponse, + AsyncCheckpointsWithRawResponse, + CheckpointsWithStreamingResponse, + AsyncCheckpointsWithStreamingResponse, +) +from .permissions import ( + Permissions, + AsyncPermissions, + PermissionsWithRawResponse, + AsyncPermissionsWithRawResponse, + PermissionsWithStreamingResponse, + AsyncPermissionsWithStreamingResponse, +) + +__all__ = [ + "Permissions", + "AsyncPermissions", + "PermissionsWithRawResponse", + "AsyncPermissionsWithRawResponse", + "PermissionsWithStreamingResponse", + "AsyncPermissionsWithStreamingResponse", + "Checkpoints", + "AsyncCheckpoints", + "CheckpointsWithRawResponse", + "AsyncCheckpointsWithRawResponse", + "CheckpointsWithStreamingResponse", + "AsyncCheckpointsWithStreamingResponse", +] diff --git a/src/openai/resources/fine_tuning/checkpoints/checkpoints.py b/src/openai/resources/fine_tuning/checkpoints/checkpoints.py new file mode 100644 index 0000000000..f59976a264 --- /dev/null +++ b/src/openai/resources/fine_tuning/checkpoints/checkpoints.py @@ -0,0 +1,102 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from ...._compat import cached_property +from .permissions import ( + Permissions, + AsyncPermissions, + PermissionsWithRawResponse, + AsyncPermissionsWithRawResponse, + PermissionsWithStreamingResponse, + AsyncPermissionsWithStreamingResponse, +) +from ...._resource import SyncAPIResource, AsyncAPIResource + +__all__ = ["Checkpoints", "AsyncCheckpoints"] + + +class Checkpoints(SyncAPIResource): + @cached_property + def permissions(self) -> Permissions: + return Permissions(self._client) + + @cached_property + def with_raw_response(self) -> CheckpointsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return CheckpointsWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> CheckpointsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return CheckpointsWithStreamingResponse(self) + + +class AsyncCheckpoints(AsyncAPIResource): + @cached_property + def permissions(self) -> AsyncPermissions: + return AsyncPermissions(self._client) + + @cached_property + def with_raw_response(self) -> AsyncCheckpointsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return AsyncCheckpointsWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncCheckpointsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return AsyncCheckpointsWithStreamingResponse(self) + + +class CheckpointsWithRawResponse: + def __init__(self, checkpoints: Checkpoints) -> None: + self._checkpoints = checkpoints + + @cached_property + def permissions(self) -> PermissionsWithRawResponse: + return PermissionsWithRawResponse(self._checkpoints.permissions) + + +class AsyncCheckpointsWithRawResponse: + def __init__(self, checkpoints: AsyncCheckpoints) -> None: + self._checkpoints = checkpoints + + @cached_property + def permissions(self) -> AsyncPermissionsWithRawResponse: + return AsyncPermissionsWithRawResponse(self._checkpoints.permissions) + + +class CheckpointsWithStreamingResponse: + def __init__(self, checkpoints: Checkpoints) -> None: + self._checkpoints = checkpoints + + @cached_property + def permissions(self) -> PermissionsWithStreamingResponse: + return PermissionsWithStreamingResponse(self._checkpoints.permissions) + + +class AsyncCheckpointsWithStreamingResponse: + def __init__(self, checkpoints: AsyncCheckpoints) -> None: + self._checkpoints = checkpoints + + @cached_property + def permissions(self) -> AsyncPermissionsWithStreamingResponse: + return AsyncPermissionsWithStreamingResponse(self._checkpoints.permissions) diff --git a/src/openai/resources/fine_tuning/checkpoints/permissions.py b/src/openai/resources/fine_tuning/checkpoints/permissions.py new file mode 100644 index 0000000000..beb7b099d3 --- /dev/null +++ b/src/openai/resources/fine_tuning/checkpoints/permissions.py @@ -0,0 +1,416 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List +from typing_extensions import Literal + +import httpx + +from .... import _legacy_response +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ...._utils import ( + maybe_transform, + async_maybe_transform, +) +from ...._compat import cached_property +from ...._resource import SyncAPIResource, AsyncAPIResource +from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ....pagination import SyncPage, AsyncPage +from ...._base_client import AsyncPaginator, make_request_options +from ....types.fine_tuning.checkpoints import permission_create_params, permission_retrieve_params +from ....types.fine_tuning.checkpoints.permission_create_response import PermissionCreateResponse +from ....types.fine_tuning.checkpoints.permission_delete_response import PermissionDeleteResponse +from ....types.fine_tuning.checkpoints.permission_retrieve_response import PermissionRetrieveResponse + +__all__ = ["Permissions", "AsyncPermissions"] + + +class Permissions(SyncAPIResource): + @cached_property + def with_raw_response(self) -> PermissionsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return PermissionsWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> PermissionsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return PermissionsWithStreamingResponse(self) + + def create( + self, + fine_tuned_model_checkpoint: str, + *, + project_ids: List[str], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> SyncPage[PermissionCreateResponse]: + """ + **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys). + + This enables organization owners to share fine-tuned models with other projects + in their organization. + + Args: + project_ids: The project identifiers to grant access to. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not fine_tuned_model_checkpoint: + raise ValueError( + f"Expected a non-empty value for `fine_tuned_model_checkpoint` but received {fine_tuned_model_checkpoint!r}" + ) + return self._get_api_list( + f"/fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions", + page=SyncPage[PermissionCreateResponse], + body=maybe_transform({"project_ids": project_ids}, permission_create_params.PermissionCreateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + model=PermissionCreateResponse, + method="post", + ) + + def retrieve( + self, + fine_tuned_model_checkpoint: str, + *, + after: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["ascending", "descending"] | NotGiven = NOT_GIVEN, + project_id: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> PermissionRetrieveResponse: + """ + **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + + Organization owners can use this endpoint to view all permissions for a + fine-tuned model checkpoint. + + Args: + after: Identifier for the last permission ID from the previous pagination request. + + limit: Number of permissions to retrieve. + + order: The order in which to retrieve permissions. + + project_id: The ID of the project to get permissions for. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not fine_tuned_model_checkpoint: + raise ValueError( + f"Expected a non-empty value for `fine_tuned_model_checkpoint` but received {fine_tuned_model_checkpoint!r}" + ) + return self._get( + f"/fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=maybe_transform( + { + "after": after, + "limit": limit, + "order": order, + "project_id": project_id, + }, + permission_retrieve_params.PermissionRetrieveParams, + ), + ), + cast_to=PermissionRetrieveResponse, + ) + + def delete( + self, + fine_tuned_model_checkpoint: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> PermissionDeleteResponse: + """ + **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + + Organization owners can use this endpoint to delete a permission for a + fine-tuned model checkpoint. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not fine_tuned_model_checkpoint: + raise ValueError( + f"Expected a non-empty value for `fine_tuned_model_checkpoint` but received {fine_tuned_model_checkpoint!r}" + ) + return self._delete( + f"/fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=PermissionDeleteResponse, + ) + + +class AsyncPermissions(AsyncAPIResource): + @cached_property + def with_raw_response(self) -> AsyncPermissionsWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return AsyncPermissionsWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncPermissionsWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return AsyncPermissionsWithStreamingResponse(self) + + def create( + self, + fine_tuned_model_checkpoint: str, + *, + project_ids: List[str], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> AsyncPaginator[PermissionCreateResponse, AsyncPage[PermissionCreateResponse]]: + """ + **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys). + + This enables organization owners to share fine-tuned models with other projects + in their organization. + + Args: + project_ids: The project identifiers to grant access to. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not fine_tuned_model_checkpoint: + raise ValueError( + f"Expected a non-empty value for `fine_tuned_model_checkpoint` but received {fine_tuned_model_checkpoint!r}" + ) + return self._get_api_list( + f"/fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions", + page=AsyncPage[PermissionCreateResponse], + body=maybe_transform({"project_ids": project_ids}, permission_create_params.PermissionCreateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + model=PermissionCreateResponse, + method="post", + ) + + async def retrieve( + self, + fine_tuned_model_checkpoint: str, + *, + after: str | NotGiven = NOT_GIVEN, + limit: int | NotGiven = NOT_GIVEN, + order: Literal["ascending", "descending"] | NotGiven = NOT_GIVEN, + project_id: str | NotGiven = NOT_GIVEN, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> PermissionRetrieveResponse: + """ + **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + + Organization owners can use this endpoint to view all permissions for a + fine-tuned model checkpoint. + + Args: + after: Identifier for the last permission ID from the previous pagination request. + + limit: Number of permissions to retrieve. + + order: The order in which to retrieve permissions. + + project_id: The ID of the project to get permissions for. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not fine_tuned_model_checkpoint: + raise ValueError( + f"Expected a non-empty value for `fine_tuned_model_checkpoint` but received {fine_tuned_model_checkpoint!r}" + ) + return await self._get( + f"/fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions", + options=make_request_options( + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + query=await async_maybe_transform( + { + "after": after, + "limit": limit, + "order": order, + "project_id": project_id, + }, + permission_retrieve_params.PermissionRetrieveParams, + ), + ), + cast_to=PermissionRetrieveResponse, + ) + + async def delete( + self, + fine_tuned_model_checkpoint: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> PermissionDeleteResponse: + """ + **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + + Organization owners can use this endpoint to delete a permission for a + fine-tuned model checkpoint. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not fine_tuned_model_checkpoint: + raise ValueError( + f"Expected a non-empty value for `fine_tuned_model_checkpoint` but received {fine_tuned_model_checkpoint!r}" + ) + return await self._delete( + f"/fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=PermissionDeleteResponse, + ) + + +class PermissionsWithRawResponse: + def __init__(self, permissions: Permissions) -> None: + self._permissions = permissions + + self.create = _legacy_response.to_raw_response_wrapper( + permissions.create, + ) + self.retrieve = _legacy_response.to_raw_response_wrapper( + permissions.retrieve, + ) + self.delete = _legacy_response.to_raw_response_wrapper( + permissions.delete, + ) + + +class AsyncPermissionsWithRawResponse: + def __init__(self, permissions: AsyncPermissions) -> None: + self._permissions = permissions + + self.create = _legacy_response.async_to_raw_response_wrapper( + permissions.create, + ) + self.retrieve = _legacy_response.async_to_raw_response_wrapper( + permissions.retrieve, + ) + self.delete = _legacy_response.async_to_raw_response_wrapper( + permissions.delete, + ) + + +class PermissionsWithStreamingResponse: + def __init__(self, permissions: Permissions) -> None: + self._permissions = permissions + + self.create = to_streamed_response_wrapper( + permissions.create, + ) + self.retrieve = to_streamed_response_wrapper( + permissions.retrieve, + ) + self.delete = to_streamed_response_wrapper( + permissions.delete, + ) + + +class AsyncPermissionsWithStreamingResponse: + def __init__(self, permissions: AsyncPermissions) -> None: + self._permissions = permissions + + self.create = async_to_streamed_response_wrapper( + permissions.create, + ) + self.retrieve = async_to_streamed_response_wrapper( + permissions.retrieve, + ) + self.delete = async_to_streamed_response_wrapper( + permissions.delete, + ) diff --git a/src/openai/resources/fine_tuning/fine_tuning.py b/src/openai/resources/fine_tuning/fine_tuning.py index eebde07d81..1388c8230c 100644 --- a/src/openai/resources/fine_tuning/fine_tuning.py +++ b/src/openai/resources/fine_tuning/fine_tuning.py @@ -12,6 +12,14 @@ AsyncJobsWithStreamingResponse, ) from ..._resource import SyncAPIResource, AsyncAPIResource +from .checkpoints.checkpoints import ( + Checkpoints, + AsyncCheckpoints, + CheckpointsWithRawResponse, + AsyncCheckpointsWithRawResponse, + CheckpointsWithStreamingResponse, + AsyncCheckpointsWithStreamingResponse, +) __all__ = ["FineTuning", "AsyncFineTuning"] @@ -21,6 +29,10 @@ class FineTuning(SyncAPIResource): def jobs(self) -> Jobs: return Jobs(self._client) + @cached_property + def checkpoints(self) -> Checkpoints: + return Checkpoints(self._client) + @cached_property def with_raw_response(self) -> FineTuningWithRawResponse: """ @@ -46,6 +58,10 @@ class AsyncFineTuning(AsyncAPIResource): def jobs(self) -> AsyncJobs: return AsyncJobs(self._client) + @cached_property + def checkpoints(self) -> AsyncCheckpoints: + return AsyncCheckpoints(self._client) + @cached_property def with_raw_response(self) -> AsyncFineTuningWithRawResponse: """ @@ -74,6 +90,10 @@ def __init__(self, fine_tuning: FineTuning) -> None: def jobs(self) -> JobsWithRawResponse: return JobsWithRawResponse(self._fine_tuning.jobs) + @cached_property + def checkpoints(self) -> CheckpointsWithRawResponse: + return CheckpointsWithRawResponse(self._fine_tuning.checkpoints) + class AsyncFineTuningWithRawResponse: def __init__(self, fine_tuning: AsyncFineTuning) -> None: @@ -83,6 +103,10 @@ def __init__(self, fine_tuning: AsyncFineTuning) -> None: def jobs(self) -> AsyncJobsWithRawResponse: return AsyncJobsWithRawResponse(self._fine_tuning.jobs) + @cached_property + def checkpoints(self) -> AsyncCheckpointsWithRawResponse: + return AsyncCheckpointsWithRawResponse(self._fine_tuning.checkpoints) + class FineTuningWithStreamingResponse: def __init__(self, fine_tuning: FineTuning) -> None: @@ -92,6 +116,10 @@ def __init__(self, fine_tuning: FineTuning) -> None: def jobs(self) -> JobsWithStreamingResponse: return JobsWithStreamingResponse(self._fine_tuning.jobs) + @cached_property + def checkpoints(self) -> CheckpointsWithStreamingResponse: + return CheckpointsWithStreamingResponse(self._fine_tuning.checkpoints) + class AsyncFineTuningWithStreamingResponse: def __init__(self, fine_tuning: AsyncFineTuning) -> None: @@ -100,3 +128,7 @@ def __init__(self, fine_tuning: AsyncFineTuning) -> None: @cached_property def jobs(self) -> AsyncJobsWithStreamingResponse: return AsyncJobsWithStreamingResponse(self._fine_tuning.jobs) + + @cached_property + def checkpoints(self) -> AsyncCheckpointsWithStreamingResponse: + return AsyncCheckpointsWithStreamingResponse(self._fine_tuning.checkpoints) diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index 11761534c9..57c91811b9 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -38,22 +38,32 @@ from .embedding_model import EmbeddingModel as EmbeddingModel from .images_response import ImagesResponse as ImagesResponse from .completion_usage import CompletionUsage as CompletionUsage +from .eval_list_params import EvalListParams as EvalListParams from .file_list_params import FileListParams as FileListParams from .moderation_model import ModerationModel as ModerationModel from .batch_list_params import BatchListParams as BatchListParams from .completion_choice import CompletionChoice as CompletionChoice from .image_edit_params import ImageEditParams as ImageEditParams +from .eval_create_params import EvalCreateParams as EvalCreateParams +from .eval_list_response import EvalListResponse as EvalListResponse +from .eval_update_params import EvalUpdateParams as EvalUpdateParams from .file_create_params import FileCreateParams as FileCreateParams from .batch_create_params import BatchCreateParams as BatchCreateParams from .batch_request_counts import BatchRequestCounts as BatchRequestCounts +from .eval_create_response import EvalCreateResponse as EvalCreateResponse +from .eval_delete_response import EvalDeleteResponse as EvalDeleteResponse +from .eval_update_response import EvalUpdateResponse as EvalUpdateResponse from .upload_create_params import UploadCreateParams as UploadCreateParams from .vector_store_deleted import VectorStoreDeleted as VectorStoreDeleted from .audio_response_format import AudioResponseFormat as AudioResponseFormat from .image_generate_params import ImageGenerateParams as ImageGenerateParams +from .eval_retrieve_response import EvalRetrieveResponse as EvalRetrieveResponse from .file_chunking_strategy import FileChunkingStrategy as FileChunkingStrategy from .upload_complete_params import UploadCompleteParams as UploadCompleteParams from .embedding_create_params import EmbeddingCreateParams as EmbeddingCreateParams +from .eval_label_model_grader import EvalLabelModelGrader as EvalLabelModelGrader from .completion_create_params import CompletionCreateParams as CompletionCreateParams +from .eval_string_check_grader import EvalStringCheckGrader as EvalStringCheckGrader from .moderation_create_params import ModerationCreateParams as ModerationCreateParams from .vector_store_list_params import VectorStoreListParams as VectorStoreListParams from .create_embedding_response import CreateEmbeddingResponse as CreateEmbeddingResponse @@ -61,18 +71,25 @@ from .vector_store_create_params import VectorStoreCreateParams as VectorStoreCreateParams from .vector_store_search_params import VectorStoreSearchParams as VectorStoreSearchParams from .vector_store_update_params import VectorStoreUpdateParams as VectorStoreUpdateParams +from .eval_text_similarity_grader import EvalTextSimilarityGrader as EvalTextSimilarityGrader from .moderation_text_input_param import ModerationTextInputParam as ModerationTextInputParam from .file_chunking_strategy_param import FileChunkingStrategyParam as FileChunkingStrategyParam from .vector_store_search_response import VectorStoreSearchResponse as VectorStoreSearchResponse from .websocket_connection_options import WebsocketConnectionOptions as WebsocketConnectionOptions from .image_create_variation_params import ImageCreateVariationParams as ImageCreateVariationParams from .static_file_chunking_strategy import StaticFileChunkingStrategy as StaticFileChunkingStrategy +from .eval_custom_data_source_config import EvalCustomDataSourceConfig as EvalCustomDataSourceConfig +from .eval_string_check_grader_param import EvalStringCheckGraderParam as EvalStringCheckGraderParam from .moderation_image_url_input_param import ModerationImageURLInputParam as ModerationImageURLInputParam from .auto_file_chunking_strategy_param import AutoFileChunkingStrategyParam as AutoFileChunkingStrategyParam +from .eval_text_similarity_grader_param import EvalTextSimilarityGraderParam as EvalTextSimilarityGraderParam from .moderation_multi_modal_input_param import ModerationMultiModalInputParam as ModerationMultiModalInputParam from .other_file_chunking_strategy_object import OtherFileChunkingStrategyObject as OtherFileChunkingStrategyObject from .static_file_chunking_strategy_param import StaticFileChunkingStrategyParam as StaticFileChunkingStrategyParam from .static_file_chunking_strategy_object import StaticFileChunkingStrategyObject as StaticFileChunkingStrategyObject +from .eval_stored_completions_data_source_config import ( + EvalStoredCompletionsDataSourceConfig as EvalStoredCompletionsDataSourceConfig, +) from .static_file_chunking_strategy_object_param import ( StaticFileChunkingStrategyObjectParam as StaticFileChunkingStrategyObjectParam, ) diff --git a/src/openai/types/eval_create_params.py b/src/openai/types/eval_create_params.py new file mode 100644 index 0000000000..8b28e51a6b --- /dev/null +++ b/src/openai/types/eval_create_params.py @@ -0,0 +1,153 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, List, Union, Iterable, Optional +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .shared_params.metadata import Metadata +from .eval_string_check_grader_param import EvalStringCheckGraderParam +from .eval_text_similarity_grader_param import EvalTextSimilarityGraderParam + +__all__ = [ + "EvalCreateParams", + "DataSourceConfig", + "DataSourceConfigCustom", + "DataSourceConfigStoredCompletions", + "TestingCriterion", + "TestingCriterionLabelModel", + "TestingCriterionLabelModelInput", + "TestingCriterionLabelModelInputSimpleInputMessage", + "TestingCriterionLabelModelInputInputMessage", + "TestingCriterionLabelModelInputInputMessageContent", + "TestingCriterionLabelModelInputOutputMessage", + "TestingCriterionLabelModelInputOutputMessageContent", +] + + +class EvalCreateParams(TypedDict, total=False): + data_source_config: Required[DataSourceConfig] + """The configuration for the data source used for the evaluation runs.""" + + testing_criteria: Required[Iterable[TestingCriterion]] + """A list of graders for all eval runs in this group.""" + + metadata: Optional[Metadata] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + """ + + name: str + """The name of the evaluation.""" + + share_with_openai: bool + """Indicates whether the evaluation is shared with OpenAI.""" + + +class DataSourceConfigCustom(TypedDict, total=False): + item_schema: Required[Dict[str, object]] + """The json schema for the run data source items.""" + + type: Required[Literal["custom"]] + """The type of data source. Always `custom`.""" + + include_sample_schema: bool + """Whether to include the sample schema in the data source.""" + + +class DataSourceConfigStoredCompletions(TypedDict, total=False): + type: Required[Literal["stored_completions"]] + """The type of data source. Always `stored_completions`.""" + + metadata: Optional[Metadata] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + """ + + +DataSourceConfig: TypeAlias = Union[DataSourceConfigCustom, DataSourceConfigStoredCompletions] + + +class TestingCriterionLabelModelInputSimpleInputMessage(TypedDict, total=False): + content: Required[str] + """The content of the message.""" + + role: Required[str] + """The role of the message (e.g. "system", "assistant", "user").""" + + +class TestingCriterionLabelModelInputInputMessageContent(TypedDict, total=False): + text: Required[str] + """The text content.""" + + type: Required[Literal["input_text"]] + """The type of content, which is always `input_text`.""" + + +class TestingCriterionLabelModelInputInputMessage(TypedDict, total=False): + content: Required[TestingCriterionLabelModelInputInputMessageContent] + + role: Required[Literal["user", "system", "developer"]] + """The role of the message. One of `user`, `system`, or `developer`.""" + + type: Required[Literal["message"]] + """The type of item, which is always `message`.""" + + +class TestingCriterionLabelModelInputOutputMessageContent(TypedDict, total=False): + text: Required[str] + """The text content.""" + + type: Required[Literal["output_text"]] + """The type of content, which is always `output_text`.""" + + +class TestingCriterionLabelModelInputOutputMessage(TypedDict, total=False): + content: Required[TestingCriterionLabelModelInputOutputMessageContent] + + role: Required[Literal["assistant"]] + """The role of the message. Must be `assistant` for output.""" + + type: Required[Literal["message"]] + """The type of item, which is always `message`.""" + + +TestingCriterionLabelModelInput: TypeAlias = Union[ + TestingCriterionLabelModelInputSimpleInputMessage, + TestingCriterionLabelModelInputInputMessage, + TestingCriterionLabelModelInputOutputMessage, +] + + +class TestingCriterionLabelModel(TypedDict, total=False): + input: Required[Iterable[TestingCriterionLabelModelInput]] + + labels: Required[List[str]] + """The labels to classify to each item in the evaluation.""" + + model: Required[str] + """The model to use for the evaluation. Must support structured outputs.""" + + name: Required[str] + """The name of the grader.""" + + passing_labels: Required[List[str]] + """The labels that indicate a passing result. Must be a subset of labels.""" + + type: Required[Literal["label_model"]] + """The object type, which is always `label_model`.""" + + +TestingCriterion: TypeAlias = Union[ + TestingCriterionLabelModel, EvalStringCheckGraderParam, EvalTextSimilarityGraderParam +] diff --git a/src/openai/types/eval_create_response.py b/src/openai/types/eval_create_response.py new file mode 100644 index 0000000000..a1c2853a2a --- /dev/null +++ b/src/openai/types/eval_create_response.py @@ -0,0 +1,56 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias + +from .._utils import PropertyInfo +from .._models import BaseModel +from .shared.metadata import Metadata +from .eval_label_model_grader import EvalLabelModelGrader +from .eval_string_check_grader import EvalStringCheckGrader +from .eval_text_similarity_grader import EvalTextSimilarityGrader +from .eval_custom_data_source_config import EvalCustomDataSourceConfig +from .eval_stored_completions_data_source_config import EvalStoredCompletionsDataSourceConfig + +__all__ = ["EvalCreateResponse", "DataSourceConfig", "TestingCriterion"] + +DataSourceConfig: TypeAlias = Annotated[ + Union[EvalCustomDataSourceConfig, EvalStoredCompletionsDataSourceConfig], PropertyInfo(discriminator="type") +] + +TestingCriterion: TypeAlias = Annotated[ + Union[EvalLabelModelGrader, EvalStringCheckGrader, EvalTextSimilarityGrader], PropertyInfo(discriminator="type") +] + + +class EvalCreateResponse(BaseModel): + id: str + """Unique identifier for the evaluation.""" + + created_at: int + """The Unix timestamp (in seconds) for when the eval was created.""" + + data_source_config: DataSourceConfig + """Configuration of data sources used in runs of the evaluation.""" + + metadata: Optional[Metadata] = None + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + """ + + name: str + """The name of the evaluation.""" + + object: Literal["eval"] + """The object type.""" + + share_with_openai: bool + """Indicates whether the evaluation is shared with OpenAI.""" + + testing_criteria: List[TestingCriterion] + """A list of testing criteria.""" diff --git a/src/openai/types/eval_custom_data_source_config.py b/src/openai/types/eval_custom_data_source_config.py new file mode 100644 index 0000000000..d99701cc71 --- /dev/null +++ b/src/openai/types/eval_custom_data_source_config.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict +from typing_extensions import Literal + +from pydantic import Field as FieldInfo + +from .._models import BaseModel + +__all__ = ["EvalCustomDataSourceConfig"] + + +class EvalCustomDataSourceConfig(BaseModel): + schema_: Dict[str, object] = FieldInfo(alias="schema") + """ + The json schema for the run data source items. Learn how to build JSON schemas + [here](https://json-schema.org/). + """ + + type: Literal["custom"] + """The type of data source. Always `custom`.""" diff --git a/src/openai/types/eval_delete_response.py b/src/openai/types/eval_delete_response.py new file mode 100644 index 0000000000..adb460ddbb --- /dev/null +++ b/src/openai/types/eval_delete_response.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +from .._models import BaseModel + +__all__ = ["EvalDeleteResponse"] + + +class EvalDeleteResponse(BaseModel): + deleted: bool + + eval_id: str + + object: str diff --git a/src/openai/types/eval_label_model_grader.py b/src/openai/types/eval_label_model_grader.py new file mode 100644 index 0000000000..826b116287 --- /dev/null +++ b/src/openai/types/eval_label_model_grader.py @@ -0,0 +1,74 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union +from typing_extensions import Literal, Annotated, TypeAlias + +from .._utils import PropertyInfo +from .._models import BaseModel + +__all__ = [ + "EvalLabelModelGrader", + "Input", + "InputInputMessage", + "InputInputMessageContent", + "InputAssistant", + "InputAssistantContent", +] + + +class InputInputMessageContent(BaseModel): + text: str + """The text content.""" + + type: Literal["input_text"] + """The type of content, which is always `input_text`.""" + + +class InputInputMessage(BaseModel): + content: InputInputMessageContent + + role: Literal["user", "system", "developer"] + """The role of the message. One of `user`, `system`, or `developer`.""" + + type: Literal["message"] + """The type of item, which is always `message`.""" + + +class InputAssistantContent(BaseModel): + text: str + """The text content.""" + + type: Literal["output_text"] + """The type of content, which is always `output_text`.""" + + +class InputAssistant(BaseModel): + content: InputAssistantContent + + role: Literal["assistant"] + """The role of the message. Must be `assistant` for output.""" + + type: Literal["message"] + """The type of item, which is always `message`.""" + + +Input: TypeAlias = Annotated[Union[InputInputMessage, InputAssistant], PropertyInfo(discriminator="role")] + + +class EvalLabelModelGrader(BaseModel): + input: List[Input] + + labels: List[str] + """The labels to assign to each item in the evaluation.""" + + model: str + """The model to use for the evaluation. Must support structured outputs.""" + + name: str + """The name of the grader.""" + + passing_labels: List[str] + """The labels that indicate a passing result. Must be a subset of labels.""" + + type: Literal["label_model"] + """The object type, which is always `label_model`.""" diff --git a/src/openai/types/eval_list_params.py b/src/openai/types/eval_list_params.py new file mode 100644 index 0000000000..d9a12d0ddf --- /dev/null +++ b/src/openai/types/eval_list_params.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, TypedDict + +__all__ = ["EvalListParams"] + + +class EvalListParams(TypedDict, total=False): + after: str + """Identifier for the last eval from the previous pagination request.""" + + limit: int + """Number of evals to retrieve.""" + + order: Literal["asc", "desc"] + """Sort order for evals by timestamp. + + Use `asc` for ascending order or `desc` for descending order. + """ + + order_by: Literal["created_at", "updated_at"] + """Evals can be ordered by creation time or last updated time. + + Use `created_at` for creation time or `updated_at` for last updated time. + """ diff --git a/src/openai/types/eval_list_response.py b/src/openai/types/eval_list_response.py new file mode 100644 index 0000000000..eb54569011 --- /dev/null +++ b/src/openai/types/eval_list_response.py @@ -0,0 +1,56 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias + +from .._utils import PropertyInfo +from .._models import BaseModel +from .shared.metadata import Metadata +from .eval_label_model_grader import EvalLabelModelGrader +from .eval_string_check_grader import EvalStringCheckGrader +from .eval_text_similarity_grader import EvalTextSimilarityGrader +from .eval_custom_data_source_config import EvalCustomDataSourceConfig +from .eval_stored_completions_data_source_config import EvalStoredCompletionsDataSourceConfig + +__all__ = ["EvalListResponse", "DataSourceConfig", "TestingCriterion"] + +DataSourceConfig: TypeAlias = Annotated[ + Union[EvalCustomDataSourceConfig, EvalStoredCompletionsDataSourceConfig], PropertyInfo(discriminator="type") +] + +TestingCriterion: TypeAlias = Annotated[ + Union[EvalLabelModelGrader, EvalStringCheckGrader, EvalTextSimilarityGrader], PropertyInfo(discriminator="type") +] + + +class EvalListResponse(BaseModel): + id: str + """Unique identifier for the evaluation.""" + + created_at: int + """The Unix timestamp (in seconds) for when the eval was created.""" + + data_source_config: DataSourceConfig + """Configuration of data sources used in runs of the evaluation.""" + + metadata: Optional[Metadata] = None + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + """ + + name: str + """The name of the evaluation.""" + + object: Literal["eval"] + """The object type.""" + + share_with_openai: bool + """Indicates whether the evaluation is shared with OpenAI.""" + + testing_criteria: List[TestingCriterion] + """A list of testing criteria.""" diff --git a/src/openai/types/eval_retrieve_response.py b/src/openai/types/eval_retrieve_response.py new file mode 100644 index 0000000000..8f3bfdf902 --- /dev/null +++ b/src/openai/types/eval_retrieve_response.py @@ -0,0 +1,56 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias + +from .._utils import PropertyInfo +from .._models import BaseModel +from .shared.metadata import Metadata +from .eval_label_model_grader import EvalLabelModelGrader +from .eval_string_check_grader import EvalStringCheckGrader +from .eval_text_similarity_grader import EvalTextSimilarityGrader +from .eval_custom_data_source_config import EvalCustomDataSourceConfig +from .eval_stored_completions_data_source_config import EvalStoredCompletionsDataSourceConfig + +__all__ = ["EvalRetrieveResponse", "DataSourceConfig", "TestingCriterion"] + +DataSourceConfig: TypeAlias = Annotated[ + Union[EvalCustomDataSourceConfig, EvalStoredCompletionsDataSourceConfig], PropertyInfo(discriminator="type") +] + +TestingCriterion: TypeAlias = Annotated[ + Union[EvalLabelModelGrader, EvalStringCheckGrader, EvalTextSimilarityGrader], PropertyInfo(discriminator="type") +] + + +class EvalRetrieveResponse(BaseModel): + id: str + """Unique identifier for the evaluation.""" + + created_at: int + """The Unix timestamp (in seconds) for when the eval was created.""" + + data_source_config: DataSourceConfig + """Configuration of data sources used in runs of the evaluation.""" + + metadata: Optional[Metadata] = None + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + """ + + name: str + """The name of the evaluation.""" + + object: Literal["eval"] + """The object type.""" + + share_with_openai: bool + """Indicates whether the evaluation is shared with OpenAI.""" + + testing_criteria: List[TestingCriterion] + """A list of testing criteria.""" diff --git a/src/openai/types/eval_stored_completions_data_source_config.py b/src/openai/types/eval_stored_completions_data_source_config.py new file mode 100644 index 0000000000..98f86a4719 --- /dev/null +++ b/src/openai/types/eval_stored_completions_data_source_config.py @@ -0,0 +1,32 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional +from typing_extensions import Literal + +from pydantic import Field as FieldInfo + +from .._models import BaseModel +from .shared.metadata import Metadata + +__all__ = ["EvalStoredCompletionsDataSourceConfig"] + + +class EvalStoredCompletionsDataSourceConfig(BaseModel): + schema_: Dict[str, object] = FieldInfo(alias="schema") + """ + The json schema for the run data source items. Learn how to build JSON schemas + [here](https://json-schema.org/). + """ + + type: Literal["stored_completions"] + """The type of data source. Always `stored_completions`.""" + + metadata: Optional[Metadata] = None + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + """ diff --git a/src/openai/types/eval_string_check_grader.py b/src/openai/types/eval_string_check_grader.py new file mode 100644 index 0000000000..4dfc8035f9 --- /dev/null +++ b/src/openai/types/eval_string_check_grader.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["EvalStringCheckGrader"] + + +class EvalStringCheckGrader(BaseModel): + input: str + """The input text. This may include template strings.""" + + name: str + """The name of the grader.""" + + operation: Literal["eq", "ne", "like", "ilike"] + """The string check operation to perform. One of `eq`, `ne`, `like`, or `ilike`.""" + + reference: str + """The reference text. This may include template strings.""" + + type: Literal["string_check"] + """The object type, which is always `string_check`.""" diff --git a/src/openai/types/eval_string_check_grader_param.py b/src/openai/types/eval_string_check_grader_param.py new file mode 100644 index 0000000000..3511329f8b --- /dev/null +++ b/src/openai/types/eval_string_check_grader_param.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["EvalStringCheckGraderParam"] + + +class EvalStringCheckGraderParam(TypedDict, total=False): + input: Required[str] + """The input text. This may include template strings.""" + + name: Required[str] + """The name of the grader.""" + + operation: Required[Literal["eq", "ne", "like", "ilike"]] + """The string check operation to perform. One of `eq`, `ne`, `like`, or `ilike`.""" + + reference: Required[str] + """The reference text. This may include template strings.""" + + type: Required[Literal["string_check"]] + """The object type, which is always `string_check`.""" diff --git a/src/openai/types/eval_text_similarity_grader.py b/src/openai/types/eval_text_similarity_grader.py new file mode 100644 index 0000000000..7c6897a4a7 --- /dev/null +++ b/src/openai/types/eval_text_similarity_grader.py @@ -0,0 +1,44 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from .._models import BaseModel + +__all__ = ["EvalTextSimilarityGrader"] + + +class EvalTextSimilarityGrader(BaseModel): + evaluation_metric: Literal[ + "fuzzy_match", + "bleu", + "gleu", + "meteor", + "rouge_1", + "rouge_2", + "rouge_3", + "rouge_4", + "rouge_5", + "rouge_l", + "cosine", + ] + """The evaluation metric to use. + + One of `cosine`, `fuzzy_match`, `bleu`, `gleu`, `meteor`, `rouge_1`, `rouge_2`, + `rouge_3`, `rouge_4`, `rouge_5`, or `rouge_l`. + """ + + input: str + """The text being graded.""" + + pass_threshold: float + """A float score where a value greater than or equal indicates a passing grade.""" + + reference: str + """The text being graded against.""" + + type: Literal["text_similarity"] + """The type of grader.""" + + name: Optional[str] = None + """The name of the grader.""" diff --git a/src/openai/types/eval_text_similarity_grader_param.py b/src/openai/types/eval_text_similarity_grader_param.py new file mode 100644 index 0000000000..4bf5d586f3 --- /dev/null +++ b/src/openai/types/eval_text_similarity_grader_param.py @@ -0,0 +1,45 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["EvalTextSimilarityGraderParam"] + + +class EvalTextSimilarityGraderParam(TypedDict, total=False): + evaluation_metric: Required[ + Literal[ + "fuzzy_match", + "bleu", + "gleu", + "meteor", + "rouge_1", + "rouge_2", + "rouge_3", + "rouge_4", + "rouge_5", + "rouge_l", + "cosine", + ] + ] + """The evaluation metric to use. + + One of `cosine`, `fuzzy_match`, `bleu`, `gleu`, `meteor`, `rouge_1`, `rouge_2`, + `rouge_3`, `rouge_4`, `rouge_5`, or `rouge_l`. + """ + + input: Required[str] + """The text being graded.""" + + pass_threshold: Required[float] + """A float score where a value greater than or equal indicates a passing grade.""" + + reference: Required[str] + """The text being graded against.""" + + type: Required[Literal["text_similarity"]] + """The type of grader.""" + + name: str + """The name of the grader.""" diff --git a/src/openai/types/eval_update_params.py b/src/openai/types/eval_update_params.py new file mode 100644 index 0000000000..042db29af5 --- /dev/null +++ b/src/openai/types/eval_update_params.py @@ -0,0 +1,25 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Optional +from typing_extensions import TypedDict + +from .shared_params.metadata import Metadata + +__all__ = ["EvalUpdateParams"] + + +class EvalUpdateParams(TypedDict, total=False): + metadata: Optional[Metadata] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + """ + + name: str + """Rename the evaluation.""" diff --git a/src/openai/types/eval_update_response.py b/src/openai/types/eval_update_response.py new file mode 100644 index 0000000000..728a291736 --- /dev/null +++ b/src/openai/types/eval_update_response.py @@ -0,0 +1,56 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias + +from .._utils import PropertyInfo +from .._models import BaseModel +from .shared.metadata import Metadata +from .eval_label_model_grader import EvalLabelModelGrader +from .eval_string_check_grader import EvalStringCheckGrader +from .eval_text_similarity_grader import EvalTextSimilarityGrader +from .eval_custom_data_source_config import EvalCustomDataSourceConfig +from .eval_stored_completions_data_source_config import EvalStoredCompletionsDataSourceConfig + +__all__ = ["EvalUpdateResponse", "DataSourceConfig", "TestingCriterion"] + +DataSourceConfig: TypeAlias = Annotated[ + Union[EvalCustomDataSourceConfig, EvalStoredCompletionsDataSourceConfig], PropertyInfo(discriminator="type") +] + +TestingCriterion: TypeAlias = Annotated[ + Union[EvalLabelModelGrader, EvalStringCheckGrader, EvalTextSimilarityGrader], PropertyInfo(discriminator="type") +] + + +class EvalUpdateResponse(BaseModel): + id: str + """Unique identifier for the evaluation.""" + + created_at: int + """The Unix timestamp (in seconds) for when the eval was created.""" + + data_source_config: DataSourceConfig + """Configuration of data sources used in runs of the evaluation.""" + + metadata: Optional[Metadata] = None + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + """ + + name: str + """The name of the evaluation.""" + + object: Literal["eval"] + """The object type.""" + + share_with_openai: bool + """Indicates whether the evaluation is shared with OpenAI.""" + + testing_criteria: List[TestingCriterion] + """A list of testing criteria.""" diff --git a/src/openai/types/evals/__init__.py b/src/openai/types/evals/__init__.py new file mode 100644 index 0000000000..ebf84c6b8d --- /dev/null +++ b/src/openai/types/evals/__init__.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .eval_api_error import EvalAPIError as EvalAPIError +from .run_list_params import RunListParams as RunListParams +from .run_create_params import RunCreateParams as RunCreateParams +from .run_list_response import RunListResponse as RunListResponse +from .run_cancel_response import RunCancelResponse as RunCancelResponse +from .run_create_response import RunCreateResponse as RunCreateResponse +from .run_delete_response import RunDeleteResponse as RunDeleteResponse +from .run_retrieve_response import RunRetrieveResponse as RunRetrieveResponse +from .create_eval_jsonl_run_data_source import CreateEvalJSONLRunDataSource as CreateEvalJSONLRunDataSource +from .create_eval_completions_run_data_source import ( + CreateEvalCompletionsRunDataSource as CreateEvalCompletionsRunDataSource, +) +from .create_eval_jsonl_run_data_source_param import ( + CreateEvalJSONLRunDataSourceParam as CreateEvalJSONLRunDataSourceParam, +) +from .create_eval_completions_run_data_source_param import ( + CreateEvalCompletionsRunDataSourceParam as CreateEvalCompletionsRunDataSourceParam, +) diff --git a/src/openai/types/evals/create_eval_completions_run_data_source.py b/src/openai/types/evals/create_eval_completions_run_data_source.py new file mode 100644 index 0000000000..07b88129e2 --- /dev/null +++ b/src/openai/types/evals/create_eval_completions_run_data_source.py @@ -0,0 +1,185 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, List, Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias + +from ..._utils import PropertyInfo +from ..._models import BaseModel +from ..shared.metadata import Metadata + +__all__ = [ + "CreateEvalCompletionsRunDataSource", + "InputMessages", + "InputMessagesTemplate", + "InputMessagesTemplateTemplate", + "InputMessagesTemplateTemplateChatMessage", + "InputMessagesTemplateTemplateInputMessage", + "InputMessagesTemplateTemplateInputMessageContent", + "InputMessagesTemplateTemplateOutputMessage", + "InputMessagesTemplateTemplateOutputMessageContent", + "InputMessagesItemReference", + "Source", + "SourceFileContent", + "SourceFileContentContent", + "SourceFileID", + "SourceStoredCompletions", + "SamplingParams", +] + + +class InputMessagesTemplateTemplateChatMessage(BaseModel): + content: str + """The content of the message.""" + + role: str + """The role of the message (e.g. "system", "assistant", "user").""" + + +class InputMessagesTemplateTemplateInputMessageContent(BaseModel): + text: str + """The text content.""" + + type: Literal["input_text"] + """The type of content, which is always `input_text`.""" + + +class InputMessagesTemplateTemplateInputMessage(BaseModel): + content: InputMessagesTemplateTemplateInputMessageContent + + role: Literal["user", "system", "developer"] + """The role of the message. One of `user`, `system`, or `developer`.""" + + type: Literal["message"] + """The type of item, which is always `message`.""" + + +class InputMessagesTemplateTemplateOutputMessageContent(BaseModel): + text: str + """The text content.""" + + type: Literal["output_text"] + """The type of content, which is always `output_text`.""" + + +class InputMessagesTemplateTemplateOutputMessage(BaseModel): + content: InputMessagesTemplateTemplateOutputMessageContent + + role: Literal["assistant"] + """The role of the message. Must be `assistant` for output.""" + + type: Literal["message"] + """The type of item, which is always `message`.""" + + +InputMessagesTemplateTemplate: TypeAlias = Union[ + InputMessagesTemplateTemplateChatMessage, + InputMessagesTemplateTemplateInputMessage, + InputMessagesTemplateTemplateOutputMessage, +] + + +class InputMessagesTemplate(BaseModel): + template: List[InputMessagesTemplateTemplate] + """A list of chat messages forming the prompt or context. + + May include variable references to the "item" namespace, ie {{item.name}}. + """ + + type: Literal["template"] + """The type of input messages. Always `template`.""" + + +class InputMessagesItemReference(BaseModel): + item_reference: str + """A reference to a variable in the "item" namespace. Ie, "item.name" """ + + type: Literal["item_reference"] + """The type of input messages. Always `item_reference`.""" + + +InputMessages: TypeAlias = Annotated[ + Union[InputMessagesTemplate, InputMessagesItemReference], PropertyInfo(discriminator="type") +] + + +class SourceFileContentContent(BaseModel): + item: Dict[str, object] + + sample: Optional[Dict[str, object]] = None + + +class SourceFileContent(BaseModel): + content: List[SourceFileContentContent] + """The content of the jsonl file.""" + + type: Literal["file_content"] + """The type of jsonl source. Always `file_content`.""" + + +class SourceFileID(BaseModel): + id: str + """The identifier of the file.""" + + type: Literal["file_id"] + """The type of jsonl source. Always `file_id`.""" + + +class SourceStoredCompletions(BaseModel): + created_after: Optional[int] = None + """An optional Unix timestamp to filter items created after this time.""" + + created_before: Optional[int] = None + """An optional Unix timestamp to filter items created before this time.""" + + limit: Optional[int] = None + """An optional maximum number of items to return.""" + + metadata: Optional[Metadata] = None + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + """ + + model: Optional[str] = None + """An optional model to filter by (e.g., 'gpt-4o').""" + + type: Literal["stored_completions"] + """The type of source. Always `stored_completions`.""" + + +Source: TypeAlias = Annotated[ + Union[SourceFileContent, SourceFileID, SourceStoredCompletions], PropertyInfo(discriminator="type") +] + + +class SamplingParams(BaseModel): + max_completion_tokens: Optional[int] = None + """The maximum number of tokens in the generated output.""" + + seed: Optional[int] = None + """A seed value to initialize the randomness, during sampling.""" + + temperature: Optional[float] = None + """A higher temperature increases randomness in the outputs.""" + + top_p: Optional[float] = None + """An alternative to temperature for nucleus sampling; 1.0 includes all tokens.""" + + +class CreateEvalCompletionsRunDataSource(BaseModel): + input_messages: InputMessages + + model: str + """The name of the model to use for generating completions (e.g. "o3-mini").""" + + source: Source + """A StoredCompletionsRunDataSource configuration describing a set of filters""" + + type: Literal["completions"] + """The type of run data source. Always `completions`.""" + + sampling_params: Optional[SamplingParams] = None diff --git a/src/openai/types/evals/create_eval_completions_run_data_source_param.py b/src/openai/types/evals/create_eval_completions_run_data_source_param.py new file mode 100644 index 0000000000..be4a6f1ec6 --- /dev/null +++ b/src/openai/types/evals/create_eval_completions_run_data_source_param.py @@ -0,0 +1,181 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Union, Iterable, Optional +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from ..shared_params.metadata import Metadata + +__all__ = [ + "CreateEvalCompletionsRunDataSourceParam", + "InputMessages", + "InputMessagesTemplate", + "InputMessagesTemplateTemplate", + "InputMessagesTemplateTemplateChatMessage", + "InputMessagesTemplateTemplateInputMessage", + "InputMessagesTemplateTemplateInputMessageContent", + "InputMessagesTemplateTemplateOutputMessage", + "InputMessagesTemplateTemplateOutputMessageContent", + "InputMessagesItemReference", + "Source", + "SourceFileContent", + "SourceFileContentContent", + "SourceFileID", + "SourceStoredCompletions", + "SamplingParams", +] + + +class InputMessagesTemplateTemplateChatMessage(TypedDict, total=False): + content: Required[str] + """The content of the message.""" + + role: Required[str] + """The role of the message (e.g. "system", "assistant", "user").""" + + +class InputMessagesTemplateTemplateInputMessageContent(TypedDict, total=False): + text: Required[str] + """The text content.""" + + type: Required[Literal["input_text"]] + """The type of content, which is always `input_text`.""" + + +class InputMessagesTemplateTemplateInputMessage(TypedDict, total=False): + content: Required[InputMessagesTemplateTemplateInputMessageContent] + + role: Required[Literal["user", "system", "developer"]] + """The role of the message. One of `user`, `system`, or `developer`.""" + + type: Required[Literal["message"]] + """The type of item, which is always `message`.""" + + +class InputMessagesTemplateTemplateOutputMessageContent(TypedDict, total=False): + text: Required[str] + """The text content.""" + + type: Required[Literal["output_text"]] + """The type of content, which is always `output_text`.""" + + +class InputMessagesTemplateTemplateOutputMessage(TypedDict, total=False): + content: Required[InputMessagesTemplateTemplateOutputMessageContent] + + role: Required[Literal["assistant"]] + """The role of the message. Must be `assistant` for output.""" + + type: Required[Literal["message"]] + """The type of item, which is always `message`.""" + + +InputMessagesTemplateTemplate: TypeAlias = Union[ + InputMessagesTemplateTemplateChatMessage, + InputMessagesTemplateTemplateInputMessage, + InputMessagesTemplateTemplateOutputMessage, +] + + +class InputMessagesTemplate(TypedDict, total=False): + template: Required[Iterable[InputMessagesTemplateTemplate]] + """A list of chat messages forming the prompt or context. + + May include variable references to the "item" namespace, ie {{item.name}}. + """ + + type: Required[Literal["template"]] + """The type of input messages. Always `template`.""" + + +class InputMessagesItemReference(TypedDict, total=False): + item_reference: Required[str] + """A reference to a variable in the "item" namespace. Ie, "item.name" """ + + type: Required[Literal["item_reference"]] + """The type of input messages. Always `item_reference`.""" + + +InputMessages: TypeAlias = Union[InputMessagesTemplate, InputMessagesItemReference] + + +class SourceFileContentContent(TypedDict, total=False): + item: Required[Dict[str, object]] + + sample: Dict[str, object] + + +class SourceFileContent(TypedDict, total=False): + content: Required[Iterable[SourceFileContentContent]] + """The content of the jsonl file.""" + + type: Required[Literal["file_content"]] + """The type of jsonl source. Always `file_content`.""" + + +class SourceFileID(TypedDict, total=False): + id: Required[str] + """The identifier of the file.""" + + type: Required[Literal["file_id"]] + """The type of jsonl source. Always `file_id`.""" + + +class SourceStoredCompletions(TypedDict, total=False): + created_after: Required[Optional[int]] + """An optional Unix timestamp to filter items created after this time.""" + + created_before: Required[Optional[int]] + """An optional Unix timestamp to filter items created before this time.""" + + limit: Required[Optional[int]] + """An optional maximum number of items to return.""" + + metadata: Required[Optional[Metadata]] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + """ + + model: Required[Optional[str]] + """An optional model to filter by (e.g., 'gpt-4o').""" + + type: Required[Literal["stored_completions"]] + """The type of source. Always `stored_completions`.""" + + +Source: TypeAlias = Union[SourceFileContent, SourceFileID, SourceStoredCompletions] + + +class SamplingParams(TypedDict, total=False): + max_completion_tokens: int + """The maximum number of tokens in the generated output.""" + + seed: int + """A seed value to initialize the randomness, during sampling.""" + + temperature: float + """A higher temperature increases randomness in the outputs.""" + + top_p: float + """An alternative to temperature for nucleus sampling; 1.0 includes all tokens.""" + + +class CreateEvalCompletionsRunDataSourceParam(TypedDict, total=False): + input_messages: Required[InputMessages] + + model: Required[str] + """The name of the model to use for generating completions (e.g. "o3-mini").""" + + source: Required[Source] + """A StoredCompletionsRunDataSource configuration describing a set of filters""" + + type: Required[Literal["completions"]] + """The type of run data source. Always `completions`.""" + + sampling_params: SamplingParams diff --git a/src/openai/types/evals/create_eval_jsonl_run_data_source.py b/src/openai/types/evals/create_eval_jsonl_run_data_source.py new file mode 100644 index 0000000000..d2be56243b --- /dev/null +++ b/src/openai/types/evals/create_eval_jsonl_run_data_source.py @@ -0,0 +1,41 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, List, Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias + +from ..._utils import PropertyInfo +from ..._models import BaseModel + +__all__ = ["CreateEvalJSONLRunDataSource", "Source", "SourceFileContent", "SourceFileContentContent", "SourceFileID"] + + +class SourceFileContentContent(BaseModel): + item: Dict[str, object] + + sample: Optional[Dict[str, object]] = None + + +class SourceFileContent(BaseModel): + content: List[SourceFileContentContent] + """The content of the jsonl file.""" + + type: Literal["file_content"] + """The type of jsonl source. Always `file_content`.""" + + +class SourceFileID(BaseModel): + id: str + """The identifier of the file.""" + + type: Literal["file_id"] + """The type of jsonl source. Always `file_id`.""" + + +Source: TypeAlias = Annotated[Union[SourceFileContent, SourceFileID], PropertyInfo(discriminator="type")] + + +class CreateEvalJSONLRunDataSource(BaseModel): + source: Source + + type: Literal["jsonl"] + """The type of data source. Always `jsonl`.""" diff --git a/src/openai/types/evals/create_eval_jsonl_run_data_source_param.py b/src/openai/types/evals/create_eval_jsonl_run_data_source_param.py new file mode 100644 index 0000000000..b8ba48a666 --- /dev/null +++ b/src/openai/types/evals/create_eval_jsonl_run_data_source_param.py @@ -0,0 +1,46 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Union, Iterable +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +__all__ = [ + "CreateEvalJSONLRunDataSourceParam", + "Source", + "SourceFileContent", + "SourceFileContentContent", + "SourceFileID", +] + + +class SourceFileContentContent(TypedDict, total=False): + item: Required[Dict[str, object]] + + sample: Dict[str, object] + + +class SourceFileContent(TypedDict, total=False): + content: Required[Iterable[SourceFileContentContent]] + """The content of the jsonl file.""" + + type: Required[Literal["file_content"]] + """The type of jsonl source. Always `file_content`.""" + + +class SourceFileID(TypedDict, total=False): + id: Required[str] + """The identifier of the file.""" + + type: Required[Literal["file_id"]] + """The type of jsonl source. Always `file_id`.""" + + +Source: TypeAlias = Union[SourceFileContent, SourceFileID] + + +class CreateEvalJSONLRunDataSourceParam(TypedDict, total=False): + source: Required[Source] + + type: Required[Literal["jsonl"]] + """The type of data source. Always `jsonl`.""" diff --git a/src/openai/types/evals/eval_api_error.py b/src/openai/types/evals/eval_api_error.py new file mode 100644 index 0000000000..d67185e981 --- /dev/null +++ b/src/openai/types/evals/eval_api_error.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +from ..._models import BaseModel + +__all__ = ["EvalAPIError"] + + +class EvalAPIError(BaseModel): + code: str + """The error code.""" + + message: str + """The error message.""" diff --git a/src/openai/types/evals/run_cancel_response.py b/src/openai/types/evals/run_cancel_response.py new file mode 100644 index 0000000000..90e52241a6 --- /dev/null +++ b/src/openai/types/evals/run_cancel_response.py @@ -0,0 +1,115 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias + +from pydantic import Field as FieldInfo + +from ..._utils import PropertyInfo +from ..._models import BaseModel +from .eval_api_error import EvalAPIError +from ..shared.metadata import Metadata +from .create_eval_jsonl_run_data_source import CreateEvalJSONLRunDataSource +from .create_eval_completions_run_data_source import CreateEvalCompletionsRunDataSource + +__all__ = ["RunCancelResponse", "DataSource", "PerModelUsage", "PerTestingCriteriaResult", "ResultCounts"] + +DataSource: TypeAlias = Annotated[ + Union[CreateEvalJSONLRunDataSource, CreateEvalCompletionsRunDataSource], PropertyInfo(discriminator="type") +] + + +class PerModelUsage(BaseModel): + cached_tokens: int + """The number of tokens retrieved from cache.""" + + completion_tokens: int + """The number of completion tokens generated.""" + + invocation_count: int + """The number of invocations.""" + + run_model_name: str = FieldInfo(alias="model_name") + """The name of the model.""" + + prompt_tokens: int + """The number of prompt tokens used.""" + + total_tokens: int + """The total number of tokens used.""" + + +class PerTestingCriteriaResult(BaseModel): + failed: int + """Number of tests failed for this criteria.""" + + passed: int + """Number of tests passed for this criteria.""" + + testing_criteria: str + """A description of the testing criteria.""" + + +class ResultCounts(BaseModel): + errored: int + """Number of output items that resulted in an error.""" + + failed: int + """Number of output items that failed to pass the evaluation.""" + + passed: int + """Number of output items that passed the evaluation.""" + + total: int + """Total number of executed output items.""" + + +class RunCancelResponse(BaseModel): + id: str + """Unique identifier for the evaluation run.""" + + created_at: int + """Unix timestamp (in seconds) when the evaluation run was created.""" + + data_source: DataSource + """Information about the run's data source.""" + + error: EvalAPIError + """An object representing an error response from the Eval API.""" + + eval_id: str + """The identifier of the associated evaluation.""" + + metadata: Optional[Metadata] = None + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + """ + + model: str + """The model that is evaluated, if applicable.""" + + name: str + """The name of the evaluation run.""" + + object: Literal["eval.run"] + """The type of the object. Always "eval.run".""" + + per_model_usage: List[PerModelUsage] + """Usage statistics for each model during the evaluation run.""" + + per_testing_criteria_results: List[PerTestingCriteriaResult] + """Results per testing criteria applied during the evaluation run.""" + + report_url: str + """The URL to the rendered evaluation run report on the UI dashboard.""" + + result_counts: ResultCounts + """Counters summarizing the outcomes of the evaluation run.""" + + status: str + """The status of the evaluation run.""" diff --git a/src/openai/types/evals/run_create_params.py b/src/openai/types/evals/run_create_params.py new file mode 100644 index 0000000000..acf7b1b126 --- /dev/null +++ b/src/openai/types/evals/run_create_params.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Optional +from typing_extensions import Required, TypeAlias, TypedDict + +from ..shared_params.metadata import Metadata +from .create_eval_jsonl_run_data_source_param import CreateEvalJSONLRunDataSourceParam +from .create_eval_completions_run_data_source_param import CreateEvalCompletionsRunDataSourceParam + +__all__ = ["RunCreateParams", "DataSource"] + + +class RunCreateParams(TypedDict, total=False): + data_source: Required[DataSource] + """Details about the run's data source.""" + + metadata: Optional[Metadata] + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + """ + + name: str + """The name of the run.""" + + +DataSource: TypeAlias = Union[CreateEvalJSONLRunDataSourceParam, CreateEvalCompletionsRunDataSourceParam] diff --git a/src/openai/types/evals/run_create_response.py b/src/openai/types/evals/run_create_response.py new file mode 100644 index 0000000000..14ca426427 --- /dev/null +++ b/src/openai/types/evals/run_create_response.py @@ -0,0 +1,115 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias + +from pydantic import Field as FieldInfo + +from ..._utils import PropertyInfo +from ..._models import BaseModel +from .eval_api_error import EvalAPIError +from ..shared.metadata import Metadata +from .create_eval_jsonl_run_data_source import CreateEvalJSONLRunDataSource +from .create_eval_completions_run_data_source import CreateEvalCompletionsRunDataSource + +__all__ = ["RunCreateResponse", "DataSource", "PerModelUsage", "PerTestingCriteriaResult", "ResultCounts"] + +DataSource: TypeAlias = Annotated[ + Union[CreateEvalJSONLRunDataSource, CreateEvalCompletionsRunDataSource], PropertyInfo(discriminator="type") +] + + +class PerModelUsage(BaseModel): + cached_tokens: int + """The number of tokens retrieved from cache.""" + + completion_tokens: int + """The number of completion tokens generated.""" + + invocation_count: int + """The number of invocations.""" + + run_model_name: str = FieldInfo(alias="model_name") + """The name of the model.""" + + prompt_tokens: int + """The number of prompt tokens used.""" + + total_tokens: int + """The total number of tokens used.""" + + +class PerTestingCriteriaResult(BaseModel): + failed: int + """Number of tests failed for this criteria.""" + + passed: int + """Number of tests passed for this criteria.""" + + testing_criteria: str + """A description of the testing criteria.""" + + +class ResultCounts(BaseModel): + errored: int + """Number of output items that resulted in an error.""" + + failed: int + """Number of output items that failed to pass the evaluation.""" + + passed: int + """Number of output items that passed the evaluation.""" + + total: int + """Total number of executed output items.""" + + +class RunCreateResponse(BaseModel): + id: str + """Unique identifier for the evaluation run.""" + + created_at: int + """Unix timestamp (in seconds) when the evaluation run was created.""" + + data_source: DataSource + """Information about the run's data source.""" + + error: EvalAPIError + """An object representing an error response from the Eval API.""" + + eval_id: str + """The identifier of the associated evaluation.""" + + metadata: Optional[Metadata] = None + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + """ + + model: str + """The model that is evaluated, if applicable.""" + + name: str + """The name of the evaluation run.""" + + object: Literal["eval.run"] + """The type of the object. Always "eval.run".""" + + per_model_usage: List[PerModelUsage] + """Usage statistics for each model during the evaluation run.""" + + per_testing_criteria_results: List[PerTestingCriteriaResult] + """Results per testing criteria applied during the evaluation run.""" + + report_url: str + """The URL to the rendered evaluation run report on the UI dashboard.""" + + result_counts: ResultCounts + """Counters summarizing the outcomes of the evaluation run.""" + + status: str + """The status of the evaluation run.""" diff --git a/src/openai/types/evals/run_delete_response.py b/src/openai/types/evals/run_delete_response.py new file mode 100644 index 0000000000..d48d01f86c --- /dev/null +++ b/src/openai/types/evals/run_delete_response.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from ..._models import BaseModel + +__all__ = ["RunDeleteResponse"] + + +class RunDeleteResponse(BaseModel): + deleted: Optional[bool] = None + + object: Optional[str] = None + + run_id: Optional[str] = None diff --git a/src/openai/types/evals/run_list_params.py b/src/openai/types/evals/run_list_params.py new file mode 100644 index 0000000000..6060eafb97 --- /dev/null +++ b/src/openai/types/evals/run_list_params.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, TypedDict + +__all__ = ["RunListParams"] + + +class RunListParams(TypedDict, total=False): + after: str + """Identifier for the last run from the previous pagination request.""" + + limit: int + """Number of runs to retrieve.""" + + order: Literal["asc", "desc"] + """Sort order for runs by timestamp. + + Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`. + """ + + status: Literal["queued", "in_progress", "completed", "canceled", "failed"] + """Filter runs by status. + + Use "queued" | "in_progress" | "failed" | "completed" | "canceled". + """ diff --git a/src/openai/types/evals/run_list_response.py b/src/openai/types/evals/run_list_response.py new file mode 100644 index 0000000000..a1022f542f --- /dev/null +++ b/src/openai/types/evals/run_list_response.py @@ -0,0 +1,115 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias + +from pydantic import Field as FieldInfo + +from ..._utils import PropertyInfo +from ..._models import BaseModel +from .eval_api_error import EvalAPIError +from ..shared.metadata import Metadata +from .create_eval_jsonl_run_data_source import CreateEvalJSONLRunDataSource +from .create_eval_completions_run_data_source import CreateEvalCompletionsRunDataSource + +__all__ = ["RunListResponse", "DataSource", "PerModelUsage", "PerTestingCriteriaResult", "ResultCounts"] + +DataSource: TypeAlias = Annotated[ + Union[CreateEvalJSONLRunDataSource, CreateEvalCompletionsRunDataSource], PropertyInfo(discriminator="type") +] + + +class PerModelUsage(BaseModel): + cached_tokens: int + """The number of tokens retrieved from cache.""" + + completion_tokens: int + """The number of completion tokens generated.""" + + invocation_count: int + """The number of invocations.""" + + run_model_name: str = FieldInfo(alias="model_name") + """The name of the model.""" + + prompt_tokens: int + """The number of prompt tokens used.""" + + total_tokens: int + """The total number of tokens used.""" + + +class PerTestingCriteriaResult(BaseModel): + failed: int + """Number of tests failed for this criteria.""" + + passed: int + """Number of tests passed for this criteria.""" + + testing_criteria: str + """A description of the testing criteria.""" + + +class ResultCounts(BaseModel): + errored: int + """Number of output items that resulted in an error.""" + + failed: int + """Number of output items that failed to pass the evaluation.""" + + passed: int + """Number of output items that passed the evaluation.""" + + total: int + """Total number of executed output items.""" + + +class RunListResponse(BaseModel): + id: str + """Unique identifier for the evaluation run.""" + + created_at: int + """Unix timestamp (in seconds) when the evaluation run was created.""" + + data_source: DataSource + """Information about the run's data source.""" + + error: EvalAPIError + """An object representing an error response from the Eval API.""" + + eval_id: str + """The identifier of the associated evaluation.""" + + metadata: Optional[Metadata] = None + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + """ + + model: str + """The model that is evaluated, if applicable.""" + + name: str + """The name of the evaluation run.""" + + object: Literal["eval.run"] + """The type of the object. Always "eval.run".""" + + per_model_usage: List[PerModelUsage] + """Usage statistics for each model during the evaluation run.""" + + per_testing_criteria_results: List[PerTestingCriteriaResult] + """Results per testing criteria applied during the evaluation run.""" + + report_url: str + """The URL to the rendered evaluation run report on the UI dashboard.""" + + result_counts: ResultCounts + """Counters summarizing the outcomes of the evaluation run.""" + + status: str + """The status of the evaluation run.""" diff --git a/src/openai/types/evals/run_retrieve_response.py b/src/openai/types/evals/run_retrieve_response.py new file mode 100644 index 0000000000..461ed43dda --- /dev/null +++ b/src/openai/types/evals/run_retrieve_response.py @@ -0,0 +1,115 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias + +from pydantic import Field as FieldInfo + +from ..._utils import PropertyInfo +from ..._models import BaseModel +from .eval_api_error import EvalAPIError +from ..shared.metadata import Metadata +from .create_eval_jsonl_run_data_source import CreateEvalJSONLRunDataSource +from .create_eval_completions_run_data_source import CreateEvalCompletionsRunDataSource + +__all__ = ["RunRetrieveResponse", "DataSource", "PerModelUsage", "PerTestingCriteriaResult", "ResultCounts"] + +DataSource: TypeAlias = Annotated[ + Union[CreateEvalJSONLRunDataSource, CreateEvalCompletionsRunDataSource], PropertyInfo(discriminator="type") +] + + +class PerModelUsage(BaseModel): + cached_tokens: int + """The number of tokens retrieved from cache.""" + + completion_tokens: int + """The number of completion tokens generated.""" + + invocation_count: int + """The number of invocations.""" + + run_model_name: str = FieldInfo(alias="model_name") + """The name of the model.""" + + prompt_tokens: int + """The number of prompt tokens used.""" + + total_tokens: int + """The total number of tokens used.""" + + +class PerTestingCriteriaResult(BaseModel): + failed: int + """Number of tests failed for this criteria.""" + + passed: int + """Number of tests passed for this criteria.""" + + testing_criteria: str + """A description of the testing criteria.""" + + +class ResultCounts(BaseModel): + errored: int + """Number of output items that resulted in an error.""" + + failed: int + """Number of output items that failed to pass the evaluation.""" + + passed: int + """Number of output items that passed the evaluation.""" + + total: int + """Total number of executed output items.""" + + +class RunRetrieveResponse(BaseModel): + id: str + """Unique identifier for the evaluation run.""" + + created_at: int + """Unix timestamp (in seconds) when the evaluation run was created.""" + + data_source: DataSource + """Information about the run's data source.""" + + error: EvalAPIError + """An object representing an error response from the Eval API.""" + + eval_id: str + """The identifier of the associated evaluation.""" + + metadata: Optional[Metadata] = None + """Set of 16 key-value pairs that can be attached to an object. + + This can be useful for storing additional information about the object in a + structured format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings with + a maximum length of 512 characters. + """ + + model: str + """The model that is evaluated, if applicable.""" + + name: str + """The name of the evaluation run.""" + + object: Literal["eval.run"] + """The type of the object. Always "eval.run".""" + + per_model_usage: List[PerModelUsage] + """Usage statistics for each model during the evaluation run.""" + + per_testing_criteria_results: List[PerTestingCriteriaResult] + """Results per testing criteria applied during the evaluation run.""" + + report_url: str + """The URL to the rendered evaluation run report on the UI dashboard.""" + + result_counts: ResultCounts + """Counters summarizing the outcomes of the evaluation run.""" + + status: str + """The status of the evaluation run.""" diff --git a/src/openai/types/evals/runs/__init__.py b/src/openai/types/evals/runs/__init__.py new file mode 100644 index 0000000000..b77cbb6acd --- /dev/null +++ b/src/openai/types/evals/runs/__init__.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .output_item_list_params import OutputItemListParams as OutputItemListParams +from .output_item_list_response import OutputItemListResponse as OutputItemListResponse +from .output_item_retrieve_response import OutputItemRetrieveResponse as OutputItemRetrieveResponse diff --git a/src/openai/types/evals/runs/output_item_list_params.py b/src/openai/types/evals/runs/output_item_list_params.py new file mode 100644 index 0000000000..073bfc69a7 --- /dev/null +++ b/src/openai/types/evals/runs/output_item_list_params.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["OutputItemListParams"] + + +class OutputItemListParams(TypedDict, total=False): + eval_id: Required[str] + + after: str + """Identifier for the last output item from the previous pagination request.""" + + limit: int + """Number of output items to retrieve.""" + + order: Literal["asc", "desc"] + """Sort order for output items by timestamp. + + Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`. + """ + + status: Literal["fail", "pass"] + """Filter output items by status. + + Use `failed` to filter by failed output items or `pass` to filter by passed + output items. + """ diff --git a/src/openai/types/evals/runs/output_item_list_response.py b/src/openai/types/evals/runs/output_item_list_response.py new file mode 100644 index 0000000000..72b1049f7b --- /dev/null +++ b/src/openai/types/evals/runs/output_item_list_response.py @@ -0,0 +1,104 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import builtins +from typing import Dict, List, Optional +from typing_extensions import Literal + +from ...._models import BaseModel +from ..eval_api_error import EvalAPIError + +__all__ = ["OutputItemListResponse", "Sample", "SampleInput", "SampleOutput", "SampleUsage"] + + +class SampleInput(BaseModel): + content: str + """The content of the message.""" + + role: str + """The role of the message sender (e.g., system, user, developer).""" + + +class SampleOutput(BaseModel): + content: Optional[str] = None + """The content of the message.""" + + role: Optional[str] = None + """The role of the message (e.g. "system", "assistant", "user").""" + + +class SampleUsage(BaseModel): + cached_tokens: int + """The number of tokens retrieved from cache.""" + + completion_tokens: int + """The number of completion tokens generated.""" + + prompt_tokens: int + """The number of prompt tokens used.""" + + total_tokens: int + """The total number of tokens used.""" + + +class Sample(BaseModel): + error: EvalAPIError + """An object representing an error response from the Eval API.""" + + finish_reason: str + """The reason why the sample generation was finished.""" + + input: List[SampleInput] + """An array of input messages.""" + + max_completion_tokens: int + """The maximum number of tokens allowed for completion.""" + + model: str + """The model used for generating the sample.""" + + output: List[SampleOutput] + """An array of output messages.""" + + seed: int + """The seed used for generating the sample.""" + + temperature: float + """The sampling temperature used.""" + + top_p: float + """The top_p value used for sampling.""" + + usage: SampleUsage + """Token usage details for the sample.""" + + +class OutputItemListResponse(BaseModel): + id: str + """Unique identifier for the evaluation run output item.""" + + created_at: int + """Unix timestamp (in seconds) when the evaluation run was created.""" + + datasource_item: Dict[str, object] + """Details of the input data source item.""" + + datasource_item_id: int + """The identifier for the data source item.""" + + eval_id: str + """The identifier of the evaluation group.""" + + object: Literal["eval.run.output_item"] + """The type of the object. Always "eval.run.output_item".""" + + results: List[Dict[str, builtins.object]] + """A list of results from the evaluation run.""" + + run_id: str + """The identifier of the evaluation run associated with this output item.""" + + sample: Sample + """A sample containing the input and output of the evaluation run.""" + + status: str + """The status of the evaluation run.""" diff --git a/src/openai/types/evals/runs/output_item_retrieve_response.py b/src/openai/types/evals/runs/output_item_retrieve_response.py new file mode 100644 index 0000000000..63aab5565f --- /dev/null +++ b/src/openai/types/evals/runs/output_item_retrieve_response.py @@ -0,0 +1,104 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import builtins +from typing import Dict, List, Optional +from typing_extensions import Literal + +from ...._models import BaseModel +from ..eval_api_error import EvalAPIError + +__all__ = ["OutputItemRetrieveResponse", "Sample", "SampleInput", "SampleOutput", "SampleUsage"] + + +class SampleInput(BaseModel): + content: str + """The content of the message.""" + + role: str + """The role of the message sender (e.g., system, user, developer).""" + + +class SampleOutput(BaseModel): + content: Optional[str] = None + """The content of the message.""" + + role: Optional[str] = None + """The role of the message (e.g. "system", "assistant", "user").""" + + +class SampleUsage(BaseModel): + cached_tokens: int + """The number of tokens retrieved from cache.""" + + completion_tokens: int + """The number of completion tokens generated.""" + + prompt_tokens: int + """The number of prompt tokens used.""" + + total_tokens: int + """The total number of tokens used.""" + + +class Sample(BaseModel): + error: EvalAPIError + """An object representing an error response from the Eval API.""" + + finish_reason: str + """The reason why the sample generation was finished.""" + + input: List[SampleInput] + """An array of input messages.""" + + max_completion_tokens: int + """The maximum number of tokens allowed for completion.""" + + model: str + """The model used for generating the sample.""" + + output: List[SampleOutput] + """An array of output messages.""" + + seed: int + """The seed used for generating the sample.""" + + temperature: float + """The sampling temperature used.""" + + top_p: float + """The top_p value used for sampling.""" + + usage: SampleUsage + """Token usage details for the sample.""" + + +class OutputItemRetrieveResponse(BaseModel): + id: str + """Unique identifier for the evaluation run output item.""" + + created_at: int + """Unix timestamp (in seconds) when the evaluation run was created.""" + + datasource_item: Dict[str, object] + """Details of the input data source item.""" + + datasource_item_id: int + """The identifier for the data source item.""" + + eval_id: str + """The identifier of the evaluation group.""" + + object: Literal["eval.run.output_item"] + """The type of the object. Always "eval.run.output_item".""" + + results: List[Dict[str, builtins.object]] + """A list of results from the evaluation run.""" + + run_id: str + """The identifier of the evaluation run associated with this output item.""" + + sample: Sample + """A sample containing the input and output of the evaluation run.""" + + status: str + """The status of the evaluation run.""" diff --git a/src/openai/types/fine_tuning/checkpoints/__init__.py b/src/openai/types/fine_tuning/checkpoints/__init__.py new file mode 100644 index 0000000000..2947b33145 --- /dev/null +++ b/src/openai/types/fine_tuning/checkpoints/__init__.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .permission_create_params import PermissionCreateParams as PermissionCreateParams +from .permission_create_response import PermissionCreateResponse as PermissionCreateResponse +from .permission_delete_response import PermissionDeleteResponse as PermissionDeleteResponse +from .permission_retrieve_params import PermissionRetrieveParams as PermissionRetrieveParams +from .permission_retrieve_response import PermissionRetrieveResponse as PermissionRetrieveResponse diff --git a/src/openai/types/fine_tuning/checkpoints/permission_create_params.py b/src/openai/types/fine_tuning/checkpoints/permission_create_params.py new file mode 100644 index 0000000000..92f98f21b9 --- /dev/null +++ b/src/openai/types/fine_tuning/checkpoints/permission_create_params.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List +from typing_extensions import Required, TypedDict + +__all__ = ["PermissionCreateParams"] + + +class PermissionCreateParams(TypedDict, total=False): + project_ids: Required[List[str]] + """The project identifiers to grant access to.""" diff --git a/src/openai/types/fine_tuning/checkpoints/permission_create_response.py b/src/openai/types/fine_tuning/checkpoints/permission_create_response.py new file mode 100644 index 0000000000..9bc14c00cc --- /dev/null +++ b/src/openai/types/fine_tuning/checkpoints/permission_create_response.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["PermissionCreateResponse"] + + +class PermissionCreateResponse(BaseModel): + id: str + """The permission identifier, which can be referenced in the API endpoints.""" + + created_at: int + """The Unix timestamp (in seconds) for when the permission was created.""" + + object: Literal["checkpoint.permission"] + """The object type, which is always "checkpoint.permission".""" + + project_id: str + """The project identifier that the permission is for.""" diff --git a/src/openai/types/fine_tuning/checkpoints/permission_delete_response.py b/src/openai/types/fine_tuning/checkpoints/permission_delete_response.py new file mode 100644 index 0000000000..1a92d912fa --- /dev/null +++ b/src/openai/types/fine_tuning/checkpoints/permission_delete_response.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["PermissionDeleteResponse"] + + +class PermissionDeleteResponse(BaseModel): + id: str + """The ID of the fine-tuned model checkpoint permission that was deleted.""" + + deleted: bool + """Whether the fine-tuned model checkpoint permission was successfully deleted.""" + + object: Literal["checkpoint.permission"] + """The object type, which is always "checkpoint.permission".""" diff --git a/src/openai/types/fine_tuning/checkpoints/permission_retrieve_params.py b/src/openai/types/fine_tuning/checkpoints/permission_retrieve_params.py new file mode 100644 index 0000000000..6e66a867ca --- /dev/null +++ b/src/openai/types/fine_tuning/checkpoints/permission_retrieve_params.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, TypedDict + +__all__ = ["PermissionRetrieveParams"] + + +class PermissionRetrieveParams(TypedDict, total=False): + after: str + """Identifier for the last permission ID from the previous pagination request.""" + + limit: int + """Number of permissions to retrieve.""" + + order: Literal["ascending", "descending"] + """The order in which to retrieve permissions.""" + + project_id: str + """The ID of the project to get permissions for.""" diff --git a/src/openai/types/fine_tuning/checkpoints/permission_retrieve_response.py b/src/openai/types/fine_tuning/checkpoints/permission_retrieve_response.py new file mode 100644 index 0000000000..14c73b55d0 --- /dev/null +++ b/src/openai/types/fine_tuning/checkpoints/permission_retrieve_response.py @@ -0,0 +1,34 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["PermissionRetrieveResponse", "Data"] + + +class Data(BaseModel): + id: str + """The permission identifier, which can be referenced in the API endpoints.""" + + created_at: int + """The Unix timestamp (in seconds) for when the permission was created.""" + + object: Literal["checkpoint.permission"] + """The object type, which is always "checkpoint.permission".""" + + project_id: str + """The project identifier that the permission is for.""" + + +class PermissionRetrieveResponse(BaseModel): + data: List[Data] + + has_more: bool + + object: Literal["list"] + + first_id: Optional[str] = None + + last_id: Optional[str] = None diff --git a/tests/api_resources/evals/__init__.py b/tests/api_resources/evals/__init__.py new file mode 100644 index 0000000000..fd8019a9a1 --- /dev/null +++ b/tests/api_resources/evals/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/evals/runs/__init__.py b/tests/api_resources/evals/runs/__init__.py new file mode 100644 index 0000000000..fd8019a9a1 --- /dev/null +++ b/tests/api_resources/evals/runs/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/evals/runs/test_output_items.py b/tests/api_resources/evals/runs/test_output_items.py new file mode 100644 index 0000000000..f764f0336e --- /dev/null +++ b/tests/api_resources/evals/runs/test_output_items.py @@ -0,0 +1,263 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai.pagination import SyncCursorPage, AsyncCursorPage +from openai.types.evals.runs import OutputItemListResponse, OutputItemRetrieveResponse + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") + + +class TestOutputItems: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + def test_method_retrieve(self, client: OpenAI) -> None: + output_item = client.evals.runs.output_items.retrieve( + output_item_id="output_item_id", + eval_id="eval_id", + run_id="run_id", + ) + assert_matches_type(OutputItemRetrieveResponse, output_item, path=["response"]) + + @parametrize + def test_raw_response_retrieve(self, client: OpenAI) -> None: + response = client.evals.runs.output_items.with_raw_response.retrieve( + output_item_id="output_item_id", + eval_id="eval_id", + run_id="run_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + output_item = response.parse() + assert_matches_type(OutputItemRetrieveResponse, output_item, path=["response"]) + + @parametrize + def test_streaming_response_retrieve(self, client: OpenAI) -> None: + with client.evals.runs.output_items.with_streaming_response.retrieve( + output_item_id="output_item_id", + eval_id="eval_id", + run_id="run_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + output_item = response.parse() + assert_matches_type(OutputItemRetrieveResponse, output_item, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_retrieve(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `eval_id` but received ''"): + client.evals.runs.output_items.with_raw_response.retrieve( + output_item_id="output_item_id", + eval_id="", + run_id="run_id", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): + client.evals.runs.output_items.with_raw_response.retrieve( + output_item_id="output_item_id", + eval_id="eval_id", + run_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `output_item_id` but received ''"): + client.evals.runs.output_items.with_raw_response.retrieve( + output_item_id="", + eval_id="eval_id", + run_id="run_id", + ) + + @parametrize + def test_method_list(self, client: OpenAI) -> None: + output_item = client.evals.runs.output_items.list( + run_id="run_id", + eval_id="eval_id", + ) + assert_matches_type(SyncCursorPage[OutputItemListResponse], output_item, path=["response"]) + + @parametrize + def test_method_list_with_all_params(self, client: OpenAI) -> None: + output_item = client.evals.runs.output_items.list( + run_id="run_id", + eval_id="eval_id", + after="after", + limit=0, + order="asc", + status="fail", + ) + assert_matches_type(SyncCursorPage[OutputItemListResponse], output_item, path=["response"]) + + @parametrize + def test_raw_response_list(self, client: OpenAI) -> None: + response = client.evals.runs.output_items.with_raw_response.list( + run_id="run_id", + eval_id="eval_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + output_item = response.parse() + assert_matches_type(SyncCursorPage[OutputItemListResponse], output_item, path=["response"]) + + @parametrize + def test_streaming_response_list(self, client: OpenAI) -> None: + with client.evals.runs.output_items.with_streaming_response.list( + run_id="run_id", + eval_id="eval_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + output_item = response.parse() + assert_matches_type(SyncCursorPage[OutputItemListResponse], output_item, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_list(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `eval_id` but received ''"): + client.evals.runs.output_items.with_raw_response.list( + run_id="run_id", + eval_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): + client.evals.runs.output_items.with_raw_response.list( + run_id="", + eval_id="eval_id", + ) + + +class TestAsyncOutputItems: + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: + output_item = await async_client.evals.runs.output_items.retrieve( + output_item_id="output_item_id", + eval_id="eval_id", + run_id="run_id", + ) + assert_matches_type(OutputItemRetrieveResponse, output_item, path=["response"]) + + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: + response = await async_client.evals.runs.output_items.with_raw_response.retrieve( + output_item_id="output_item_id", + eval_id="eval_id", + run_id="run_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + output_item = response.parse() + assert_matches_type(OutputItemRetrieveResponse, output_item, path=["response"]) + + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: + async with async_client.evals.runs.output_items.with_streaming_response.retrieve( + output_item_id="output_item_id", + eval_id="eval_id", + run_id="run_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + output_item = await response.parse() + assert_matches_type(OutputItemRetrieveResponse, output_item, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `eval_id` but received ''"): + await async_client.evals.runs.output_items.with_raw_response.retrieve( + output_item_id="output_item_id", + eval_id="", + run_id="run_id", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): + await async_client.evals.runs.output_items.with_raw_response.retrieve( + output_item_id="output_item_id", + eval_id="eval_id", + run_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `output_item_id` but received ''"): + await async_client.evals.runs.output_items.with_raw_response.retrieve( + output_item_id="", + eval_id="eval_id", + run_id="run_id", + ) + + @parametrize + async def test_method_list(self, async_client: AsyncOpenAI) -> None: + output_item = await async_client.evals.runs.output_items.list( + run_id="run_id", + eval_id="eval_id", + ) + assert_matches_type(AsyncCursorPage[OutputItemListResponse], output_item, path=["response"]) + + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: + output_item = await async_client.evals.runs.output_items.list( + run_id="run_id", + eval_id="eval_id", + after="after", + limit=0, + order="asc", + status="fail", + ) + assert_matches_type(AsyncCursorPage[OutputItemListResponse], output_item, path=["response"]) + + @parametrize + async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: + response = await async_client.evals.runs.output_items.with_raw_response.list( + run_id="run_id", + eval_id="eval_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + output_item = response.parse() + assert_matches_type(AsyncCursorPage[OutputItemListResponse], output_item, path=["response"]) + + @parametrize + async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: + async with async_client.evals.runs.output_items.with_streaming_response.list( + run_id="run_id", + eval_id="eval_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + output_item = await response.parse() + assert_matches_type(AsyncCursorPage[OutputItemListResponse], output_item, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_list(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `eval_id` but received ''"): + await async_client.evals.runs.output_items.with_raw_response.list( + run_id="run_id", + eval_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): + await async_client.evals.runs.output_items.with_raw_response.list( + run_id="", + eval_id="eval_id", + ) diff --git a/tests/api_resources/evals/test_runs.py b/tests/api_resources/evals/test_runs.py new file mode 100644 index 0000000000..cefb1c82ff --- /dev/null +++ b/tests/api_resources/evals/test_runs.py @@ -0,0 +1,589 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai.pagination import SyncCursorPage, AsyncCursorPage +from openai.types.evals import ( + RunListResponse, + RunCancelResponse, + RunCreateResponse, + RunDeleteResponse, + RunRetrieveResponse, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") + + +class TestRuns: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + def test_method_create(self, client: OpenAI) -> None: + run = client.evals.runs.create( + eval_id="eval_id", + data_source={ + "source": { + "content": [{"item": {"foo": "bar"}}], + "type": "file_content", + }, + "type": "jsonl", + }, + ) + assert_matches_type(RunCreateResponse, run, path=["response"]) + + @parametrize + def test_method_create_with_all_params(self, client: OpenAI) -> None: + run = client.evals.runs.create( + eval_id="eval_id", + data_source={ + "source": { + "content": [ + { + "item": {"foo": "bar"}, + "sample": {"foo": "bar"}, + } + ], + "type": "file_content", + }, + "type": "jsonl", + }, + metadata={"foo": "string"}, + name="name", + ) + assert_matches_type(RunCreateResponse, run, path=["response"]) + + @parametrize + def test_raw_response_create(self, client: OpenAI) -> None: + response = client.evals.runs.with_raw_response.create( + eval_id="eval_id", + data_source={ + "source": { + "content": [{"item": {"foo": "bar"}}], + "type": "file_content", + }, + "type": "jsonl", + }, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + run = response.parse() + assert_matches_type(RunCreateResponse, run, path=["response"]) + + @parametrize + def test_streaming_response_create(self, client: OpenAI) -> None: + with client.evals.runs.with_streaming_response.create( + eval_id="eval_id", + data_source={ + "source": { + "content": [{"item": {"foo": "bar"}}], + "type": "file_content", + }, + "type": "jsonl", + }, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + run = response.parse() + assert_matches_type(RunCreateResponse, run, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_create(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `eval_id` but received ''"): + client.evals.runs.with_raw_response.create( + eval_id="", + data_source={ + "source": { + "content": [{"item": {"foo": "bar"}}], + "type": "file_content", + }, + "type": "jsonl", + }, + ) + + @parametrize + def test_method_retrieve(self, client: OpenAI) -> None: + run = client.evals.runs.retrieve( + run_id="run_id", + eval_id="eval_id", + ) + assert_matches_type(RunRetrieveResponse, run, path=["response"]) + + @parametrize + def test_raw_response_retrieve(self, client: OpenAI) -> None: + response = client.evals.runs.with_raw_response.retrieve( + run_id="run_id", + eval_id="eval_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + run = response.parse() + assert_matches_type(RunRetrieveResponse, run, path=["response"]) + + @parametrize + def test_streaming_response_retrieve(self, client: OpenAI) -> None: + with client.evals.runs.with_streaming_response.retrieve( + run_id="run_id", + eval_id="eval_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + run = response.parse() + assert_matches_type(RunRetrieveResponse, run, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_retrieve(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `eval_id` but received ''"): + client.evals.runs.with_raw_response.retrieve( + run_id="run_id", + eval_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): + client.evals.runs.with_raw_response.retrieve( + run_id="", + eval_id="eval_id", + ) + + @parametrize + def test_method_list(self, client: OpenAI) -> None: + run = client.evals.runs.list( + eval_id="eval_id", + ) + assert_matches_type(SyncCursorPage[RunListResponse], run, path=["response"]) + + @parametrize + def test_method_list_with_all_params(self, client: OpenAI) -> None: + run = client.evals.runs.list( + eval_id="eval_id", + after="after", + limit=0, + order="asc", + status="queued", + ) + assert_matches_type(SyncCursorPage[RunListResponse], run, path=["response"]) + + @parametrize + def test_raw_response_list(self, client: OpenAI) -> None: + response = client.evals.runs.with_raw_response.list( + eval_id="eval_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + run = response.parse() + assert_matches_type(SyncCursorPage[RunListResponse], run, path=["response"]) + + @parametrize + def test_streaming_response_list(self, client: OpenAI) -> None: + with client.evals.runs.with_streaming_response.list( + eval_id="eval_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + run = response.parse() + assert_matches_type(SyncCursorPage[RunListResponse], run, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_list(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `eval_id` but received ''"): + client.evals.runs.with_raw_response.list( + eval_id="", + ) + + @parametrize + def test_method_delete(self, client: OpenAI) -> None: + run = client.evals.runs.delete( + run_id="run_id", + eval_id="eval_id", + ) + assert_matches_type(RunDeleteResponse, run, path=["response"]) + + @parametrize + def test_raw_response_delete(self, client: OpenAI) -> None: + response = client.evals.runs.with_raw_response.delete( + run_id="run_id", + eval_id="eval_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + run = response.parse() + assert_matches_type(RunDeleteResponse, run, path=["response"]) + + @parametrize + def test_streaming_response_delete(self, client: OpenAI) -> None: + with client.evals.runs.with_streaming_response.delete( + run_id="run_id", + eval_id="eval_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + run = response.parse() + assert_matches_type(RunDeleteResponse, run, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_delete(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `eval_id` but received ''"): + client.evals.runs.with_raw_response.delete( + run_id="run_id", + eval_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): + client.evals.runs.with_raw_response.delete( + run_id="", + eval_id="eval_id", + ) + + @parametrize + def test_method_cancel(self, client: OpenAI) -> None: + run = client.evals.runs.cancel( + run_id="run_id", + eval_id="eval_id", + ) + assert_matches_type(RunCancelResponse, run, path=["response"]) + + @parametrize + def test_raw_response_cancel(self, client: OpenAI) -> None: + response = client.evals.runs.with_raw_response.cancel( + run_id="run_id", + eval_id="eval_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + run = response.parse() + assert_matches_type(RunCancelResponse, run, path=["response"]) + + @parametrize + def test_streaming_response_cancel(self, client: OpenAI) -> None: + with client.evals.runs.with_streaming_response.cancel( + run_id="run_id", + eval_id="eval_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + run = response.parse() + assert_matches_type(RunCancelResponse, run, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_cancel(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `eval_id` but received ''"): + client.evals.runs.with_raw_response.cancel( + run_id="run_id", + eval_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): + client.evals.runs.with_raw_response.cancel( + run_id="", + eval_id="eval_id", + ) + + +class TestAsyncRuns: + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + async def test_method_create(self, async_client: AsyncOpenAI) -> None: + run = await async_client.evals.runs.create( + eval_id="eval_id", + data_source={ + "source": { + "content": [{"item": {"foo": "bar"}}], + "type": "file_content", + }, + "type": "jsonl", + }, + ) + assert_matches_type(RunCreateResponse, run, path=["response"]) + + @parametrize + async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: + run = await async_client.evals.runs.create( + eval_id="eval_id", + data_source={ + "source": { + "content": [ + { + "item": {"foo": "bar"}, + "sample": {"foo": "bar"}, + } + ], + "type": "file_content", + }, + "type": "jsonl", + }, + metadata={"foo": "string"}, + name="name", + ) + assert_matches_type(RunCreateResponse, run, path=["response"]) + + @parametrize + async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: + response = await async_client.evals.runs.with_raw_response.create( + eval_id="eval_id", + data_source={ + "source": { + "content": [{"item": {"foo": "bar"}}], + "type": "file_content", + }, + "type": "jsonl", + }, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + run = response.parse() + assert_matches_type(RunCreateResponse, run, path=["response"]) + + @parametrize + async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: + async with async_client.evals.runs.with_streaming_response.create( + eval_id="eval_id", + data_source={ + "source": { + "content": [{"item": {"foo": "bar"}}], + "type": "file_content", + }, + "type": "jsonl", + }, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + run = await response.parse() + assert_matches_type(RunCreateResponse, run, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_create(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `eval_id` but received ''"): + await async_client.evals.runs.with_raw_response.create( + eval_id="", + data_source={ + "source": { + "content": [{"item": {"foo": "bar"}}], + "type": "file_content", + }, + "type": "jsonl", + }, + ) + + @parametrize + async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: + run = await async_client.evals.runs.retrieve( + run_id="run_id", + eval_id="eval_id", + ) + assert_matches_type(RunRetrieveResponse, run, path=["response"]) + + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: + response = await async_client.evals.runs.with_raw_response.retrieve( + run_id="run_id", + eval_id="eval_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + run = response.parse() + assert_matches_type(RunRetrieveResponse, run, path=["response"]) + + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: + async with async_client.evals.runs.with_streaming_response.retrieve( + run_id="run_id", + eval_id="eval_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + run = await response.parse() + assert_matches_type(RunRetrieveResponse, run, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `eval_id` but received ''"): + await async_client.evals.runs.with_raw_response.retrieve( + run_id="run_id", + eval_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): + await async_client.evals.runs.with_raw_response.retrieve( + run_id="", + eval_id="eval_id", + ) + + @parametrize + async def test_method_list(self, async_client: AsyncOpenAI) -> None: + run = await async_client.evals.runs.list( + eval_id="eval_id", + ) + assert_matches_type(AsyncCursorPage[RunListResponse], run, path=["response"]) + + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: + run = await async_client.evals.runs.list( + eval_id="eval_id", + after="after", + limit=0, + order="asc", + status="queued", + ) + assert_matches_type(AsyncCursorPage[RunListResponse], run, path=["response"]) + + @parametrize + async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: + response = await async_client.evals.runs.with_raw_response.list( + eval_id="eval_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + run = response.parse() + assert_matches_type(AsyncCursorPage[RunListResponse], run, path=["response"]) + + @parametrize + async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: + async with async_client.evals.runs.with_streaming_response.list( + eval_id="eval_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + run = await response.parse() + assert_matches_type(AsyncCursorPage[RunListResponse], run, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_list(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `eval_id` but received ''"): + await async_client.evals.runs.with_raw_response.list( + eval_id="", + ) + + @parametrize + async def test_method_delete(self, async_client: AsyncOpenAI) -> None: + run = await async_client.evals.runs.delete( + run_id="run_id", + eval_id="eval_id", + ) + assert_matches_type(RunDeleteResponse, run, path=["response"]) + + @parametrize + async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None: + response = await async_client.evals.runs.with_raw_response.delete( + run_id="run_id", + eval_id="eval_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + run = response.parse() + assert_matches_type(RunDeleteResponse, run, path=["response"]) + + @parametrize + async def test_streaming_response_delete(self, async_client: AsyncOpenAI) -> None: + async with async_client.evals.runs.with_streaming_response.delete( + run_id="run_id", + eval_id="eval_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + run = await response.parse() + assert_matches_type(RunDeleteResponse, run, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_delete(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `eval_id` but received ''"): + await async_client.evals.runs.with_raw_response.delete( + run_id="run_id", + eval_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): + await async_client.evals.runs.with_raw_response.delete( + run_id="", + eval_id="eval_id", + ) + + @parametrize + async def test_method_cancel(self, async_client: AsyncOpenAI) -> None: + run = await async_client.evals.runs.cancel( + run_id="run_id", + eval_id="eval_id", + ) + assert_matches_type(RunCancelResponse, run, path=["response"]) + + @parametrize + async def test_raw_response_cancel(self, async_client: AsyncOpenAI) -> None: + response = await async_client.evals.runs.with_raw_response.cancel( + run_id="run_id", + eval_id="eval_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + run = response.parse() + assert_matches_type(RunCancelResponse, run, path=["response"]) + + @parametrize + async def test_streaming_response_cancel(self, async_client: AsyncOpenAI) -> None: + async with async_client.evals.runs.with_streaming_response.cancel( + run_id="run_id", + eval_id="eval_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + run = await response.parse() + assert_matches_type(RunCancelResponse, run, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_cancel(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `eval_id` but received ''"): + await async_client.evals.runs.with_raw_response.cancel( + run_id="run_id", + eval_id="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `run_id` but received ''"): + await async_client.evals.runs.with_raw_response.cancel( + run_id="", + eval_id="eval_id", + ) diff --git a/tests/api_resources/fine_tuning/checkpoints/__init__.py b/tests/api_resources/fine_tuning/checkpoints/__init__.py new file mode 100644 index 0000000000..fd8019a9a1 --- /dev/null +++ b/tests/api_resources/fine_tuning/checkpoints/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/fine_tuning/checkpoints/test_permissions.py b/tests/api_resources/fine_tuning/checkpoints/test_permissions.py new file mode 100644 index 0000000000..d25c784c33 --- /dev/null +++ b/tests/api_resources/fine_tuning/checkpoints/test_permissions.py @@ -0,0 +1,297 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai.pagination import SyncPage, AsyncPage +from openai.types.fine_tuning.checkpoints import ( + PermissionCreateResponse, + PermissionDeleteResponse, + PermissionRetrieveResponse, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") + + +class TestPermissions: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + def test_method_create(self, client: OpenAI) -> None: + permission = client.fine_tuning.checkpoints.permissions.create( + fine_tuned_model_checkpoint="ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", + project_ids=["string"], + ) + assert_matches_type(SyncPage[PermissionCreateResponse], permission, path=["response"]) + + @parametrize + def test_raw_response_create(self, client: OpenAI) -> None: + response = client.fine_tuning.checkpoints.permissions.with_raw_response.create( + fine_tuned_model_checkpoint="ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", + project_ids=["string"], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + permission = response.parse() + assert_matches_type(SyncPage[PermissionCreateResponse], permission, path=["response"]) + + @parametrize + def test_streaming_response_create(self, client: OpenAI) -> None: + with client.fine_tuning.checkpoints.permissions.with_streaming_response.create( + fine_tuned_model_checkpoint="ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", + project_ids=["string"], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + permission = response.parse() + assert_matches_type(SyncPage[PermissionCreateResponse], permission, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_create(self, client: OpenAI) -> None: + with pytest.raises( + ValueError, match=r"Expected a non-empty value for `fine_tuned_model_checkpoint` but received ''" + ): + client.fine_tuning.checkpoints.permissions.with_raw_response.create( + fine_tuned_model_checkpoint="", + project_ids=["string"], + ) + + @parametrize + def test_method_retrieve(self, client: OpenAI) -> None: + permission = client.fine_tuning.checkpoints.permissions.retrieve( + fine_tuned_model_checkpoint="ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert_matches_type(PermissionRetrieveResponse, permission, path=["response"]) + + @parametrize + def test_method_retrieve_with_all_params(self, client: OpenAI) -> None: + permission = client.fine_tuning.checkpoints.permissions.retrieve( + fine_tuned_model_checkpoint="ft-AF1WoRqd3aJAHsqc9NY7iL8F", + after="after", + limit=0, + order="ascending", + project_id="project_id", + ) + assert_matches_type(PermissionRetrieveResponse, permission, path=["response"]) + + @parametrize + def test_raw_response_retrieve(self, client: OpenAI) -> None: + response = client.fine_tuning.checkpoints.permissions.with_raw_response.retrieve( + fine_tuned_model_checkpoint="ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + permission = response.parse() + assert_matches_type(PermissionRetrieveResponse, permission, path=["response"]) + + @parametrize + def test_streaming_response_retrieve(self, client: OpenAI) -> None: + with client.fine_tuning.checkpoints.permissions.with_streaming_response.retrieve( + fine_tuned_model_checkpoint="ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + permission = response.parse() + assert_matches_type(PermissionRetrieveResponse, permission, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_retrieve(self, client: OpenAI) -> None: + with pytest.raises( + ValueError, match=r"Expected a non-empty value for `fine_tuned_model_checkpoint` but received ''" + ): + client.fine_tuning.checkpoints.permissions.with_raw_response.retrieve( + fine_tuned_model_checkpoint="", + ) + + @parametrize + def test_method_delete(self, client: OpenAI) -> None: + permission = client.fine_tuning.checkpoints.permissions.delete( + "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", + ) + assert_matches_type(PermissionDeleteResponse, permission, path=["response"]) + + @parametrize + def test_raw_response_delete(self, client: OpenAI) -> None: + response = client.fine_tuning.checkpoints.permissions.with_raw_response.delete( + "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + permission = response.parse() + assert_matches_type(PermissionDeleteResponse, permission, path=["response"]) + + @parametrize + def test_streaming_response_delete(self, client: OpenAI) -> None: + with client.fine_tuning.checkpoints.permissions.with_streaming_response.delete( + "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + permission = response.parse() + assert_matches_type(PermissionDeleteResponse, permission, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_delete(self, client: OpenAI) -> None: + with pytest.raises( + ValueError, match=r"Expected a non-empty value for `fine_tuned_model_checkpoint` but received ''" + ): + client.fine_tuning.checkpoints.permissions.with_raw_response.delete( + "", + ) + + +class TestAsyncPermissions: + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + async def test_method_create(self, async_client: AsyncOpenAI) -> None: + permission = await async_client.fine_tuning.checkpoints.permissions.create( + fine_tuned_model_checkpoint="ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", + project_ids=["string"], + ) + assert_matches_type(AsyncPage[PermissionCreateResponse], permission, path=["response"]) + + @parametrize + async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: + response = await async_client.fine_tuning.checkpoints.permissions.with_raw_response.create( + fine_tuned_model_checkpoint="ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", + project_ids=["string"], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + permission = response.parse() + assert_matches_type(AsyncPage[PermissionCreateResponse], permission, path=["response"]) + + @parametrize + async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: + async with async_client.fine_tuning.checkpoints.permissions.with_streaming_response.create( + fine_tuned_model_checkpoint="ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", + project_ids=["string"], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + permission = await response.parse() + assert_matches_type(AsyncPage[PermissionCreateResponse], permission, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_create(self, async_client: AsyncOpenAI) -> None: + with pytest.raises( + ValueError, match=r"Expected a non-empty value for `fine_tuned_model_checkpoint` but received ''" + ): + await async_client.fine_tuning.checkpoints.permissions.with_raw_response.create( + fine_tuned_model_checkpoint="", + project_ids=["string"], + ) + + @parametrize + async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: + permission = await async_client.fine_tuning.checkpoints.permissions.retrieve( + fine_tuned_model_checkpoint="ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert_matches_type(PermissionRetrieveResponse, permission, path=["response"]) + + @parametrize + async def test_method_retrieve_with_all_params(self, async_client: AsyncOpenAI) -> None: + permission = await async_client.fine_tuning.checkpoints.permissions.retrieve( + fine_tuned_model_checkpoint="ft-AF1WoRqd3aJAHsqc9NY7iL8F", + after="after", + limit=0, + order="ascending", + project_id="project_id", + ) + assert_matches_type(PermissionRetrieveResponse, permission, path=["response"]) + + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: + response = await async_client.fine_tuning.checkpoints.permissions.with_raw_response.retrieve( + fine_tuned_model_checkpoint="ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + permission = response.parse() + assert_matches_type(PermissionRetrieveResponse, permission, path=["response"]) + + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: + async with async_client.fine_tuning.checkpoints.permissions.with_streaming_response.retrieve( + fine_tuned_model_checkpoint="ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + permission = await response.parse() + assert_matches_type(PermissionRetrieveResponse, permission, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: + with pytest.raises( + ValueError, match=r"Expected a non-empty value for `fine_tuned_model_checkpoint` but received ''" + ): + await async_client.fine_tuning.checkpoints.permissions.with_raw_response.retrieve( + fine_tuned_model_checkpoint="", + ) + + @parametrize + async def test_method_delete(self, async_client: AsyncOpenAI) -> None: + permission = await async_client.fine_tuning.checkpoints.permissions.delete( + "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", + ) + assert_matches_type(PermissionDeleteResponse, permission, path=["response"]) + + @parametrize + async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None: + response = await async_client.fine_tuning.checkpoints.permissions.with_raw_response.delete( + "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + permission = response.parse() + assert_matches_type(PermissionDeleteResponse, permission, path=["response"]) + + @parametrize + async def test_streaming_response_delete(self, async_client: AsyncOpenAI) -> None: + async with async_client.fine_tuning.checkpoints.permissions.with_streaming_response.delete( + "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + permission = await response.parse() + assert_matches_type(PermissionDeleteResponse, permission, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_delete(self, async_client: AsyncOpenAI) -> None: + with pytest.raises( + ValueError, match=r"Expected a non-empty value for `fine_tuned_model_checkpoint` but received ''" + ): + await async_client.fine_tuning.checkpoints.permissions.with_raw_response.delete( + "", + ) diff --git a/tests/api_resources/test_evals.py b/tests/api_resources/test_evals.py new file mode 100644 index 0000000000..33ba92cda5 --- /dev/null +++ b/tests/api_resources/test_evals.py @@ -0,0 +1,1701 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai.types import ( + EvalListResponse, + EvalCreateResponse, + EvalDeleteResponse, + EvalUpdateResponse, + EvalRetrieveResponse, +) +from openai.pagination import SyncCursorPage, AsyncCursorPage + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") + + +class TestEvals: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + def test_method_create(self, client: OpenAI) -> None: + eval = client.evals.create( + data_source_config={ + "item_schema": { + "0": "bar", + "1": "bar", + "2": "bar", + "3": "bar", + "4": "bar", + "5": "bar", + "6": "bar", + "7": "bar", + "8": "bar", + "9": "bar", + "10": "bar", + "11": "bar", + "12": "bar", + "13": "bar", + "14": "bar", + "15": "bar", + "16": "bar", + "17": "bar", + "18": "bar", + "19": "bar", + "20": "bar", + "21": "bar", + "22": "bar", + "23": "bar", + "24": "bar", + "25": "bar", + "26": "bar", + "27": "bar", + "28": "bar", + "29": "bar", + "30": "bar", + "31": "bar", + "32": "bar", + "33": "bar", + "34": "bar", + "35": "bar", + "36": "bar", + "37": "bar", + "38": "bar", + "39": "bar", + "40": "bar", + "41": "bar", + "42": "bar", + "43": "bar", + "44": "bar", + "45": "bar", + "46": "bar", + "47": "bar", + "48": "bar", + "49": "bar", + "50": "bar", + "51": "bar", + "52": "bar", + "53": "bar", + "54": "bar", + "55": "bar", + "56": "bar", + "57": "bar", + "58": "bar", + "59": "bar", + "60": "bar", + "61": "bar", + "62": "bar", + "63": "bar", + "64": "bar", + "65": "bar", + "66": "bar", + "67": "bar", + "68": "bar", + "69": "bar", + "70": "bar", + "71": "bar", + "72": "bar", + "73": "bar", + "74": "bar", + "75": "bar", + "76": "bar", + "77": "bar", + "78": "bar", + "79": "bar", + "80": "bar", + "81": "bar", + "82": "bar", + "83": "bar", + "84": "bar", + "85": "bar", + "86": "bar", + "87": "bar", + "88": "bar", + "89": "bar", + "90": "bar", + "91": "bar", + "92": "bar", + "93": "bar", + "94": "bar", + "95": "bar", + "96": "bar", + "97": "bar", + "98": "bar", + "99": "bar", + "100": "bar", + "101": "bar", + "102": "bar", + "103": "bar", + "104": "bar", + "105": "bar", + "106": "bar", + "107": "bar", + "108": "bar", + "109": "bar", + "110": "bar", + "111": "bar", + "112": "bar", + "113": "bar", + "114": "bar", + "115": "bar", + "116": "bar", + "117": "bar", + "118": "bar", + "119": "bar", + "120": "bar", + "121": "bar", + "122": "bar", + "123": "bar", + "124": "bar", + "125": "bar", + "126": "bar", + "127": "bar", + "128": "bar", + "129": "bar", + "130": "bar", + "131": "bar", + "132": "bar", + "133": "bar", + "134": "bar", + "135": "bar", + "136": "bar", + "137": "bar", + "138": "bar", + "139": "bar", + }, + "type": "custom", + }, + testing_criteria=[ + { + "input": [ + { + "content": "content", + "role": "role", + } + ], + "labels": ["string"], + "model": "model", + "name": "name", + "passing_labels": ["string"], + "type": "label_model", + } + ], + ) + assert_matches_type(EvalCreateResponse, eval, path=["response"]) + + @parametrize + def test_method_create_with_all_params(self, client: OpenAI) -> None: + eval = client.evals.create( + data_source_config={ + "item_schema": { + "0": "bar", + "1": "bar", + "2": "bar", + "3": "bar", + "4": "bar", + "5": "bar", + "6": "bar", + "7": "bar", + "8": "bar", + "9": "bar", + "10": "bar", + "11": "bar", + "12": "bar", + "13": "bar", + "14": "bar", + "15": "bar", + "16": "bar", + "17": "bar", + "18": "bar", + "19": "bar", + "20": "bar", + "21": "bar", + "22": "bar", + "23": "bar", + "24": "bar", + "25": "bar", + "26": "bar", + "27": "bar", + "28": "bar", + "29": "bar", + "30": "bar", + "31": "bar", + "32": "bar", + "33": "bar", + "34": "bar", + "35": "bar", + "36": "bar", + "37": "bar", + "38": "bar", + "39": "bar", + "40": "bar", + "41": "bar", + "42": "bar", + "43": "bar", + "44": "bar", + "45": "bar", + "46": "bar", + "47": "bar", + "48": "bar", + "49": "bar", + "50": "bar", + "51": "bar", + "52": "bar", + "53": "bar", + "54": "bar", + "55": "bar", + "56": "bar", + "57": "bar", + "58": "bar", + "59": "bar", + "60": "bar", + "61": "bar", + "62": "bar", + "63": "bar", + "64": "bar", + "65": "bar", + "66": "bar", + "67": "bar", + "68": "bar", + "69": "bar", + "70": "bar", + "71": "bar", + "72": "bar", + "73": "bar", + "74": "bar", + "75": "bar", + "76": "bar", + "77": "bar", + "78": "bar", + "79": "bar", + "80": "bar", + "81": "bar", + "82": "bar", + "83": "bar", + "84": "bar", + "85": "bar", + "86": "bar", + "87": "bar", + "88": "bar", + "89": "bar", + "90": "bar", + "91": "bar", + "92": "bar", + "93": "bar", + "94": "bar", + "95": "bar", + "96": "bar", + "97": "bar", + "98": "bar", + "99": "bar", + "100": "bar", + "101": "bar", + "102": "bar", + "103": "bar", + "104": "bar", + "105": "bar", + "106": "bar", + "107": "bar", + "108": "bar", + "109": "bar", + "110": "bar", + "111": "bar", + "112": "bar", + "113": "bar", + "114": "bar", + "115": "bar", + "116": "bar", + "117": "bar", + "118": "bar", + "119": "bar", + "120": "bar", + "121": "bar", + "122": "bar", + "123": "bar", + "124": "bar", + "125": "bar", + "126": "bar", + "127": "bar", + "128": "bar", + "129": "bar", + "130": "bar", + "131": "bar", + "132": "bar", + "133": "bar", + "134": "bar", + "135": "bar", + "136": "bar", + "137": "bar", + "138": "bar", + "139": "bar", + }, + "type": "custom", + "include_sample_schema": True, + }, + testing_criteria=[ + { + "input": [ + { + "content": "content", + "role": "role", + } + ], + "labels": ["string"], + "model": "model", + "name": "name", + "passing_labels": ["string"], + "type": "label_model", + } + ], + metadata={"foo": "string"}, + name="name", + share_with_openai=True, + ) + assert_matches_type(EvalCreateResponse, eval, path=["response"]) + + @parametrize + def test_raw_response_create(self, client: OpenAI) -> None: + response = client.evals.with_raw_response.create( + data_source_config={ + "item_schema": { + "0": "bar", + "1": "bar", + "2": "bar", + "3": "bar", + "4": "bar", + "5": "bar", + "6": "bar", + "7": "bar", + "8": "bar", + "9": "bar", + "10": "bar", + "11": "bar", + "12": "bar", + "13": "bar", + "14": "bar", + "15": "bar", + "16": "bar", + "17": "bar", + "18": "bar", + "19": "bar", + "20": "bar", + "21": "bar", + "22": "bar", + "23": "bar", + "24": "bar", + "25": "bar", + "26": "bar", + "27": "bar", + "28": "bar", + "29": "bar", + "30": "bar", + "31": "bar", + "32": "bar", + "33": "bar", + "34": "bar", + "35": "bar", + "36": "bar", + "37": "bar", + "38": "bar", + "39": "bar", + "40": "bar", + "41": "bar", + "42": "bar", + "43": "bar", + "44": "bar", + "45": "bar", + "46": "bar", + "47": "bar", + "48": "bar", + "49": "bar", + "50": "bar", + "51": "bar", + "52": "bar", + "53": "bar", + "54": "bar", + "55": "bar", + "56": "bar", + "57": "bar", + "58": "bar", + "59": "bar", + "60": "bar", + "61": "bar", + "62": "bar", + "63": "bar", + "64": "bar", + "65": "bar", + "66": "bar", + "67": "bar", + "68": "bar", + "69": "bar", + "70": "bar", + "71": "bar", + "72": "bar", + "73": "bar", + "74": "bar", + "75": "bar", + "76": "bar", + "77": "bar", + "78": "bar", + "79": "bar", + "80": "bar", + "81": "bar", + "82": "bar", + "83": "bar", + "84": "bar", + "85": "bar", + "86": "bar", + "87": "bar", + "88": "bar", + "89": "bar", + "90": "bar", + "91": "bar", + "92": "bar", + "93": "bar", + "94": "bar", + "95": "bar", + "96": "bar", + "97": "bar", + "98": "bar", + "99": "bar", + "100": "bar", + "101": "bar", + "102": "bar", + "103": "bar", + "104": "bar", + "105": "bar", + "106": "bar", + "107": "bar", + "108": "bar", + "109": "bar", + "110": "bar", + "111": "bar", + "112": "bar", + "113": "bar", + "114": "bar", + "115": "bar", + "116": "bar", + "117": "bar", + "118": "bar", + "119": "bar", + "120": "bar", + "121": "bar", + "122": "bar", + "123": "bar", + "124": "bar", + "125": "bar", + "126": "bar", + "127": "bar", + "128": "bar", + "129": "bar", + "130": "bar", + "131": "bar", + "132": "bar", + "133": "bar", + "134": "bar", + "135": "bar", + "136": "bar", + "137": "bar", + "138": "bar", + "139": "bar", + }, + "type": "custom", + }, + testing_criteria=[ + { + "input": [ + { + "content": "content", + "role": "role", + } + ], + "labels": ["string"], + "model": "model", + "name": "name", + "passing_labels": ["string"], + "type": "label_model", + } + ], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + eval = response.parse() + assert_matches_type(EvalCreateResponse, eval, path=["response"]) + + @parametrize + def test_streaming_response_create(self, client: OpenAI) -> None: + with client.evals.with_streaming_response.create( + data_source_config={ + "item_schema": { + "0": "bar", + "1": "bar", + "2": "bar", + "3": "bar", + "4": "bar", + "5": "bar", + "6": "bar", + "7": "bar", + "8": "bar", + "9": "bar", + "10": "bar", + "11": "bar", + "12": "bar", + "13": "bar", + "14": "bar", + "15": "bar", + "16": "bar", + "17": "bar", + "18": "bar", + "19": "bar", + "20": "bar", + "21": "bar", + "22": "bar", + "23": "bar", + "24": "bar", + "25": "bar", + "26": "bar", + "27": "bar", + "28": "bar", + "29": "bar", + "30": "bar", + "31": "bar", + "32": "bar", + "33": "bar", + "34": "bar", + "35": "bar", + "36": "bar", + "37": "bar", + "38": "bar", + "39": "bar", + "40": "bar", + "41": "bar", + "42": "bar", + "43": "bar", + "44": "bar", + "45": "bar", + "46": "bar", + "47": "bar", + "48": "bar", + "49": "bar", + "50": "bar", + "51": "bar", + "52": "bar", + "53": "bar", + "54": "bar", + "55": "bar", + "56": "bar", + "57": "bar", + "58": "bar", + "59": "bar", + "60": "bar", + "61": "bar", + "62": "bar", + "63": "bar", + "64": "bar", + "65": "bar", + "66": "bar", + "67": "bar", + "68": "bar", + "69": "bar", + "70": "bar", + "71": "bar", + "72": "bar", + "73": "bar", + "74": "bar", + "75": "bar", + "76": "bar", + "77": "bar", + "78": "bar", + "79": "bar", + "80": "bar", + "81": "bar", + "82": "bar", + "83": "bar", + "84": "bar", + "85": "bar", + "86": "bar", + "87": "bar", + "88": "bar", + "89": "bar", + "90": "bar", + "91": "bar", + "92": "bar", + "93": "bar", + "94": "bar", + "95": "bar", + "96": "bar", + "97": "bar", + "98": "bar", + "99": "bar", + "100": "bar", + "101": "bar", + "102": "bar", + "103": "bar", + "104": "bar", + "105": "bar", + "106": "bar", + "107": "bar", + "108": "bar", + "109": "bar", + "110": "bar", + "111": "bar", + "112": "bar", + "113": "bar", + "114": "bar", + "115": "bar", + "116": "bar", + "117": "bar", + "118": "bar", + "119": "bar", + "120": "bar", + "121": "bar", + "122": "bar", + "123": "bar", + "124": "bar", + "125": "bar", + "126": "bar", + "127": "bar", + "128": "bar", + "129": "bar", + "130": "bar", + "131": "bar", + "132": "bar", + "133": "bar", + "134": "bar", + "135": "bar", + "136": "bar", + "137": "bar", + "138": "bar", + "139": "bar", + }, + "type": "custom", + }, + testing_criteria=[ + { + "input": [ + { + "content": "content", + "role": "role", + } + ], + "labels": ["string"], + "model": "model", + "name": "name", + "passing_labels": ["string"], + "type": "label_model", + } + ], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + eval = response.parse() + assert_matches_type(EvalCreateResponse, eval, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_method_retrieve(self, client: OpenAI) -> None: + eval = client.evals.retrieve( + "eval_id", + ) + assert_matches_type(EvalRetrieveResponse, eval, path=["response"]) + + @parametrize + def test_raw_response_retrieve(self, client: OpenAI) -> None: + response = client.evals.with_raw_response.retrieve( + "eval_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + eval = response.parse() + assert_matches_type(EvalRetrieveResponse, eval, path=["response"]) + + @parametrize + def test_streaming_response_retrieve(self, client: OpenAI) -> None: + with client.evals.with_streaming_response.retrieve( + "eval_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + eval = response.parse() + assert_matches_type(EvalRetrieveResponse, eval, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_retrieve(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `eval_id` but received ''"): + client.evals.with_raw_response.retrieve( + "", + ) + + @parametrize + def test_method_update(self, client: OpenAI) -> None: + eval = client.evals.update( + eval_id="eval_id", + ) + assert_matches_type(EvalUpdateResponse, eval, path=["response"]) + + @parametrize + def test_method_update_with_all_params(self, client: OpenAI) -> None: + eval = client.evals.update( + eval_id="eval_id", + metadata={"foo": "string"}, + name="name", + ) + assert_matches_type(EvalUpdateResponse, eval, path=["response"]) + + @parametrize + def test_raw_response_update(self, client: OpenAI) -> None: + response = client.evals.with_raw_response.update( + eval_id="eval_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + eval = response.parse() + assert_matches_type(EvalUpdateResponse, eval, path=["response"]) + + @parametrize + def test_streaming_response_update(self, client: OpenAI) -> None: + with client.evals.with_streaming_response.update( + eval_id="eval_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + eval = response.parse() + assert_matches_type(EvalUpdateResponse, eval, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_update(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `eval_id` but received ''"): + client.evals.with_raw_response.update( + eval_id="", + ) + + @parametrize + def test_method_list(self, client: OpenAI) -> None: + eval = client.evals.list() + assert_matches_type(SyncCursorPage[EvalListResponse], eval, path=["response"]) + + @parametrize + def test_method_list_with_all_params(self, client: OpenAI) -> None: + eval = client.evals.list( + after="after", + limit=0, + order="asc", + order_by="created_at", + ) + assert_matches_type(SyncCursorPage[EvalListResponse], eval, path=["response"]) + + @parametrize + def test_raw_response_list(self, client: OpenAI) -> None: + response = client.evals.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + eval = response.parse() + assert_matches_type(SyncCursorPage[EvalListResponse], eval, path=["response"]) + + @parametrize + def test_streaming_response_list(self, client: OpenAI) -> None: + with client.evals.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + eval = response.parse() + assert_matches_type(SyncCursorPage[EvalListResponse], eval, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_method_delete(self, client: OpenAI) -> None: + eval = client.evals.delete( + "eval_id", + ) + assert_matches_type(EvalDeleteResponse, eval, path=["response"]) + + @parametrize + def test_raw_response_delete(self, client: OpenAI) -> None: + response = client.evals.with_raw_response.delete( + "eval_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + eval = response.parse() + assert_matches_type(EvalDeleteResponse, eval, path=["response"]) + + @parametrize + def test_streaming_response_delete(self, client: OpenAI) -> None: + with client.evals.with_streaming_response.delete( + "eval_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + eval = response.parse() + assert_matches_type(EvalDeleteResponse, eval, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_delete(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `eval_id` but received ''"): + client.evals.with_raw_response.delete( + "", + ) + + +class TestAsyncEvals: + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + async def test_method_create(self, async_client: AsyncOpenAI) -> None: + eval = await async_client.evals.create( + data_source_config={ + "item_schema": { + "0": "bar", + "1": "bar", + "2": "bar", + "3": "bar", + "4": "bar", + "5": "bar", + "6": "bar", + "7": "bar", + "8": "bar", + "9": "bar", + "10": "bar", + "11": "bar", + "12": "bar", + "13": "bar", + "14": "bar", + "15": "bar", + "16": "bar", + "17": "bar", + "18": "bar", + "19": "bar", + "20": "bar", + "21": "bar", + "22": "bar", + "23": "bar", + "24": "bar", + "25": "bar", + "26": "bar", + "27": "bar", + "28": "bar", + "29": "bar", + "30": "bar", + "31": "bar", + "32": "bar", + "33": "bar", + "34": "bar", + "35": "bar", + "36": "bar", + "37": "bar", + "38": "bar", + "39": "bar", + "40": "bar", + "41": "bar", + "42": "bar", + "43": "bar", + "44": "bar", + "45": "bar", + "46": "bar", + "47": "bar", + "48": "bar", + "49": "bar", + "50": "bar", + "51": "bar", + "52": "bar", + "53": "bar", + "54": "bar", + "55": "bar", + "56": "bar", + "57": "bar", + "58": "bar", + "59": "bar", + "60": "bar", + "61": "bar", + "62": "bar", + "63": "bar", + "64": "bar", + "65": "bar", + "66": "bar", + "67": "bar", + "68": "bar", + "69": "bar", + "70": "bar", + "71": "bar", + "72": "bar", + "73": "bar", + "74": "bar", + "75": "bar", + "76": "bar", + "77": "bar", + "78": "bar", + "79": "bar", + "80": "bar", + "81": "bar", + "82": "bar", + "83": "bar", + "84": "bar", + "85": "bar", + "86": "bar", + "87": "bar", + "88": "bar", + "89": "bar", + "90": "bar", + "91": "bar", + "92": "bar", + "93": "bar", + "94": "bar", + "95": "bar", + "96": "bar", + "97": "bar", + "98": "bar", + "99": "bar", + "100": "bar", + "101": "bar", + "102": "bar", + "103": "bar", + "104": "bar", + "105": "bar", + "106": "bar", + "107": "bar", + "108": "bar", + "109": "bar", + "110": "bar", + "111": "bar", + "112": "bar", + "113": "bar", + "114": "bar", + "115": "bar", + "116": "bar", + "117": "bar", + "118": "bar", + "119": "bar", + "120": "bar", + "121": "bar", + "122": "bar", + "123": "bar", + "124": "bar", + "125": "bar", + "126": "bar", + "127": "bar", + "128": "bar", + "129": "bar", + "130": "bar", + "131": "bar", + "132": "bar", + "133": "bar", + "134": "bar", + "135": "bar", + "136": "bar", + "137": "bar", + "138": "bar", + "139": "bar", + }, + "type": "custom", + }, + testing_criteria=[ + { + "input": [ + { + "content": "content", + "role": "role", + } + ], + "labels": ["string"], + "model": "model", + "name": "name", + "passing_labels": ["string"], + "type": "label_model", + } + ], + ) + assert_matches_type(EvalCreateResponse, eval, path=["response"]) + + @parametrize + async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: + eval = await async_client.evals.create( + data_source_config={ + "item_schema": { + "0": "bar", + "1": "bar", + "2": "bar", + "3": "bar", + "4": "bar", + "5": "bar", + "6": "bar", + "7": "bar", + "8": "bar", + "9": "bar", + "10": "bar", + "11": "bar", + "12": "bar", + "13": "bar", + "14": "bar", + "15": "bar", + "16": "bar", + "17": "bar", + "18": "bar", + "19": "bar", + "20": "bar", + "21": "bar", + "22": "bar", + "23": "bar", + "24": "bar", + "25": "bar", + "26": "bar", + "27": "bar", + "28": "bar", + "29": "bar", + "30": "bar", + "31": "bar", + "32": "bar", + "33": "bar", + "34": "bar", + "35": "bar", + "36": "bar", + "37": "bar", + "38": "bar", + "39": "bar", + "40": "bar", + "41": "bar", + "42": "bar", + "43": "bar", + "44": "bar", + "45": "bar", + "46": "bar", + "47": "bar", + "48": "bar", + "49": "bar", + "50": "bar", + "51": "bar", + "52": "bar", + "53": "bar", + "54": "bar", + "55": "bar", + "56": "bar", + "57": "bar", + "58": "bar", + "59": "bar", + "60": "bar", + "61": "bar", + "62": "bar", + "63": "bar", + "64": "bar", + "65": "bar", + "66": "bar", + "67": "bar", + "68": "bar", + "69": "bar", + "70": "bar", + "71": "bar", + "72": "bar", + "73": "bar", + "74": "bar", + "75": "bar", + "76": "bar", + "77": "bar", + "78": "bar", + "79": "bar", + "80": "bar", + "81": "bar", + "82": "bar", + "83": "bar", + "84": "bar", + "85": "bar", + "86": "bar", + "87": "bar", + "88": "bar", + "89": "bar", + "90": "bar", + "91": "bar", + "92": "bar", + "93": "bar", + "94": "bar", + "95": "bar", + "96": "bar", + "97": "bar", + "98": "bar", + "99": "bar", + "100": "bar", + "101": "bar", + "102": "bar", + "103": "bar", + "104": "bar", + "105": "bar", + "106": "bar", + "107": "bar", + "108": "bar", + "109": "bar", + "110": "bar", + "111": "bar", + "112": "bar", + "113": "bar", + "114": "bar", + "115": "bar", + "116": "bar", + "117": "bar", + "118": "bar", + "119": "bar", + "120": "bar", + "121": "bar", + "122": "bar", + "123": "bar", + "124": "bar", + "125": "bar", + "126": "bar", + "127": "bar", + "128": "bar", + "129": "bar", + "130": "bar", + "131": "bar", + "132": "bar", + "133": "bar", + "134": "bar", + "135": "bar", + "136": "bar", + "137": "bar", + "138": "bar", + "139": "bar", + }, + "type": "custom", + "include_sample_schema": True, + }, + testing_criteria=[ + { + "input": [ + { + "content": "content", + "role": "role", + } + ], + "labels": ["string"], + "model": "model", + "name": "name", + "passing_labels": ["string"], + "type": "label_model", + } + ], + metadata={"foo": "string"}, + name="name", + share_with_openai=True, + ) + assert_matches_type(EvalCreateResponse, eval, path=["response"]) + + @parametrize + async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: + response = await async_client.evals.with_raw_response.create( + data_source_config={ + "item_schema": { + "0": "bar", + "1": "bar", + "2": "bar", + "3": "bar", + "4": "bar", + "5": "bar", + "6": "bar", + "7": "bar", + "8": "bar", + "9": "bar", + "10": "bar", + "11": "bar", + "12": "bar", + "13": "bar", + "14": "bar", + "15": "bar", + "16": "bar", + "17": "bar", + "18": "bar", + "19": "bar", + "20": "bar", + "21": "bar", + "22": "bar", + "23": "bar", + "24": "bar", + "25": "bar", + "26": "bar", + "27": "bar", + "28": "bar", + "29": "bar", + "30": "bar", + "31": "bar", + "32": "bar", + "33": "bar", + "34": "bar", + "35": "bar", + "36": "bar", + "37": "bar", + "38": "bar", + "39": "bar", + "40": "bar", + "41": "bar", + "42": "bar", + "43": "bar", + "44": "bar", + "45": "bar", + "46": "bar", + "47": "bar", + "48": "bar", + "49": "bar", + "50": "bar", + "51": "bar", + "52": "bar", + "53": "bar", + "54": "bar", + "55": "bar", + "56": "bar", + "57": "bar", + "58": "bar", + "59": "bar", + "60": "bar", + "61": "bar", + "62": "bar", + "63": "bar", + "64": "bar", + "65": "bar", + "66": "bar", + "67": "bar", + "68": "bar", + "69": "bar", + "70": "bar", + "71": "bar", + "72": "bar", + "73": "bar", + "74": "bar", + "75": "bar", + "76": "bar", + "77": "bar", + "78": "bar", + "79": "bar", + "80": "bar", + "81": "bar", + "82": "bar", + "83": "bar", + "84": "bar", + "85": "bar", + "86": "bar", + "87": "bar", + "88": "bar", + "89": "bar", + "90": "bar", + "91": "bar", + "92": "bar", + "93": "bar", + "94": "bar", + "95": "bar", + "96": "bar", + "97": "bar", + "98": "bar", + "99": "bar", + "100": "bar", + "101": "bar", + "102": "bar", + "103": "bar", + "104": "bar", + "105": "bar", + "106": "bar", + "107": "bar", + "108": "bar", + "109": "bar", + "110": "bar", + "111": "bar", + "112": "bar", + "113": "bar", + "114": "bar", + "115": "bar", + "116": "bar", + "117": "bar", + "118": "bar", + "119": "bar", + "120": "bar", + "121": "bar", + "122": "bar", + "123": "bar", + "124": "bar", + "125": "bar", + "126": "bar", + "127": "bar", + "128": "bar", + "129": "bar", + "130": "bar", + "131": "bar", + "132": "bar", + "133": "bar", + "134": "bar", + "135": "bar", + "136": "bar", + "137": "bar", + "138": "bar", + "139": "bar", + }, + "type": "custom", + }, + testing_criteria=[ + { + "input": [ + { + "content": "content", + "role": "role", + } + ], + "labels": ["string"], + "model": "model", + "name": "name", + "passing_labels": ["string"], + "type": "label_model", + } + ], + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + eval = response.parse() + assert_matches_type(EvalCreateResponse, eval, path=["response"]) + + @parametrize + async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: + async with async_client.evals.with_streaming_response.create( + data_source_config={ + "item_schema": { + "0": "bar", + "1": "bar", + "2": "bar", + "3": "bar", + "4": "bar", + "5": "bar", + "6": "bar", + "7": "bar", + "8": "bar", + "9": "bar", + "10": "bar", + "11": "bar", + "12": "bar", + "13": "bar", + "14": "bar", + "15": "bar", + "16": "bar", + "17": "bar", + "18": "bar", + "19": "bar", + "20": "bar", + "21": "bar", + "22": "bar", + "23": "bar", + "24": "bar", + "25": "bar", + "26": "bar", + "27": "bar", + "28": "bar", + "29": "bar", + "30": "bar", + "31": "bar", + "32": "bar", + "33": "bar", + "34": "bar", + "35": "bar", + "36": "bar", + "37": "bar", + "38": "bar", + "39": "bar", + "40": "bar", + "41": "bar", + "42": "bar", + "43": "bar", + "44": "bar", + "45": "bar", + "46": "bar", + "47": "bar", + "48": "bar", + "49": "bar", + "50": "bar", + "51": "bar", + "52": "bar", + "53": "bar", + "54": "bar", + "55": "bar", + "56": "bar", + "57": "bar", + "58": "bar", + "59": "bar", + "60": "bar", + "61": "bar", + "62": "bar", + "63": "bar", + "64": "bar", + "65": "bar", + "66": "bar", + "67": "bar", + "68": "bar", + "69": "bar", + "70": "bar", + "71": "bar", + "72": "bar", + "73": "bar", + "74": "bar", + "75": "bar", + "76": "bar", + "77": "bar", + "78": "bar", + "79": "bar", + "80": "bar", + "81": "bar", + "82": "bar", + "83": "bar", + "84": "bar", + "85": "bar", + "86": "bar", + "87": "bar", + "88": "bar", + "89": "bar", + "90": "bar", + "91": "bar", + "92": "bar", + "93": "bar", + "94": "bar", + "95": "bar", + "96": "bar", + "97": "bar", + "98": "bar", + "99": "bar", + "100": "bar", + "101": "bar", + "102": "bar", + "103": "bar", + "104": "bar", + "105": "bar", + "106": "bar", + "107": "bar", + "108": "bar", + "109": "bar", + "110": "bar", + "111": "bar", + "112": "bar", + "113": "bar", + "114": "bar", + "115": "bar", + "116": "bar", + "117": "bar", + "118": "bar", + "119": "bar", + "120": "bar", + "121": "bar", + "122": "bar", + "123": "bar", + "124": "bar", + "125": "bar", + "126": "bar", + "127": "bar", + "128": "bar", + "129": "bar", + "130": "bar", + "131": "bar", + "132": "bar", + "133": "bar", + "134": "bar", + "135": "bar", + "136": "bar", + "137": "bar", + "138": "bar", + "139": "bar", + }, + "type": "custom", + }, + testing_criteria=[ + { + "input": [ + { + "content": "content", + "role": "role", + } + ], + "labels": ["string"], + "model": "model", + "name": "name", + "passing_labels": ["string"], + "type": "label_model", + } + ], + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + eval = await response.parse() + assert_matches_type(EvalCreateResponse, eval, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None: + eval = await async_client.evals.retrieve( + "eval_id", + ) + assert_matches_type(EvalRetrieveResponse, eval, path=["response"]) + + @parametrize + async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None: + response = await async_client.evals.with_raw_response.retrieve( + "eval_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + eval = response.parse() + assert_matches_type(EvalRetrieveResponse, eval, path=["response"]) + + @parametrize + async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None: + async with async_client.evals.with_streaming_response.retrieve( + "eval_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + eval = await response.parse() + assert_matches_type(EvalRetrieveResponse, eval, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `eval_id` but received ''"): + await async_client.evals.with_raw_response.retrieve( + "", + ) + + @parametrize + async def test_method_update(self, async_client: AsyncOpenAI) -> None: + eval = await async_client.evals.update( + eval_id="eval_id", + ) + assert_matches_type(EvalUpdateResponse, eval, path=["response"]) + + @parametrize + async def test_method_update_with_all_params(self, async_client: AsyncOpenAI) -> None: + eval = await async_client.evals.update( + eval_id="eval_id", + metadata={"foo": "string"}, + name="name", + ) + assert_matches_type(EvalUpdateResponse, eval, path=["response"]) + + @parametrize + async def test_raw_response_update(self, async_client: AsyncOpenAI) -> None: + response = await async_client.evals.with_raw_response.update( + eval_id="eval_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + eval = response.parse() + assert_matches_type(EvalUpdateResponse, eval, path=["response"]) + + @parametrize + async def test_streaming_response_update(self, async_client: AsyncOpenAI) -> None: + async with async_client.evals.with_streaming_response.update( + eval_id="eval_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + eval = await response.parse() + assert_matches_type(EvalUpdateResponse, eval, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_update(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `eval_id` but received ''"): + await async_client.evals.with_raw_response.update( + eval_id="", + ) + + @parametrize + async def test_method_list(self, async_client: AsyncOpenAI) -> None: + eval = await async_client.evals.list() + assert_matches_type(AsyncCursorPage[EvalListResponse], eval, path=["response"]) + + @parametrize + async def test_method_list_with_all_params(self, async_client: AsyncOpenAI) -> None: + eval = await async_client.evals.list( + after="after", + limit=0, + order="asc", + order_by="created_at", + ) + assert_matches_type(AsyncCursorPage[EvalListResponse], eval, path=["response"]) + + @parametrize + async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None: + response = await async_client.evals.with_raw_response.list() + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + eval = response.parse() + assert_matches_type(AsyncCursorPage[EvalListResponse], eval, path=["response"]) + + @parametrize + async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None: + async with async_client.evals.with_streaming_response.list() as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + eval = await response.parse() + assert_matches_type(AsyncCursorPage[EvalListResponse], eval, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_method_delete(self, async_client: AsyncOpenAI) -> None: + eval = await async_client.evals.delete( + "eval_id", + ) + assert_matches_type(EvalDeleteResponse, eval, path=["response"]) + + @parametrize + async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None: + response = await async_client.evals.with_raw_response.delete( + "eval_id", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + eval = response.parse() + assert_matches_type(EvalDeleteResponse, eval, path=["response"]) + + @parametrize + async def test_streaming_response_delete(self, async_client: AsyncOpenAI) -> None: + async with async_client.evals.with_streaming_response.delete( + "eval_id", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + eval = await response.parse() + assert_matches_type(EvalDeleteResponse, eval, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_delete(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `eval_id` but received ''"): + await async_client.evals.with_raw_response.delete( + "", + ) From 58163842137c006c37e833c7d08e02dc7415a59b Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 8 Apr 2025 19:44:37 +0000 Subject: [PATCH 766/816] chore(internal): fix examples (#2288) --- .stats.yml | 4 +- tests/api_resources/beta/test_threads.py | 8 +- tests/api_resources/beta/threads/test_runs.py | 8 +- tests/api_resources/test_evals.py | 1144 +---------------- tests/api_resources/test_images.py | 12 +- tests/api_resources/test_moderations.py | 4 +- 6 files changed, 26 insertions(+), 1154 deletions(-) diff --git a/.stats.yml b/.stats.yml index ebe07c1372..4a82ee242d 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 97 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-472fe3036ea745365257fe870c0330917fb3153705c2826f49873cd631319b0a.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-32de3bc513663c5fac922c49be41c222b6ee8c0b841d8966bcdfa489d441daa3.yml openapi_spec_hash: ea86343b5e9858a74e85da8ab2c532f6 -config_hash: ef19d36c307306f14f2e1cd5c834a151 +config_hash: d6c61213488683418adb860a9ee1501b diff --git a/tests/api_resources/beta/test_threads.py b/tests/api_resources/beta/test_threads.py index ecf5b11102..9916d5bdc6 100644 --- a/tests/api_resources/beta/test_threads.py +++ b/tests/api_resources/beta/test_threads.py @@ -220,7 +220,7 @@ def test_method_create_and_run_with_all_params_overload_1(self, client: OpenAI) max_completion_tokens=256, max_prompt_tokens=256, metadata={"foo": "string"}, - model="gpt-4o", + model="string", parallel_tool_calls=True, response_format="auto", stream=False, @@ -309,7 +309,7 @@ def test_method_create_and_run_with_all_params_overload_2(self, client: OpenAI) max_completion_tokens=256, max_prompt_tokens=256, metadata={"foo": "string"}, - model="gpt-4o", + model="string", parallel_tool_calls=True, response_format="auto", temperature=1, @@ -584,7 +584,7 @@ async def test_method_create_and_run_with_all_params_overload_1(self, async_clie max_completion_tokens=256, max_prompt_tokens=256, metadata={"foo": "string"}, - model="gpt-4o", + model="string", parallel_tool_calls=True, response_format="auto", stream=False, @@ -673,7 +673,7 @@ async def test_method_create_and_run_with_all_params_overload_2(self, async_clie max_completion_tokens=256, max_prompt_tokens=256, metadata={"foo": "string"}, - model="gpt-4o", + model="string", parallel_tool_calls=True, response_format="auto", temperature=1, diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index d05ee96144..4230ccebe4 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -54,7 +54,7 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: max_completion_tokens=256, max_prompt_tokens=256, metadata={"foo": "string"}, - model="gpt-4o", + model="string", parallel_tool_calls=True, reasoning_effort="low", response_format="auto", @@ -138,7 +138,7 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: max_completion_tokens=256, max_prompt_tokens=256, metadata={"foo": "string"}, - model="gpt-4o", + model="string", parallel_tool_calls=True, reasoning_effort="low", response_format="auto", @@ -552,7 +552,7 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn max_completion_tokens=256, max_prompt_tokens=256, metadata={"foo": "string"}, - model="gpt-4o", + model="string", parallel_tool_calls=True, reasoning_effort="low", response_format="auto", @@ -636,7 +636,7 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn max_completion_tokens=256, max_prompt_tokens=256, metadata={"foo": "string"}, - model="gpt-4o", + model="string", parallel_tool_calls=True, reasoning_effort="low", response_format="auto", diff --git a/tests/api_resources/test_evals.py b/tests/api_resources/test_evals.py index 33ba92cda5..8d03513b32 100644 --- a/tests/api_resources/test_evals.py +++ b/tests/api_resources/test_evals.py @@ -28,148 +28,7 @@ class TestEvals: def test_method_create(self, client: OpenAI) -> None: eval = client.evals.create( data_source_config={ - "item_schema": { - "0": "bar", - "1": "bar", - "2": "bar", - "3": "bar", - "4": "bar", - "5": "bar", - "6": "bar", - "7": "bar", - "8": "bar", - "9": "bar", - "10": "bar", - "11": "bar", - "12": "bar", - "13": "bar", - "14": "bar", - "15": "bar", - "16": "bar", - "17": "bar", - "18": "bar", - "19": "bar", - "20": "bar", - "21": "bar", - "22": "bar", - "23": "bar", - "24": "bar", - "25": "bar", - "26": "bar", - "27": "bar", - "28": "bar", - "29": "bar", - "30": "bar", - "31": "bar", - "32": "bar", - "33": "bar", - "34": "bar", - "35": "bar", - "36": "bar", - "37": "bar", - "38": "bar", - "39": "bar", - "40": "bar", - "41": "bar", - "42": "bar", - "43": "bar", - "44": "bar", - "45": "bar", - "46": "bar", - "47": "bar", - "48": "bar", - "49": "bar", - "50": "bar", - "51": "bar", - "52": "bar", - "53": "bar", - "54": "bar", - "55": "bar", - "56": "bar", - "57": "bar", - "58": "bar", - "59": "bar", - "60": "bar", - "61": "bar", - "62": "bar", - "63": "bar", - "64": "bar", - "65": "bar", - "66": "bar", - "67": "bar", - "68": "bar", - "69": "bar", - "70": "bar", - "71": "bar", - "72": "bar", - "73": "bar", - "74": "bar", - "75": "bar", - "76": "bar", - "77": "bar", - "78": "bar", - "79": "bar", - "80": "bar", - "81": "bar", - "82": "bar", - "83": "bar", - "84": "bar", - "85": "bar", - "86": "bar", - "87": "bar", - "88": "bar", - "89": "bar", - "90": "bar", - "91": "bar", - "92": "bar", - "93": "bar", - "94": "bar", - "95": "bar", - "96": "bar", - "97": "bar", - "98": "bar", - "99": "bar", - "100": "bar", - "101": "bar", - "102": "bar", - "103": "bar", - "104": "bar", - "105": "bar", - "106": "bar", - "107": "bar", - "108": "bar", - "109": "bar", - "110": "bar", - "111": "bar", - "112": "bar", - "113": "bar", - "114": "bar", - "115": "bar", - "116": "bar", - "117": "bar", - "118": "bar", - "119": "bar", - "120": "bar", - "121": "bar", - "122": "bar", - "123": "bar", - "124": "bar", - "125": "bar", - "126": "bar", - "127": "bar", - "128": "bar", - "129": "bar", - "130": "bar", - "131": "bar", - "132": "bar", - "133": "bar", - "134": "bar", - "135": "bar", - "136": "bar", - "137": "bar", - "138": "bar", - "139": "bar", - }, + "item_schema": {"foo": "bar"}, "type": "custom", }, testing_criteria=[ @@ -194,148 +53,7 @@ def test_method_create(self, client: OpenAI) -> None: def test_method_create_with_all_params(self, client: OpenAI) -> None: eval = client.evals.create( data_source_config={ - "item_schema": { - "0": "bar", - "1": "bar", - "2": "bar", - "3": "bar", - "4": "bar", - "5": "bar", - "6": "bar", - "7": "bar", - "8": "bar", - "9": "bar", - "10": "bar", - "11": "bar", - "12": "bar", - "13": "bar", - "14": "bar", - "15": "bar", - "16": "bar", - "17": "bar", - "18": "bar", - "19": "bar", - "20": "bar", - "21": "bar", - "22": "bar", - "23": "bar", - "24": "bar", - "25": "bar", - "26": "bar", - "27": "bar", - "28": "bar", - "29": "bar", - "30": "bar", - "31": "bar", - "32": "bar", - "33": "bar", - "34": "bar", - "35": "bar", - "36": "bar", - "37": "bar", - "38": "bar", - "39": "bar", - "40": "bar", - "41": "bar", - "42": "bar", - "43": "bar", - "44": "bar", - "45": "bar", - "46": "bar", - "47": "bar", - "48": "bar", - "49": "bar", - "50": "bar", - "51": "bar", - "52": "bar", - "53": "bar", - "54": "bar", - "55": "bar", - "56": "bar", - "57": "bar", - "58": "bar", - "59": "bar", - "60": "bar", - "61": "bar", - "62": "bar", - "63": "bar", - "64": "bar", - "65": "bar", - "66": "bar", - "67": "bar", - "68": "bar", - "69": "bar", - "70": "bar", - "71": "bar", - "72": "bar", - "73": "bar", - "74": "bar", - "75": "bar", - "76": "bar", - "77": "bar", - "78": "bar", - "79": "bar", - "80": "bar", - "81": "bar", - "82": "bar", - "83": "bar", - "84": "bar", - "85": "bar", - "86": "bar", - "87": "bar", - "88": "bar", - "89": "bar", - "90": "bar", - "91": "bar", - "92": "bar", - "93": "bar", - "94": "bar", - "95": "bar", - "96": "bar", - "97": "bar", - "98": "bar", - "99": "bar", - "100": "bar", - "101": "bar", - "102": "bar", - "103": "bar", - "104": "bar", - "105": "bar", - "106": "bar", - "107": "bar", - "108": "bar", - "109": "bar", - "110": "bar", - "111": "bar", - "112": "bar", - "113": "bar", - "114": "bar", - "115": "bar", - "116": "bar", - "117": "bar", - "118": "bar", - "119": "bar", - "120": "bar", - "121": "bar", - "122": "bar", - "123": "bar", - "124": "bar", - "125": "bar", - "126": "bar", - "127": "bar", - "128": "bar", - "129": "bar", - "130": "bar", - "131": "bar", - "132": "bar", - "133": "bar", - "134": "bar", - "135": "bar", - "136": "bar", - "137": "bar", - "138": "bar", - "139": "bar", - }, + "item_schema": {"foo": "bar"}, "type": "custom", "include_sample_schema": True, }, @@ -364,148 +82,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: def test_raw_response_create(self, client: OpenAI) -> None: response = client.evals.with_raw_response.create( data_source_config={ - "item_schema": { - "0": "bar", - "1": "bar", - "2": "bar", - "3": "bar", - "4": "bar", - "5": "bar", - "6": "bar", - "7": "bar", - "8": "bar", - "9": "bar", - "10": "bar", - "11": "bar", - "12": "bar", - "13": "bar", - "14": "bar", - "15": "bar", - "16": "bar", - "17": "bar", - "18": "bar", - "19": "bar", - "20": "bar", - "21": "bar", - "22": "bar", - "23": "bar", - "24": "bar", - "25": "bar", - "26": "bar", - "27": "bar", - "28": "bar", - "29": "bar", - "30": "bar", - "31": "bar", - "32": "bar", - "33": "bar", - "34": "bar", - "35": "bar", - "36": "bar", - "37": "bar", - "38": "bar", - "39": "bar", - "40": "bar", - "41": "bar", - "42": "bar", - "43": "bar", - "44": "bar", - "45": "bar", - "46": "bar", - "47": "bar", - "48": "bar", - "49": "bar", - "50": "bar", - "51": "bar", - "52": "bar", - "53": "bar", - "54": "bar", - "55": "bar", - "56": "bar", - "57": "bar", - "58": "bar", - "59": "bar", - "60": "bar", - "61": "bar", - "62": "bar", - "63": "bar", - "64": "bar", - "65": "bar", - "66": "bar", - "67": "bar", - "68": "bar", - "69": "bar", - "70": "bar", - "71": "bar", - "72": "bar", - "73": "bar", - "74": "bar", - "75": "bar", - "76": "bar", - "77": "bar", - "78": "bar", - "79": "bar", - "80": "bar", - "81": "bar", - "82": "bar", - "83": "bar", - "84": "bar", - "85": "bar", - "86": "bar", - "87": "bar", - "88": "bar", - "89": "bar", - "90": "bar", - "91": "bar", - "92": "bar", - "93": "bar", - "94": "bar", - "95": "bar", - "96": "bar", - "97": "bar", - "98": "bar", - "99": "bar", - "100": "bar", - "101": "bar", - "102": "bar", - "103": "bar", - "104": "bar", - "105": "bar", - "106": "bar", - "107": "bar", - "108": "bar", - "109": "bar", - "110": "bar", - "111": "bar", - "112": "bar", - "113": "bar", - "114": "bar", - "115": "bar", - "116": "bar", - "117": "bar", - "118": "bar", - "119": "bar", - "120": "bar", - "121": "bar", - "122": "bar", - "123": "bar", - "124": "bar", - "125": "bar", - "126": "bar", - "127": "bar", - "128": "bar", - "129": "bar", - "130": "bar", - "131": "bar", - "132": "bar", - "133": "bar", - "134": "bar", - "135": "bar", - "136": "bar", - "137": "bar", - "138": "bar", - "139": "bar", - }, + "item_schema": {"foo": "bar"}, "type": "custom", }, testing_criteria=[ @@ -534,148 +111,7 @@ def test_raw_response_create(self, client: OpenAI) -> None: def test_streaming_response_create(self, client: OpenAI) -> None: with client.evals.with_streaming_response.create( data_source_config={ - "item_schema": { - "0": "bar", - "1": "bar", - "2": "bar", - "3": "bar", - "4": "bar", - "5": "bar", - "6": "bar", - "7": "bar", - "8": "bar", - "9": "bar", - "10": "bar", - "11": "bar", - "12": "bar", - "13": "bar", - "14": "bar", - "15": "bar", - "16": "bar", - "17": "bar", - "18": "bar", - "19": "bar", - "20": "bar", - "21": "bar", - "22": "bar", - "23": "bar", - "24": "bar", - "25": "bar", - "26": "bar", - "27": "bar", - "28": "bar", - "29": "bar", - "30": "bar", - "31": "bar", - "32": "bar", - "33": "bar", - "34": "bar", - "35": "bar", - "36": "bar", - "37": "bar", - "38": "bar", - "39": "bar", - "40": "bar", - "41": "bar", - "42": "bar", - "43": "bar", - "44": "bar", - "45": "bar", - "46": "bar", - "47": "bar", - "48": "bar", - "49": "bar", - "50": "bar", - "51": "bar", - "52": "bar", - "53": "bar", - "54": "bar", - "55": "bar", - "56": "bar", - "57": "bar", - "58": "bar", - "59": "bar", - "60": "bar", - "61": "bar", - "62": "bar", - "63": "bar", - "64": "bar", - "65": "bar", - "66": "bar", - "67": "bar", - "68": "bar", - "69": "bar", - "70": "bar", - "71": "bar", - "72": "bar", - "73": "bar", - "74": "bar", - "75": "bar", - "76": "bar", - "77": "bar", - "78": "bar", - "79": "bar", - "80": "bar", - "81": "bar", - "82": "bar", - "83": "bar", - "84": "bar", - "85": "bar", - "86": "bar", - "87": "bar", - "88": "bar", - "89": "bar", - "90": "bar", - "91": "bar", - "92": "bar", - "93": "bar", - "94": "bar", - "95": "bar", - "96": "bar", - "97": "bar", - "98": "bar", - "99": "bar", - "100": "bar", - "101": "bar", - "102": "bar", - "103": "bar", - "104": "bar", - "105": "bar", - "106": "bar", - "107": "bar", - "108": "bar", - "109": "bar", - "110": "bar", - "111": "bar", - "112": "bar", - "113": "bar", - "114": "bar", - "115": "bar", - "116": "bar", - "117": "bar", - "118": "bar", - "119": "bar", - "120": "bar", - "121": "bar", - "122": "bar", - "123": "bar", - "124": "bar", - "125": "bar", - "126": "bar", - "127": "bar", - "128": "bar", - "129": "bar", - "130": "bar", - "131": "bar", - "132": "bar", - "133": "bar", - "134": "bar", - "135": "bar", - "136": "bar", - "137": "bar", - "138": "bar", - "139": "bar", - }, + "item_schema": {"foo": "bar"}, "type": "custom", }, testing_criteria=[ @@ -868,148 +304,7 @@ class TestAsyncEvals: async def test_method_create(self, async_client: AsyncOpenAI) -> None: eval = await async_client.evals.create( data_source_config={ - "item_schema": { - "0": "bar", - "1": "bar", - "2": "bar", - "3": "bar", - "4": "bar", - "5": "bar", - "6": "bar", - "7": "bar", - "8": "bar", - "9": "bar", - "10": "bar", - "11": "bar", - "12": "bar", - "13": "bar", - "14": "bar", - "15": "bar", - "16": "bar", - "17": "bar", - "18": "bar", - "19": "bar", - "20": "bar", - "21": "bar", - "22": "bar", - "23": "bar", - "24": "bar", - "25": "bar", - "26": "bar", - "27": "bar", - "28": "bar", - "29": "bar", - "30": "bar", - "31": "bar", - "32": "bar", - "33": "bar", - "34": "bar", - "35": "bar", - "36": "bar", - "37": "bar", - "38": "bar", - "39": "bar", - "40": "bar", - "41": "bar", - "42": "bar", - "43": "bar", - "44": "bar", - "45": "bar", - "46": "bar", - "47": "bar", - "48": "bar", - "49": "bar", - "50": "bar", - "51": "bar", - "52": "bar", - "53": "bar", - "54": "bar", - "55": "bar", - "56": "bar", - "57": "bar", - "58": "bar", - "59": "bar", - "60": "bar", - "61": "bar", - "62": "bar", - "63": "bar", - "64": "bar", - "65": "bar", - "66": "bar", - "67": "bar", - "68": "bar", - "69": "bar", - "70": "bar", - "71": "bar", - "72": "bar", - "73": "bar", - "74": "bar", - "75": "bar", - "76": "bar", - "77": "bar", - "78": "bar", - "79": "bar", - "80": "bar", - "81": "bar", - "82": "bar", - "83": "bar", - "84": "bar", - "85": "bar", - "86": "bar", - "87": "bar", - "88": "bar", - "89": "bar", - "90": "bar", - "91": "bar", - "92": "bar", - "93": "bar", - "94": "bar", - "95": "bar", - "96": "bar", - "97": "bar", - "98": "bar", - "99": "bar", - "100": "bar", - "101": "bar", - "102": "bar", - "103": "bar", - "104": "bar", - "105": "bar", - "106": "bar", - "107": "bar", - "108": "bar", - "109": "bar", - "110": "bar", - "111": "bar", - "112": "bar", - "113": "bar", - "114": "bar", - "115": "bar", - "116": "bar", - "117": "bar", - "118": "bar", - "119": "bar", - "120": "bar", - "121": "bar", - "122": "bar", - "123": "bar", - "124": "bar", - "125": "bar", - "126": "bar", - "127": "bar", - "128": "bar", - "129": "bar", - "130": "bar", - "131": "bar", - "132": "bar", - "133": "bar", - "134": "bar", - "135": "bar", - "136": "bar", - "137": "bar", - "138": "bar", - "139": "bar", - }, + "item_schema": {"foo": "bar"}, "type": "custom", }, testing_criteria=[ @@ -1034,148 +329,7 @@ async def test_method_create(self, async_client: AsyncOpenAI) -> None: async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: eval = await async_client.evals.create( data_source_config={ - "item_schema": { - "0": "bar", - "1": "bar", - "2": "bar", - "3": "bar", - "4": "bar", - "5": "bar", - "6": "bar", - "7": "bar", - "8": "bar", - "9": "bar", - "10": "bar", - "11": "bar", - "12": "bar", - "13": "bar", - "14": "bar", - "15": "bar", - "16": "bar", - "17": "bar", - "18": "bar", - "19": "bar", - "20": "bar", - "21": "bar", - "22": "bar", - "23": "bar", - "24": "bar", - "25": "bar", - "26": "bar", - "27": "bar", - "28": "bar", - "29": "bar", - "30": "bar", - "31": "bar", - "32": "bar", - "33": "bar", - "34": "bar", - "35": "bar", - "36": "bar", - "37": "bar", - "38": "bar", - "39": "bar", - "40": "bar", - "41": "bar", - "42": "bar", - "43": "bar", - "44": "bar", - "45": "bar", - "46": "bar", - "47": "bar", - "48": "bar", - "49": "bar", - "50": "bar", - "51": "bar", - "52": "bar", - "53": "bar", - "54": "bar", - "55": "bar", - "56": "bar", - "57": "bar", - "58": "bar", - "59": "bar", - "60": "bar", - "61": "bar", - "62": "bar", - "63": "bar", - "64": "bar", - "65": "bar", - "66": "bar", - "67": "bar", - "68": "bar", - "69": "bar", - "70": "bar", - "71": "bar", - "72": "bar", - "73": "bar", - "74": "bar", - "75": "bar", - "76": "bar", - "77": "bar", - "78": "bar", - "79": "bar", - "80": "bar", - "81": "bar", - "82": "bar", - "83": "bar", - "84": "bar", - "85": "bar", - "86": "bar", - "87": "bar", - "88": "bar", - "89": "bar", - "90": "bar", - "91": "bar", - "92": "bar", - "93": "bar", - "94": "bar", - "95": "bar", - "96": "bar", - "97": "bar", - "98": "bar", - "99": "bar", - "100": "bar", - "101": "bar", - "102": "bar", - "103": "bar", - "104": "bar", - "105": "bar", - "106": "bar", - "107": "bar", - "108": "bar", - "109": "bar", - "110": "bar", - "111": "bar", - "112": "bar", - "113": "bar", - "114": "bar", - "115": "bar", - "116": "bar", - "117": "bar", - "118": "bar", - "119": "bar", - "120": "bar", - "121": "bar", - "122": "bar", - "123": "bar", - "124": "bar", - "125": "bar", - "126": "bar", - "127": "bar", - "128": "bar", - "129": "bar", - "130": "bar", - "131": "bar", - "132": "bar", - "133": "bar", - "134": "bar", - "135": "bar", - "136": "bar", - "137": "bar", - "138": "bar", - "139": "bar", - }, + "item_schema": {"foo": "bar"}, "type": "custom", "include_sample_schema": True, }, @@ -1204,148 +358,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: response = await async_client.evals.with_raw_response.create( data_source_config={ - "item_schema": { - "0": "bar", - "1": "bar", - "2": "bar", - "3": "bar", - "4": "bar", - "5": "bar", - "6": "bar", - "7": "bar", - "8": "bar", - "9": "bar", - "10": "bar", - "11": "bar", - "12": "bar", - "13": "bar", - "14": "bar", - "15": "bar", - "16": "bar", - "17": "bar", - "18": "bar", - "19": "bar", - "20": "bar", - "21": "bar", - "22": "bar", - "23": "bar", - "24": "bar", - "25": "bar", - "26": "bar", - "27": "bar", - "28": "bar", - "29": "bar", - "30": "bar", - "31": "bar", - "32": "bar", - "33": "bar", - "34": "bar", - "35": "bar", - "36": "bar", - "37": "bar", - "38": "bar", - "39": "bar", - "40": "bar", - "41": "bar", - "42": "bar", - "43": "bar", - "44": "bar", - "45": "bar", - "46": "bar", - "47": "bar", - "48": "bar", - "49": "bar", - "50": "bar", - "51": "bar", - "52": "bar", - "53": "bar", - "54": "bar", - "55": "bar", - "56": "bar", - "57": "bar", - "58": "bar", - "59": "bar", - "60": "bar", - "61": "bar", - "62": "bar", - "63": "bar", - "64": "bar", - "65": "bar", - "66": "bar", - "67": "bar", - "68": "bar", - "69": "bar", - "70": "bar", - "71": "bar", - "72": "bar", - "73": "bar", - "74": "bar", - "75": "bar", - "76": "bar", - "77": "bar", - "78": "bar", - "79": "bar", - "80": "bar", - "81": "bar", - "82": "bar", - "83": "bar", - "84": "bar", - "85": "bar", - "86": "bar", - "87": "bar", - "88": "bar", - "89": "bar", - "90": "bar", - "91": "bar", - "92": "bar", - "93": "bar", - "94": "bar", - "95": "bar", - "96": "bar", - "97": "bar", - "98": "bar", - "99": "bar", - "100": "bar", - "101": "bar", - "102": "bar", - "103": "bar", - "104": "bar", - "105": "bar", - "106": "bar", - "107": "bar", - "108": "bar", - "109": "bar", - "110": "bar", - "111": "bar", - "112": "bar", - "113": "bar", - "114": "bar", - "115": "bar", - "116": "bar", - "117": "bar", - "118": "bar", - "119": "bar", - "120": "bar", - "121": "bar", - "122": "bar", - "123": "bar", - "124": "bar", - "125": "bar", - "126": "bar", - "127": "bar", - "128": "bar", - "129": "bar", - "130": "bar", - "131": "bar", - "132": "bar", - "133": "bar", - "134": "bar", - "135": "bar", - "136": "bar", - "137": "bar", - "138": "bar", - "139": "bar", - }, + "item_schema": {"foo": "bar"}, "type": "custom", }, testing_criteria=[ @@ -1374,148 +387,7 @@ async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: async with async_client.evals.with_streaming_response.create( data_source_config={ - "item_schema": { - "0": "bar", - "1": "bar", - "2": "bar", - "3": "bar", - "4": "bar", - "5": "bar", - "6": "bar", - "7": "bar", - "8": "bar", - "9": "bar", - "10": "bar", - "11": "bar", - "12": "bar", - "13": "bar", - "14": "bar", - "15": "bar", - "16": "bar", - "17": "bar", - "18": "bar", - "19": "bar", - "20": "bar", - "21": "bar", - "22": "bar", - "23": "bar", - "24": "bar", - "25": "bar", - "26": "bar", - "27": "bar", - "28": "bar", - "29": "bar", - "30": "bar", - "31": "bar", - "32": "bar", - "33": "bar", - "34": "bar", - "35": "bar", - "36": "bar", - "37": "bar", - "38": "bar", - "39": "bar", - "40": "bar", - "41": "bar", - "42": "bar", - "43": "bar", - "44": "bar", - "45": "bar", - "46": "bar", - "47": "bar", - "48": "bar", - "49": "bar", - "50": "bar", - "51": "bar", - "52": "bar", - "53": "bar", - "54": "bar", - "55": "bar", - "56": "bar", - "57": "bar", - "58": "bar", - "59": "bar", - "60": "bar", - "61": "bar", - "62": "bar", - "63": "bar", - "64": "bar", - "65": "bar", - "66": "bar", - "67": "bar", - "68": "bar", - "69": "bar", - "70": "bar", - "71": "bar", - "72": "bar", - "73": "bar", - "74": "bar", - "75": "bar", - "76": "bar", - "77": "bar", - "78": "bar", - "79": "bar", - "80": "bar", - "81": "bar", - "82": "bar", - "83": "bar", - "84": "bar", - "85": "bar", - "86": "bar", - "87": "bar", - "88": "bar", - "89": "bar", - "90": "bar", - "91": "bar", - "92": "bar", - "93": "bar", - "94": "bar", - "95": "bar", - "96": "bar", - "97": "bar", - "98": "bar", - "99": "bar", - "100": "bar", - "101": "bar", - "102": "bar", - "103": "bar", - "104": "bar", - "105": "bar", - "106": "bar", - "107": "bar", - "108": "bar", - "109": "bar", - "110": "bar", - "111": "bar", - "112": "bar", - "113": "bar", - "114": "bar", - "115": "bar", - "116": "bar", - "117": "bar", - "118": "bar", - "119": "bar", - "120": "bar", - "121": "bar", - "122": "bar", - "123": "bar", - "124": "bar", - "125": "bar", - "126": "bar", - "127": "bar", - "128": "bar", - "129": "bar", - "130": "bar", - "131": "bar", - "132": "bar", - "133": "bar", - "134": "bar", - "135": "bar", - "136": "bar", - "137": "bar", - "138": "bar", - "139": "bar", - }, + "item_schema": {"foo": "bar"}, "type": "custom", }, testing_criteria=[ diff --git a/tests/api_resources/test_images.py b/tests/api_resources/test_images.py index 2e31f3354a..0a88f2ebcf 100644 --- a/tests/api_resources/test_images.py +++ b/tests/api_resources/test_images.py @@ -28,7 +28,7 @@ def test_method_create_variation(self, client: OpenAI) -> None: def test_method_create_variation_with_all_params(self, client: OpenAI) -> None: image = client.images.create_variation( image=b"raw file contents", - model="dall-e-2", + model="string", n=1, response_format="url", size="1024x1024", @@ -74,7 +74,7 @@ def test_method_edit_with_all_params(self, client: OpenAI) -> None: image=b"raw file contents", prompt="A cute baby sea otter wearing a beret", mask=b"raw file contents", - model="dall-e-2", + model="string", n=1, response_format="url", size="1024x1024", @@ -119,7 +119,7 @@ def test_method_generate(self, client: OpenAI) -> None: def test_method_generate_with_all_params(self, client: OpenAI) -> None: image = client.images.generate( prompt="A cute baby sea otter", - model="dall-e-3", + model="string", n=1, quality="standard", response_format="url", @@ -168,7 +168,7 @@ async def test_method_create_variation(self, async_client: AsyncOpenAI) -> None: async def test_method_create_variation_with_all_params(self, async_client: AsyncOpenAI) -> None: image = await async_client.images.create_variation( image=b"raw file contents", - model="dall-e-2", + model="string", n=1, response_format="url", size="1024x1024", @@ -214,7 +214,7 @@ async def test_method_edit_with_all_params(self, async_client: AsyncOpenAI) -> N image=b"raw file contents", prompt="A cute baby sea otter wearing a beret", mask=b"raw file contents", - model="dall-e-2", + model="string", n=1, response_format="url", size="1024x1024", @@ -259,7 +259,7 @@ async def test_method_generate(self, async_client: AsyncOpenAI) -> None: async def test_method_generate_with_all_params(self, async_client: AsyncOpenAI) -> None: image = await async_client.images.generate( prompt="A cute baby sea otter", - model="dall-e-3", + model="string", n=1, quality="standard", response_format="url", diff --git a/tests/api_resources/test_moderations.py b/tests/api_resources/test_moderations.py index bbdeb63e49..6df6464110 100644 --- a/tests/api_resources/test_moderations.py +++ b/tests/api_resources/test_moderations.py @@ -28,7 +28,7 @@ def test_method_create(self, client: OpenAI) -> None: def test_method_create_with_all_params(self, client: OpenAI) -> None: moderation = client.moderations.create( input="I want to kill them.", - model="omni-moderation-2024-09-26", + model="string", ) assert_matches_type(ModerationCreateResponse, moderation, path=["response"]) @@ -71,7 +71,7 @@ async def test_method_create(self, async_client: AsyncOpenAI) -> None: async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: moderation = await async_client.moderations.create( input="I want to kill them.", - model="omni-moderation-2024-09-26", + model="string", ) assert_matches_type(ModerationCreateResponse, moderation, path=["response"]) From 13ff6dd33e45d3c3c470d5673e81d3777b51aa5b Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 8 Apr 2025 19:46:29 +0000 Subject: [PATCH 767/816] chore(internal): skip broken test (#2289) --- .stats.yml | 2 +- .../fine_tuning/checkpoints/test_permissions.py | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index 4a82ee242d..c39ce1186a 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 97 openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-32de3bc513663c5fac922c49be41c222b6ee8c0b841d8966bcdfa489d441daa3.yml openapi_spec_hash: ea86343b5e9858a74e85da8ab2c532f6 -config_hash: d6c61213488683418adb860a9ee1501b +config_hash: 43dc8df20ffec9d1503f91866cb2b7d9 diff --git a/tests/api_resources/fine_tuning/checkpoints/test_permissions.py b/tests/api_resources/fine_tuning/checkpoints/test_permissions.py index d25c784c33..d40466919a 100644 --- a/tests/api_resources/fine_tuning/checkpoints/test_permissions.py +++ b/tests/api_resources/fine_tuning/checkpoints/test_permissions.py @@ -117,6 +117,7 @@ def test_path_params_retrieve(self, client: OpenAI) -> None: fine_tuned_model_checkpoint="", ) + @pytest.mark.skip(reason="OpenAPI spec is slightly incorrect") @parametrize def test_method_delete(self, client: OpenAI) -> None: permission = client.fine_tuning.checkpoints.permissions.delete( @@ -124,6 +125,7 @@ def test_method_delete(self, client: OpenAI) -> None: ) assert_matches_type(PermissionDeleteResponse, permission, path=["response"]) + @pytest.mark.skip(reason="OpenAPI spec is slightly incorrect") @parametrize def test_raw_response_delete(self, client: OpenAI) -> None: response = client.fine_tuning.checkpoints.permissions.with_raw_response.delete( @@ -135,6 +137,7 @@ def test_raw_response_delete(self, client: OpenAI) -> None: permission = response.parse() assert_matches_type(PermissionDeleteResponse, permission, path=["response"]) + @pytest.mark.skip(reason="OpenAPI spec is slightly incorrect") @parametrize def test_streaming_response_delete(self, client: OpenAI) -> None: with client.fine_tuning.checkpoints.permissions.with_streaming_response.delete( @@ -148,6 +151,7 @@ def test_streaming_response_delete(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True + @pytest.mark.skip(reason="OpenAPI spec is slightly incorrect") @parametrize def test_path_params_delete(self, client: OpenAI) -> None: with pytest.raises( @@ -256,6 +260,7 @@ async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: fine_tuned_model_checkpoint="", ) + @pytest.mark.skip(reason="OpenAPI spec is slightly incorrect") @parametrize async def test_method_delete(self, async_client: AsyncOpenAI) -> None: permission = await async_client.fine_tuning.checkpoints.permissions.delete( @@ -263,6 +268,7 @@ async def test_method_delete(self, async_client: AsyncOpenAI) -> None: ) assert_matches_type(PermissionDeleteResponse, permission, path=["response"]) + @pytest.mark.skip(reason="OpenAPI spec is slightly incorrect") @parametrize async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None: response = await async_client.fine_tuning.checkpoints.permissions.with_raw_response.delete( @@ -274,6 +280,7 @@ async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None: permission = response.parse() assert_matches_type(PermissionDeleteResponse, permission, path=["response"]) + @pytest.mark.skip(reason="OpenAPI spec is slightly incorrect") @parametrize async def test_streaming_response_delete(self, async_client: AsyncOpenAI) -> None: async with async_client.fine_tuning.checkpoints.permissions.with_streaming_response.delete( @@ -287,6 +294,7 @@ async def test_streaming_response_delete(self, async_client: AsyncOpenAI) -> Non assert cast(Any, response.is_closed) is True + @pytest.mark.skip(reason="OpenAPI spec is slightly incorrect") @parametrize async def test_path_params_delete(self, async_client: AsyncOpenAI) -> None: with pytest.raises( From 0c8343bb928b26d42feedd2a1a039e16ac58e744 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 8 Apr 2025 19:47:02 +0000 Subject: [PATCH 768/816] release: 1.72.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 16 ++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 19 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index c7704ce953..e6484623c0 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.71.0" + ".": "1.72.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index e8f2e22cb8..b02fae7e87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## 1.72.0 (2025-04-08) + +Full Changelog: [v1.71.0...v1.72.0](https://github.com/openai/openai-python/compare/v1.71.0...v1.72.0) + +### Features + +* **api:** Add evalapi to sdk ([#2287](https://github.com/openai/openai-python/issues/2287)) ([35262fc](https://github.com/openai/openai-python/commit/35262fcef6ccb7d1f75c9abdfdc68c3dcf87ef53)) + + +### Chores + +* **internal:** fix examples ([#2288](https://github.com/openai/openai-python/issues/2288)) ([39defd6](https://github.com/openai/openai-python/commit/39defd61e81ea0ec6b898be12e9fb7e621c0e532)) +* **internal:** skip broken test ([#2289](https://github.com/openai/openai-python/issues/2289)) ([e2c9bce](https://github.com/openai/openai-python/commit/e2c9bce1f59686ee053b495d06ea118b4a89e09e)) +* **internal:** slight transform perf improvement ([#2284](https://github.com/openai/openai-python/issues/2284)) ([746174f](https://github.com/openai/openai-python/commit/746174fae7a018ece5dab54fb0b5a15fcdd18f2f)) +* **tests:** improve enum examples ([#2286](https://github.com/openai/openai-python/issues/2286)) ([c9dd81c](https://github.com/openai/openai-python/commit/c9dd81ce0277e8b1f5db5e0a39c4c2bcd9004bcc)) + ## 1.71.0 (2025-04-07) Full Changelog: [v1.70.0...v1.71.0](https://github.com/openai/openai-python/compare/v1.70.0...v1.71.0) diff --git a/pyproject.toml b/pyproject.toml index 4583a5531f..29abf3ac4c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.71.0" +version = "1.72.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 12e9d20bb1..e7c16742a2 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.71.0" # x-release-please-version +__version__ = "1.72.0" # x-release-please-version From ee272dd8dcfdb8cbe4faf6aa197fd03e24d978fa Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 8 Apr 2025 20:05:13 +0000 Subject: [PATCH 769/816] feat(api): manual updates --- .stats.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.stats.yml b/.stats.yml index c39ce1186a..d4a4370a78 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 97 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-32de3bc513663c5fac922c49be41c222b6ee8c0b841d8966bcdfa489d441daa3.yml +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-44b20fa9d24544217fe6bb48852037537030a1ad29b202936425110744fe66fb.yml openapi_spec_hash: ea86343b5e9858a74e85da8ab2c532f6 -config_hash: 43dc8df20ffec9d1503f91866cb2b7d9 +config_hash: 69e3afd56ccb0f0f822a7a9dc130fc99 From acf68ef3a57dfdae804072cc4f8abed32fd4f703 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 8 Apr 2025 21:49:05 +0000 Subject: [PATCH 770/816] chore: slight wording improvement in README (#2291) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c52bffbb5f..f7e0eb6467 100644 --- a/README.md +++ b/README.md @@ -351,7 +351,7 @@ response = client.chat.responses.create( ## File uploads -Request parameters that correspond to file uploads can be passed as `bytes`, a [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike) instance or a tuple of `(filename, contents, media type)`. +Request parameters that correspond to file uploads can be passed as `bytes`, or a [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike) instance or a tuple of `(filename, contents, media type)`. ```python from pathlib import Path From df5b323ea3963939d6a331c200116e688ce507e8 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 9 Apr 2025 09:26:34 +0000 Subject: [PATCH 771/816] chore: workaround build errors --- .stats.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index d4a4370a78..9d8d07c6ac 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 97 openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-44b20fa9d24544217fe6bb48852037537030a1ad29b202936425110744fe66fb.yml openapi_spec_hash: ea86343b5e9858a74e85da8ab2c532f6 -config_hash: 69e3afd56ccb0f0f822a7a9dc130fc99 +config_hash: 5ea32de61ff42fcf5e66cff8d9e247ea From 5020669996e299ee268db2f2f45f7b7cefc0ccd6 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 9 Apr 2025 16:31:40 +0000 Subject: [PATCH 772/816] chore(internal): expand CI branch coverage (#2295) --- .github/workflows/ci.yml | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6d2699cca8..bcd3e9d9d3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,18 +1,18 @@ name: CI on: push: - branches: - - main - pull_request: - branches: - - main - - next + branches-ignore: + - 'generated' + - 'codegen/**' + - 'integrated/**' + - 'preview-head/**' + - 'preview-base/**' + - 'preview/**' jobs: lint: name: lint runs-on: ubuntu-latest - steps: - uses: actions/checkout@v4 @@ -33,7 +33,6 @@ jobs: test: name: test runs-on: ubuntu-latest - steps: - uses: actions/checkout@v4 From c8833fc38f9634c43d3ca4091ecda6e3c4a07a56 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 9 Apr 2025 21:08:33 +0000 Subject: [PATCH 773/816] chore(internal): reduce CI branch coverage --- .github/workflows/ci.yml | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bcd3e9d9d3..6f9cf84bb4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,13 +1,12 @@ name: CI on: push: - branches-ignore: - - 'generated' - - 'codegen/**' - - 'integrated/**' - - 'preview-head/**' - - 'preview-base/**' - - 'preview/**' + branches: + - main + pull_request: + branches: + - main + - next jobs: lint: From 284415c968c031c001ad833b4b955d99c6fbbc50 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 11 Apr 2025 12:22:53 +0000 Subject: [PATCH 774/816] fix(perf): skip traversing types for NotGiven values --- src/openai/_utils/_transform.py | 11 +++++++++++ tests/test_transform.py | 9 ++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/openai/_utils/_transform.py b/src/openai/_utils/_transform.py index 3ec620818c..3b2b8e009a 100644 --- a/src/openai/_utils/_transform.py +++ b/src/openai/_utils/_transform.py @@ -12,6 +12,7 @@ from ._utils import ( is_list, + is_given, is_mapping, is_iterable, ) @@ -258,6 +259,11 @@ def _transform_typeddict( result: dict[str, object] = {} annotations = get_type_hints(expected_type, include_extras=True) for key, value in data.items(): + if not is_given(value): + # we don't need to include `NotGiven` values here as they'll + # be stripped out before the request is sent anyway + continue + type_ = annotations.get(key) if type_ is None: # we do not have a type annotation for this field, leave it as is @@ -415,6 +421,11 @@ async def _async_transform_typeddict( result: dict[str, object] = {} annotations = get_type_hints(expected_type, include_extras=True) for key, value in data.items(): + if not is_given(value): + # we don't need to include `NotGiven` values here as they'll + # be stripped out before the request is sent anyway + continue + type_ = annotations.get(key) if type_ is None: # we do not have a type annotation for this field, leave it as is diff --git a/tests/test_transform.py b/tests/test_transform.py index cd584756d7..965f65f74f 100644 --- a/tests/test_transform.py +++ b/tests/test_transform.py @@ -8,7 +8,7 @@ import pytest -from openai._types import Base64FileInput +from openai._types import NOT_GIVEN, Base64FileInput from openai._utils import ( PropertyInfo, transform as _transform, @@ -444,3 +444,10 @@ async def test_transform_skipping(use_async: bool) -> None: # iterables of ints are converted to a list data = iter([1, 2, 3]) assert await transform(data, Iterable[int], use_async) == [1, 2, 3] + + +@parametrize +@pytest.mark.asyncio +async def test_strips_notgiven(use_async: bool) -> None: + assert await transform({"foo_bar": "bar"}, Foo1, use_async) == {"fooBar": "bar"} + assert await transform({"foo_bar": NOT_GIVEN}, Foo1, use_async) == {} From 8086d61769128eeb249449eb12da9b6b3c46562e Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 11 Apr 2025 13:35:38 +0000 Subject: [PATCH 775/816] fix(perf): optimize some hot paths --- src/openai/_utils/_transform.py | 14 +++++++++++++- src/openai/_utils/_typing.py | 2 ++ src/openai/resources/audio/transcriptions.py | 14 ++++++++++++-- src/openai/resources/beta/threads/runs/runs.py | 12 ++++++++---- src/openai/resources/beta/threads/threads.py | 8 ++++++-- .../resources/chat/completions/completions.py | 8 ++++++-- src/openai/resources/completions.py | 8 ++++++-- src/openai/resources/responses/responses.py | 8 ++++++-- 8 files changed, 59 insertions(+), 15 deletions(-) diff --git a/src/openai/_utils/_transform.py b/src/openai/_utils/_transform.py index 3b2b8e009a..b0cc20a735 100644 --- a/src/openai/_utils/_transform.py +++ b/src/openai/_utils/_transform.py @@ -5,7 +5,7 @@ import pathlib from typing import Any, Mapping, TypeVar, cast from datetime import date, datetime -from typing_extensions import Literal, get_args, override, get_type_hints +from typing_extensions import Literal, get_args, override, get_type_hints as _get_type_hints import anyio import pydantic @@ -13,6 +13,7 @@ from ._utils import ( is_list, is_given, + lru_cache, is_mapping, is_iterable, ) @@ -109,6 +110,7 @@ class Params(TypedDict, total=False): return cast(_T, transformed) +@lru_cache(maxsize=8096) def _get_annotated_type(type_: type) -> type | None: """If the given type is an `Annotated` type then it is returned, if not `None` is returned. @@ -433,3 +435,13 @@ async def _async_transform_typeddict( else: result[_maybe_transform_key(key, type_)] = await _async_transform_recursive(value, annotation=type_) return result + + +@lru_cache(maxsize=8096) +def get_type_hints( + obj: Any, + globalns: dict[str, Any] | None = None, + localns: Mapping[str, Any] | None = None, + include_extras: bool = False, +) -> dict[str, Any]: + return _get_type_hints(obj, globalns=globalns, localns=localns, include_extras=include_extras) diff --git a/src/openai/_utils/_typing.py b/src/openai/_utils/_typing.py index 278749b147..1958820f8d 100644 --- a/src/openai/_utils/_typing.py +++ b/src/openai/_utils/_typing.py @@ -13,6 +13,7 @@ get_origin, ) +from ._utils import lru_cache from .._types import InheritsGeneric from .._compat import is_union as _is_union @@ -66,6 +67,7 @@ def is_type_alias_type(tp: Any, /) -> TypeIs[typing_extensions.TypeAliasType]: # Extracts T from Annotated[T, ...] or from Required[Annotated[T, ...]] +@lru_cache(maxsize=8096) def strip_annotated_type(typ: type) -> type: if is_required_type(typ) or is_annotated_type(typ): return strip_annotated_type(cast(type, get_args(typ)[0])) diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index 2a77f91d69..7e62f70f60 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -321,7 +321,12 @@ def create( extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} return self._post( # type: ignore[return-value] "/audio/transcriptions", - body=maybe_transform(body, transcription_create_params.TranscriptionCreateParams), + body=maybe_transform( + body, + transcription_create_params.TranscriptionCreateParamsStreaming + if stream + else transcription_create_params.TranscriptionCreateParamsNonStreaming, + ), files=files, options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout @@ -616,7 +621,12 @@ async def create( extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})} return await self._post( "/audio/transcriptions", - body=await async_maybe_transform(body, transcription_create_params.TranscriptionCreateParams), + body=await async_maybe_transform( + body, + transcription_create_params.TranscriptionCreateParamsStreaming + if stream + else transcription_create_params.TranscriptionCreateParamsNonStreaming, + ), files=files, options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index acb1c9b261..4d19010fea 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -587,7 +587,7 @@ def create( "top_p": top_p, "truncation_strategy": truncation_strategy, }, - run_create_params.RunCreateParams, + run_create_params.RunCreateParamsStreaming if stream else run_create_params.RunCreateParamsNonStreaming, ), options=make_request_options( extra_headers=extra_headers, @@ -1324,7 +1324,9 @@ def submit_tool_outputs( "tool_outputs": tool_outputs, "stream": stream, }, - run_submit_tool_outputs_params.RunSubmitToolOutputsParams, + run_submit_tool_outputs_params.RunSubmitToolOutputsParamsStreaming + if stream + else run_submit_tool_outputs_params.RunSubmitToolOutputsParamsNonStreaming, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout @@ -1996,7 +1998,7 @@ async def create( "top_p": top_p, "truncation_strategy": truncation_strategy, }, - run_create_params.RunCreateParams, + run_create_params.RunCreateParamsStreaming if stream else run_create_params.RunCreateParamsNonStreaming, ), options=make_request_options( extra_headers=extra_headers, @@ -2732,7 +2734,9 @@ async def submit_tool_outputs( "tool_outputs": tool_outputs, "stream": stream, }, - run_submit_tool_outputs_params.RunSubmitToolOutputsParams, + run_submit_tool_outputs_params.RunSubmitToolOutputsParamsStreaming + if stream + else run_submit_tool_outputs_params.RunSubmitToolOutputsParamsNonStreaming, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index d88559bdeb..c697be416d 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -717,7 +717,9 @@ def create_and_run( "top_p": top_p, "truncation_strategy": truncation_strategy, }, - thread_create_and_run_params.ThreadCreateAndRunParams, + thread_create_and_run_params.ThreadCreateAndRunParamsStreaming + if stream + else thread_create_and_run_params.ThreadCreateAndRunParamsNonStreaming, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout @@ -1564,7 +1566,9 @@ async def create_and_run( "top_p": top_p, "truncation_strategy": truncation_strategy, }, - thread_create_and_run_params.ThreadCreateAndRunParams, + thread_create_and_run_params.ThreadCreateAndRunParamsStreaming + if stream + else thread_create_and_run_params.ThreadCreateAndRunParamsNonStreaming, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout diff --git a/src/openai/resources/chat/completions/completions.py b/src/openai/resources/chat/completions/completions.py index d28be012c9..f9e380cc72 100644 --- a/src/openai/resources/chat/completions/completions.py +++ b/src/openai/resources/chat/completions/completions.py @@ -947,7 +947,9 @@ def create( "user": user, "web_search_options": web_search_options, }, - completion_create_params.CompletionCreateParams, + completion_create_params.CompletionCreateParamsStreaming + if stream + else completion_create_params.CompletionCreateParamsNonStreaming, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout @@ -2033,7 +2035,9 @@ async def create( "user": user, "web_search_options": web_search_options, }, - completion_create_params.CompletionCreateParams, + completion_create_params.CompletionCreateParamsStreaming + if stream + else completion_create_params.CompletionCreateParamsNonStreaming, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index 171f509352..592696f7da 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -559,7 +559,9 @@ def create( "top_p": top_p, "user": user, }, - completion_create_params.CompletionCreateParams, + completion_create_params.CompletionCreateParamsStreaming + if stream + else completion_create_params.CompletionCreateParamsNonStreaming, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout @@ -1101,7 +1103,9 @@ async def create( "top_p": top_p, "user": user, }, - completion_create_params.CompletionCreateParams, + completion_create_params.CompletionCreateParamsStreaming + if stream + else completion_create_params.CompletionCreateParamsNonStreaming, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout diff --git a/src/openai/resources/responses/responses.py b/src/openai/resources/responses/responses.py index 29ed3de42a..f8588178ed 100644 --- a/src/openai/resources/responses/responses.py +++ b/src/openai/resources/responses/responses.py @@ -623,7 +623,9 @@ def create( "truncation": truncation, "user": user, }, - response_create_params.ResponseCreateParams, + response_create_params.ResponseCreateParamsStreaming + if stream + else response_create_params.ResponseCreateParamsNonStreaming, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout @@ -1435,7 +1437,9 @@ async def create( "truncation": truncation, "user": user, }, - response_create_params.ResponseCreateParams, + response_create_params.ResponseCreateParamsStreaming + if stream + else response_create_params.ResponseCreateParamsNonStreaming, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout From ab091ca05349c594343dcb78ad5e7fd015d5804d Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Sat, 12 Apr 2025 05:03:44 +0000 Subject: [PATCH 776/816] release: 1.73.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 22 ++++++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 25 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index e6484623c0..c174a89798 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.72.0" + ".": "1.73.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index b02fae7e87..7dffc39909 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,27 @@ # Changelog +## 1.73.0 (2025-04-12) + +Full Changelog: [v1.72.0...v1.73.0](https://github.com/openai/openai-python/compare/v1.72.0...v1.73.0) + +### Features + +* **api:** manual updates ([a3253dd](https://github.com/openai/openai-python/commit/a3253dd798c1eccd9810d4fc593e8c2a568bcf4f)) + + +### Bug Fixes + +* **perf:** optimize some hot paths ([f79d39f](https://github.com/openai/openai-python/commit/f79d39fbcaea8f366a9e48c06fb1696bab3e607d)) +* **perf:** skip traversing types for NotGiven values ([28d220d](https://github.com/openai/openai-python/commit/28d220de3b4a09d80450d0bcc9b347bbf68f81ec)) + + +### Chores + +* **internal:** expand CI branch coverage ([#2295](https://github.com/openai/openai-python/issues/2295)) ([0ae783b](https://github.com/openai/openai-python/commit/0ae783b99122975be521365de0b6d2bce46056c9)) +* **internal:** reduce CI branch coverage ([2fb7d42](https://github.com/openai/openai-python/commit/2fb7d425cda679a54aa3262090479fd747363bb4)) +* slight wording improvement in README ([#2291](https://github.com/openai/openai-python/issues/2291)) ([e020759](https://github.com/openai/openai-python/commit/e0207598d16a2a9cb3cb3a8e8e97fa9cfdccd5e8)) +* workaround build errors ([4e10c96](https://github.com/openai/openai-python/commit/4e10c96a483db28dedc2d8c2908765fb7317e049)) + ## 1.72.0 (2025-04-08) Full Changelog: [v1.71.0...v1.72.0](https://github.com/openai/openai-python/compare/v1.71.0...v1.72.0) diff --git a/pyproject.toml b/pyproject.toml index 29abf3ac4c..1126c96040 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.72.0" +version = "1.73.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index e7c16742a2..bcc08e9c6d 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.72.0" # x-release-please-version +__version__ = "1.73.0" # x-release-please-version From e3e791c85f0c508f530848025a7adeed71a8bbae Mon Sep 17 00:00:00 2001 From: Nikolai Pismennyi Date: Mon, 14 Apr 2025 12:04:43 +0300 Subject: [PATCH 777/816] fix(chat): skip azure async filter events (#2255) --- src/openai/lib/streaming/chat/_completions.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/openai/lib/streaming/chat/_completions.py b/src/openai/lib/streaming/chat/_completions.py index 2146091354..f147696cca 100644 --- a/src/openai/lib/streaming/chat/_completions.py +++ b/src/openai/lib/streaming/chat/_completions.py @@ -113,6 +113,8 @@ def current_completion_snapshot(self) -> ParsedChatCompletionSnapshot: def __stream__(self) -> Iterator[ChatCompletionStreamEvent[ResponseFormatT]]: for sse_event in self._raw_stream: + if not _is_valid_chat_completion_chunk_weak(sse_event): + continue events_to_fire = self._state.handle_chunk(sse_event) for event in events_to_fire: yield event @@ -234,6 +236,8 @@ def current_completion_snapshot(self) -> ParsedChatCompletionSnapshot: async def __stream__(self) -> AsyncIterator[ChatCompletionStreamEvent[ResponseFormatT]]: async for sse_event in self._raw_stream: + if not _is_valid_chat_completion_chunk_weak(sse_event): + continue events_to_fire = self._state.handle_chunk(sse_event) for event in events_to_fire: yield event @@ -753,3 +757,12 @@ def _convert_initial_chunk_into_snapshot(chunk: ChatCompletionChunk) -> ParsedCh }, ), ) + + +def _is_valid_chat_completion_chunk_weak(sse_event: ChatCompletionChunk) -> bool: + # Although the _raw_stream is always supposed to contain only objects adhering to ChatCompletionChunk schema, + # this is broken by the Azure OpenAI in case of Asynchronous Filter enabled. + # An easy filter is to check for the "object" property: + # - should be "chat.completion.chunk" for a ChatCompletionChunk; + # - is an empty string for Asynchronous Filter events. + return sse_event.object == "chat.completion.chunk" # type: ignore # pylance reports this as a useless check From 1828fb6a71b12ba5deb7d57e7caa8584d2fe1aeb Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 14 Apr 2025 12:24:00 +0000 Subject: [PATCH 778/816] chore(internal): update pyright settings --- pyproject.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/pyproject.toml b/pyproject.toml index 1126c96040..27db20295f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -166,6 +166,7 @@ exclude = [ ] reportImplicitOverride = true +reportOverlappingOverload = false reportImportCycles = false reportPrivateUsage = false From 77ba4182e4e4a6f7e986762f6aef925ebb40f2f0 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 14 Apr 2025 14:30:49 +0000 Subject: [PATCH 779/816] chore(client): minor internal fixes --- src/openai/_base_client.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index f31e5af54b..1dd3a4772c 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -411,7 +411,8 @@ def _build_headers(self, options: FinalRequestOptions, *, retries_taken: int = 0 idempotency_header = self._idempotency_header if idempotency_header and options.method.lower() != "get" and idempotency_header not in headers: - headers[idempotency_header] = options.idempotency_key or self._idempotency_key() + options.idempotency_key = options.idempotency_key or self._idempotency_key() + headers[idempotency_header] = options.idempotency_key # Don't set these headers if they were already set or removed by the caller. We check # `custom_headers`, which can contain `Omit()`, instead of `headers` to account for the removal case. @@ -945,6 +946,10 @@ def _request( request = self._build_request(options, retries_taken=retries_taken) self._prepare_request(request) + if options.idempotency_key: + # ensure the idempotency key is reused between requests + input_options.idempotency_key = options.idempotency_key + kwargs: HttpxSendArgs = {} if self.custom_auth is not None: kwargs["auth"] = self.custom_auth @@ -1492,6 +1497,10 @@ async def _request( request = self._build_request(options, retries_taken=retries_taken) await self._prepare_request(request) + if options.idempotency_key: + # ensure the idempotency key is reused between requests + input_options.idempotency_key = options.idempotency_key + kwargs: HttpxSendArgs = {} if self.custom_auth is not None: kwargs["auth"] = self.custom_auth From 7d2b97d660882f68283cb2b54303660d1f73bec1 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 14 Apr 2025 16:40:51 +0000 Subject: [PATCH 780/816] feat(api): adding gpt-4.1 family of model IDs --- .stats.yml | 4 ++-- src/openai/resources/beta/assistants.py | 12 ++++++++++++ src/openai/types/beta/assistant_update_params.py | 6 ++++++ src/openai/types/shared/chat_model.py | 6 ++++++ src/openai/types/shared_params/chat_model.py | 6 ++++++ 5 files changed, 32 insertions(+), 2 deletions(-) diff --git a/.stats.yml b/.stats.yml index 9d8d07c6ac..b40485bd0a 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 97 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-44b20fa9d24544217fe6bb48852037537030a1ad29b202936425110744fe66fb.yml -openapi_spec_hash: ea86343b5e9858a74e85da8ab2c532f6 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-a555f81249cb084f463dcefa4aba069f9341fdaf3dd6ac27d7f237fc90e8f488.yml +openapi_spec_hash: 8e590296cd1a54b9508510b0c7a2c45a config_hash: 5ea32de61ff42fcf5e66cff8d9e247ea diff --git a/src/openai/resources/beta/assistants.py b/src/openai/resources/beta/assistants.py index 1c7cbf3737..43f6a7f135 100644 --- a/src/openai/resources/beta/assistants.py +++ b/src/openai/resources/beta/assistants.py @@ -223,6 +223,12 @@ def update( model: Union[ str, Literal[ + "gpt-4.1", + "gpt-4.1-mini", + "gpt-4.1-nano", + "gpt-4.1-2025-04-14", + "gpt-4.1-mini-2025-04-14", + "gpt-4.1-nano-2025-04-14", "o3-mini", "o3-mini-2025-01-31", "o1", @@ -666,6 +672,12 @@ async def update( model: Union[ str, Literal[ + "gpt-4.1", + "gpt-4.1-mini", + "gpt-4.1-nano", + "gpt-4.1-2025-04-14", + "gpt-4.1-mini-2025-04-14", + "gpt-4.1-nano-2025-04-14", "o3-mini", "o3-mini-2025-01-31", "o1", diff --git a/src/openai/types/beta/assistant_update_params.py b/src/openai/types/beta/assistant_update_params.py index d3ec7614fd..b28094a6a5 100644 --- a/src/openai/types/beta/assistant_update_params.py +++ b/src/openai/types/beta/assistant_update_params.py @@ -36,6 +36,12 @@ class AssistantUpdateParams(TypedDict, total=False): model: Union[ str, Literal[ + "gpt-4.1", + "gpt-4.1-mini", + "gpt-4.1-nano", + "gpt-4.1-2025-04-14", + "gpt-4.1-mini-2025-04-14", + "gpt-4.1-nano-2025-04-14", "o3-mini", "o3-mini-2025-01-31", "o1", diff --git a/src/openai/types/shared/chat_model.py b/src/openai/types/shared/chat_model.py index b19375725d..30878b4347 100644 --- a/src/openai/types/shared/chat_model.py +++ b/src/openai/types/shared/chat_model.py @@ -5,6 +5,12 @@ __all__ = ["ChatModel"] ChatModel: TypeAlias = Literal[ + "gpt-4.1", + "gpt-4.1-mini", + "gpt-4.1-nano", + "gpt-4.1-2025-04-14", + "gpt-4.1-mini-2025-04-14", + "gpt-4.1-nano-2025-04-14", "o3-mini", "o3-mini-2025-01-31", "o1", diff --git a/src/openai/types/shared_params/chat_model.py b/src/openai/types/shared_params/chat_model.py index ff81b07ac3..f606beb693 100644 --- a/src/openai/types/shared_params/chat_model.py +++ b/src/openai/types/shared_params/chat_model.py @@ -7,6 +7,12 @@ __all__ = ["ChatModel"] ChatModel: TypeAlias = Literal[ + "gpt-4.1", + "gpt-4.1-mini", + "gpt-4.1-nano", + "gpt-4.1-2025-04-14", + "gpt-4.1-mini-2025-04-14", + "gpt-4.1-nano-2025-04-14", "o3-mini", "o3-mini-2025-01-31", "o1", From 05810dd4088b6dbfc4194d7b0bea03eec236c83a Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 14 Apr 2025 16:41:56 +0000 Subject: [PATCH 781/816] release: 1.74.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 19 +++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 22 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index c174a89798..71a38f2845 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.73.0" + ".": "1.74.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 7dffc39909..90af38d900 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,24 @@ # Changelog +## 1.74.0 (2025-04-14) + +Full Changelog: [v1.73.0...v1.74.0](https://github.com/openai/openai-python/compare/v1.73.0...v1.74.0) + +### Features + +* **api:** adding gpt-4.1 family of model IDs ([d4dae55](https://github.com/openai/openai-python/commit/d4dae5553ff3a2879b9ab79a6423661b212421f9)) + + +### Bug Fixes + +* **chat:** skip azure async filter events ([#2255](https://github.com/openai/openai-python/issues/2255)) ([fd3a38b](https://github.com/openai/openai-python/commit/fd3a38b1ed30af0a9f3302c1cfc6be6b352e65de)) + + +### Chores + +* **client:** minor internal fixes ([6071ae5](https://github.com/openai/openai-python/commit/6071ae5e8b4faa465afc8d07370737e66901900a)) +* **internal:** update pyright settings ([c8f8beb](https://github.com/openai/openai-python/commit/c8f8bebf852380a224701bc36826291d6387c53d)) + ## 1.73.0 (2025-04-12) Full Changelog: [v1.72.0...v1.73.0](https://github.com/openai/openai-python/compare/v1.72.0...v1.73.0) diff --git a/pyproject.toml b/pyproject.toml index 27db20295f..eb07cd5ba7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.73.0" +version = "1.74.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index bcc08e9c6d..b203ed859f 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.73.0" # x-release-please-version +__version__ = "1.74.0" # x-release-please-version From 6d110a147f91cc5e9352ab1e823ed5eb4db06137 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 16 Apr 2025 12:06:05 +0000 Subject: [PATCH 782/816] chore(internal): bump pyright version --- pyproject.toml | 2 +- requirements-dev.lock | 2 +- src/openai/_base_client.py | 6 +++++- src/openai/_models.py | 1 - src/openai/_utils/_typing.py | 2 +- tests/conftest.py | 2 +- tests/test_models.py | 2 +- 7 files changed, 10 insertions(+), 7 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index eb07cd5ba7..244dd2ecb1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -51,7 +51,7 @@ voice_helpers = ["sounddevice>=0.5.1", "numpy>=2.0.2"] managed = true # version pins are in requirements-dev.lock dev-dependencies = [ - "pyright>=1.1.359", + "pyright==1.1.399", "mypy", "respx", "pytest", diff --git a/requirements-dev.lock b/requirements-dev.lock index 11bb5c1b30..9875a2b860 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -126,7 +126,7 @@ pygments==2.18.0 # via rich pyjwt==2.8.0 # via msal -pyright==1.1.392.post0 +pyright==1.1.399 pytest==8.3.3 # via pytest-asyncio pytest-asyncio==0.24.0 diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 1dd3a4772c..d167c43763 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -100,7 +100,11 @@ _AsyncStreamT = TypeVar("_AsyncStreamT", bound=AsyncStream[Any]) if TYPE_CHECKING: - from httpx._config import DEFAULT_TIMEOUT_CONFIG as HTTPX_DEFAULT_TIMEOUT + from httpx._config import ( + DEFAULT_TIMEOUT_CONFIG, # pyright: ignore[reportPrivateImportUsage] + ) + + HTTPX_DEFAULT_TIMEOUT = DEFAULT_TIMEOUT_CONFIG else: try: from httpx._config import DEFAULT_TIMEOUT_CONFIG as HTTPX_DEFAULT_TIMEOUT diff --git a/src/openai/_models.py b/src/openai/_models.py index fc4f201e4e..9b1aeb30bf 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -20,7 +20,6 @@ ) import pydantic -import pydantic.generics from pydantic.fields import FieldInfo from ._types import ( diff --git a/src/openai/_utils/_typing.py b/src/openai/_utils/_typing.py index 1958820f8d..1bac9542e2 100644 --- a/src/openai/_utils/_typing.py +++ b/src/openai/_utils/_typing.py @@ -110,7 +110,7 @@ class MyResponse(Foo[_T]): ``` """ cls = cast(object, get_origin(typ) or typ) - if cls in generic_bases: + if cls in generic_bases: # pyright: ignore[reportUnnecessaryContains] # we're given the class directly return extract_type_arg(typ, index) diff --git a/tests/conftest.py b/tests/conftest.py index fa82d39d86..8b01753e2f 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -10,7 +10,7 @@ from openai import OpenAI, AsyncOpenAI if TYPE_CHECKING: - from _pytest.fixtures import FixtureRequest + from _pytest.fixtures import FixtureRequest # pyright: ignore[reportPrivateImportUsage] pytest.register_assert_rewrite("tests.utils") diff --git a/tests/test_models.py b/tests/test_models.py index b9be1f3ea3..4b18940b49 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -832,7 +832,7 @@ class B(BaseModel): @pytest.mark.skipif(not PYDANTIC_V2, reason="TypeAliasType is not supported in Pydantic v1") def test_type_alias_type() -> None: - Alias = TypeAliasType("Alias", str) + Alias = TypeAliasType("Alias", str) # pyright: ignore class Model(BaseModel): alias: Alias From ea638838b7aa5989516df3659a1be16825681fc6 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 16 Apr 2025 12:59:19 +0000 Subject: [PATCH 783/816] chore(internal): base client updates --- src/openai/_base_client.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index d167c43763..8b43a20699 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -121,6 +121,7 @@ class PageInfo: url: URL | NotGiven params: Query | NotGiven + json: Body | NotGiven @overload def __init__( @@ -136,19 +137,30 @@ def __init__( params: Query, ) -> None: ... + @overload + def __init__( + self, + *, + json: Body, + ) -> None: ... + def __init__( self, *, url: URL | NotGiven = NOT_GIVEN, + json: Body | NotGiven = NOT_GIVEN, params: Query | NotGiven = NOT_GIVEN, ) -> None: self.url = url + self.json = json self.params = params @override def __repr__(self) -> str: if self.url: return f"{self.__class__.__name__}(url={self.url})" + if self.json: + return f"{self.__class__.__name__}(json={self.json})" return f"{self.__class__.__name__}(params={self.params})" @@ -197,6 +209,19 @@ def _info_to_options(self, info: PageInfo) -> FinalRequestOptions: options.url = str(url) return options + if not isinstance(info.json, NotGiven): + if not is_mapping(info.json): + raise TypeError("Pagination is only supported with mappings") + + if not options.json_data: + options.json_data = {**info.json} + else: + if not is_mapping(options.json_data): + raise TypeError("Pagination is only supported with mappings") + + options.json_data = {**options.json_data, **info.json} + return options + raise ValueError("Unexpected PageInfo state") From bf6dd816052d6ece746acc0339e5225d425dc1b3 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 16 Apr 2025 12:59:51 +0000 Subject: [PATCH 784/816] release: 1.74.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 9 +++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 71a38f2845..6603053537 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.74.0" + ".": "1.74.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 90af38d900..b03bbedb52 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 1.74.1 (2025-04-16) + +Full Changelog: [v1.74.0...v1.74.1](https://github.com/openai/openai-python/compare/v1.74.0...v1.74.1) + +### Chores + +* **internal:** base client updates ([06303b5](https://github.com/openai/openai-python/commit/06303b501f8c17040c495971a4ee79ae340f6f4a)) +* **internal:** bump pyright version ([9fd1c77](https://github.com/openai/openai-python/commit/9fd1c778c3231616bf1331cb1daa86fdfca4cb7f)) + ## 1.74.0 (2025-04-14) Full Changelog: [v1.73.0...v1.74.0](https://github.com/openai/openai-python/compare/v1.73.0...v1.74.0) diff --git a/pyproject.toml b/pyproject.toml index 244dd2ecb1..e2cd25f69c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.74.0" +version = "1.74.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index b203ed859f..5bbfee3232 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.74.0" # x-release-please-version +__version__ = "1.74.1" # x-release-please-version From c5ede36c6e2138e64f5194ecd5015ddc7cf50ec7 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 16 Apr 2025 16:42:28 +0000 Subject: [PATCH 785/816] feat(api): add o3 and o4-mini model IDs --- .stats.yml | 6 +- .../resources/chat/completions/completions.py | 82 +++++++---- src/openai/resources/completions.py | 24 +++- src/openai/resources/responses/responses.py | 130 +++++++++++++++++- src/openai/types/chat/chat_completion.py | 22 ++- .../types/chat/chat_completion_audio_param.py | 6 +- .../types/chat/chat_completion_chunk.py | 22 ++- .../types/chat/completion_create_params.py | 14 +- src/openai/types/completion_create_params.py | 5 +- src/openai/types/responses/response.py | 23 +++- .../types/responses/response_create_params.py | 23 +++- src/openai/types/shared/chat_model.py | 4 + src/openai/types/shared/reasoning.py | 15 +- src/openai/types/shared_params/chat_model.py | 4 + src/openai/types/shared_params/reasoning.py | 15 +- tests/api_resources/test_responses.py | 16 ++- 16 files changed, 342 insertions(+), 69 deletions(-) diff --git a/.stats.yml b/.stats.yml index b40485bd0a..848c5b5adb 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 97 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-a555f81249cb084f463dcefa4aba069f9341fdaf3dd6ac27d7f237fc90e8f488.yml -openapi_spec_hash: 8e590296cd1a54b9508510b0c7a2c45a -config_hash: 5ea32de61ff42fcf5e66cff8d9e247ea +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-5633633cc38734869cf7d993f7b549bb8e4d10e0ec45381ec2cd91507cd8eb8f.yml +openapi_spec_hash: c855121b2b2324b99499c9244c21d24d +config_hash: d20837393b73efdb19cd08e04c1cc9a1 diff --git a/src/openai/resources/chat/completions/completions.py b/src/openai/resources/chat/completions/completions.py index f9e380cc72..d6214225d8 100644 --- a/src/openai/resources/chat/completions/completions.py +++ b/src/openai/resources/chat/completions/completions.py @@ -99,7 +99,7 @@ def create( reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, - service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default", "flex"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, @@ -145,7 +145,7 @@ def create( [images](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio). - model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + model: Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a wide range of models with different capabilities, performance characteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models) to browse and compare @@ -201,7 +201,7 @@ def create( This value is now deprecated in favor of `max_completion_tokens`, and is not compatible with - [o1 series models](https://platform.openai.com/docs/guides/reasoning). + [o-series models](https://platform.openai.com/docs/guides/reasoning). metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format, and @@ -270,12 +270,17 @@ def create( latency guarentee. - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. + - If set to 'flex', the request will be processed with the Flex Processing + service tier. + [Learn more](https://platform.openai.com/docs/guides/flex-processing). - When not set, the default behavior is 'auto'. When this parameter is set, the response body will include the `service_tier` utilized. - stop: Up to 4 sequences where the API will stop generating further tokens. The + stop: Not supported with latest reasoning models `o3` and `o4-mini`. + + Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. store: Whether or not to store the output of this chat completion request for use in @@ -364,7 +369,7 @@ def create( reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, - service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default", "flex"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, @@ -409,7 +414,7 @@ def create( [images](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio). - model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + model: Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a wide range of models with different capabilities, performance characteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models) to browse and compare @@ -474,7 +479,7 @@ def create( This value is now deprecated in favor of `max_completion_tokens`, and is not compatible with - [o1 series models](https://platform.openai.com/docs/guides/reasoning). + [o-series models](https://platform.openai.com/docs/guides/reasoning). metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format, and @@ -543,12 +548,17 @@ def create( latency guarentee. - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. + - If set to 'flex', the request will be processed with the Flex Processing + service tier. + [Learn more](https://platform.openai.com/docs/guides/flex-processing). - When not set, the default behavior is 'auto'. When this parameter is set, the response body will include the `service_tier` utilized. - stop: Up to 4 sequences where the API will stop generating further tokens. The + stop: Not supported with latest reasoning models `o3` and `o4-mini`. + + Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. store: Whether or not to store the output of this chat completion request for use in @@ -628,7 +638,7 @@ def create( reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, - service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default", "flex"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, @@ -673,7 +683,7 @@ def create( [images](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio). - model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + model: Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a wide range of models with different capabilities, performance characteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models) to browse and compare @@ -738,7 +748,7 @@ def create( This value is now deprecated in favor of `max_completion_tokens`, and is not compatible with - [o1 series models](https://platform.openai.com/docs/guides/reasoning). + [o-series models](https://platform.openai.com/docs/guides/reasoning). metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format, and @@ -807,12 +817,17 @@ def create( latency guarentee. - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. + - If set to 'flex', the request will be processed with the Flex Processing + service tier. + [Learn more](https://platform.openai.com/docs/guides/flex-processing). - When not set, the default behavior is 'auto'. When this parameter is set, the response body will include the `service_tier` utilized. - stop: Up to 4 sequences where the API will stop generating further tokens. The + stop: Not supported with latest reasoning models `o3` and `o4-mini`. + + Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. store: Whether or not to store the output of this chat completion request for use in @@ -891,7 +906,7 @@ def create( reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, - service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default", "flex"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, @@ -1187,7 +1202,7 @@ async def create( reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, - service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default", "flex"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, @@ -1233,7 +1248,7 @@ async def create( [images](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio). - model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + model: Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a wide range of models with different capabilities, performance characteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models) to browse and compare @@ -1289,7 +1304,7 @@ async def create( This value is now deprecated in favor of `max_completion_tokens`, and is not compatible with - [o1 series models](https://platform.openai.com/docs/guides/reasoning). + [o-series models](https://platform.openai.com/docs/guides/reasoning). metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format, and @@ -1358,12 +1373,17 @@ async def create( latency guarentee. - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. + - If set to 'flex', the request will be processed with the Flex Processing + service tier. + [Learn more](https://platform.openai.com/docs/guides/flex-processing). - When not set, the default behavior is 'auto'. When this parameter is set, the response body will include the `service_tier` utilized. - stop: Up to 4 sequences where the API will stop generating further tokens. The + stop: Not supported with latest reasoning models `o3` and `o4-mini`. + + Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. store: Whether or not to store the output of this chat completion request for use in @@ -1452,7 +1472,7 @@ async def create( reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, - service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default", "flex"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, @@ -1497,7 +1517,7 @@ async def create( [images](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio). - model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + model: Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a wide range of models with different capabilities, performance characteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models) to browse and compare @@ -1562,7 +1582,7 @@ async def create( This value is now deprecated in favor of `max_completion_tokens`, and is not compatible with - [o1 series models](https://platform.openai.com/docs/guides/reasoning). + [o-series models](https://platform.openai.com/docs/guides/reasoning). metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format, and @@ -1631,12 +1651,17 @@ async def create( latency guarentee. - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. + - If set to 'flex', the request will be processed with the Flex Processing + service tier. + [Learn more](https://platform.openai.com/docs/guides/flex-processing). - When not set, the default behavior is 'auto'. When this parameter is set, the response body will include the `service_tier` utilized. - stop: Up to 4 sequences where the API will stop generating further tokens. The + stop: Not supported with latest reasoning models `o3` and `o4-mini`. + + Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. store: Whether or not to store the output of this chat completion request for use in @@ -1716,7 +1741,7 @@ async def create( reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, - service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default", "flex"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, @@ -1761,7 +1786,7 @@ async def create( [images](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio). - model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + model: Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a wide range of models with different capabilities, performance characteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models) to browse and compare @@ -1826,7 +1851,7 @@ async def create( This value is now deprecated in favor of `max_completion_tokens`, and is not compatible with - [o1 series models](https://platform.openai.com/docs/guides/reasoning). + [o-series models](https://platform.openai.com/docs/guides/reasoning). metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format, and @@ -1895,12 +1920,17 @@ async def create( latency guarentee. - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. + - If set to 'flex', the request will be processed with the Flex Processing + service tier. + [Learn more](https://platform.openai.com/docs/guides/flex-processing). - When not set, the default behavior is 'auto'. When this parameter is set, the response body will include the `service_tier` utilized. - stop: Up to 4 sequences where the API will stop generating further tokens. The + stop: Not supported with latest reasoning models `o3` and `o4-mini`. + + Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. store: Whether or not to store the output of this chat completion request for use in @@ -1979,7 +2009,7 @@ async def create( reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, response_format: completion_create_params.ResponseFormat | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, - service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default", "flex"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index 592696f7da..aebf35d1f1 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -159,7 +159,9 @@ def create( Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend. - stop: Up to 4 sequences where the API will stop generating further tokens. The + stop: Not supported with latest reasoning models `o3` and `o4-mini`. + + Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. stream: Whether to stream back partial progress. If set, tokens will be sent as @@ -319,7 +321,9 @@ def create( Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend. - stop: Up to 4 sequences where the API will stop generating further tokens. The + stop: Not supported with latest reasoning models `o3` and `o4-mini`. + + Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. stream_options: Options for streaming response. Only set this when you set `stream: true`. @@ -472,7 +476,9 @@ def create( Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend. - stop: Up to 4 sequences where the API will stop generating further tokens. The + stop: Not supported with latest reasoning models `o3` and `o4-mini`. + + Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. stream_options: Options for streaming response. Only set this when you set `stream: true`. @@ -703,7 +709,9 @@ async def create( Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend. - stop: Up to 4 sequences where the API will stop generating further tokens. The + stop: Not supported with latest reasoning models `o3` and `o4-mini`. + + Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. stream: Whether to stream back partial progress. If set, tokens will be sent as @@ -863,7 +871,9 @@ async def create( Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend. - stop: Up to 4 sequences where the API will stop generating further tokens. The + stop: Not supported with latest reasoning models `o3` and `o4-mini`. + + Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. stream_options: Options for streaming response. Only set this when you set `stream: true`. @@ -1016,7 +1026,9 @@ async def create( Determinism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend. - stop: Up to 4 sequences where the API will stop generating further tokens. The + stop: Not supported with latest reasoning models `o3` and `o4-mini`. + + Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. stream_options: Options for streaming response. Only set this when you set `stream: true`. diff --git a/src/openai/resources/responses/responses.py b/src/openai/resources/responses/responses.py index f8588178ed..f07b4d8c4a 100644 --- a/src/openai/resources/responses/responses.py +++ b/src/openai/resources/responses/responses.py @@ -89,6 +89,7 @@ def create( parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default", "flex"]] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -130,7 +131,7 @@ def create( - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) - [Function calling](https://platform.openai.com/docs/guides/function-calling) - model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + model: Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a wide range of models with different capabilities, performance characteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models) to browse and compare @@ -174,6 +175,24 @@ def create( Configuration options for [reasoning models](https://platform.openai.com/docs/guides/reasoning). + service_tier: Specifies the latency tier to use for processing the request. This parameter is + relevant for customers subscribed to the scale tier service: + + - If set to 'auto', and the Project is Scale tier enabled, the system will + utilize scale tier credits until they are exhausted. + - If set to 'auto', and the Project is not Scale tier enabled, the request will + be processed using the default service tier with a lower uptime SLA and no + latency guarentee. + - If set to 'default', the request will be processed using the default service + tier with a lower uptime SLA and no latency guarentee. + - If set to 'flex', the request will be processed with the Flex Processing + service tier. + [Learn more](https://platform.openai.com/docs/guides/flex-processing). + - When not set, the default behavior is 'auto'. + + When this parameter is set, the response body will include the `service_tier` + utilized. + store: Whether to store the generated model response for later retrieval via API. stream: If set to true, the model response data will be streamed to the client as it is @@ -255,6 +274,7 @@ def create( parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default", "flex"]] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, @@ -295,7 +315,7 @@ def create( - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) - [Function calling](https://platform.openai.com/docs/guides/function-calling) - model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + model: Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a wide range of models with different capabilities, performance characteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models) to browse and compare @@ -346,6 +366,24 @@ def create( Configuration options for [reasoning models](https://platform.openai.com/docs/guides/reasoning). + service_tier: Specifies the latency tier to use for processing the request. This parameter is + relevant for customers subscribed to the scale tier service: + + - If set to 'auto', and the Project is Scale tier enabled, the system will + utilize scale tier credits until they are exhausted. + - If set to 'auto', and the Project is not Scale tier enabled, the request will + be processed using the default service tier with a lower uptime SLA and no + latency guarentee. + - If set to 'default', the request will be processed using the default service + tier with a lower uptime SLA and no latency guarentee. + - If set to 'flex', the request will be processed with the Flex Processing + service tier. + [Learn more](https://platform.openai.com/docs/guides/flex-processing). + - When not set, the default behavior is 'auto'. + + When this parameter is set, the response body will include the `service_tier` + utilized. + store: Whether to store the generated model response for later retrieval via API. temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will @@ -420,6 +458,7 @@ def create( parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default", "flex"]] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, @@ -460,7 +499,7 @@ def create( - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) - [Function calling](https://platform.openai.com/docs/guides/function-calling) - model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + model: Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a wide range of models with different capabilities, performance characteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models) to browse and compare @@ -511,6 +550,24 @@ def create( Configuration options for [reasoning models](https://platform.openai.com/docs/guides/reasoning). + service_tier: Specifies the latency tier to use for processing the request. This parameter is + relevant for customers subscribed to the scale tier service: + + - If set to 'auto', and the Project is Scale tier enabled, the system will + utilize scale tier credits until they are exhausted. + - If set to 'auto', and the Project is not Scale tier enabled, the request will + be processed using the default service tier with a lower uptime SLA and no + latency guarentee. + - If set to 'default', the request will be processed using the default service + tier with a lower uptime SLA and no latency guarentee. + - If set to 'flex', the request will be processed with the Flex Processing + service tier. + [Learn more](https://platform.openai.com/docs/guides/flex-processing). + - When not set, the default behavior is 'auto'. + + When this parameter is set, the response body will include the `service_tier` + utilized. + store: Whether to store the generated model response for later retrieval via API. temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will @@ -584,6 +641,7 @@ def create( parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default", "flex"]] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -613,6 +671,7 @@ def create( "parallel_tool_calls": parallel_tool_calls, "previous_response_id": previous_response_id, "reasoning": reasoning, + "service_tier": service_tier, "store": store, "stream": stream, "temperature": temperature, @@ -903,6 +962,7 @@ async def create( parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default", "flex"]] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -944,7 +1004,7 @@ async def create( - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) - [Function calling](https://platform.openai.com/docs/guides/function-calling) - model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + model: Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a wide range of models with different capabilities, performance characteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models) to browse and compare @@ -988,6 +1048,24 @@ async def create( Configuration options for [reasoning models](https://platform.openai.com/docs/guides/reasoning). + service_tier: Specifies the latency tier to use for processing the request. This parameter is + relevant for customers subscribed to the scale tier service: + + - If set to 'auto', and the Project is Scale tier enabled, the system will + utilize scale tier credits until they are exhausted. + - If set to 'auto', and the Project is not Scale tier enabled, the request will + be processed using the default service tier with a lower uptime SLA and no + latency guarentee. + - If set to 'default', the request will be processed using the default service + tier with a lower uptime SLA and no latency guarentee. + - If set to 'flex', the request will be processed with the Flex Processing + service tier. + [Learn more](https://platform.openai.com/docs/guides/flex-processing). + - When not set, the default behavior is 'auto'. + + When this parameter is set, the response body will include the `service_tier` + utilized. + store: Whether to store the generated model response for later retrieval via API. stream: If set to true, the model response data will be streamed to the client as it is @@ -1069,6 +1147,7 @@ async def create( parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default", "flex"]] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, @@ -1109,7 +1188,7 @@ async def create( - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) - [Function calling](https://platform.openai.com/docs/guides/function-calling) - model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + model: Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a wide range of models with different capabilities, performance characteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models) to browse and compare @@ -1160,6 +1239,24 @@ async def create( Configuration options for [reasoning models](https://platform.openai.com/docs/guides/reasoning). + service_tier: Specifies the latency tier to use for processing the request. This parameter is + relevant for customers subscribed to the scale tier service: + + - If set to 'auto', and the Project is Scale tier enabled, the system will + utilize scale tier credits until they are exhausted. + - If set to 'auto', and the Project is not Scale tier enabled, the request will + be processed using the default service tier with a lower uptime SLA and no + latency guarentee. + - If set to 'default', the request will be processed using the default service + tier with a lower uptime SLA and no latency guarentee. + - If set to 'flex', the request will be processed with the Flex Processing + service tier. + [Learn more](https://platform.openai.com/docs/guides/flex-processing). + - When not set, the default behavior is 'auto'. + + When this parameter is set, the response body will include the `service_tier` + utilized. + store: Whether to store the generated model response for later retrieval via API. temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will @@ -1234,6 +1331,7 @@ async def create( parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default", "flex"]] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, text: ResponseTextConfigParam | NotGiven = NOT_GIVEN, @@ -1274,7 +1372,7 @@ async def create( - [Conversation state](https://platform.openai.com/docs/guides/conversation-state) - [Function calling](https://platform.openai.com/docs/guides/function-calling) - model: Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a + model: Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a wide range of models with different capabilities, performance characteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models) to browse and compare @@ -1325,6 +1423,24 @@ async def create( Configuration options for [reasoning models](https://platform.openai.com/docs/guides/reasoning). + service_tier: Specifies the latency tier to use for processing the request. This parameter is + relevant for customers subscribed to the scale tier service: + + - If set to 'auto', and the Project is Scale tier enabled, the system will + utilize scale tier credits until they are exhausted. + - If set to 'auto', and the Project is not Scale tier enabled, the request will + be processed using the default service tier with a lower uptime SLA and no + latency guarentee. + - If set to 'default', the request will be processed using the default service + tier with a lower uptime SLA and no latency guarentee. + - If set to 'flex', the request will be processed with the Flex Processing + service tier. + [Learn more](https://platform.openai.com/docs/guides/flex-processing). + - When not set, the default behavior is 'auto'. + + When this parameter is set, the response body will include the `service_tier` + utilized. + store: Whether to store the generated model response for later retrieval via API. temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will @@ -1398,6 +1514,7 @@ async def create( parallel_tool_calls: Optional[bool] | NotGiven = NOT_GIVEN, previous_response_id: Optional[str] | NotGiven = NOT_GIVEN, reasoning: Optional[Reasoning] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default", "flex"]] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN, temperature: Optional[float] | NotGiven = NOT_GIVEN, @@ -1427,6 +1544,7 @@ async def create( "parallel_tool_calls": parallel_tool_calls, "previous_response_id": previous_response_id, "reasoning": reasoning, + "service_tier": service_tier, "store": store, "stream": stream, "temperature": temperature, diff --git a/src/openai/types/chat/chat_completion.py b/src/openai/types/chat/chat_completion.py index cb812a2702..3a235f89a5 100644 --- a/src/openai/types/chat/chat_completion.py +++ b/src/openai/types/chat/chat_completion.py @@ -59,8 +59,26 @@ class ChatCompletion(BaseModel): object: Literal["chat.completion"] """The object type, which is always `chat.completion`.""" - service_tier: Optional[Literal["scale", "default"]] = None - """The service tier used for processing the request.""" + service_tier: Optional[Literal["auto", "default", "flex"]] = None + """Specifies the latency tier to use for processing the request. + + This parameter is relevant for customers subscribed to the scale tier service: + + - If set to 'auto', and the Project is Scale tier enabled, the system will + utilize scale tier credits until they are exhausted. + - If set to 'auto', and the Project is not Scale tier enabled, the request will + be processed using the default service tier with a lower uptime SLA and no + latency guarentee. + - If set to 'default', the request will be processed using the default service + tier with a lower uptime SLA and no latency guarentee. + - If set to 'flex', the request will be processed with the Flex Processing + service tier. + [Learn more](https://platform.openai.com/docs/guides/flex-processing). + - When not set, the default behavior is 'auto'. + + When this parameter is set, the response body will include the `service_tier` + utilized. + """ system_fingerprint: Optional[str] = None """This fingerprint represents the backend configuration that the model runs with. diff --git a/src/openai/types/chat/chat_completion_audio_param.py b/src/openai/types/chat/chat_completion_audio_param.py index b902f2667f..25caada177 100644 --- a/src/openai/types/chat/chat_completion_audio_param.py +++ b/src/openai/types/chat/chat_completion_audio_param.py @@ -9,7 +9,7 @@ class ChatCompletionAudioParam(TypedDict, total=False): - format: Required[Literal["wav", "mp3", "flac", "opus", "pcm16"]] + format: Required[Literal["wav", "aac", "mp3", "flac", "opus", "pcm16"]] """Specifies the output audio format. Must be one of `wav`, `mp3`, `flac`, `opus`, or `pcm16`. @@ -22,6 +22,6 @@ class ChatCompletionAudioParam(TypedDict, total=False): ] """The voice the model uses to respond. - Supported voices are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, and - `shimmer`. + Supported voices are `alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `nova`, + `onyx`, `sage`, and `shimmer`. """ diff --git a/src/openai/types/chat/chat_completion_chunk.py b/src/openai/types/chat/chat_completion_chunk.py index 31b9cb5456..6fe996dd95 100644 --- a/src/openai/types/chat/chat_completion_chunk.py +++ b/src/openai/types/chat/chat_completion_chunk.py @@ -128,8 +128,26 @@ class ChatCompletionChunk(BaseModel): object: Literal["chat.completion.chunk"] """The object type, which is always `chat.completion.chunk`.""" - service_tier: Optional[Literal["scale", "default"]] = None - """The service tier used for processing the request.""" + service_tier: Optional[Literal["auto", "default", "flex"]] = None + """Specifies the latency tier to use for processing the request. + + This parameter is relevant for customers subscribed to the scale tier service: + + - If set to 'auto', and the Project is Scale tier enabled, the system will + utilize scale tier credits until they are exhausted. + - If set to 'auto', and the Project is not Scale tier enabled, the request will + be processed using the default service tier with a lower uptime SLA and no + latency guarentee. + - If set to 'default', the request will be processed using the default service + tier with a lower uptime SLA and no latency guarentee. + - If set to 'flex', the request will be processed with the Flex Processing + service tier. + [Learn more](https://platform.openai.com/docs/guides/flex-processing). + - When not set, the default behavior is 'auto'. + + When this parameter is set, the response body will include the `service_tier` + utilized. + """ system_fingerprint: Optional[str] = None """ diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 05103fba91..60d5f53cdd 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -45,7 +45,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): """ model: Required[Union[str, ChatModel]] - """Model ID used to generate the response, like `gpt-4o` or `o1`. + """Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a wide range of models with different capabilities, performance characteristics, and price points. Refer to the @@ -123,7 +123,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): This value is now deprecated in favor of `max_completion_tokens`, and is not compatible with - [o1 series models](https://platform.openai.com/docs/guides/reasoning). + [o-series models](https://platform.openai.com/docs/guides/reasoning). """ metadata: Optional[Metadata] @@ -208,7 +208,7 @@ class CompletionCreateParamsBase(TypedDict, total=False): in the backend. """ - service_tier: Optional[Literal["auto", "default"]] + service_tier: Optional[Literal["auto", "default", "flex"]] """Specifies the latency tier to use for processing the request. This parameter is relevant for customers subscribed to the scale tier service: @@ -220,6 +220,9 @@ class CompletionCreateParamsBase(TypedDict, total=False): latency guarentee. - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarentee. + - If set to 'flex', the request will be processed with the Flex Processing + service tier. + [Learn more](https://platform.openai.com/docs/guides/flex-processing). - When not set, the default behavior is 'auto'. When this parameter is set, the response body will include the `service_tier` @@ -227,9 +230,10 @@ class CompletionCreateParamsBase(TypedDict, total=False): """ stop: Union[Optional[str], List[str], None] - """Up to 4 sequences where the API will stop generating further tokens. + """Not supported with latest reasoning models `o3` and `o4-mini`. - The returned text will not contain the stop sequence. + Up to 4 sequences where the API will stop generating further tokens. The + returned text will not contain the stop sequence. """ store: Optional[bool] diff --git a/src/openai/types/completion_create_params.py b/src/openai/types/completion_create_params.py index fdb1680d26..6ae20cff83 100644 --- a/src/openai/types/completion_create_params.py +++ b/src/openai/types/completion_create_params.py @@ -120,9 +120,10 @@ class CompletionCreateParamsBase(TypedDict, total=False): """ stop: Union[Optional[str], List[str], None] - """Up to 4 sequences where the API will stop generating further tokens. + """Not supported with latest reasoning models `o3` and `o4-mini`. - The returned text will not contain the stop sequence. + Up to 4 sequences where the API will stop generating further tokens. The + returned text will not contain the stop sequence. """ stream_options: Optional[ChatCompletionStreamOptionsParam] diff --git a/src/openai/types/responses/response.py b/src/openai/types/responses/response.py index 8cd1e01144..254f7e204b 100644 --- a/src/openai/types/responses/response.py +++ b/src/openai/types/responses/response.py @@ -62,7 +62,7 @@ class Response(BaseModel): """ model: ResponsesModel - """Model ID used to generate the response, like `gpt-4o` or `o1`. + """Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a wide range of models with different capabilities, performance characteristics, and price points. Refer to the @@ -149,6 +149,27 @@ class Response(BaseModel): [reasoning models](https://platform.openai.com/docs/guides/reasoning). """ + service_tier: Optional[Literal["auto", "default", "flex"]] = None + """Specifies the latency tier to use for processing the request. + + This parameter is relevant for customers subscribed to the scale tier service: + + - If set to 'auto', and the Project is Scale tier enabled, the system will + utilize scale tier credits until they are exhausted. + - If set to 'auto', and the Project is not Scale tier enabled, the request will + be processed using the default service tier with a lower uptime SLA and no + latency guarentee. + - If set to 'default', the request will be processed using the default service + tier with a lower uptime SLA and no latency guarentee. + - If set to 'flex', the request will be processed with the Flex Processing + service tier. + [Learn more](https://platform.openai.com/docs/guides/flex-processing). + - When not set, the default behavior is 'auto'. + + When this parameter is set, the response body will include the `service_tier` + utilized. + """ + status: Optional[ResponseStatus] = None """The status of the response generation. diff --git a/src/openai/types/responses/response_create_params.py b/src/openai/types/responses/response_create_params.py index ed82e678e5..3c0a9d7b8a 100644 --- a/src/openai/types/responses/response_create_params.py +++ b/src/openai/types/responses/response_create_params.py @@ -38,7 +38,7 @@ class ResponseCreateParamsBase(TypedDict, total=False): """ model: Required[ResponsesModel] - """Model ID used to generate the response, like `gpt-4o` or `o1`. + """Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a wide range of models with different capabilities, performance characteristics, and price points. Refer to the @@ -102,6 +102,27 @@ class ResponseCreateParamsBase(TypedDict, total=False): [reasoning models](https://platform.openai.com/docs/guides/reasoning). """ + service_tier: Optional[Literal["auto", "default", "flex"]] + """Specifies the latency tier to use for processing the request. + + This parameter is relevant for customers subscribed to the scale tier service: + + - If set to 'auto', and the Project is Scale tier enabled, the system will + utilize scale tier credits until they are exhausted. + - If set to 'auto', and the Project is not Scale tier enabled, the request will + be processed using the default service tier with a lower uptime SLA and no + latency guarentee. + - If set to 'default', the request will be processed using the default service + tier with a lower uptime SLA and no latency guarentee. + - If set to 'flex', the request will be processed with the Flex Processing + service tier. + [Learn more](https://platform.openai.com/docs/guides/flex-processing). + - When not set, the default behavior is 'auto'. + + When this parameter is set, the response body will include the `service_tier` + utilized. + """ + store: Optional[bool] """Whether to store the generated model response for later retrieval via API.""" diff --git a/src/openai/types/shared/chat_model.py b/src/openai/types/shared/chat_model.py index 30878b4347..4869cd325c 100644 --- a/src/openai/types/shared/chat_model.py +++ b/src/openai/types/shared/chat_model.py @@ -11,6 +11,10 @@ "gpt-4.1-2025-04-14", "gpt-4.1-mini-2025-04-14", "gpt-4.1-nano-2025-04-14", + "o4-mini", + "o4-mini-2025-04-16", + "o3", + "o3-2025-04-16", "o3-mini", "o3-mini-2025-01-31", "o1", diff --git a/src/openai/types/shared/reasoning.py b/src/openai/types/shared/reasoning.py index 78a396d738..107aab2e4a 100644 --- a/src/openai/types/shared/reasoning.py +++ b/src/openai/types/shared/reasoning.py @@ -19,10 +19,17 @@ class Reasoning(BaseModel): result in faster responses and fewer tokens used on reasoning in a response. """ - generate_summary: Optional[Literal["concise", "detailed"]] = None - """**computer_use_preview only** + generate_summary: Optional[Literal["auto", "concise", "detailed"]] = None + """**Deprecated:** use `summary` instead. A summary of the reasoning performed by the model. This can be useful for - debugging and understanding the model's reasoning process. One of `concise` or - `detailed`. + debugging and understanding the model's reasoning process. One of `auto`, + `concise`, or `detailed`. + """ + + summary: Optional[Literal["auto", "concise", "detailed"]] = None + """A summary of the reasoning performed by the model. + + This can be useful for debugging and understanding the model's reasoning + process. One of `auto`, `concise`, or `detailed`. """ diff --git a/src/openai/types/shared_params/chat_model.py b/src/openai/types/shared_params/chat_model.py index f606beb693..99e082fc11 100644 --- a/src/openai/types/shared_params/chat_model.py +++ b/src/openai/types/shared_params/chat_model.py @@ -13,6 +13,10 @@ "gpt-4.1-2025-04-14", "gpt-4.1-mini-2025-04-14", "gpt-4.1-nano-2025-04-14", + "o4-mini", + "o4-mini-2025-04-16", + "o3", + "o3-2025-04-16", "o3-mini", "o3-mini-2025-01-31", "o1", diff --git a/src/openai/types/shared_params/reasoning.py b/src/openai/types/shared_params/reasoning.py index 2953b895c4..73e1a008df 100644 --- a/src/openai/types/shared_params/reasoning.py +++ b/src/openai/types/shared_params/reasoning.py @@ -20,10 +20,17 @@ class Reasoning(TypedDict, total=False): result in faster responses and fewer tokens used on reasoning in a response. """ - generate_summary: Optional[Literal["concise", "detailed"]] - """**computer_use_preview only** + generate_summary: Optional[Literal["auto", "concise", "detailed"]] + """**Deprecated:** use `summary` instead. A summary of the reasoning performed by the model. This can be useful for - debugging and understanding the model's reasoning process. One of `concise` or - `detailed`. + debugging and understanding the model's reasoning process. One of `auto`, + `concise`, or `detailed`. + """ + + summary: Optional[Literal["auto", "concise", "detailed"]] + """A summary of the reasoning performed by the model. + + This can be useful for debugging and understanding the model's reasoning + process. One of `auto`, `concise`, or `detailed`. """ diff --git a/tests/api_resources/test_responses.py b/tests/api_resources/test_responses.py index e45a5becf3..3753af8fdb 100644 --- a/tests/api_resources/test_responses.py +++ b/tests/api_resources/test_responses.py @@ -38,8 +38,10 @@ def test_method_create_with_all_params_overload_1(self, client: OpenAI) -> None: previous_response_id="previous_response_id", reasoning={ "effort": "low", - "generate_summary": "concise", + "generate_summary": "auto", + "summary": "auto", }, + service_tier="auto", store=True, stream=False, temperature=1, @@ -116,8 +118,10 @@ def test_method_create_with_all_params_overload_2(self, client: OpenAI) -> None: previous_response_id="previous_response_id", reasoning={ "effort": "low", - "generate_summary": "concise", + "generate_summary": "auto", + "summary": "auto", }, + service_tier="auto", store=True, temperature=1, text={"format": {"type": "text"}}, @@ -280,8 +284,10 @@ async def test_method_create_with_all_params_overload_1(self, async_client: Asyn previous_response_id="previous_response_id", reasoning={ "effort": "low", - "generate_summary": "concise", + "generate_summary": "auto", + "summary": "auto", }, + service_tier="auto", store=True, stream=False, temperature=1, @@ -358,8 +364,10 @@ async def test_method_create_with_all_params_overload_2(self, async_client: Asyn previous_response_id="previous_response_id", reasoning={ "effort": "low", - "generate_summary": "concise", + "generate_summary": "auto", + "summary": "auto", }, + service_tier="auto", store=True, temperature=1, text={"format": {"type": "text"}}, From ed53107e10e6c86754866b48f8bd862659134ca8 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 16 Apr 2025 16:43:01 +0000 Subject: [PATCH 786/816] release: 1.75.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 6603053537..cb464946f0 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.74.1" + ".": "1.75.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index b03bbedb52..fb077b91c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.75.0 (2025-04-16) + +Full Changelog: [v1.74.1...v1.75.0](https://github.com/openai/openai-python/compare/v1.74.1...v1.75.0) + +### Features + +* **api:** add o3 and o4-mini model IDs ([4bacbd5](https://github.com/openai/openai-python/commit/4bacbd5503137e266c127dc643ebae496cb4f158)) + ## 1.74.1 (2025-04-16) Full Changelog: [v1.74.0...v1.74.1](https://github.com/openai/openai-python/compare/v1.74.0...v1.74.1) diff --git a/pyproject.toml b/pyproject.toml index e2cd25f69c..b5648e9e51 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.74.1" +version = "1.75.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 5bbfee3232..8eab2d7416 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.74.1" # x-release-please-version +__version__ = "1.75.0" # x-release-please-version From 5d65ddfa34ed9c910f9a695e0a52f1458cc95b71 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 18 Apr 2025 10:17:31 +0000 Subject: [PATCH 787/816] chore(internal): update models test --- tests/test_models.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/test_models.py b/tests/test_models.py index 4b18940b49..440e17a08c 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -492,12 +492,15 @@ class Model(BaseModel): resource_id: Optional[str] = None m = Model.construct() + assert m.resource_id is None assert "resource_id" not in m.model_fields_set m = Model.construct(resource_id=None) + assert m.resource_id is None assert "resource_id" in m.model_fields_set m = Model.construct(resource_id="foo") + assert m.resource_id == "foo" assert "resource_id" in m.model_fields_set From 15902dc595a69ca37452d8bf9682ebf229d460d3 Mon Sep 17 00:00:00 2001 From: dogisgreat Date: Mon, 21 Apr 2025 14:23:33 -0400 Subject: [PATCH 788/816] chore: update completion parse signature --- src/openai/resources/beta/chat/completions.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/openai/resources/beta/chat/completions.py b/src/openai/resources/beta/chat/completions.py index 545a3f4087..80e015615f 100644 --- a/src/openai/resources/beta/chat/completions.py +++ b/src/openai/resources/beta/chat/completions.py @@ -81,7 +81,7 @@ def parse( presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, - service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default", "flex"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, @@ -228,7 +228,7 @@ def stream( presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, - service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default", "flex"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, @@ -360,7 +360,7 @@ async def parse( presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, - service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default", "flex"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, @@ -507,7 +507,7 @@ def stream( presence_penalty: Optional[float] | NotGiven = NOT_GIVEN, reasoning_effort: Optional[ReasoningEffort] | NotGiven = NOT_GIVEN, seed: Optional[int] | NotGiven = NOT_GIVEN, - service_tier: Optional[Literal["auto", "default"]] | NotGiven = NOT_GIVEN, + service_tier: Optional[Literal["auto", "default", "flex"]] | NotGiven = NOT_GIVEN, stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN, store: Optional[bool] | NotGiven = NOT_GIVEN, stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN, From 271d979a0893b7afa892d5109968c3fcfb6c13b4 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 22 Apr 2025 20:12:49 +0000 Subject: [PATCH 789/816] chore(ci): add timeout thresholds for CI jobs --- .github/workflows/ci.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6f9cf84bb4..d148b34a9e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -10,6 +10,7 @@ on: jobs: lint: + timeout-minutes: 10 name: lint runs-on: ubuntu-latest steps: @@ -30,6 +31,7 @@ jobs: run: ./scripts/lint test: + timeout-minutes: 10 name: test runs-on: ubuntu-latest steps: @@ -50,6 +52,7 @@ jobs: run: ./scripts/test examples: + timeout-minutes: 10 name: examples runs-on: ubuntu-latest if: github.repository == 'openai/openai-python' From 1157528d952d02036058943f08fba99ef0d79d4f Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 22 Apr 2025 20:37:29 +0000 Subject: [PATCH 790/816] chore(internal): import reformatting --- src/openai/resources/audio/speech.py | 5 +---- src/openai/resources/audio/transcriptions.py | 8 +------- src/openai/resources/audio/translations.py | 7 +------ src/openai/resources/batches.py | 5 +---- src/openai/resources/beta/assistants.py | 5 +---- src/openai/resources/beta/realtime/sessions.py | 5 +---- .../resources/beta/realtime/transcription_sessions.py | 5 +---- src/openai/resources/beta/threads/messages.py | 5 +---- src/openai/resources/beta/threads/runs/steps.py | 5 +---- src/openai/resources/beta/threads/threads.py | 6 +----- src/openai/resources/chat/completions/completions.py | 6 +----- src/openai/resources/completions.py | 6 +----- src/openai/resources/evals/evals.py | 5 +---- src/openai/resources/evals/runs/runs.py | 5 +---- src/openai/resources/files.py | 7 +------ .../resources/fine_tuning/checkpoints/permissions.py | 5 +---- src/openai/resources/fine_tuning/jobs/jobs.py | 5 +---- src/openai/resources/images.py | 7 +------ src/openai/resources/moderations.py | 5 +---- src/openai/resources/responses/responses.py | 7 +------ src/openai/resources/uploads/parts.py | 7 +------ src/openai/resources/uploads/uploads.py | 5 +---- src/openai/resources/vector_stores/file_batches.py | 6 +----- src/openai/resources/vector_stores/files.py | 6 +----- src/openai/resources/vector_stores/vector_stores.py | 5 +---- 25 files changed, 25 insertions(+), 118 deletions(-) diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index 1ee53db9d5..fad18dcdf5 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -9,10 +9,7 @@ from ... import _legacy_response from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ..._utils import ( - maybe_transform, - async_maybe_transform, -) +from ..._utils import maybe_transform, async_maybe_transform from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import ( diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index 7e62f70f60..0c7ebca7a6 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -11,13 +11,7 @@ from ... import _legacy_response from ...types import AudioResponseFormat from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes -from ..._utils import ( - extract_files, - required_args, - maybe_transform, - deepcopy_minimal, - async_maybe_transform, -) +from ..._utils import extract_files, required_args, maybe_transform, deepcopy_minimal, async_maybe_transform from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index f55dbd0ee5..28b577ce2e 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -10,12 +10,7 @@ from ... import _legacy_response from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes -from ..._utils import ( - extract_files, - maybe_transform, - deepcopy_minimal, - async_maybe_transform, -) +from ..._utils import extract_files, maybe_transform, deepcopy_minimal, async_maybe_transform from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper diff --git a/src/openai/resources/batches.py b/src/openai/resources/batches.py index b7a299be12..26ea498b31 100644 --- a/src/openai/resources/batches.py +++ b/src/openai/resources/batches.py @@ -10,10 +10,7 @@ from .. import _legacy_response from ..types import batch_list_params, batch_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from .._utils import ( - maybe_transform, - async_maybe_transform, -) +from .._utils import maybe_transform, async_maybe_transform from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper diff --git a/src/openai/resources/beta/assistants.py b/src/openai/resources/beta/assistants.py index 43f6a7f135..9059d93616 100644 --- a/src/openai/resources/beta/assistants.py +++ b/src/openai/resources/beta/assistants.py @@ -9,10 +9,7 @@ from ... import _legacy_response from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ..._utils import ( - maybe_transform, - async_maybe_transform, -) +from ..._utils import maybe_transform, async_maybe_transform from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper diff --git a/src/openai/resources/beta/realtime/sessions.py b/src/openai/resources/beta/realtime/sessions.py index 3e1c956fe4..3c0d4d47c1 100644 --- a/src/openai/resources/beta/realtime/sessions.py +++ b/src/openai/resources/beta/realtime/sessions.py @@ -9,10 +9,7 @@ from .... import _legacy_response from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ...._utils import ( - maybe_transform, - async_maybe_transform, -) +from ...._utils import maybe_transform, async_maybe_transform from ...._compat import cached_property from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper diff --git a/src/openai/resources/beta/realtime/transcription_sessions.py b/src/openai/resources/beta/realtime/transcription_sessions.py index 0917da71fa..dbcb1bb33b 100644 --- a/src/openai/resources/beta/realtime/transcription_sessions.py +++ b/src/openai/resources/beta/realtime/transcription_sessions.py @@ -9,10 +9,7 @@ from .... import _legacy_response from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ...._utils import ( - maybe_transform, - async_maybe_transform, -) +from ...._utils import maybe_transform, async_maybe_transform from ...._compat import cached_property from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper diff --git a/src/openai/resources/beta/threads/messages.py b/src/openai/resources/beta/threads/messages.py index e3374aba37..3a8913ef16 100644 --- a/src/openai/resources/beta/threads/messages.py +++ b/src/openai/resources/beta/threads/messages.py @@ -9,10 +9,7 @@ from .... import _legacy_response from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ...._utils import ( - maybe_transform, - async_maybe_transform, -) +from ...._utils import maybe_transform, async_maybe_transform from ...._compat import cached_property from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper diff --git a/src/openai/resources/beta/threads/runs/steps.py b/src/openai/resources/beta/threads/runs/steps.py index 709c729d45..3d2148687b 100644 --- a/src/openai/resources/beta/threads/runs/steps.py +++ b/src/openai/resources/beta/threads/runs/steps.py @@ -9,10 +9,7 @@ from ..... import _legacy_response from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ....._utils import ( - maybe_transform, - async_maybe_transform, -) +from ....._utils import maybe_transform, async_maybe_transform from ....._compat import cached_property from ....._resource import SyncAPIResource, AsyncAPIResource from ....._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index c697be416d..9c6954a9b3 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -18,11 +18,7 @@ AsyncMessagesWithStreamingResponse, ) from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ...._utils import ( - required_args, - maybe_transform, - async_maybe_transform, -) +from ...._utils import required_args, maybe_transform, async_maybe_transform from .runs.runs import ( Runs, AsyncRuns, diff --git a/src/openai/resources/chat/completions/completions.py b/src/openai/resources/chat/completions/completions.py index d6214225d8..0ab105a389 100644 --- a/src/openai/resources/chat/completions/completions.py +++ b/src/openai/resources/chat/completions/completions.py @@ -19,11 +19,7 @@ AsyncMessagesWithStreamingResponse, ) from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ...._utils import ( - required_args, - maybe_transform, - async_maybe_transform, -) +from ...._utils import required_args, maybe_transform, async_maybe_transform from ...._compat import cached_property from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index aebf35d1f1..43b923b9b9 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -10,11 +10,7 @@ from .. import _legacy_response from ..types import completion_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from .._utils import ( - required_args, - maybe_transform, - async_maybe_transform, -) +from .._utils import required_args, maybe_transform, async_maybe_transform from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper diff --git a/src/openai/resources/evals/evals.py b/src/openai/resources/evals/evals.py index 24a0350cfb..30ac4bdf32 100644 --- a/src/openai/resources/evals/evals.py +++ b/src/openai/resources/evals/evals.py @@ -10,10 +10,7 @@ from ... import _legacy_response from ...types import eval_list_params, eval_create_params, eval_update_params from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ..._utils import ( - maybe_transform, - async_maybe_transform, -) +from ..._utils import maybe_transform, async_maybe_transform from ..._compat import cached_property from .runs.runs import ( Runs, diff --git a/src/openai/resources/evals/runs/runs.py b/src/openai/resources/evals/runs/runs.py index 6df0b6d121..9c626d0903 100644 --- a/src/openai/resources/evals/runs/runs.py +++ b/src/openai/resources/evals/runs/runs.py @@ -9,10 +9,7 @@ from .... import _legacy_response from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ...._utils import ( - maybe_transform, - async_maybe_transform, -) +from ...._utils import maybe_transform, async_maybe_transform from ...._compat import cached_property from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index 2eaa4a6401..179af870ba 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -12,12 +12,7 @@ from .. import _legacy_response from ..types import FilePurpose, file_list_params, file_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes -from .._utils import ( - extract_files, - maybe_transform, - deepcopy_minimal, - async_maybe_transform, -) +from .._utils import extract_files, maybe_transform, deepcopy_minimal, async_maybe_transform from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import ( diff --git a/src/openai/resources/fine_tuning/checkpoints/permissions.py b/src/openai/resources/fine_tuning/checkpoints/permissions.py index beb7b099d3..b2bcb33020 100644 --- a/src/openai/resources/fine_tuning/checkpoints/permissions.py +++ b/src/openai/resources/fine_tuning/checkpoints/permissions.py @@ -9,10 +9,7 @@ from .... import _legacy_response from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ...._utils import ( - maybe_transform, - async_maybe_transform, -) +from ...._utils import maybe_transform, async_maybe_transform from ...._compat import cached_property from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper diff --git a/src/openai/resources/fine_tuning/jobs/jobs.py b/src/openai/resources/fine_tuning/jobs/jobs.py index bbeff60bc6..90619c8609 100644 --- a/src/openai/resources/fine_tuning/jobs/jobs.py +++ b/src/openai/resources/fine_tuning/jobs/jobs.py @@ -9,10 +9,7 @@ from .... import _legacy_response from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ...._utils import ( - maybe_transform, - async_maybe_transform, -) +from ...._utils import maybe_transform, async_maybe_transform from ...._compat import cached_property from .checkpoints import ( Checkpoints, diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py index 30473c14f7..e3398930e9 100644 --- a/src/openai/resources/images.py +++ b/src/openai/resources/images.py @@ -10,12 +10,7 @@ from .. import _legacy_response from ..types import image_edit_params, image_generate_params, image_create_variation_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes -from .._utils import ( - extract_files, - maybe_transform, - deepcopy_minimal, - async_maybe_transform, -) +from .._utils import extract_files, maybe_transform, deepcopy_minimal, async_maybe_transform from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper diff --git a/src/openai/resources/moderations.py b/src/openai/resources/moderations.py index a8f03142bc..f7a8b52c23 100644 --- a/src/openai/resources/moderations.py +++ b/src/openai/resources/moderations.py @@ -9,10 +9,7 @@ from .. import _legacy_response from ..types import moderation_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from .._utils import ( - maybe_transform, - async_maybe_transform, -) +from .._utils import maybe_transform, async_maybe_transform from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper diff --git a/src/openai/resources/responses/responses.py b/src/openai/resources/responses/responses.py index f07b4d8c4a..4a0687f9f3 100644 --- a/src/openai/resources/responses/responses.py +++ b/src/openai/resources/responses/responses.py @@ -10,12 +10,7 @@ from ... import _legacy_response from ..._types import NOT_GIVEN, Body, Query, Headers, NoneType, NotGiven -from ..._utils import ( - is_given, - required_args, - maybe_transform, - async_maybe_transform, -) +from ..._utils import is_given, required_args, maybe_transform, async_maybe_transform from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper diff --git a/src/openai/resources/uploads/parts.py b/src/openai/resources/uploads/parts.py index 777469ac8e..a32f4eb1d2 100644 --- a/src/openai/resources/uploads/parts.py +++ b/src/openai/resources/uploads/parts.py @@ -8,12 +8,7 @@ from ... import _legacy_response from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes -from ..._utils import ( - extract_files, - maybe_transform, - deepcopy_minimal, - async_maybe_transform, -) +from ..._utils import extract_files, maybe_transform, deepcopy_minimal, async_maybe_transform from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper diff --git a/src/openai/resources/uploads/uploads.py b/src/openai/resources/uploads/uploads.py index 9297dbc2c3..ecfcee4800 100644 --- a/src/openai/resources/uploads/uploads.py +++ b/src/openai/resources/uploads/uploads.py @@ -23,10 +23,7 @@ ) from ...types import FilePurpose, upload_create_params, upload_complete_params from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ..._utils import ( - maybe_transform, - async_maybe_transform, -) +from ..._utils import maybe_transform, async_maybe_transform from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper diff --git a/src/openai/resources/vector_stores/file_batches.py b/src/openai/resources/vector_stores/file_batches.py index 9b4b64d35e..4dd4430b71 100644 --- a/src/openai/resources/vector_stores/file_batches.py +++ b/src/openai/resources/vector_stores/file_batches.py @@ -13,11 +13,7 @@ from ... import _legacy_response from ...types import FileChunkingStrategyParam from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes -from ..._utils import ( - is_given, - maybe_transform, - async_maybe_transform, -) +from ..._utils import is_given, maybe_transform, async_maybe_transform from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper diff --git a/src/openai/resources/vector_stores/files.py b/src/openai/resources/vector_stores/files.py index 7d93798adf..f860384629 100644 --- a/src/openai/resources/vector_stores/files.py +++ b/src/openai/resources/vector_stores/files.py @@ -10,11 +10,7 @@ from ... import _legacy_response from ...types import FileChunkingStrategyParam from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes -from ..._utils import ( - is_given, - maybe_transform, - async_maybe_transform, -) +from ..._utils import is_given, maybe_transform, async_maybe_transform from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper diff --git a/src/openai/resources/vector_stores/vector_stores.py b/src/openai/resources/vector_stores/vector_stores.py index aaa6ed2757..9fc17b183b 100644 --- a/src/openai/resources/vector_stores/vector_stores.py +++ b/src/openai/resources/vector_stores/vector_stores.py @@ -24,10 +24,7 @@ vector_store_update_params, ) from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven -from ..._utils import ( - maybe_transform, - async_maybe_transform, -) +from ..._utils import maybe_transform, async_maybe_transform from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper From 1e7dea203321d1ca50d3607aaa33f29fbe534a91 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 22 Apr 2025 22:01:33 +0000 Subject: [PATCH 791/816] chore(internal): fix list file params --- src/openai/_utils/_utils.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/openai/_utils/_utils.py b/src/openai/_utils/_utils.py index d6734e6b8f..1e7d013b51 100644 --- a/src/openai/_utils/_utils.py +++ b/src/openai/_utils/_utils.py @@ -76,8 +76,16 @@ def _extract_items( from .._files import assert_is_file_content # We have exhausted the path, return the entry we found. - assert_is_file_content(obj, key=flattened_key) assert flattened_key is not None + + if is_list(obj): + files: list[tuple[str, FileTypes]] = [] + for entry in obj: + assert_is_file_content(entry, key=flattened_key + "[]" if flattened_key else "") + files.append((flattened_key + "[]", cast(FileTypes, entry))) + return files + + assert_is_file_content(obj, key=flattened_key) return [(flattened_key, cast(FileTypes, obj))] index += 1 From 7de6c5ce26a23ca450994c412d12e4244d2bb43c Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 22 Apr 2025 22:53:21 +0000 Subject: [PATCH 792/816] chore(internal): refactor retries to not use recursion --- src/openai/_base_client.py | 417 ++++++++++++++++--------------------- 1 file changed, 177 insertions(+), 240 deletions(-) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 8b43a20699..a0f9cce7d8 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -439,8 +439,7 @@ def _build_headers(self, options: FinalRequestOptions, *, retries_taken: int = 0 headers = httpx.Headers(headers_dict) idempotency_header = self._idempotency_header - if idempotency_header and options.method.lower() != "get" and idempotency_header not in headers: - options.idempotency_key = options.idempotency_key or self._idempotency_key() + if idempotency_header and options.idempotency_key and idempotency_header not in headers: headers[idempotency_header] = options.idempotency_key # Don't set these headers if they were already set or removed by the caller. We check @@ -905,7 +904,6 @@ def request( self, cast_to: Type[ResponseT], options: FinalRequestOptions, - remaining_retries: Optional[int] = None, *, stream: Literal[True], stream_cls: Type[_StreamT], @@ -916,7 +914,6 @@ def request( self, cast_to: Type[ResponseT], options: FinalRequestOptions, - remaining_retries: Optional[int] = None, *, stream: Literal[False] = False, ) -> ResponseT: ... @@ -926,7 +923,6 @@ def request( self, cast_to: Type[ResponseT], options: FinalRequestOptions, - remaining_retries: Optional[int] = None, *, stream: bool = False, stream_cls: Type[_StreamT] | None = None, @@ -936,126 +932,110 @@ def request( self, cast_to: Type[ResponseT], options: FinalRequestOptions, - remaining_retries: Optional[int] = None, *, stream: bool = False, stream_cls: type[_StreamT] | None = None, ) -> ResponseT | _StreamT: - if remaining_retries is not None: - retries_taken = options.get_max_retries(self.max_retries) - remaining_retries - else: - retries_taken = 0 - - return self._request( - cast_to=cast_to, - options=options, - stream=stream, - stream_cls=stream_cls, - retries_taken=retries_taken, - ) + cast_to = self._maybe_override_cast_to(cast_to, options) - def _request( - self, - *, - cast_to: Type[ResponseT], - options: FinalRequestOptions, - retries_taken: int, - stream: bool, - stream_cls: type[_StreamT] | None, - ) -> ResponseT | _StreamT: # create a copy of the options we were given so that if the # options are mutated later & we then retry, the retries are # given the original options input_options = model_copy(options) - - cast_to = self._maybe_override_cast_to(cast_to, options) - options = self._prepare_options(options) - - remaining_retries = options.get_max_retries(self.max_retries) - retries_taken - request = self._build_request(options, retries_taken=retries_taken) - self._prepare_request(request) - - if options.idempotency_key: + if input_options.idempotency_key is None and input_options.method.lower() != "get": # ensure the idempotency key is reused between requests - input_options.idempotency_key = options.idempotency_key + input_options.idempotency_key = self._idempotency_key() - kwargs: HttpxSendArgs = {} - if self.custom_auth is not None: - kwargs["auth"] = self.custom_auth + response: httpx.Response | None = None + max_retries = input_options.get_max_retries(self.max_retries) - log.debug("Sending HTTP Request: %s %s", request.method, request.url) + retries_taken = 0 + for retries_taken in range(max_retries + 1): + options = model_copy(input_options) + options = self._prepare_options(options) - try: - response = self._client.send( - request, - stream=stream or self._should_stream_response_body(request=request), - **kwargs, - ) - except httpx.TimeoutException as err: - log.debug("Encountered httpx.TimeoutException", exc_info=True) + remaining_retries = max_retries - retries_taken + request = self._build_request(options, retries_taken=retries_taken) + self._prepare_request(request) - if remaining_retries > 0: - return self._retry_request( - input_options, - cast_to, - retries_taken=retries_taken, - stream=stream, - stream_cls=stream_cls, - response_headers=None, - ) + kwargs: HttpxSendArgs = {} + if self.custom_auth is not None: + kwargs["auth"] = self.custom_auth - log.debug("Raising timeout error") - raise APITimeoutError(request=request) from err - except Exception as err: - log.debug("Encountered Exception", exc_info=True) + log.debug("Sending HTTP Request: %s %s", request.method, request.url) - if remaining_retries > 0: - return self._retry_request( - input_options, - cast_to, - retries_taken=retries_taken, - stream=stream, - stream_cls=stream_cls, - response_headers=None, + response = None + try: + response = self._client.send( + request, + stream=stream or self._should_stream_response_body(request=request), + **kwargs, ) + except httpx.TimeoutException as err: + log.debug("Encountered httpx.TimeoutException", exc_info=True) + + if remaining_retries > 0: + self._sleep_for_retry( + retries_taken=retries_taken, + max_retries=max_retries, + options=input_options, + response=None, + ) + continue + + log.debug("Raising timeout error") + raise APITimeoutError(request=request) from err + except Exception as err: + log.debug("Encountered Exception", exc_info=True) + + if remaining_retries > 0: + self._sleep_for_retry( + retries_taken=retries_taken, + max_retries=max_retries, + options=input_options, + response=None, + ) + continue + + log.debug("Raising connection error") + raise APIConnectionError(request=request) from err + + log.debug( + 'HTTP Response: %s %s "%i %s" %s', + request.method, + request.url, + response.status_code, + response.reason_phrase, + response.headers, + ) + log.debug("request_id: %s", response.headers.get("x-request-id")) - log.debug("Raising connection error") - raise APIConnectionError(request=request) from err - - log.debug( - 'HTTP Response: %s %s "%i %s" %s', - request.method, - request.url, - response.status_code, - response.reason_phrase, - response.headers, - ) - log.debug("request_id: %s", response.headers.get("x-request-id")) + try: + response.raise_for_status() + except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code + log.debug("Encountered httpx.HTTPStatusError", exc_info=True) + + if remaining_retries > 0 and self._should_retry(err.response): + err.response.close() + self._sleep_for_retry( + retries_taken=retries_taken, + max_retries=max_retries, + options=input_options, + response=response, + ) + continue - try: - response.raise_for_status() - except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code - log.debug("Encountered httpx.HTTPStatusError", exc_info=True) - - if remaining_retries > 0 and self._should_retry(err.response): - err.response.close() - return self._retry_request( - input_options, - cast_to, - retries_taken=retries_taken, - response_headers=err.response.headers, - stream=stream, - stream_cls=stream_cls, - ) + # If the response is streamed then we need to explicitly read the response + # to completion before attempting to access the response text. + if not err.response.is_closed: + err.response.read() - # If the response is streamed then we need to explicitly read the response - # to completion before attempting to access the response text. - if not err.response.is_closed: - err.response.read() + log.debug("Re-raising status error") + raise self._make_status_error_from_response(err.response) from None - log.debug("Re-raising status error") - raise self._make_status_error_from_response(err.response) from None + break + assert response is not None, "could not resolve response (should never happen)" return self._process_response( cast_to=cast_to, options=options, @@ -1065,37 +1045,20 @@ def _request( retries_taken=retries_taken, ) - def _retry_request( - self, - options: FinalRequestOptions, - cast_to: Type[ResponseT], - *, - retries_taken: int, - response_headers: httpx.Headers | None, - stream: bool, - stream_cls: type[_StreamT] | None, - ) -> ResponseT | _StreamT: - remaining_retries = options.get_max_retries(self.max_retries) - retries_taken + def _sleep_for_retry( + self, *, retries_taken: int, max_retries: int, options: FinalRequestOptions, response: httpx.Response | None + ) -> None: + remaining_retries = max_retries - retries_taken if remaining_retries == 1: log.debug("1 retry left") else: log.debug("%i retries left", remaining_retries) - timeout = self._calculate_retry_timeout(remaining_retries, options, response_headers) + timeout = self._calculate_retry_timeout(remaining_retries, options, response.headers if response else None) log.info("Retrying request to %s in %f seconds", options.url, timeout) - # In a synchronous context we are blocking the entire thread. Up to the library user to run the client in a - # different thread if necessary. time.sleep(timeout) - return self._request( - options=options, - cast_to=cast_to, - retries_taken=retries_taken + 1, - stream=stream, - stream_cls=stream_cls, - ) - def _process_response( self, *, @@ -1453,7 +1416,6 @@ async def request( options: FinalRequestOptions, *, stream: Literal[False] = False, - remaining_retries: Optional[int] = None, ) -> ResponseT: ... @overload @@ -1464,7 +1426,6 @@ async def request( *, stream: Literal[True], stream_cls: type[_AsyncStreamT], - remaining_retries: Optional[int] = None, ) -> _AsyncStreamT: ... @overload @@ -1475,7 +1436,6 @@ async def request( *, stream: bool, stream_cls: type[_AsyncStreamT] | None = None, - remaining_retries: Optional[int] = None, ) -> ResponseT | _AsyncStreamT: ... async def request( @@ -1485,120 +1445,112 @@ async def request( *, stream: bool = False, stream_cls: type[_AsyncStreamT] | None = None, - remaining_retries: Optional[int] = None, - ) -> ResponseT | _AsyncStreamT: - if remaining_retries is not None: - retries_taken = options.get_max_retries(self.max_retries) - remaining_retries - else: - retries_taken = 0 - - return await self._request( - cast_to=cast_to, - options=options, - stream=stream, - stream_cls=stream_cls, - retries_taken=retries_taken, - ) - - async def _request( - self, - cast_to: Type[ResponseT], - options: FinalRequestOptions, - *, - stream: bool, - stream_cls: type[_AsyncStreamT] | None, - retries_taken: int, ) -> ResponseT | _AsyncStreamT: if self._platform is None: # `get_platform` can make blocking IO calls so we # execute it earlier while we are in an async context self._platform = await asyncify(get_platform)() + cast_to = self._maybe_override_cast_to(cast_to, options) + # create a copy of the options we were given so that if the # options are mutated later & we then retry, the retries are # given the original options input_options = model_copy(options) - - cast_to = self._maybe_override_cast_to(cast_to, options) - options = await self._prepare_options(options) - - remaining_retries = options.get_max_retries(self.max_retries) - retries_taken - request = self._build_request(options, retries_taken=retries_taken) - await self._prepare_request(request) - - if options.idempotency_key: + if input_options.idempotency_key is None and input_options.method.lower() != "get": # ensure the idempotency key is reused between requests - input_options.idempotency_key = options.idempotency_key + input_options.idempotency_key = self._idempotency_key() - kwargs: HttpxSendArgs = {} - if self.custom_auth is not None: - kwargs["auth"] = self.custom_auth + response: httpx.Response | None = None + max_retries = input_options.get_max_retries(self.max_retries) - try: - response = await self._client.send( - request, - stream=stream or self._should_stream_response_body(request=request), - **kwargs, - ) - except httpx.TimeoutException as err: - log.debug("Encountered httpx.TimeoutException", exc_info=True) + retries_taken = 0 + for retries_taken in range(max_retries + 1): + options = model_copy(input_options) + options = await self._prepare_options(options) - if remaining_retries > 0: - return await self._retry_request( - input_options, - cast_to, - retries_taken=retries_taken, - stream=stream, - stream_cls=stream_cls, - response_headers=None, - ) + remaining_retries = max_retries - retries_taken + request = self._build_request(options, retries_taken=retries_taken) + await self._prepare_request(request) - log.debug("Raising timeout error") - raise APITimeoutError(request=request) from err - except Exception as err: - log.debug("Encountered Exception", exc_info=True) + kwargs: HttpxSendArgs = {} + if self.custom_auth is not None: + kwargs["auth"] = self.custom_auth - if remaining_retries > 0: - return await self._retry_request( - input_options, - cast_to, - retries_taken=retries_taken, - stream=stream, - stream_cls=stream_cls, - response_headers=None, - ) + log.debug("Sending HTTP Request: %s %s", request.method, request.url) - log.debug("Raising connection error") - raise APIConnectionError(request=request) from err + response = None + try: + response = await self._client.send( + request, + stream=stream or self._should_stream_response_body(request=request), + **kwargs, + ) + except httpx.TimeoutException as err: + log.debug("Encountered httpx.TimeoutException", exc_info=True) + + if remaining_retries > 0: + await self._sleep_for_retry( + retries_taken=retries_taken, + max_retries=max_retries, + options=input_options, + response=None, + ) + continue + + log.debug("Raising timeout error") + raise APITimeoutError(request=request) from err + except Exception as err: + log.debug("Encountered Exception", exc_info=True) + + if remaining_retries > 0: + await self._sleep_for_retry( + retries_taken=retries_taken, + max_retries=max_retries, + options=input_options, + response=None, + ) + continue + + log.debug("Raising connection error") + raise APIConnectionError(request=request) from err + + log.debug( + 'HTTP Response: %s %s "%i %s" %s', + request.method, + request.url, + response.status_code, + response.reason_phrase, + response.headers, + ) + log.debug("request_id: %s", response.headers.get("x-request-id")) - log.debug( - 'HTTP Request: %s %s "%i %s"', request.method, request.url, response.status_code, response.reason_phrase - ) + try: + response.raise_for_status() + except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code + log.debug("Encountered httpx.HTTPStatusError", exc_info=True) + + if remaining_retries > 0 and self._should_retry(err.response): + await err.response.aclose() + await self._sleep_for_retry( + retries_taken=retries_taken, + max_retries=max_retries, + options=input_options, + response=response, + ) + continue - try: - response.raise_for_status() - except httpx.HTTPStatusError as err: # thrown on 4xx and 5xx status code - log.debug("Encountered httpx.HTTPStatusError", exc_info=True) - - if remaining_retries > 0 and self._should_retry(err.response): - await err.response.aclose() - return await self._retry_request( - input_options, - cast_to, - retries_taken=retries_taken, - response_headers=err.response.headers, - stream=stream, - stream_cls=stream_cls, - ) + # If the response is streamed then we need to explicitly read the response + # to completion before attempting to access the response text. + if not err.response.is_closed: + await err.response.aread() - # If the response is streamed then we need to explicitly read the response - # to completion before attempting to access the response text. - if not err.response.is_closed: - await err.response.aread() + log.debug("Re-raising status error") + raise self._make_status_error_from_response(err.response) from None - log.debug("Re-raising status error") - raise self._make_status_error_from_response(err.response) from None + break + assert response is not None, "could not resolve response (should never happen)" return await self._process_response( cast_to=cast_to, options=options, @@ -1608,35 +1560,20 @@ async def _request( retries_taken=retries_taken, ) - async def _retry_request( - self, - options: FinalRequestOptions, - cast_to: Type[ResponseT], - *, - retries_taken: int, - response_headers: httpx.Headers | None, - stream: bool, - stream_cls: type[_AsyncStreamT] | None, - ) -> ResponseT | _AsyncStreamT: - remaining_retries = options.get_max_retries(self.max_retries) - retries_taken + async def _sleep_for_retry( + self, *, retries_taken: int, max_retries: int, options: FinalRequestOptions, response: httpx.Response | None + ) -> None: + remaining_retries = max_retries - retries_taken if remaining_retries == 1: log.debug("1 retry left") else: log.debug("%i retries left", remaining_retries) - timeout = self._calculate_retry_timeout(remaining_retries, options, response_headers) + timeout = self._calculate_retry_timeout(remaining_retries, options, response.headers if response else None) log.info("Retrying request to %s in %f seconds", options.url, timeout) await anyio.sleep(timeout) - return await self._request( - options=options, - cast_to=cast_to, - retries_taken=retries_taken + 1, - stream=stream, - stream_cls=stream_cls, - ) - async def _process_response( self, *, From 6a2dfbb86c24edea66ecc57fc25e28c4d7d73616 Mon Sep 17 00:00:00 2001 From: Konnor-Young <97478325+Konnor-Young@users.noreply.github.com> Date: Tue, 22 Apr 2025 17:24:20 -0600 Subject: [PATCH 793/816] fix(pydantic v1): more robust `ModelField.annotation` check (#2163) --------- Co-authored-by: Konnor Young Co-authored-by: Robert Craigie --- src/openai/_models.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/openai/_models.py b/src/openai/_models.py index 9b1aeb30bf..6b6f8e9294 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -651,8 +651,8 @@ def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any, # Note: if one variant defines an alias then they all should discriminator_alias = field_info.alias - if field_info.annotation and is_literal_type(field_info.annotation): - for entry in get_args(field_info.annotation): + if (annotation := getattr(field_info, 'annotation', None)) and is_literal_type(annotation): + for entry in get_args(annotation): if isinstance(entry, str): mapping[entry] = variant From 8830a6c9234ebcc058f7661978b961c2bbdd2c93 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 23 Apr 2025 12:00:43 +0000 Subject: [PATCH 794/816] fix(pydantic v1): more robust ModelField.annotation check --- src/openai/_models.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/openai/_models.py b/src/openai/_models.py index 6b6f8e9294..e2fce49250 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -651,7 +651,7 @@ def _build_discriminated_union_meta(*, union: type, meta_annotations: tuple[Any, # Note: if one variant defines an alias then they all should discriminator_alias = field_info.alias - if (annotation := getattr(field_info, 'annotation', None)) and is_literal_type(annotation): + if (annotation := getattr(field_info, "annotation", None)) and is_literal_type(annotation): for entry in get_args(annotation): if isinstance(entry, str): mapping[entry] = variant From 1c1d144e428c60643f0fce52e3ffd9b681c9083c Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 23 Apr 2025 16:20:27 +0000 Subject: [PATCH 795/816] chore(internal): minor formatting changes --- src/openai/types/audio/transcription_word.py | 1 - src/openai/types/audio/translation.py | 1 - src/openai/types/batch_request_counts.py | 1 - src/openai/types/beta/assistant_tool_choice_function.py | 1 - src/openai/types/chat/chat_completion_audio.py | 1 - src/openai/types/chat/chat_completion_reasoning_effort.py | 1 - src/openai/types/chat/chat_completion_store_message.py | 1 - src/openai/types/chat_model.py | 1 - src/openai/types/eval_delete_response.py | 1 - src/openai/types/evals/eval_api_error.py | 1 - src/openai/types/fine_tuning/fine_tuning_job_integration.py | 1 - src/openai/types/model_deleted.py | 1 - src/openai/types/responses/response_function_tool_call_item.py | 1 - src/openai/types/responses/response_usage.py | 1 - src/openai/types/static_file_chunking_strategy.py | 1 - 15 files changed, 15 deletions(-) diff --git a/src/openai/types/audio/transcription_word.py b/src/openai/types/audio/transcription_word.py index 969da32509..2ce682f957 100644 --- a/src/openai/types/audio/transcription_word.py +++ b/src/openai/types/audio/transcription_word.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from ..._models import BaseModel __all__ = ["TranscriptionWord"] diff --git a/src/openai/types/audio/translation.py b/src/openai/types/audio/translation.py index 7c0e905189..efc56f7f9b 100644 --- a/src/openai/types/audio/translation.py +++ b/src/openai/types/audio/translation.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from ..._models import BaseModel __all__ = ["Translation"] diff --git a/src/openai/types/batch_request_counts.py b/src/openai/types/batch_request_counts.py index 7e1d49fb88..068b071af1 100644 --- a/src/openai/types/batch_request_counts.py +++ b/src/openai/types/batch_request_counts.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from .._models import BaseModel __all__ = ["BatchRequestCounts"] diff --git a/src/openai/types/beta/assistant_tool_choice_function.py b/src/openai/types/beta/assistant_tool_choice_function.py index 0c896d8087..87f38310ca 100644 --- a/src/openai/types/beta/assistant_tool_choice_function.py +++ b/src/openai/types/beta/assistant_tool_choice_function.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from ..._models import BaseModel __all__ = ["AssistantToolChoiceFunction"] diff --git a/src/openai/types/chat/chat_completion_audio.py b/src/openai/types/chat/chat_completion_audio.py index dd15508ebb..232d60563d 100644 --- a/src/openai/types/chat/chat_completion_audio.py +++ b/src/openai/types/chat/chat_completion_audio.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from ..._models import BaseModel __all__ = ["ChatCompletionAudio"] diff --git a/src/openai/types/chat/chat_completion_reasoning_effort.py b/src/openai/types/chat/chat_completion_reasoning_effort.py index e4785c90bf..42a980c5b8 100644 --- a/src/openai/types/chat/chat_completion_reasoning_effort.py +++ b/src/openai/types/chat/chat_completion_reasoning_effort.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from ..shared.reasoning_effort import ReasoningEffort __all__ = ["ChatCompletionReasoningEffort"] diff --git a/src/openai/types/chat/chat_completion_store_message.py b/src/openai/types/chat/chat_completion_store_message.py index 95adc08af8..8dc093f7b8 100644 --- a/src/openai/types/chat/chat_completion_store_message.py +++ b/src/openai/types/chat/chat_completion_store_message.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from .chat_completion_message import ChatCompletionMessage __all__ = ["ChatCompletionStoreMessage"] diff --git a/src/openai/types/chat_model.py b/src/openai/types/chat_model.py index 9304d195d6..f3b0e310cc 100644 --- a/src/openai/types/chat_model.py +++ b/src/openai/types/chat_model.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from .shared import chat_model __all__ = ["ChatModel"] diff --git a/src/openai/types/eval_delete_response.py b/src/openai/types/eval_delete_response.py index adb460ddbb..a27261e242 100644 --- a/src/openai/types/eval_delete_response.py +++ b/src/openai/types/eval_delete_response.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from .._models import BaseModel __all__ = ["EvalDeleteResponse"] diff --git a/src/openai/types/evals/eval_api_error.py b/src/openai/types/evals/eval_api_error.py index d67185e981..fe76871024 100644 --- a/src/openai/types/evals/eval_api_error.py +++ b/src/openai/types/evals/eval_api_error.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from ..._models import BaseModel __all__ = ["EvalAPIError"] diff --git a/src/openai/types/fine_tuning/fine_tuning_job_integration.py b/src/openai/types/fine_tuning/fine_tuning_job_integration.py index 9a66aa4f17..2af73fbffb 100644 --- a/src/openai/types/fine_tuning/fine_tuning_job_integration.py +++ b/src/openai/types/fine_tuning/fine_tuning_job_integration.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from .fine_tuning_job_wandb_integration_object import FineTuningJobWandbIntegrationObject FineTuningJobIntegration = FineTuningJobWandbIntegrationObject diff --git a/src/openai/types/model_deleted.py b/src/openai/types/model_deleted.py index 7f81e1b380..e7601f74e4 100644 --- a/src/openai/types/model_deleted.py +++ b/src/openai/types/model_deleted.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from .._models import BaseModel __all__ = ["ModelDeleted"] diff --git a/src/openai/types/responses/response_function_tool_call_item.py b/src/openai/types/responses/response_function_tool_call_item.py index 25984f9451..762015a4b1 100644 --- a/src/openai/types/responses/response_function_tool_call_item.py +++ b/src/openai/types/responses/response_function_tool_call_item.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from .response_function_tool_call import ResponseFunctionToolCall __all__ = ["ResponseFunctionToolCallItem"] diff --git a/src/openai/types/responses/response_usage.py b/src/openai/types/responses/response_usage.py index 9ad36bd326..52b93ac578 100644 --- a/src/openai/types/responses/response_usage.py +++ b/src/openai/types/responses/response_usage.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from ..._models import BaseModel __all__ = ["ResponseUsage", "InputTokensDetails", "OutputTokensDetails"] diff --git a/src/openai/types/static_file_chunking_strategy.py b/src/openai/types/static_file_chunking_strategy.py index 2813bc6630..cb842442c1 100644 --- a/src/openai/types/static_file_chunking_strategy.py +++ b/src/openai/types/static_file_chunking_strategy.py @@ -1,6 +1,5 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - from .._models import BaseModel __all__ = ["StaticFileChunkingStrategy"] From 6321004aef37251116e7b79bcde71e404fce0300 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 23 Apr 2025 16:29:55 +0000 Subject: [PATCH 796/816] feat(api): adding new image model support --- .stats.yml | 6 +- api.md | 6 +- .../resources/beta/realtime/realtime.py | 34 +++ src/openai/resources/beta/threads/threads.py | 17 +- src/openai/resources/evals/evals.py | 8 - src/openai/resources/evals/runs/runs.py | 8 +- .../fine_tuning/checkpoints/permissions.py | 14 +- src/openai/resources/images.py | 248 +++++++++++++----- .../beta/realtime/realtime_client_event.py | 17 +- .../realtime/realtime_client_event_param.py | 14 +- .../beta/realtime/realtime_server_event.py | 44 +++- .../beta/thread_create_and_run_params.py | 9 +- src/openai/types/eval_create_params.py | 166 ++++++++---- src/openai/types/eval_create_response.py | 96 ++++++- src/openai/types/eval_label_model_grader.py | 57 ++-- src/openai/types/eval_list_response.py | 96 ++++++- src/openai/types/eval_retrieve_response.py | 96 ++++++- .../types/eval_text_similarity_grader.py | 16 +- .../eval_text_similarity_grader_param.py | 16 +- src/openai/types/eval_update_response.py | 96 ++++++- ...create_eval_completions_run_data_source.py | 165 ++++++------ ..._eval_completions_run_data_source_param.py | 169 ++++++------ src/openai/types/evals/run_cancel_response.py | 218 ++++++++++++++- src/openai/types/evals/run_create_params.py | 222 +++++++++++++++- src/openai/types/evals/run_create_response.py | 218 ++++++++++++++- src/openai/types/evals/run_list_params.py | 2 +- src/openai/types/evals/run_list_response.py | 218 ++++++++++++++- .../types/evals/run_retrieve_response.py | 218 ++++++++++++++- src/openai/types/image.py | 18 +- .../types/image_create_variation_params.py | 5 +- src/openai/types/image_edit_params.py | 37 ++- src/openai/types/image_generate_params.py | 74 ++++-- src/openai/types/image_model.py | 2 +- src/openai/types/images_response.py | 33 ++- src/openai/types/responses/__init__.py | 13 + .../types/responses/easy_input_message.py | 26 ++ ...onse_reasoning_summary_part_added_event.py | 32 +++ ...ponse_reasoning_summary_part_done_event.py | 32 +++ ...onse_reasoning_summary_text_delta_event.py | 24 ++ ...ponse_reasoning_summary_text_done_event.py | 24 ++ .../types/responses/response_stream_event.py | 8 + .../checkpoints/test_permissions.py | 44 ++-- tests/api_resources/test_evals.py | 2 - tests/api_resources/test_images.py | 14 +- 44 files changed, 2367 insertions(+), 515 deletions(-) create mode 100644 src/openai/types/responses/easy_input_message.py create mode 100644 src/openai/types/responses/response_reasoning_summary_part_added_event.py create mode 100644 src/openai/types/responses/response_reasoning_summary_part_done_event.py create mode 100644 src/openai/types/responses/response_reasoning_summary_text_delta_event.py create mode 100644 src/openai/types/responses/response_reasoning_summary_text_done_event.py diff --git a/.stats.yml b/.stats.yml index 848c5b5adb..d92408173b 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 97 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-5633633cc38734869cf7d993f7b549bb8e4d10e0ec45381ec2cd91507cd8eb8f.yml -openapi_spec_hash: c855121b2b2324b99499c9244c21d24d -config_hash: d20837393b73efdb19cd08e04c1cc9a1 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-8b68ae6b807dca92e914da1dd9e835a20f69b075e79102a264367fd7fddddb33.yml +openapi_spec_hash: b6ade5b1a6327339e6669e1134de2d03 +config_hash: b597cd9a31e9e5ec709e2eefb4c54122 diff --git a/api.md b/api.md index e06f55c2cc..d04c76960e 100644 --- a/api.md +++ b/api.md @@ -277,7 +277,7 @@ Methods: - client.fine_tuning.checkpoints.permissions.create(fine_tuned_model_checkpoint, \*\*params) -> SyncPage[PermissionCreateResponse] - client.fine_tuning.checkpoints.permissions.retrieve(fine_tuned_model_checkpoint, \*\*params) -> PermissionRetrieveResponse -- client.fine_tuning.checkpoints.permissions.delete(fine_tuned_model_checkpoint) -> PermissionDeleteResponse +- client.fine_tuning.checkpoints.permissions.delete(permission_id, \*, fine_tuned_model_checkpoint) -> PermissionDeleteResponse # VectorStores @@ -689,6 +689,10 @@ from openai.types.responses import ( ResponseOutputRefusal, ResponseOutputText, ResponseReasoningItem, + ResponseReasoningSummaryPartAddedEvent, + ResponseReasoningSummaryPartDoneEvent, + ResponseReasoningSummaryTextDeltaEvent, + ResponseReasoningSummaryTextDoneEvent, ResponseRefusalDeltaEvent, ResponseRefusalDoneEvent, ResponseStatus, diff --git a/src/openai/resources/beta/realtime/realtime.py b/src/openai/resources/beta/realtime/realtime.py index 5cafce1322..d39db48e05 100644 --- a/src/openai/resources/beta/realtime/realtime.py +++ b/src/openai/resources/beta/realtime/realtime.py @@ -233,6 +233,7 @@ class AsyncRealtimeConnection: response: AsyncRealtimeResponseResource input_audio_buffer: AsyncRealtimeInputAudioBufferResource conversation: AsyncRealtimeConversationResource + output_audio_buffer: AsyncRealtimeOutputAudioBufferResource transcription_session: AsyncRealtimeTranscriptionSessionResource _connection: AsyncWebsocketConnection @@ -244,6 +245,7 @@ def __init__(self, connection: AsyncWebsocketConnection) -> None: self.response = AsyncRealtimeResponseResource(self) self.input_audio_buffer = AsyncRealtimeInputAudioBufferResource(self) self.conversation = AsyncRealtimeConversationResource(self) + self.output_audio_buffer = AsyncRealtimeOutputAudioBufferResource(self) self.transcription_session = AsyncRealtimeTranscriptionSessionResource(self) async def __aiter__(self) -> AsyncIterator[RealtimeServerEvent]: @@ -413,6 +415,7 @@ class RealtimeConnection: response: RealtimeResponseResource input_audio_buffer: RealtimeInputAudioBufferResource conversation: RealtimeConversationResource + output_audio_buffer: RealtimeOutputAudioBufferResource transcription_session: RealtimeTranscriptionSessionResource _connection: WebsocketConnection @@ -424,6 +427,7 @@ def __init__(self, connection: WebsocketConnection) -> None: self.response = RealtimeResponseResource(self) self.input_audio_buffer = RealtimeInputAudioBufferResource(self) self.conversation = RealtimeConversationResource(self) + self.output_audio_buffer = RealtimeOutputAudioBufferResource(self) self.transcription_session = RealtimeTranscriptionSessionResource(self) def __iter__(self) -> Iterator[RealtimeServerEvent]: @@ -808,6 +812,21 @@ def retrieve(self, *, item_id: str, event_id: str | NotGiven = NOT_GIVEN) -> Non ) +class RealtimeOutputAudioBufferResource(BaseRealtimeConnectionResource): + def clear(self, *, event_id: str | NotGiven = NOT_GIVEN) -> None: + """**WebRTC Only:** Emit to cut off the current audio response. + + This will trigger the server to + stop generating audio and emit a `output_audio_buffer.cleared` event. This + event should be preceded by a `response.cancel` client event to stop the + generation of the current response. + [Learn more](https://platform.openai.com/docs/guides/realtime-model-capabilities#client-and-server-events-for-audio-in-webrtc). + """ + self._connection.send( + cast(RealtimeClientEventParam, strip_not_given({"type": "output_audio_buffer.clear", "event_id": event_id})) + ) + + class RealtimeTranscriptionSessionResource(BaseRealtimeConnectionResource): def update( self, *, session: transcription_session_update_param.Session, event_id: str | NotGiven = NOT_GIVEN @@ -1045,6 +1064,21 @@ async def retrieve(self, *, item_id: str, event_id: str | NotGiven = NOT_GIVEN) ) +class AsyncRealtimeOutputAudioBufferResource(BaseAsyncRealtimeConnectionResource): + async def clear(self, *, event_id: str | NotGiven = NOT_GIVEN) -> None: + """**WebRTC Only:** Emit to cut off the current audio response. + + This will trigger the server to + stop generating audio and emit a `output_audio_buffer.cleared` event. This + event should be preceded by a `response.cancel` client event to stop the + generation of the current response. + [Learn more](https://platform.openai.com/docs/guides/realtime-model-capabilities#client-and-server-events-for-audio-in-webrtc). + """ + await self._connection.send( + cast(RealtimeClientEventParam, strip_not_given({"type": "output_audio_buffer.clear", "event_id": event_id})) + ) + + class AsyncRealtimeTranscriptionSessionResource(BaseAsyncRealtimeConnectionResource): async def update( self, *, session: transcription_session_update_param.Session, event_id: str | NotGiven = NOT_GIVEN diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 9c6954a9b3..22dc5fe0ea 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -50,6 +50,7 @@ from ....types.shared.chat_model import ChatModel from ....types.beta.thread_deleted import ThreadDeleted from ....types.shared_params.metadata import Metadata +from ....types.beta.assistant_tool_param import AssistantToolParam from ....types.beta.assistant_stream_event import AssistantStreamEvent from ....types.beta.assistant_tool_choice_option_param import AssistantToolChoiceOptionParam from ....types.beta.assistant_response_format_option_param import AssistantResponseFormatOptionParam @@ -282,7 +283,7 @@ def create_and_run( thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, - tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -415,7 +416,7 @@ def create_and_run( thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, - tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -548,7 +549,7 @@ def create_and_run( thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, - tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -681,7 +682,7 @@ def create_and_run( thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, - tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -1131,7 +1132,7 @@ async def create_and_run( thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, - tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -1264,7 +1265,7 @@ async def create_and_run( thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, - tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -1397,7 +1398,7 @@ async def create_and_run( thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, - tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -1530,7 +1531,7 @@ async def create_and_run( thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, - tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. diff --git a/src/openai/resources/evals/evals.py b/src/openai/resources/evals/evals.py index 30ac4bdf32..c12562a86d 100644 --- a/src/openai/resources/evals/evals.py +++ b/src/openai/resources/evals/evals.py @@ -65,7 +65,6 @@ def create( testing_criteria: Iterable[eval_create_params.TestingCriterion], metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, name: str | NotGiven = NOT_GIVEN, - share_with_openai: bool | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -94,8 +93,6 @@ def create( name: The name of the evaluation. - share_with_openai: Indicates whether the evaluation is shared with OpenAI. - extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -112,7 +109,6 @@ def create( "testing_criteria": testing_criteria, "metadata": metadata, "name": name, - "share_with_openai": share_with_openai, }, eval_create_params.EvalCreateParams, ), @@ -328,7 +324,6 @@ async def create( testing_criteria: Iterable[eval_create_params.TestingCriterion], metadata: Optional[Metadata] | NotGiven = NOT_GIVEN, name: str | NotGiven = NOT_GIVEN, - share_with_openai: bool | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -357,8 +352,6 @@ async def create( name: The name of the evaluation. - share_with_openai: Indicates whether the evaluation is shared with OpenAI. - extra_headers: Send extra headers extra_query: Add additional query parameters to the request @@ -375,7 +368,6 @@ async def create( "testing_criteria": testing_criteria, "metadata": metadata, "name": name, - "share_with_openai": share_with_openai, }, eval_create_params.EvalCreateParams, ), diff --git a/src/openai/resources/evals/runs/runs.py b/src/openai/resources/evals/runs/runs.py index 9c626d0903..d74c91e3c4 100644 --- a/src/openai/resources/evals/runs/runs.py +++ b/src/openai/resources/evals/runs/runs.py @@ -176,8 +176,8 @@ def list( order: Sort order for runs by timestamp. Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`. - status: Filter runs by status. Use "queued" | "in_progress" | "failed" | "completed" | - "canceled". + status: Filter runs by status. One of `queued` | `in_progress` | `failed` | `completed` + | `canceled`. extra_headers: Send extra headers @@ -425,8 +425,8 @@ def list( order: Sort order for runs by timestamp. Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`. - status: Filter runs by status. Use "queued" | "in_progress" | "failed" | "completed" | - "canceled". + status: Filter runs by status. One of `queued` | `in_progress` | `failed` | `completed` + | `canceled`. extra_headers: Send extra headers diff --git a/src/openai/resources/fine_tuning/checkpoints/permissions.py b/src/openai/resources/fine_tuning/checkpoints/permissions.py index b2bcb33020..547e42ecac 100644 --- a/src/openai/resources/fine_tuning/checkpoints/permissions.py +++ b/src/openai/resources/fine_tuning/checkpoints/permissions.py @@ -151,8 +151,9 @@ def retrieve( def delete( self, - fine_tuned_model_checkpoint: str, + permission_id: str, *, + fine_tuned_model_checkpoint: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -179,8 +180,10 @@ def delete( raise ValueError( f"Expected a non-empty value for `fine_tuned_model_checkpoint` but received {fine_tuned_model_checkpoint!r}" ) + if not permission_id: + raise ValueError(f"Expected a non-empty value for `permission_id` but received {permission_id!r}") return self._delete( - f"/fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions", + f"/fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions/{permission_id}", options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), @@ -316,8 +319,9 @@ async def retrieve( async def delete( self, - fine_tuned_model_checkpoint: str, + permission_id: str, *, + fine_tuned_model_checkpoint: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, @@ -344,8 +348,10 @@ async def delete( raise ValueError( f"Expected a non-empty value for `fine_tuned_model_checkpoint` but received {fine_tuned_model_checkpoint!r}" ) + if not permission_id: + raise ValueError(f"Expected a non-empty value for `permission_id` but received {permission_id!r}") return await self._delete( - f"/fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions", + f"/fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions/{permission_id}", options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py index e3398930e9..e59d0ce35c 100644 --- a/src/openai/resources/images.py +++ b/src/openai/resources/images.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Union, Mapping, Optional, cast +from typing import List, Union, Mapping, Optional, cast from typing_extensions import Literal import httpx @@ -57,8 +57,9 @@ def create_variation( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ImagesResponse: - """ - Creates a variation of a given image. + """Creates a variation of a given image. + + This endpoint only supports `dall-e-2`. Args: image: The image to use as the basis for the variation(s). Must be a valid PNG file, @@ -67,8 +68,7 @@ def create_variation( model: The model to use for image generation. Only `dall-e-2` is supported at this time. - n: The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only - `n=1` is supported. + n: The number of images to generate. Must be between 1 and 10. response_format: The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been @@ -117,11 +117,12 @@ def create_variation( def edit( self, *, - image: FileTypes, + image: Union[FileTypes, List[FileTypes]], prompt: str, mask: FileTypes | NotGiven = NOT_GIVEN, model: Union[str, ImageModel, None] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, + quality: Optional[Literal["standard", "low", "medium", "high", "auto"]] | NotGiven = NOT_GIVEN, response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN, size: Optional[Literal["256x256", "512x512", "1024x1024"]] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, @@ -132,31 +133,43 @@ def edit( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ImagesResponse: - """ - Creates an edited or extended image given an original image and a prompt. + """Creates an edited or extended image given one or more source images and a + prompt. + + This endpoint only supports `gpt-image-1` and `dall-e-2`. Args: - image: The image to edit. Must be a valid PNG file, less than 4MB, and square. If mask - is not provided, image must have transparency, which will be used as the mask. + image: The image(s) to edit. Must be a supported image file or an array of images. For + `gpt-image-1`, each image should be a `png`, `webp`, or `jpg` file less than + 25MB. For `dall-e-2`, you can only provide one image, and it should be a square + `png` file less than 4MB. prompt: A text description of the desired image(s). The maximum length is 1000 - characters. + characters for `dall-e-2`, and 32000 characters for `gpt-image-1`. mask: An additional image whose fully transparent areas (e.g. where alpha is zero) - indicate where `image` should be edited. Must be a valid PNG file, less than + indicate where `image` should be edited. If there are multiple images provided, + the mask will be applied on the first image. Must be a valid PNG file, less than 4MB, and have the same dimensions as `image`. - model: The model to use for image generation. Only `dall-e-2` is supported at this - time. + model: The model to use for image generation. Only `dall-e-2` and `gpt-image-1` are + supported. Defaults to `dall-e-2` unless a parameter specific to `gpt-image-1` + is used. n: The number of images to generate. Must be between 1 and 10. + quality: The quality of the image that will be generated. `high`, `medium` and `low` are + only supported for `gpt-image-1`. `dall-e-2` only supports `standard` quality. + Defaults to `auto`. + response_format: The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been - generated. + generated. This parameter is only supported for `dall-e-2`, as `gpt-image-1` + will always return base64-encoded images. - size: The size of the generated images. Must be one of `256x256`, `512x512`, or - `1024x1024`. + size: The size of the generated images. Must be one of `1024x1024`, `1536x1024` + (landscape), `1024x1536` (portrait), or `auto` (default value) for + `gpt-image-1`, and one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`. user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. @@ -177,12 +190,13 @@ def edit( "mask": mask, "model": model, "n": n, + "quality": quality, "response_format": response_format, "size": size, "user": user, } ) - files = extract_files(cast(Mapping[str, object], body), paths=[["image"], ["mask"]]) + files = extract_files(cast(Mapping[str, object], body), paths=[["image"], ["image", ""], ["mask"]]) # It should be noted that the actual Content-Type header that will be # sent to the server will contain a `boundary` parameter, e.g. # multipart/form-data; boundary=---abc-- @@ -201,11 +215,18 @@ def generate( self, *, prompt: str, + background: Optional[Literal["transparent", "opaque", "auto"]] | NotGiven = NOT_GIVEN, model: Union[str, ImageModel, None] | NotGiven = NOT_GIVEN, + moderation: Optional[Literal["low", "auto"]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, - quality: Literal["standard", "hd"] | NotGiven = NOT_GIVEN, + output_compression: Optional[int] | NotGiven = NOT_GIVEN, + output_format: Optional[Literal["png", "jpeg", "webp"]] | NotGiven = NOT_GIVEN, + quality: Optional[Literal["standard", "hd", "low", "medium", "high", "auto"]] | NotGiven = NOT_GIVEN, response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN, - size: Optional[Literal["256x256", "512x512", "1024x1024", "1792x1024", "1024x1792"]] | NotGiven = NOT_GIVEN, + size: Optional[ + Literal["auto", "1024x1024", "1536x1024", "1024x1536", "256x256", "512x512", "1792x1024", "1024x1792"] + ] + | NotGiven = NOT_GIVEN, style: Optional[Literal["vivid", "natural"]] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -217,32 +238,60 @@ def generate( ) -> ImagesResponse: """ Creates an image given a prompt. + [Learn more](https://platform.openai.com/docs/guides/images). Args: - prompt: A text description of the desired image(s). The maximum length is 1000 - characters for `dall-e-2` and 4000 characters for `dall-e-3`. + prompt: A text description of the desired image(s). The maximum length is 32000 + characters for `gpt-image-1`, 1000 characters for `dall-e-2` and 4000 characters + for `dall-e-3`. + + background: Allows to set transparency for the background of the generated image(s). This + parameter is only supported for `gpt-image-1`. Must be one of `transparent`, + `opaque` or `auto` (default value). When `auto` is used, the model will + automatically determine the best background for the image. + + If `transparent`, the output format needs to support transparency, so it should + be set to either `png` (default value) or `webp`. - model: The model to use for image generation. + model: The model to use for image generation. One of `dall-e-2`, `dall-e-3`, or + `gpt-image-1`. Defaults to `dall-e-2` unless a parameter specific to + `gpt-image-1` is used. + + moderation: Control the content-moderation level for images generated by `gpt-image-1`. Must + be either `low` for less restrictive filtering or `auto` (default value). n: The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only `n=1` is supported. - quality: The quality of the image that will be generated. `hd` creates images with finer - details and greater consistency across the image. This param is only supported - for `dall-e-3`. + output_compression: The compression level (0-100%) for the generated images. This parameter is only + supported for `gpt-image-1` with the `webp` or `jpeg` output formats, and + defaults to 100. - response_format: The format in which the generated images are returned. Must be one of `url` or - `b64_json`. URLs are only valid for 60 minutes after the image has been - generated. + output_format: The format in which the generated images are returned. This parameter is only + supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`. - size: The size of the generated images. Must be one of `256x256`, `512x512`, or - `1024x1024` for `dall-e-2`. Must be one of `1024x1024`, `1792x1024`, or - `1024x1792` for `dall-e-3` models. + quality: The quality of the image that will be generated. + + - `auto` (default value) will automatically select the best quality for the + given model. + - `high`, `medium` and `low` are supported for `gpt-image-1`. + - `hd` and `standard` are supported for `dall-e-3`. + - `standard` is the only option for `dall-e-2`. + + response_format: The format in which generated images with `dall-e-2` and `dall-e-3` are + returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes + after the image has been generated. This parameter isn't supported for + `gpt-image-1` which will always return base64-encoded images. + + size: The size of the generated images. Must be one of `1024x1024`, `1536x1024` + (landscape), `1024x1536` (portrait), or `auto` (default value) for + `gpt-image-1`, one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`, and + one of `1024x1024`, `1792x1024`, or `1024x1792` for `dall-e-3`. - style: The style of the generated images. Must be one of `vivid` or `natural`. Vivid - causes the model to lean towards generating hyper-real and dramatic images. - Natural causes the model to produce more natural, less hyper-real looking - images. This param is only supported for `dall-e-3`. + style: The style of the generated images. This parameter is only supported for + `dall-e-3`. Must be one of `vivid` or `natural`. Vivid causes the model to lean + towards generating hyper-real and dramatic images. Natural causes the model to + produce more natural, less hyper-real looking images. user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. @@ -261,8 +310,12 @@ def generate( body=maybe_transform( { "prompt": prompt, + "background": background, "model": model, + "moderation": moderation, "n": n, + "output_compression": output_compression, + "output_format": output_format, "quality": quality, "response_format": response_format, "size": size, @@ -314,8 +367,9 @@ async def create_variation( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ImagesResponse: - """ - Creates a variation of a given image. + """Creates a variation of a given image. + + This endpoint only supports `dall-e-2`. Args: image: The image to use as the basis for the variation(s). Must be a valid PNG file, @@ -324,8 +378,7 @@ async def create_variation( model: The model to use for image generation. Only `dall-e-2` is supported at this time. - n: The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only - `n=1` is supported. + n: The number of images to generate. Must be between 1 and 10. response_format: The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been @@ -374,11 +427,12 @@ async def create_variation( async def edit( self, *, - image: FileTypes, + image: Union[FileTypes, List[FileTypes]], prompt: str, mask: FileTypes | NotGiven = NOT_GIVEN, model: Union[str, ImageModel, None] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, + quality: Optional[Literal["standard", "low", "medium", "high", "auto"]] | NotGiven = NOT_GIVEN, response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN, size: Optional[Literal["256x256", "512x512", "1024x1024"]] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, @@ -389,31 +443,43 @@ async def edit( extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> ImagesResponse: - """ - Creates an edited or extended image given an original image and a prompt. + """Creates an edited or extended image given one or more source images and a + prompt. + + This endpoint only supports `gpt-image-1` and `dall-e-2`. Args: - image: The image to edit. Must be a valid PNG file, less than 4MB, and square. If mask - is not provided, image must have transparency, which will be used as the mask. + image: The image(s) to edit. Must be a supported image file or an array of images. For + `gpt-image-1`, each image should be a `png`, `webp`, or `jpg` file less than + 25MB. For `dall-e-2`, you can only provide one image, and it should be a square + `png` file less than 4MB. prompt: A text description of the desired image(s). The maximum length is 1000 - characters. + characters for `dall-e-2`, and 32000 characters for `gpt-image-1`. mask: An additional image whose fully transparent areas (e.g. where alpha is zero) - indicate where `image` should be edited. Must be a valid PNG file, less than + indicate where `image` should be edited. If there are multiple images provided, + the mask will be applied on the first image. Must be a valid PNG file, less than 4MB, and have the same dimensions as `image`. - model: The model to use for image generation. Only `dall-e-2` is supported at this - time. + model: The model to use for image generation. Only `dall-e-2` and `gpt-image-1` are + supported. Defaults to `dall-e-2` unless a parameter specific to `gpt-image-1` + is used. n: The number of images to generate. Must be between 1 and 10. + quality: The quality of the image that will be generated. `high`, `medium` and `low` are + only supported for `gpt-image-1`. `dall-e-2` only supports `standard` quality. + Defaults to `auto`. + response_format: The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been - generated. + generated. This parameter is only supported for `dall-e-2`, as `gpt-image-1` + will always return base64-encoded images. - size: The size of the generated images. Must be one of `256x256`, `512x512`, or - `1024x1024`. + size: The size of the generated images. Must be one of `1024x1024`, `1536x1024` + (landscape), `1024x1536` (portrait), or `auto` (default value) for + `gpt-image-1`, and one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`. user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. @@ -434,12 +500,13 @@ async def edit( "mask": mask, "model": model, "n": n, + "quality": quality, "response_format": response_format, "size": size, "user": user, } ) - files = extract_files(cast(Mapping[str, object], body), paths=[["image"], ["mask"]]) + files = extract_files(cast(Mapping[str, object], body), paths=[["image"], ["image", ""], ["mask"]]) # It should be noted that the actual Content-Type header that will be # sent to the server will contain a `boundary` parameter, e.g. # multipart/form-data; boundary=---abc-- @@ -458,11 +525,18 @@ async def generate( self, *, prompt: str, + background: Optional[Literal["transparent", "opaque", "auto"]] | NotGiven = NOT_GIVEN, model: Union[str, ImageModel, None] | NotGiven = NOT_GIVEN, + moderation: Optional[Literal["low", "auto"]] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, - quality: Literal["standard", "hd"] | NotGiven = NOT_GIVEN, + output_compression: Optional[int] | NotGiven = NOT_GIVEN, + output_format: Optional[Literal["png", "jpeg", "webp"]] | NotGiven = NOT_GIVEN, + quality: Optional[Literal["standard", "hd", "low", "medium", "high", "auto"]] | NotGiven = NOT_GIVEN, response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN, - size: Optional[Literal["256x256", "512x512", "1024x1024", "1792x1024", "1024x1792"]] | NotGiven = NOT_GIVEN, + size: Optional[ + Literal["auto", "1024x1024", "1536x1024", "1024x1536", "256x256", "512x512", "1792x1024", "1024x1792"] + ] + | NotGiven = NOT_GIVEN, style: Optional[Literal["vivid", "natural"]] | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -474,32 +548,60 @@ async def generate( ) -> ImagesResponse: """ Creates an image given a prompt. + [Learn more](https://platform.openai.com/docs/guides/images). Args: - prompt: A text description of the desired image(s). The maximum length is 1000 - characters for `dall-e-2` and 4000 characters for `dall-e-3`. + prompt: A text description of the desired image(s). The maximum length is 32000 + characters for `gpt-image-1`, 1000 characters for `dall-e-2` and 4000 characters + for `dall-e-3`. + + background: Allows to set transparency for the background of the generated image(s). This + parameter is only supported for `gpt-image-1`. Must be one of `transparent`, + `opaque` or `auto` (default value). When `auto` is used, the model will + automatically determine the best background for the image. + + If `transparent`, the output format needs to support transparency, so it should + be set to either `png` (default value) or `webp`. - model: The model to use for image generation. + model: The model to use for image generation. One of `dall-e-2`, `dall-e-3`, or + `gpt-image-1`. Defaults to `dall-e-2` unless a parameter specific to + `gpt-image-1` is used. + + moderation: Control the content-moderation level for images generated by `gpt-image-1`. Must + be either `low` for less restrictive filtering or `auto` (default value). n: The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only `n=1` is supported. - quality: The quality of the image that will be generated. `hd` creates images with finer - details and greater consistency across the image. This param is only supported - for `dall-e-3`. + output_compression: The compression level (0-100%) for the generated images. This parameter is only + supported for `gpt-image-1` with the `webp` or `jpeg` output formats, and + defaults to 100. - response_format: The format in which the generated images are returned. Must be one of `url` or - `b64_json`. URLs are only valid for 60 minutes after the image has been - generated. + output_format: The format in which the generated images are returned. This parameter is only + supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`. - size: The size of the generated images. Must be one of `256x256`, `512x512`, or - `1024x1024` for `dall-e-2`. Must be one of `1024x1024`, `1792x1024`, or - `1024x1792` for `dall-e-3` models. + quality: The quality of the image that will be generated. + + - `auto` (default value) will automatically select the best quality for the + given model. + - `high`, `medium` and `low` are supported for `gpt-image-1`. + - `hd` and `standard` are supported for `dall-e-3`. + - `standard` is the only option for `dall-e-2`. + + response_format: The format in which generated images with `dall-e-2` and `dall-e-3` are + returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes + after the image has been generated. This parameter isn't supported for + `gpt-image-1` which will always return base64-encoded images. + + size: The size of the generated images. Must be one of `1024x1024`, `1536x1024` + (landscape), `1024x1536` (portrait), or `auto` (default value) for + `gpt-image-1`, one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`, and + one of `1024x1024`, `1792x1024`, or `1024x1792` for `dall-e-3`. - style: The style of the generated images. Must be one of `vivid` or `natural`. Vivid - causes the model to lean towards generating hyper-real and dramatic images. - Natural causes the model to produce more natural, less hyper-real looking - images. This param is only supported for `dall-e-3`. + style: The style of the generated images. This parameter is only supported for + `dall-e-3`. Must be one of `vivid` or `natural`. Vivid causes the model to lean + towards generating hyper-real and dramatic images. Natural causes the model to + produce more natural, less hyper-real looking images. user: A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. @@ -518,8 +620,12 @@ async def generate( body=await async_maybe_transform( { "prompt": prompt, + "background": background, "model": model, + "moderation": moderation, "n": n, + "output_compression": output_compression, + "output_format": output_format, "quality": quality, "response_format": response_format, "size": size, diff --git a/src/openai/types/beta/realtime/realtime_client_event.py b/src/openai/types/beta/realtime/realtime_client_event.py index f962a505cd..5f4858d688 100644 --- a/src/openai/types/beta/realtime/realtime_client_event.py +++ b/src/openai/types/beta/realtime/realtime_client_event.py @@ -1,9 +1,10 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing import Union -from typing_extensions import Annotated, TypeAlias +from typing import Union, Optional +from typing_extensions import Literal, Annotated, TypeAlias from ...._utils import PropertyInfo +from ...._models import BaseModel from .session_update_event import SessionUpdateEvent from .response_cancel_event import ResponseCancelEvent from .response_create_event import ResponseCreateEvent @@ -16,7 +17,16 @@ from .conversation_item_retrieve_event import ConversationItemRetrieveEvent from .conversation_item_truncate_event import ConversationItemTruncateEvent -__all__ = ["RealtimeClientEvent"] +__all__ = ["RealtimeClientEvent", "OutputAudioBufferClear"] + + +class OutputAudioBufferClear(BaseModel): + type: Literal["output_audio_buffer.clear"] + """The event type, must be `output_audio_buffer.clear`.""" + + event_id: Optional[str] = None + """The unique ID of the client event used for error handling.""" + RealtimeClientEvent: TypeAlias = Annotated[ Union[ @@ -26,6 +36,7 @@ ConversationItemTruncateEvent, InputAudioBufferAppendEvent, InputAudioBufferClearEvent, + OutputAudioBufferClear, InputAudioBufferCommitEvent, ResponseCancelEvent, ResponseCreateEvent, diff --git a/src/openai/types/beta/realtime/realtime_client_event_param.py b/src/openai/types/beta/realtime/realtime_client_event_param.py index 6fdba4b87c..e7dfba241e 100644 --- a/src/openai/types/beta/realtime/realtime_client_event_param.py +++ b/src/openai/types/beta/realtime/realtime_client_event_param.py @@ -3,7 +3,7 @@ from __future__ import annotations from typing import Union -from typing_extensions import TypeAlias +from typing_extensions import Literal, Required, TypeAlias, TypedDict from .session_update_event_param import SessionUpdateEventParam from .response_cancel_event_param import ResponseCancelEventParam @@ -17,7 +17,16 @@ from .conversation_item_retrieve_event_param import ConversationItemRetrieveEventParam from .conversation_item_truncate_event_param import ConversationItemTruncateEventParam -__all__ = ["RealtimeClientEventParam"] +__all__ = ["RealtimeClientEventParam", "OutputAudioBufferClear"] + + +class OutputAudioBufferClear(TypedDict, total=False): + type: Required[Literal["output_audio_buffer.clear"]] + """The event type, must be `output_audio_buffer.clear`.""" + + event_id: str + """The unique ID of the client event used for error handling.""" + RealtimeClientEventParam: TypeAlias = Union[ ConversationItemCreateEventParam, @@ -26,6 +35,7 @@ ConversationItemTruncateEventParam, InputAudioBufferAppendEventParam, InputAudioBufferClearEventParam, + OutputAudioBufferClear, InputAudioBufferCommitEventParam, ResponseCancelEventParam, ResponseCreateEventParam, diff --git a/src/openai/types/beta/realtime/realtime_server_event.py b/src/openai/types/beta/realtime/realtime_server_event.py index ba1d324445..c12f5df977 100644 --- a/src/openai/types/beta/realtime/realtime_server_event.py +++ b/src/openai/types/beta/realtime/realtime_server_event.py @@ -39,7 +39,13 @@ ConversationItemInputAudioTranscriptionCompletedEvent, ) -__all__ = ["RealtimeServerEvent", "ConversationItemRetrieved"] +__all__ = [ + "RealtimeServerEvent", + "ConversationItemRetrieved", + "OutputAudioBufferStarted", + "OutputAudioBufferStopped", + "OutputAudioBufferCleared", +] class ConversationItemRetrieved(BaseModel): @@ -53,6 +59,39 @@ class ConversationItemRetrieved(BaseModel): """The event type, must be `conversation.item.retrieved`.""" +class OutputAudioBufferStarted(BaseModel): + event_id: str + """The unique ID of the server event.""" + + response_id: str + """The unique ID of the response that produced the audio.""" + + type: Literal["output_audio_buffer.started"] + """The event type, must be `output_audio_buffer.started`.""" + + +class OutputAudioBufferStopped(BaseModel): + event_id: str + """The unique ID of the server event.""" + + response_id: str + """The unique ID of the response that produced the audio.""" + + type: Literal["output_audio_buffer.stopped"] + """The event type, must be `output_audio_buffer.stopped`.""" + + +class OutputAudioBufferCleared(BaseModel): + event_id: str + """The unique ID of the server event.""" + + response_id: str + """The unique ID of the response that produced the audio.""" + + type: Literal["output_audio_buffer.cleared"] + """The event type, must be `output_audio_buffer.cleared`.""" + + RealtimeServerEvent: TypeAlias = Annotated[ Union[ ConversationCreatedEvent, @@ -86,6 +125,9 @@ class ConversationItemRetrieved(BaseModel): SessionCreatedEvent, SessionUpdatedEvent, TranscriptionSessionUpdatedEvent, + OutputAudioBufferStarted, + OutputAudioBufferStopped, + OutputAudioBufferCleared, ], PropertyInfo(discriminator="type"), ] diff --git a/src/openai/types/beta/thread_create_and_run_params.py b/src/openai/types/beta/thread_create_and_run_params.py index 065c390f4e..d813710579 100644 --- a/src/openai/types/beta/thread_create_and_run_params.py +++ b/src/openai/types/beta/thread_create_and_run_params.py @@ -6,8 +6,7 @@ from typing_extensions import Literal, Required, TypeAlias, TypedDict from ..shared.chat_model import ChatModel -from .function_tool_param import FunctionToolParam -from .file_search_tool_param import FileSearchToolParam +from .assistant_tool_param import AssistantToolParam from ..shared_params.metadata import Metadata from .code_interpreter_tool_param import CodeInterpreterToolParam from .assistant_tool_choice_option_param import AssistantToolChoiceOptionParam @@ -32,7 +31,6 @@ "ToolResources", "ToolResourcesCodeInterpreter", "ToolResourcesFileSearch", - "Tool", "TruncationStrategy", "ThreadCreateAndRunParamsNonStreaming", "ThreadCreateAndRunParamsStreaming", @@ -153,7 +151,7 @@ class ThreadCreateAndRunParamsBase(TypedDict, total=False): tool requires a list of vector store IDs. """ - tools: Optional[Iterable[Tool]] + tools: Optional[Iterable[AssistantToolParam]] """Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. @@ -360,9 +358,6 @@ class ToolResources(TypedDict, total=False): file_search: ToolResourcesFileSearch -Tool: TypeAlias = Union[CodeInterpreterToolParam, FileSearchToolParam, FunctionToolParam] - - class TruncationStrategy(TypedDict, total=False): type: Required[Literal["auto", "last_messages"]] """The truncation strategy to use for the thread. diff --git a/src/openai/types/eval_create_params.py b/src/openai/types/eval_create_params.py index 8b28e51a6b..03f44f2c8c 100644 --- a/src/openai/types/eval_create_params.py +++ b/src/openai/types/eval_create_params.py @@ -8,20 +8,25 @@ from .shared_params.metadata import Metadata from .eval_string_check_grader_param import EvalStringCheckGraderParam from .eval_text_similarity_grader_param import EvalTextSimilarityGraderParam +from .responses.response_input_text_param import ResponseInputTextParam __all__ = [ "EvalCreateParams", "DataSourceConfig", "DataSourceConfigCustom", - "DataSourceConfigStoredCompletions", + "DataSourceConfigLogs", "TestingCriterion", "TestingCriterionLabelModel", "TestingCriterionLabelModelInput", "TestingCriterionLabelModelInputSimpleInputMessage", - "TestingCriterionLabelModelInputInputMessage", - "TestingCriterionLabelModelInputInputMessageContent", - "TestingCriterionLabelModelInputOutputMessage", - "TestingCriterionLabelModelInputOutputMessageContent", + "TestingCriterionLabelModelInputEvalItem", + "TestingCriterionLabelModelInputEvalItemContent", + "TestingCriterionLabelModelInputEvalItemContentOutputText", + "TestingCriterionPython", + "TestingCriterionScoreModel", + "TestingCriterionScoreModelInput", + "TestingCriterionScoreModelInputContent", + "TestingCriterionScoreModelInputContentOutputText", ] @@ -45,37 +50,30 @@ class EvalCreateParams(TypedDict, total=False): name: str """The name of the evaluation.""" - share_with_openai: bool - """Indicates whether the evaluation is shared with OpenAI.""" - class DataSourceConfigCustom(TypedDict, total=False): item_schema: Required[Dict[str, object]] - """The json schema for the run data source items.""" + """The json schema for each row in the data source.""" type: Required[Literal["custom"]] """The type of data source. Always `custom`.""" include_sample_schema: bool - """Whether to include the sample schema in the data source.""" - - -class DataSourceConfigStoredCompletions(TypedDict, total=False): - type: Required[Literal["stored_completions"]] - """The type of data source. Always `stored_completions`.""" + """ + Whether the eval should expect you to populate the sample namespace (ie, by + generating responses off of your data source) + """ - metadata: Optional[Metadata] - """Set of 16 key-value pairs that can be attached to an object. - This can be useful for storing additional information about the object in a - structured format, and querying for objects via API or the dashboard. +class DataSourceConfigLogs(TypedDict, total=False): + type: Required[Literal["logs"]] + """The type of data source. Always `logs`.""" - Keys are strings with a maximum length of 64 characters. Values are strings with - a maximum length of 512 characters. - """ + metadata: Dict[str, object] + """Metadata filters for the logs data source.""" -DataSourceConfig: TypeAlias = Union[DataSourceConfigCustom, DataSourceConfigStoredCompletions] +DataSourceConfig: TypeAlias = Union[DataSourceConfigCustom, DataSourceConfigLogs] class TestingCriterionLabelModelInputSimpleInputMessage(TypedDict, total=False): @@ -86,51 +84,44 @@ class TestingCriterionLabelModelInputSimpleInputMessage(TypedDict, total=False): """The role of the message (e.g. "system", "assistant", "user").""" -class TestingCriterionLabelModelInputInputMessageContent(TypedDict, total=False): +class TestingCriterionLabelModelInputEvalItemContentOutputText(TypedDict, total=False): text: Required[str] - """The text content.""" - - type: Required[Literal["input_text"]] - """The type of content, which is always `input_text`.""" - + """The text output from the model.""" -class TestingCriterionLabelModelInputInputMessage(TypedDict, total=False): - content: Required[TestingCriterionLabelModelInputInputMessageContent] - - role: Required[Literal["user", "system", "developer"]] - """The role of the message. One of `user`, `system`, or `developer`.""" - - type: Required[Literal["message"]] - """The type of item, which is always `message`.""" + type: Required[Literal["output_text"]] + """The type of the output text. Always `output_text`.""" -class TestingCriterionLabelModelInputOutputMessageContent(TypedDict, total=False): - text: Required[str] - """The text content.""" +TestingCriterionLabelModelInputEvalItemContent: TypeAlias = Union[ + str, ResponseInputTextParam, TestingCriterionLabelModelInputEvalItemContentOutputText +] - type: Required[Literal["output_text"]] - """The type of content, which is always `output_text`.""" +class TestingCriterionLabelModelInputEvalItem(TypedDict, total=False): + content: Required[TestingCriterionLabelModelInputEvalItemContent] + """Text inputs to the model - can contain template strings.""" -class TestingCriterionLabelModelInputOutputMessage(TypedDict, total=False): - content: Required[TestingCriterionLabelModelInputOutputMessageContent] + role: Required[Literal["user", "assistant", "system", "developer"]] + """The role of the message input. - role: Required[Literal["assistant"]] - """The role of the message. Must be `assistant` for output.""" + One of `user`, `assistant`, `system`, or `developer`. + """ - type: Required[Literal["message"]] - """The type of item, which is always `message`.""" + type: Literal["message"] + """The type of the message input. Always `message`.""" TestingCriterionLabelModelInput: TypeAlias = Union[ - TestingCriterionLabelModelInputSimpleInputMessage, - TestingCriterionLabelModelInputInputMessage, - TestingCriterionLabelModelInputOutputMessage, + TestingCriterionLabelModelInputSimpleInputMessage, TestingCriterionLabelModelInputEvalItem ] class TestingCriterionLabelModel(TypedDict, total=False): input: Required[Iterable[TestingCriterionLabelModelInput]] + """A list of chat messages forming the prompt or context. + + May include variable references to the "item" namespace, ie {{item.name}}. + """ labels: Required[List[str]] """The labels to classify to each item in the evaluation.""" @@ -148,6 +139,77 @@ class TestingCriterionLabelModel(TypedDict, total=False): """The object type, which is always `label_model`.""" +class TestingCriterionPython(TypedDict, total=False): + name: Required[str] + """The name of the grader.""" + + source: Required[str] + """The source code of the python script.""" + + type: Required[Literal["python"]] + """The object type, which is always `python`.""" + + image_tag: str + """The image tag to use for the python script.""" + + pass_threshold: float + """The threshold for the score.""" + + +class TestingCriterionScoreModelInputContentOutputText(TypedDict, total=False): + text: Required[str] + """The text output from the model.""" + + type: Required[Literal["output_text"]] + """The type of the output text. Always `output_text`.""" + + +TestingCriterionScoreModelInputContent: TypeAlias = Union[ + str, ResponseInputTextParam, TestingCriterionScoreModelInputContentOutputText +] + + +class TestingCriterionScoreModelInput(TypedDict, total=False): + content: Required[TestingCriterionScoreModelInputContent] + """Text inputs to the model - can contain template strings.""" + + role: Required[Literal["user", "assistant", "system", "developer"]] + """The role of the message input. + + One of `user`, `assistant`, `system`, or `developer`. + """ + + type: Literal["message"] + """The type of the message input. Always `message`.""" + + +class TestingCriterionScoreModel(TypedDict, total=False): + input: Required[Iterable[TestingCriterionScoreModelInput]] + """The input text. This may include template strings.""" + + model: Required[str] + """The model to use for the evaluation.""" + + name: Required[str] + """The name of the grader.""" + + type: Required[Literal["score_model"]] + """The object type, which is always `score_model`.""" + + pass_threshold: float + """The threshold for the score.""" + + range: Iterable[float] + """The range of the score. Defaults to `[0, 1]`.""" + + sampling_params: object + """The sampling parameters for the model.""" + + TestingCriterion: TypeAlias = Union[ - TestingCriterionLabelModel, EvalStringCheckGraderParam, EvalTextSimilarityGraderParam + TestingCriterionLabelModel, + EvalStringCheckGraderParam, + EvalTextSimilarityGraderParam, + TestingCriterionPython, + TestingCriterionScoreModel, ] diff --git a/src/openai/types/eval_create_response.py b/src/openai/types/eval_create_response.py index a1c2853a2a..6d77a81870 100644 --- a/src/openai/types/eval_create_response.py +++ b/src/openai/types/eval_create_response.py @@ -9,17 +9,106 @@ from .eval_label_model_grader import EvalLabelModelGrader from .eval_string_check_grader import EvalStringCheckGrader from .eval_text_similarity_grader import EvalTextSimilarityGrader +from .responses.response_input_text import ResponseInputText from .eval_custom_data_source_config import EvalCustomDataSourceConfig from .eval_stored_completions_data_source_config import EvalStoredCompletionsDataSourceConfig -__all__ = ["EvalCreateResponse", "DataSourceConfig", "TestingCriterion"] +__all__ = [ + "EvalCreateResponse", + "DataSourceConfig", + "TestingCriterion", + "TestingCriterionPython", + "TestingCriterionScoreModel", + "TestingCriterionScoreModelInput", + "TestingCriterionScoreModelInputContent", + "TestingCriterionScoreModelInputContentOutputText", +] DataSourceConfig: TypeAlias = Annotated[ Union[EvalCustomDataSourceConfig, EvalStoredCompletionsDataSourceConfig], PropertyInfo(discriminator="type") ] + +class TestingCriterionPython(BaseModel): + __test__ = False + name: str + """The name of the grader.""" + + source: str + """The source code of the python script.""" + + type: Literal["python"] + """The object type, which is always `python`.""" + + image_tag: Optional[str] = None + """The image tag to use for the python script.""" + + pass_threshold: Optional[float] = None + """The threshold for the score.""" + + +class TestingCriterionScoreModelInputContentOutputText(BaseModel): + __test__ = False + text: str + """The text output from the model.""" + + type: Literal["output_text"] + """The type of the output text. Always `output_text`.""" + + +TestingCriterionScoreModelInputContent: TypeAlias = Union[ + str, ResponseInputText, TestingCriterionScoreModelInputContentOutputText +] + + +class TestingCriterionScoreModelInput(BaseModel): + __test__ = False + content: TestingCriterionScoreModelInputContent + """Text inputs to the model - can contain template strings.""" + + role: Literal["user", "assistant", "system", "developer"] + """The role of the message input. + + One of `user`, `assistant`, `system`, or `developer`. + """ + + type: Optional[Literal["message"]] = None + """The type of the message input. Always `message`.""" + + +class TestingCriterionScoreModel(BaseModel): + __test__ = False + input: List[TestingCriterionScoreModelInput] + """The input text. This may include template strings.""" + + model: str + """The model to use for the evaluation.""" + + name: str + """The name of the grader.""" + + type: Literal["score_model"] + """The object type, which is always `score_model`.""" + + pass_threshold: Optional[float] = None + """The threshold for the score.""" + + range: Optional[List[float]] = None + """The range of the score. Defaults to `[0, 1]`.""" + + sampling_params: Optional[object] = None + """The sampling parameters for the model.""" + + TestingCriterion: TypeAlias = Annotated[ - Union[EvalLabelModelGrader, EvalStringCheckGrader, EvalTextSimilarityGrader], PropertyInfo(discriminator="type") + Union[ + EvalLabelModelGrader, + EvalStringCheckGrader, + EvalTextSimilarityGrader, + TestingCriterionPython, + TestingCriterionScoreModel, + ], + PropertyInfo(discriminator="type"), ] @@ -49,8 +138,5 @@ class EvalCreateResponse(BaseModel): object: Literal["eval"] """The object type.""" - share_with_openai: bool - """Indicates whether the evaluation is shared with OpenAI.""" - testing_criteria: List[TestingCriterion] """A list of testing criteria.""" diff --git a/src/openai/types/eval_label_model_grader.py b/src/openai/types/eval_label_model_grader.py index 826b116287..40e6bda140 100644 --- a/src/openai/types/eval_label_model_grader.py +++ b/src/openai/types/eval_label_model_grader.py @@ -1,58 +1,37 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing import List, Union -from typing_extensions import Literal, Annotated, TypeAlias +from typing import List, Union, Optional +from typing_extensions import Literal, TypeAlias -from .._utils import PropertyInfo from .._models import BaseModel +from .responses.response_input_text import ResponseInputText -__all__ = [ - "EvalLabelModelGrader", - "Input", - "InputInputMessage", - "InputInputMessageContent", - "InputAssistant", - "InputAssistantContent", -] +__all__ = ["EvalLabelModelGrader", "Input", "InputContent", "InputContentOutputText"] -class InputInputMessageContent(BaseModel): +class InputContentOutputText(BaseModel): text: str - """The text content.""" - - type: Literal["input_text"] - """The type of content, which is always `input_text`.""" - - -class InputInputMessage(BaseModel): - content: InputInputMessageContent - - role: Literal["user", "system", "developer"] - """The role of the message. One of `user`, `system`, or `developer`.""" - - type: Literal["message"] - """The type of item, which is always `message`.""" - - -class InputAssistantContent(BaseModel): - text: str - """The text content.""" + """The text output from the model.""" type: Literal["output_text"] - """The type of content, which is always `output_text`.""" + """The type of the output text. Always `output_text`.""" + +InputContent: TypeAlias = Union[str, ResponseInputText, InputContentOutputText] -class InputAssistant(BaseModel): - content: InputAssistantContent - role: Literal["assistant"] - """The role of the message. Must be `assistant` for output.""" +class Input(BaseModel): + content: InputContent + """Text inputs to the model - can contain template strings.""" - type: Literal["message"] - """The type of item, which is always `message`.""" + role: Literal["user", "assistant", "system", "developer"] + """The role of the message input. + One of `user`, `assistant`, `system`, or `developer`. + """ -Input: TypeAlias = Annotated[Union[InputInputMessage, InputAssistant], PropertyInfo(discriminator="role")] + type: Optional[Literal["message"]] = None + """The type of the message input. Always `message`.""" class EvalLabelModelGrader(BaseModel): diff --git a/src/openai/types/eval_list_response.py b/src/openai/types/eval_list_response.py index eb54569011..8c7e9c5588 100644 --- a/src/openai/types/eval_list_response.py +++ b/src/openai/types/eval_list_response.py @@ -9,17 +9,106 @@ from .eval_label_model_grader import EvalLabelModelGrader from .eval_string_check_grader import EvalStringCheckGrader from .eval_text_similarity_grader import EvalTextSimilarityGrader +from .responses.response_input_text import ResponseInputText from .eval_custom_data_source_config import EvalCustomDataSourceConfig from .eval_stored_completions_data_source_config import EvalStoredCompletionsDataSourceConfig -__all__ = ["EvalListResponse", "DataSourceConfig", "TestingCriterion"] +__all__ = [ + "EvalListResponse", + "DataSourceConfig", + "TestingCriterion", + "TestingCriterionPython", + "TestingCriterionScoreModel", + "TestingCriterionScoreModelInput", + "TestingCriterionScoreModelInputContent", + "TestingCriterionScoreModelInputContentOutputText", +] DataSourceConfig: TypeAlias = Annotated[ Union[EvalCustomDataSourceConfig, EvalStoredCompletionsDataSourceConfig], PropertyInfo(discriminator="type") ] + +class TestingCriterionPython(BaseModel): + __test__ = False + name: str + """The name of the grader.""" + + source: str + """The source code of the python script.""" + + type: Literal["python"] + """The object type, which is always `python`.""" + + image_tag: Optional[str] = None + """The image tag to use for the python script.""" + + pass_threshold: Optional[float] = None + """The threshold for the score.""" + + +class TestingCriterionScoreModelInputContentOutputText(BaseModel): + __test__ = False + text: str + """The text output from the model.""" + + type: Literal["output_text"] + """The type of the output text. Always `output_text`.""" + + +TestingCriterionScoreModelInputContent: TypeAlias = Union[ + str, ResponseInputText, TestingCriterionScoreModelInputContentOutputText +] + + +class TestingCriterionScoreModelInput(BaseModel): + __test__ = False + content: TestingCriterionScoreModelInputContent + """Text inputs to the model - can contain template strings.""" + + role: Literal["user", "assistant", "system", "developer"] + """The role of the message input. + + One of `user`, `assistant`, `system`, or `developer`. + """ + + type: Optional[Literal["message"]] = None + """The type of the message input. Always `message`.""" + + +class TestingCriterionScoreModel(BaseModel): + __test__ = False + input: List[TestingCriterionScoreModelInput] + """The input text. This may include template strings.""" + + model: str + """The model to use for the evaluation.""" + + name: str + """The name of the grader.""" + + type: Literal["score_model"] + """The object type, which is always `score_model`.""" + + pass_threshold: Optional[float] = None + """The threshold for the score.""" + + range: Optional[List[float]] = None + """The range of the score. Defaults to `[0, 1]`.""" + + sampling_params: Optional[object] = None + """The sampling parameters for the model.""" + + TestingCriterion: TypeAlias = Annotated[ - Union[EvalLabelModelGrader, EvalStringCheckGrader, EvalTextSimilarityGrader], PropertyInfo(discriminator="type") + Union[ + EvalLabelModelGrader, + EvalStringCheckGrader, + EvalTextSimilarityGrader, + TestingCriterionPython, + TestingCriterionScoreModel, + ], + PropertyInfo(discriminator="type"), ] @@ -49,8 +138,5 @@ class EvalListResponse(BaseModel): object: Literal["eval"] """The object type.""" - share_with_openai: bool - """Indicates whether the evaluation is shared with OpenAI.""" - testing_criteria: List[TestingCriterion] """A list of testing criteria.""" diff --git a/src/openai/types/eval_retrieve_response.py b/src/openai/types/eval_retrieve_response.py index 8f3bfdf902..625bae80f4 100644 --- a/src/openai/types/eval_retrieve_response.py +++ b/src/openai/types/eval_retrieve_response.py @@ -9,17 +9,106 @@ from .eval_label_model_grader import EvalLabelModelGrader from .eval_string_check_grader import EvalStringCheckGrader from .eval_text_similarity_grader import EvalTextSimilarityGrader +from .responses.response_input_text import ResponseInputText from .eval_custom_data_source_config import EvalCustomDataSourceConfig from .eval_stored_completions_data_source_config import EvalStoredCompletionsDataSourceConfig -__all__ = ["EvalRetrieveResponse", "DataSourceConfig", "TestingCriterion"] +__all__ = [ + "EvalRetrieveResponse", + "DataSourceConfig", + "TestingCriterion", + "TestingCriterionPython", + "TestingCriterionScoreModel", + "TestingCriterionScoreModelInput", + "TestingCriterionScoreModelInputContent", + "TestingCriterionScoreModelInputContentOutputText", +] DataSourceConfig: TypeAlias = Annotated[ Union[EvalCustomDataSourceConfig, EvalStoredCompletionsDataSourceConfig], PropertyInfo(discriminator="type") ] + +class TestingCriterionPython(BaseModel): + __test__ = False + name: str + """The name of the grader.""" + + source: str + """The source code of the python script.""" + + type: Literal["python"] + """The object type, which is always `python`.""" + + image_tag: Optional[str] = None + """The image tag to use for the python script.""" + + pass_threshold: Optional[float] = None + """The threshold for the score.""" + + +class TestingCriterionScoreModelInputContentOutputText(BaseModel): + __test__ = False + text: str + """The text output from the model.""" + + type: Literal["output_text"] + """The type of the output text. Always `output_text`.""" + + +TestingCriterionScoreModelInputContent: TypeAlias = Union[ + str, ResponseInputText, TestingCriterionScoreModelInputContentOutputText +] + + +class TestingCriterionScoreModelInput(BaseModel): + __test__ = False + content: TestingCriterionScoreModelInputContent + """Text inputs to the model - can contain template strings.""" + + role: Literal["user", "assistant", "system", "developer"] + """The role of the message input. + + One of `user`, `assistant`, `system`, or `developer`. + """ + + type: Optional[Literal["message"]] = None + """The type of the message input. Always `message`.""" + + +class TestingCriterionScoreModel(BaseModel): + __test__ = False + input: List[TestingCriterionScoreModelInput] + """The input text. This may include template strings.""" + + model: str + """The model to use for the evaluation.""" + + name: str + """The name of the grader.""" + + type: Literal["score_model"] + """The object type, which is always `score_model`.""" + + pass_threshold: Optional[float] = None + """The threshold for the score.""" + + range: Optional[List[float]] = None + """The range of the score. Defaults to `[0, 1]`.""" + + sampling_params: Optional[object] = None + """The sampling parameters for the model.""" + + TestingCriterion: TypeAlias = Annotated[ - Union[EvalLabelModelGrader, EvalStringCheckGrader, EvalTextSimilarityGrader], PropertyInfo(discriminator="type") + Union[ + EvalLabelModelGrader, + EvalStringCheckGrader, + EvalTextSimilarityGrader, + TestingCriterionPython, + TestingCriterionScoreModel, + ], + PropertyInfo(discriminator="type"), ] @@ -49,8 +138,5 @@ class EvalRetrieveResponse(BaseModel): object: Literal["eval"] """The object type.""" - share_with_openai: bool - """Indicates whether the evaluation is shared with OpenAI.""" - testing_criteria: List[TestingCriterion] """A list of testing criteria.""" diff --git a/src/openai/types/eval_text_similarity_grader.py b/src/openai/types/eval_text_similarity_grader.py index 7c6897a4a7..853c6d4fbf 100644 --- a/src/openai/types/eval_text_similarity_grader.py +++ b/src/openai/types/eval_text_similarity_grader.py @@ -10,22 +10,12 @@ class EvalTextSimilarityGrader(BaseModel): evaluation_metric: Literal[ - "fuzzy_match", - "bleu", - "gleu", - "meteor", - "rouge_1", - "rouge_2", - "rouge_3", - "rouge_4", - "rouge_5", - "rouge_l", - "cosine", + "fuzzy_match", "bleu", "gleu", "meteor", "rouge_1", "rouge_2", "rouge_3", "rouge_4", "rouge_5", "rouge_l" ] """The evaluation metric to use. - One of `cosine`, `fuzzy_match`, `bleu`, `gleu`, `meteor`, `rouge_1`, `rouge_2`, - `rouge_3`, `rouge_4`, `rouge_5`, or `rouge_l`. + One of `fuzzy_match`, `bleu`, `gleu`, `meteor`, `rouge_1`, `rouge_2`, `rouge_3`, + `rouge_4`, `rouge_5`, or `rouge_l`. """ input: str diff --git a/src/openai/types/eval_text_similarity_grader_param.py b/src/openai/types/eval_text_similarity_grader_param.py index 4bf5d586f3..f07cc29178 100644 --- a/src/openai/types/eval_text_similarity_grader_param.py +++ b/src/openai/types/eval_text_similarity_grader_param.py @@ -10,23 +10,13 @@ class EvalTextSimilarityGraderParam(TypedDict, total=False): evaluation_metric: Required[ Literal[ - "fuzzy_match", - "bleu", - "gleu", - "meteor", - "rouge_1", - "rouge_2", - "rouge_3", - "rouge_4", - "rouge_5", - "rouge_l", - "cosine", + "fuzzy_match", "bleu", "gleu", "meteor", "rouge_1", "rouge_2", "rouge_3", "rouge_4", "rouge_5", "rouge_l" ] ] """The evaluation metric to use. - One of `cosine`, `fuzzy_match`, `bleu`, `gleu`, `meteor`, `rouge_1`, `rouge_2`, - `rouge_3`, `rouge_4`, `rouge_5`, or `rouge_l`. + One of `fuzzy_match`, `bleu`, `gleu`, `meteor`, `rouge_1`, `rouge_2`, `rouge_3`, + `rouge_4`, `rouge_5`, or `rouge_l`. """ input: Required[str] diff --git a/src/openai/types/eval_update_response.py b/src/openai/types/eval_update_response.py index 728a291736..2c280977a1 100644 --- a/src/openai/types/eval_update_response.py +++ b/src/openai/types/eval_update_response.py @@ -9,17 +9,106 @@ from .eval_label_model_grader import EvalLabelModelGrader from .eval_string_check_grader import EvalStringCheckGrader from .eval_text_similarity_grader import EvalTextSimilarityGrader +from .responses.response_input_text import ResponseInputText from .eval_custom_data_source_config import EvalCustomDataSourceConfig from .eval_stored_completions_data_source_config import EvalStoredCompletionsDataSourceConfig -__all__ = ["EvalUpdateResponse", "DataSourceConfig", "TestingCriterion"] +__all__ = [ + "EvalUpdateResponse", + "DataSourceConfig", + "TestingCriterion", + "TestingCriterionPython", + "TestingCriterionScoreModel", + "TestingCriterionScoreModelInput", + "TestingCriterionScoreModelInputContent", + "TestingCriterionScoreModelInputContentOutputText", +] DataSourceConfig: TypeAlias = Annotated[ Union[EvalCustomDataSourceConfig, EvalStoredCompletionsDataSourceConfig], PropertyInfo(discriminator="type") ] + +class TestingCriterionPython(BaseModel): + __test__ = False + name: str + """The name of the grader.""" + + source: str + """The source code of the python script.""" + + type: Literal["python"] + """The object type, which is always `python`.""" + + image_tag: Optional[str] = None + """The image tag to use for the python script.""" + + pass_threshold: Optional[float] = None + """The threshold for the score.""" + + +class TestingCriterionScoreModelInputContentOutputText(BaseModel): + __test__ = False + text: str + """The text output from the model.""" + + type: Literal["output_text"] + """The type of the output text. Always `output_text`.""" + + +TestingCriterionScoreModelInputContent: TypeAlias = Union[ + str, ResponseInputText, TestingCriterionScoreModelInputContentOutputText +] + + +class TestingCriterionScoreModelInput(BaseModel): + __test__ = False + content: TestingCriterionScoreModelInputContent + """Text inputs to the model - can contain template strings.""" + + role: Literal["user", "assistant", "system", "developer"] + """The role of the message input. + + One of `user`, `assistant`, `system`, or `developer`. + """ + + type: Optional[Literal["message"]] = None + """The type of the message input. Always `message`.""" + + +class TestingCriterionScoreModel(BaseModel): + __test__ = False + input: List[TestingCriterionScoreModelInput] + """The input text. This may include template strings.""" + + model: str + """The model to use for the evaluation.""" + + name: str + """The name of the grader.""" + + type: Literal["score_model"] + """The object type, which is always `score_model`.""" + + pass_threshold: Optional[float] = None + """The threshold for the score.""" + + range: Optional[List[float]] = None + """The range of the score. Defaults to `[0, 1]`.""" + + sampling_params: Optional[object] = None + """The sampling parameters for the model.""" + + TestingCriterion: TypeAlias = Annotated[ - Union[EvalLabelModelGrader, EvalStringCheckGrader, EvalTextSimilarityGrader], PropertyInfo(discriminator="type") + Union[ + EvalLabelModelGrader, + EvalStringCheckGrader, + EvalTextSimilarityGrader, + TestingCriterionPython, + TestingCriterionScoreModel, + ], + PropertyInfo(discriminator="type"), ] @@ -49,8 +138,5 @@ class EvalUpdateResponse(BaseModel): object: Literal["eval"] """The object type.""" - share_with_openai: bool - """Indicates whether the evaluation is shared with OpenAI.""" - testing_criteria: List[TestingCriterion] """A list of testing criteria.""" diff --git a/src/openai/types/evals/create_eval_completions_run_data_source.py b/src/openai/types/evals/create_eval_completions_run_data_source.py index 07b88129e2..29c687b542 100644 --- a/src/openai/types/evals/create_eval_completions_run_data_source.py +++ b/src/openai/types/evals/create_eval_completions_run_data_source.py @@ -6,102 +6,27 @@ from ..._utils import PropertyInfo from ..._models import BaseModel from ..shared.metadata import Metadata +from ..responses.easy_input_message import EasyInputMessage +from ..responses.response_input_text import ResponseInputText __all__ = [ "CreateEvalCompletionsRunDataSource", - "InputMessages", - "InputMessagesTemplate", - "InputMessagesTemplateTemplate", - "InputMessagesTemplateTemplateChatMessage", - "InputMessagesTemplateTemplateInputMessage", - "InputMessagesTemplateTemplateInputMessageContent", - "InputMessagesTemplateTemplateOutputMessage", - "InputMessagesTemplateTemplateOutputMessageContent", - "InputMessagesItemReference", "Source", "SourceFileContent", "SourceFileContentContent", "SourceFileID", "SourceStoredCompletions", + "InputMessages", + "InputMessagesTemplate", + "InputMessagesTemplateTemplate", + "InputMessagesTemplateTemplateMessage", + "InputMessagesTemplateTemplateMessageContent", + "InputMessagesTemplateTemplateMessageContentOutputText", + "InputMessagesItemReference", "SamplingParams", ] -class InputMessagesTemplateTemplateChatMessage(BaseModel): - content: str - """The content of the message.""" - - role: str - """The role of the message (e.g. "system", "assistant", "user").""" - - -class InputMessagesTemplateTemplateInputMessageContent(BaseModel): - text: str - """The text content.""" - - type: Literal["input_text"] - """The type of content, which is always `input_text`.""" - - -class InputMessagesTemplateTemplateInputMessage(BaseModel): - content: InputMessagesTemplateTemplateInputMessageContent - - role: Literal["user", "system", "developer"] - """The role of the message. One of `user`, `system`, or `developer`.""" - - type: Literal["message"] - """The type of item, which is always `message`.""" - - -class InputMessagesTemplateTemplateOutputMessageContent(BaseModel): - text: str - """The text content.""" - - type: Literal["output_text"] - """The type of content, which is always `output_text`.""" - - -class InputMessagesTemplateTemplateOutputMessage(BaseModel): - content: InputMessagesTemplateTemplateOutputMessageContent - - role: Literal["assistant"] - """The role of the message. Must be `assistant` for output.""" - - type: Literal["message"] - """The type of item, which is always `message`.""" - - -InputMessagesTemplateTemplate: TypeAlias = Union[ - InputMessagesTemplateTemplateChatMessage, - InputMessagesTemplateTemplateInputMessage, - InputMessagesTemplateTemplateOutputMessage, -] - - -class InputMessagesTemplate(BaseModel): - template: List[InputMessagesTemplateTemplate] - """A list of chat messages forming the prompt or context. - - May include variable references to the "item" namespace, ie {{item.name}}. - """ - - type: Literal["template"] - """The type of input messages. Always `template`.""" - - -class InputMessagesItemReference(BaseModel): - item_reference: str - """A reference to a variable in the "item" namespace. Ie, "item.name" """ - - type: Literal["item_reference"] - """The type of input messages. Always `item_reference`.""" - - -InputMessages: TypeAlias = Annotated[ - Union[InputMessagesTemplate, InputMessagesItemReference], PropertyInfo(discriminator="type") -] - - class SourceFileContentContent(BaseModel): item: Dict[str, object] @@ -125,6 +50,9 @@ class SourceFileID(BaseModel): class SourceStoredCompletions(BaseModel): + type: Literal["stored_completions"] + """The type of source. Always `stored_completions`.""" + created_after: Optional[int] = None """An optional Unix timestamp to filter items created after this time.""" @@ -147,15 +75,68 @@ class SourceStoredCompletions(BaseModel): model: Optional[str] = None """An optional model to filter by (e.g., 'gpt-4o').""" - type: Literal["stored_completions"] - """The type of source. Always `stored_completions`.""" - Source: TypeAlias = Annotated[ Union[SourceFileContent, SourceFileID, SourceStoredCompletions], PropertyInfo(discriminator="type") ] +class InputMessagesTemplateTemplateMessageContentOutputText(BaseModel): + text: str + """The text output from the model.""" + + type: Literal["output_text"] + """The type of the output text. Always `output_text`.""" + + +InputMessagesTemplateTemplateMessageContent: TypeAlias = Union[ + str, ResponseInputText, InputMessagesTemplateTemplateMessageContentOutputText +] + + +class InputMessagesTemplateTemplateMessage(BaseModel): + content: InputMessagesTemplateTemplateMessageContent + """Text inputs to the model - can contain template strings.""" + + role: Literal["user", "assistant", "system", "developer"] + """The role of the message input. + + One of `user`, `assistant`, `system`, or `developer`. + """ + + type: Optional[Literal["message"]] = None + """The type of the message input. Always `message`.""" + + +InputMessagesTemplateTemplate: TypeAlias = Annotated[ + Union[EasyInputMessage, InputMessagesTemplateTemplateMessage], PropertyInfo(discriminator="type") +] + + +class InputMessagesTemplate(BaseModel): + template: List[InputMessagesTemplateTemplate] + """A list of chat messages forming the prompt or context. + + May include variable references to the "item" namespace, ie {{item.name}}. + """ + + type: Literal["template"] + """The type of input messages. Always `template`.""" + + +class InputMessagesItemReference(BaseModel): + item_reference: str + """A reference to a variable in the "item" namespace. Ie, "item.name" """ + + type: Literal["item_reference"] + """The type of input messages. Always `item_reference`.""" + + +InputMessages: TypeAlias = Annotated[ + Union[InputMessagesTemplate, InputMessagesItemReference], PropertyInfo(discriminator="type") +] + + class SamplingParams(BaseModel): max_completion_tokens: Optional[int] = None """The maximum number of tokens in the generated output.""" @@ -171,15 +152,15 @@ class SamplingParams(BaseModel): class CreateEvalCompletionsRunDataSource(BaseModel): - input_messages: InputMessages - - model: str - """The name of the model to use for generating completions (e.g. "o3-mini").""" - source: Source """A StoredCompletionsRunDataSource configuration describing a set of filters""" type: Literal["completions"] """The type of run data source. Always `completions`.""" + input_messages: Optional[InputMessages] = None + + model: Optional[str] = None + """The name of the model to use for generating completions (e.g. "o3-mini").""" + sampling_params: Optional[SamplingParams] = None diff --git a/src/openai/types/evals/create_eval_completions_run_data_source_param.py b/src/openai/types/evals/create_eval_completions_run_data_source_param.py index be4a6f1ec6..c53064ee27 100644 --- a/src/openai/types/evals/create_eval_completions_run_data_source_param.py +++ b/src/openai/types/evals/create_eval_completions_run_data_source_param.py @@ -6,100 +6,27 @@ from typing_extensions import Literal, Required, TypeAlias, TypedDict from ..shared_params.metadata import Metadata +from ..responses.easy_input_message_param import EasyInputMessageParam +from ..responses.response_input_text_param import ResponseInputTextParam __all__ = [ "CreateEvalCompletionsRunDataSourceParam", - "InputMessages", - "InputMessagesTemplate", - "InputMessagesTemplateTemplate", - "InputMessagesTemplateTemplateChatMessage", - "InputMessagesTemplateTemplateInputMessage", - "InputMessagesTemplateTemplateInputMessageContent", - "InputMessagesTemplateTemplateOutputMessage", - "InputMessagesTemplateTemplateOutputMessageContent", - "InputMessagesItemReference", "Source", "SourceFileContent", "SourceFileContentContent", "SourceFileID", "SourceStoredCompletions", + "InputMessages", + "InputMessagesTemplate", + "InputMessagesTemplateTemplate", + "InputMessagesTemplateTemplateMessage", + "InputMessagesTemplateTemplateMessageContent", + "InputMessagesTemplateTemplateMessageContentOutputText", + "InputMessagesItemReference", "SamplingParams", ] -class InputMessagesTemplateTemplateChatMessage(TypedDict, total=False): - content: Required[str] - """The content of the message.""" - - role: Required[str] - """The role of the message (e.g. "system", "assistant", "user").""" - - -class InputMessagesTemplateTemplateInputMessageContent(TypedDict, total=False): - text: Required[str] - """The text content.""" - - type: Required[Literal["input_text"]] - """The type of content, which is always `input_text`.""" - - -class InputMessagesTemplateTemplateInputMessage(TypedDict, total=False): - content: Required[InputMessagesTemplateTemplateInputMessageContent] - - role: Required[Literal["user", "system", "developer"]] - """The role of the message. One of `user`, `system`, or `developer`.""" - - type: Required[Literal["message"]] - """The type of item, which is always `message`.""" - - -class InputMessagesTemplateTemplateOutputMessageContent(TypedDict, total=False): - text: Required[str] - """The text content.""" - - type: Required[Literal["output_text"]] - """The type of content, which is always `output_text`.""" - - -class InputMessagesTemplateTemplateOutputMessage(TypedDict, total=False): - content: Required[InputMessagesTemplateTemplateOutputMessageContent] - - role: Required[Literal["assistant"]] - """The role of the message. Must be `assistant` for output.""" - - type: Required[Literal["message"]] - """The type of item, which is always `message`.""" - - -InputMessagesTemplateTemplate: TypeAlias = Union[ - InputMessagesTemplateTemplateChatMessage, - InputMessagesTemplateTemplateInputMessage, - InputMessagesTemplateTemplateOutputMessage, -] - - -class InputMessagesTemplate(TypedDict, total=False): - template: Required[Iterable[InputMessagesTemplateTemplate]] - """A list of chat messages forming the prompt or context. - - May include variable references to the "item" namespace, ie {{item.name}}. - """ - - type: Required[Literal["template"]] - """The type of input messages. Always `template`.""" - - -class InputMessagesItemReference(TypedDict, total=False): - item_reference: Required[str] - """A reference to a variable in the "item" namespace. Ie, "item.name" """ - - type: Required[Literal["item_reference"]] - """The type of input messages. Always `item_reference`.""" - - -InputMessages: TypeAlias = Union[InputMessagesTemplate, InputMessagesItemReference] - - class SourceFileContentContent(TypedDict, total=False): item: Required[Dict[str, object]] @@ -123,16 +50,19 @@ class SourceFileID(TypedDict, total=False): class SourceStoredCompletions(TypedDict, total=False): - created_after: Required[Optional[int]] + type: Required[Literal["stored_completions"]] + """The type of source. Always `stored_completions`.""" + + created_after: Optional[int] """An optional Unix timestamp to filter items created after this time.""" - created_before: Required[Optional[int]] + created_before: Optional[int] """An optional Unix timestamp to filter items created before this time.""" - limit: Required[Optional[int]] + limit: Optional[int] """An optional maximum number of items to return.""" - metadata: Required[Optional[Metadata]] + metadata: Optional[Metadata] """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a @@ -142,16 +72,65 @@ class SourceStoredCompletions(TypedDict, total=False): a maximum length of 512 characters. """ - model: Required[Optional[str]] + model: Optional[str] """An optional model to filter by (e.g., 'gpt-4o').""" - type: Required[Literal["stored_completions"]] - """The type of source. Always `stored_completions`.""" - Source: TypeAlias = Union[SourceFileContent, SourceFileID, SourceStoredCompletions] +class InputMessagesTemplateTemplateMessageContentOutputText(TypedDict, total=False): + text: Required[str] + """The text output from the model.""" + + type: Required[Literal["output_text"]] + """The type of the output text. Always `output_text`.""" + + +InputMessagesTemplateTemplateMessageContent: TypeAlias = Union[ + str, ResponseInputTextParam, InputMessagesTemplateTemplateMessageContentOutputText +] + + +class InputMessagesTemplateTemplateMessage(TypedDict, total=False): + content: Required[InputMessagesTemplateTemplateMessageContent] + """Text inputs to the model - can contain template strings.""" + + role: Required[Literal["user", "assistant", "system", "developer"]] + """The role of the message input. + + One of `user`, `assistant`, `system`, or `developer`. + """ + + type: Literal["message"] + """The type of the message input. Always `message`.""" + + +InputMessagesTemplateTemplate: TypeAlias = Union[EasyInputMessageParam, InputMessagesTemplateTemplateMessage] + + +class InputMessagesTemplate(TypedDict, total=False): + template: Required[Iterable[InputMessagesTemplateTemplate]] + """A list of chat messages forming the prompt or context. + + May include variable references to the "item" namespace, ie {{item.name}}. + """ + + type: Required[Literal["template"]] + """The type of input messages. Always `template`.""" + + +class InputMessagesItemReference(TypedDict, total=False): + item_reference: Required[str] + """A reference to a variable in the "item" namespace. Ie, "item.name" """ + + type: Required[Literal["item_reference"]] + """The type of input messages. Always `item_reference`.""" + + +InputMessages: TypeAlias = Union[InputMessagesTemplate, InputMessagesItemReference] + + class SamplingParams(TypedDict, total=False): max_completion_tokens: int """The maximum number of tokens in the generated output.""" @@ -167,15 +146,15 @@ class SamplingParams(TypedDict, total=False): class CreateEvalCompletionsRunDataSourceParam(TypedDict, total=False): - input_messages: Required[InputMessages] - - model: Required[str] - """The name of the model to use for generating completions (e.g. "o3-mini").""" - source: Required[Source] """A StoredCompletionsRunDataSource configuration describing a set of filters""" type: Required[Literal["completions"]] """The type of run data source. Always `completions`.""" + input_messages: InputMessages + + model: str + """The name of the model to use for generating completions (e.g. "o3-mini").""" + sampling_params: SamplingParams diff --git a/src/openai/types/evals/run_cancel_response.py b/src/openai/types/evals/run_cancel_response.py index 90e52241a6..eb6d689fc3 100644 --- a/src/openai/types/evals/run_cancel_response.py +++ b/src/openai/types/evals/run_cancel_response.py @@ -1,6 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing import List, Union, Optional +from typing import Dict, List, Union, Optional from typing_extensions import Literal, Annotated, TypeAlias from pydantic import Field as FieldInfo @@ -9,13 +9,225 @@ from ..._models import BaseModel from .eval_api_error import EvalAPIError from ..shared.metadata import Metadata +from ..shared.reasoning_effort import ReasoningEffort +from ..responses.response_input_text import ResponseInputText from .create_eval_jsonl_run_data_source import CreateEvalJSONLRunDataSource from .create_eval_completions_run_data_source import CreateEvalCompletionsRunDataSource -__all__ = ["RunCancelResponse", "DataSource", "PerModelUsage", "PerTestingCriteriaResult", "ResultCounts"] +__all__ = [ + "RunCancelResponse", + "DataSource", + "DataSourceCompletions", + "DataSourceCompletionsSource", + "DataSourceCompletionsSourceFileContent", + "DataSourceCompletionsSourceFileContentContent", + "DataSourceCompletionsSourceFileID", + "DataSourceCompletionsSourceResponses", + "DataSourceCompletionsInputMessages", + "DataSourceCompletionsInputMessagesTemplate", + "DataSourceCompletionsInputMessagesTemplateTemplate", + "DataSourceCompletionsInputMessagesTemplateTemplateChatMessage", + "DataSourceCompletionsInputMessagesTemplateTemplateEvalItem", + "DataSourceCompletionsInputMessagesTemplateTemplateEvalItemContent", + "DataSourceCompletionsInputMessagesTemplateTemplateEvalItemContentOutputText", + "DataSourceCompletionsInputMessagesItemReference", + "DataSourceCompletionsSamplingParams", + "PerModelUsage", + "PerTestingCriteriaResult", + "ResultCounts", +] + + +class DataSourceCompletionsSourceFileContentContent(BaseModel): + item: Dict[str, object] + + sample: Optional[Dict[str, object]] = None + + +class DataSourceCompletionsSourceFileContent(BaseModel): + content: List[DataSourceCompletionsSourceFileContentContent] + """The content of the jsonl file.""" + + type: Literal["file_content"] + """The type of jsonl source. Always `file_content`.""" + + +class DataSourceCompletionsSourceFileID(BaseModel): + id: str + """The identifier of the file.""" + + type: Literal["file_id"] + """The type of jsonl source. Always `file_id`.""" + + +class DataSourceCompletionsSourceResponses(BaseModel): + type: Literal["responses"] + """The type of run data source. Always `responses`.""" + + allow_parallel_tool_calls: Optional[bool] = None + """Whether to allow parallel tool calls. + + This is a query parameter used to select responses. + """ + + created_after: Optional[int] = None + """Only include items created after this timestamp (inclusive). + + This is a query parameter used to select responses. + """ + + created_before: Optional[int] = None + """Only include items created before this timestamp (inclusive). + + This is a query parameter used to select responses. + """ + + has_tool_calls: Optional[bool] = None + """Whether the response has tool calls. + + This is a query parameter used to select responses. + """ + + instructions_search: Optional[str] = None + """Optional search string for instructions. + + This is a query parameter used to select responses. + """ + + metadata: Optional[object] = None + """Metadata filter for the responses. + + This is a query parameter used to select responses. + """ + + model: Optional[str] = None + """The name of the model to find responses for. + + This is a query parameter used to select responses. + """ + + reasoning_effort: Optional[ReasoningEffort] = None + """Optional reasoning effort parameter. + + This is a query parameter used to select responses. + """ + + temperature: Optional[float] = None + """Sampling temperature. This is a query parameter used to select responses.""" + + top_p: Optional[float] = None + """Nucleus sampling parameter. This is a query parameter used to select responses.""" + + users: Optional[List[str]] = None + """List of user identifiers. This is a query parameter used to select responses.""" + + +DataSourceCompletionsSource: TypeAlias = Annotated[ + Union[ + DataSourceCompletionsSourceFileContent, DataSourceCompletionsSourceFileID, DataSourceCompletionsSourceResponses + ], + PropertyInfo(discriminator="type"), +] + + +class DataSourceCompletionsInputMessagesTemplateTemplateChatMessage(BaseModel): + content: str + """The content of the message.""" + + role: str + """The role of the message (e.g. "system", "assistant", "user").""" + + +class DataSourceCompletionsInputMessagesTemplateTemplateEvalItemContentOutputText(BaseModel): + text: str + """The text output from the model.""" + + type: Literal["output_text"] + """The type of the output text. Always `output_text`.""" + + +DataSourceCompletionsInputMessagesTemplateTemplateEvalItemContent: TypeAlias = Union[ + str, ResponseInputText, DataSourceCompletionsInputMessagesTemplateTemplateEvalItemContentOutputText +] + + +class DataSourceCompletionsInputMessagesTemplateTemplateEvalItem(BaseModel): + content: DataSourceCompletionsInputMessagesTemplateTemplateEvalItemContent + """Text inputs to the model - can contain template strings.""" + + role: Literal["user", "assistant", "system", "developer"] + """The role of the message input. + + One of `user`, `assistant`, `system`, or `developer`. + """ + + type: Optional[Literal["message"]] = None + """The type of the message input. Always `message`.""" + + +DataSourceCompletionsInputMessagesTemplateTemplate: TypeAlias = Union[ + DataSourceCompletionsInputMessagesTemplateTemplateChatMessage, + DataSourceCompletionsInputMessagesTemplateTemplateEvalItem, +] + + +class DataSourceCompletionsInputMessagesTemplate(BaseModel): + template: List[DataSourceCompletionsInputMessagesTemplateTemplate] + """A list of chat messages forming the prompt or context. + + May include variable references to the "item" namespace, ie {{item.name}}. + """ + + type: Literal["template"] + """The type of input messages. Always `template`.""" + + +class DataSourceCompletionsInputMessagesItemReference(BaseModel): + item_reference: str + """A reference to a variable in the "item" namespace. Ie, "item.name" """ + + type: Literal["item_reference"] + """The type of input messages. Always `item_reference`.""" + + +DataSourceCompletionsInputMessages: TypeAlias = Annotated[ + Union[DataSourceCompletionsInputMessagesTemplate, DataSourceCompletionsInputMessagesItemReference], + PropertyInfo(discriminator="type"), +] + + +class DataSourceCompletionsSamplingParams(BaseModel): + max_completion_tokens: Optional[int] = None + """The maximum number of tokens in the generated output.""" + + seed: Optional[int] = None + """A seed value to initialize the randomness, during sampling.""" + + temperature: Optional[float] = None + """A higher temperature increases randomness in the outputs.""" + + top_p: Optional[float] = None + """An alternative to temperature for nucleus sampling; 1.0 includes all tokens.""" + + +class DataSourceCompletions(BaseModel): + source: DataSourceCompletionsSource + """A EvalResponsesSource object describing a run data source configuration.""" + + type: Literal["completions"] + """The type of run data source. Always `completions`.""" + + input_messages: Optional[DataSourceCompletionsInputMessages] = None + + model: Optional[str] = None + """The name of the model to use for generating completions (e.g. "o3-mini").""" + + sampling_params: Optional[DataSourceCompletionsSamplingParams] = None + DataSource: TypeAlias = Annotated[ - Union[CreateEvalJSONLRunDataSource, CreateEvalCompletionsRunDataSource], PropertyInfo(discriminator="type") + Union[CreateEvalJSONLRunDataSource, CreateEvalCompletionsRunDataSource, DataSourceCompletions], + PropertyInfo(discriminator="type"), ] diff --git a/src/openai/types/evals/run_create_params.py b/src/openai/types/evals/run_create_params.py index acf7b1b126..0c9720ea7a 100644 --- a/src/openai/types/evals/run_create_params.py +++ b/src/openai/types/evals/run_create_params.py @@ -2,14 +2,34 @@ from __future__ import annotations -from typing import Union, Optional -from typing_extensions import Required, TypeAlias, TypedDict +from typing import Dict, List, Union, Iterable, Optional +from typing_extensions import Literal, Required, TypeAlias, TypedDict from ..shared_params.metadata import Metadata +from ..shared.reasoning_effort import ReasoningEffort +from ..responses.response_input_text_param import ResponseInputTextParam from .create_eval_jsonl_run_data_source_param import CreateEvalJSONLRunDataSourceParam from .create_eval_completions_run_data_source_param import CreateEvalCompletionsRunDataSourceParam -__all__ = ["RunCreateParams", "DataSource"] +__all__ = [ + "RunCreateParams", + "DataSource", + "DataSourceCreateEvalResponsesRunDataSource", + "DataSourceCreateEvalResponsesRunDataSourceSource", + "DataSourceCreateEvalResponsesRunDataSourceSourceFileContent", + "DataSourceCreateEvalResponsesRunDataSourceSourceFileContentContent", + "DataSourceCreateEvalResponsesRunDataSourceSourceFileID", + "DataSourceCreateEvalResponsesRunDataSourceSourceResponses", + "DataSourceCreateEvalResponsesRunDataSourceInputMessages", + "DataSourceCreateEvalResponsesRunDataSourceInputMessagesTemplate", + "DataSourceCreateEvalResponsesRunDataSourceInputMessagesTemplateTemplate", + "DataSourceCreateEvalResponsesRunDataSourceInputMessagesTemplateTemplateChatMessage", + "DataSourceCreateEvalResponsesRunDataSourceInputMessagesTemplateTemplateEvalItem", + "DataSourceCreateEvalResponsesRunDataSourceInputMessagesTemplateTemplateEvalItemContent", + "DataSourceCreateEvalResponsesRunDataSourceInputMessagesTemplateTemplateEvalItemContentOutputText", + "DataSourceCreateEvalResponsesRunDataSourceInputMessagesItemReference", + "DataSourceCreateEvalResponsesRunDataSourceSamplingParams", +] class RunCreateParams(TypedDict, total=False): @@ -30,4 +50,198 @@ class RunCreateParams(TypedDict, total=False): """The name of the run.""" -DataSource: TypeAlias = Union[CreateEvalJSONLRunDataSourceParam, CreateEvalCompletionsRunDataSourceParam] +class DataSourceCreateEvalResponsesRunDataSourceSourceFileContentContent(TypedDict, total=False): + item: Required[Dict[str, object]] + + sample: Dict[str, object] + + +class DataSourceCreateEvalResponsesRunDataSourceSourceFileContent(TypedDict, total=False): + content: Required[Iterable[DataSourceCreateEvalResponsesRunDataSourceSourceFileContentContent]] + """The content of the jsonl file.""" + + type: Required[Literal["file_content"]] + """The type of jsonl source. Always `file_content`.""" + + +class DataSourceCreateEvalResponsesRunDataSourceSourceFileID(TypedDict, total=False): + id: Required[str] + """The identifier of the file.""" + + type: Required[Literal["file_id"]] + """The type of jsonl source. Always `file_id`.""" + + +class DataSourceCreateEvalResponsesRunDataSourceSourceResponses(TypedDict, total=False): + type: Required[Literal["responses"]] + """The type of run data source. Always `responses`.""" + + allow_parallel_tool_calls: Optional[bool] + """Whether to allow parallel tool calls. + + This is a query parameter used to select responses. + """ + + created_after: Optional[int] + """Only include items created after this timestamp (inclusive). + + This is a query parameter used to select responses. + """ + + created_before: Optional[int] + """Only include items created before this timestamp (inclusive). + + This is a query parameter used to select responses. + """ + + has_tool_calls: Optional[bool] + """Whether the response has tool calls. + + This is a query parameter used to select responses. + """ + + instructions_search: Optional[str] + """Optional search string for instructions. + + This is a query parameter used to select responses. + """ + + metadata: Optional[object] + """Metadata filter for the responses. + + This is a query parameter used to select responses. + """ + + model: Optional[str] + """The name of the model to find responses for. + + This is a query parameter used to select responses. + """ + + reasoning_effort: Optional[ReasoningEffort] + """Optional reasoning effort parameter. + + This is a query parameter used to select responses. + """ + + temperature: Optional[float] + """Sampling temperature. This is a query parameter used to select responses.""" + + top_p: Optional[float] + """Nucleus sampling parameter. This is a query parameter used to select responses.""" + + users: Optional[List[str]] + """List of user identifiers. This is a query parameter used to select responses.""" + + +DataSourceCreateEvalResponsesRunDataSourceSource: TypeAlias = Union[ + DataSourceCreateEvalResponsesRunDataSourceSourceFileContent, + DataSourceCreateEvalResponsesRunDataSourceSourceFileID, + DataSourceCreateEvalResponsesRunDataSourceSourceResponses, +] + + +class DataSourceCreateEvalResponsesRunDataSourceInputMessagesTemplateTemplateChatMessage(TypedDict, total=False): + content: Required[str] + """The content of the message.""" + + role: Required[str] + """The role of the message (e.g. "system", "assistant", "user").""" + + +class DataSourceCreateEvalResponsesRunDataSourceInputMessagesTemplateTemplateEvalItemContentOutputText( + TypedDict, total=False +): + text: Required[str] + """The text output from the model.""" + + type: Required[Literal["output_text"]] + """The type of the output text. Always `output_text`.""" + + +DataSourceCreateEvalResponsesRunDataSourceInputMessagesTemplateTemplateEvalItemContent: TypeAlias = Union[ + str, + ResponseInputTextParam, + DataSourceCreateEvalResponsesRunDataSourceInputMessagesTemplateTemplateEvalItemContentOutputText, +] + + +class DataSourceCreateEvalResponsesRunDataSourceInputMessagesTemplateTemplateEvalItem(TypedDict, total=False): + content: Required[DataSourceCreateEvalResponsesRunDataSourceInputMessagesTemplateTemplateEvalItemContent] + """Text inputs to the model - can contain template strings.""" + + role: Required[Literal["user", "assistant", "system", "developer"]] + """The role of the message input. + + One of `user`, `assistant`, `system`, or `developer`. + """ + + type: Literal["message"] + """The type of the message input. Always `message`.""" + + +DataSourceCreateEvalResponsesRunDataSourceInputMessagesTemplateTemplate: TypeAlias = Union[ + DataSourceCreateEvalResponsesRunDataSourceInputMessagesTemplateTemplateChatMessage, + DataSourceCreateEvalResponsesRunDataSourceInputMessagesTemplateTemplateEvalItem, +] + + +class DataSourceCreateEvalResponsesRunDataSourceInputMessagesTemplate(TypedDict, total=False): + template: Required[Iterable[DataSourceCreateEvalResponsesRunDataSourceInputMessagesTemplateTemplate]] + """A list of chat messages forming the prompt or context. + + May include variable references to the "item" namespace, ie {{item.name}}. + """ + + type: Required[Literal["template"]] + """The type of input messages. Always `template`.""" + + +class DataSourceCreateEvalResponsesRunDataSourceInputMessagesItemReference(TypedDict, total=False): + item_reference: Required[str] + """A reference to a variable in the "item" namespace. Ie, "item.name" """ + + type: Required[Literal["item_reference"]] + """The type of input messages. Always `item_reference`.""" + + +DataSourceCreateEvalResponsesRunDataSourceInputMessages: TypeAlias = Union[ + DataSourceCreateEvalResponsesRunDataSourceInputMessagesTemplate, + DataSourceCreateEvalResponsesRunDataSourceInputMessagesItemReference, +] + + +class DataSourceCreateEvalResponsesRunDataSourceSamplingParams(TypedDict, total=False): + max_completion_tokens: int + """The maximum number of tokens in the generated output.""" + + seed: int + """A seed value to initialize the randomness, during sampling.""" + + temperature: float + """A higher temperature increases randomness in the outputs.""" + + top_p: float + """An alternative to temperature for nucleus sampling; 1.0 includes all tokens.""" + + +class DataSourceCreateEvalResponsesRunDataSource(TypedDict, total=False): + source: Required[DataSourceCreateEvalResponsesRunDataSourceSource] + """A EvalResponsesSource object describing a run data source configuration.""" + + type: Required[Literal["completions"]] + """The type of run data source. Always `completions`.""" + + input_messages: DataSourceCreateEvalResponsesRunDataSourceInputMessages + + model: str + """The name of the model to use for generating completions (e.g. "o3-mini").""" + + sampling_params: DataSourceCreateEvalResponsesRunDataSourceSamplingParams + + +DataSource: TypeAlias = Union[ + CreateEvalJSONLRunDataSourceParam, + CreateEvalCompletionsRunDataSourceParam, + DataSourceCreateEvalResponsesRunDataSource, +] diff --git a/src/openai/types/evals/run_create_response.py b/src/openai/types/evals/run_create_response.py index 14ca426427..459399511c 100644 --- a/src/openai/types/evals/run_create_response.py +++ b/src/openai/types/evals/run_create_response.py @@ -1,6 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing import List, Union, Optional +from typing import Dict, List, Union, Optional from typing_extensions import Literal, Annotated, TypeAlias from pydantic import Field as FieldInfo @@ -9,13 +9,225 @@ from ..._models import BaseModel from .eval_api_error import EvalAPIError from ..shared.metadata import Metadata +from ..shared.reasoning_effort import ReasoningEffort +from ..responses.response_input_text import ResponseInputText from .create_eval_jsonl_run_data_source import CreateEvalJSONLRunDataSource from .create_eval_completions_run_data_source import CreateEvalCompletionsRunDataSource -__all__ = ["RunCreateResponse", "DataSource", "PerModelUsage", "PerTestingCriteriaResult", "ResultCounts"] +__all__ = [ + "RunCreateResponse", + "DataSource", + "DataSourceCompletions", + "DataSourceCompletionsSource", + "DataSourceCompletionsSourceFileContent", + "DataSourceCompletionsSourceFileContentContent", + "DataSourceCompletionsSourceFileID", + "DataSourceCompletionsSourceResponses", + "DataSourceCompletionsInputMessages", + "DataSourceCompletionsInputMessagesTemplate", + "DataSourceCompletionsInputMessagesTemplateTemplate", + "DataSourceCompletionsInputMessagesTemplateTemplateChatMessage", + "DataSourceCompletionsInputMessagesTemplateTemplateEvalItem", + "DataSourceCompletionsInputMessagesTemplateTemplateEvalItemContent", + "DataSourceCompletionsInputMessagesTemplateTemplateEvalItemContentOutputText", + "DataSourceCompletionsInputMessagesItemReference", + "DataSourceCompletionsSamplingParams", + "PerModelUsage", + "PerTestingCriteriaResult", + "ResultCounts", +] + + +class DataSourceCompletionsSourceFileContentContent(BaseModel): + item: Dict[str, object] + + sample: Optional[Dict[str, object]] = None + + +class DataSourceCompletionsSourceFileContent(BaseModel): + content: List[DataSourceCompletionsSourceFileContentContent] + """The content of the jsonl file.""" + + type: Literal["file_content"] + """The type of jsonl source. Always `file_content`.""" + + +class DataSourceCompletionsSourceFileID(BaseModel): + id: str + """The identifier of the file.""" + + type: Literal["file_id"] + """The type of jsonl source. Always `file_id`.""" + + +class DataSourceCompletionsSourceResponses(BaseModel): + type: Literal["responses"] + """The type of run data source. Always `responses`.""" + + allow_parallel_tool_calls: Optional[bool] = None + """Whether to allow parallel tool calls. + + This is a query parameter used to select responses. + """ + + created_after: Optional[int] = None + """Only include items created after this timestamp (inclusive). + + This is a query parameter used to select responses. + """ + + created_before: Optional[int] = None + """Only include items created before this timestamp (inclusive). + + This is a query parameter used to select responses. + """ + + has_tool_calls: Optional[bool] = None + """Whether the response has tool calls. + + This is a query parameter used to select responses. + """ + + instructions_search: Optional[str] = None + """Optional search string for instructions. + + This is a query parameter used to select responses. + """ + + metadata: Optional[object] = None + """Metadata filter for the responses. + + This is a query parameter used to select responses. + """ + + model: Optional[str] = None + """The name of the model to find responses for. + + This is a query parameter used to select responses. + """ + + reasoning_effort: Optional[ReasoningEffort] = None + """Optional reasoning effort parameter. + + This is a query parameter used to select responses. + """ + + temperature: Optional[float] = None + """Sampling temperature. This is a query parameter used to select responses.""" + + top_p: Optional[float] = None + """Nucleus sampling parameter. This is a query parameter used to select responses.""" + + users: Optional[List[str]] = None + """List of user identifiers. This is a query parameter used to select responses.""" + + +DataSourceCompletionsSource: TypeAlias = Annotated[ + Union[ + DataSourceCompletionsSourceFileContent, DataSourceCompletionsSourceFileID, DataSourceCompletionsSourceResponses + ], + PropertyInfo(discriminator="type"), +] + + +class DataSourceCompletionsInputMessagesTemplateTemplateChatMessage(BaseModel): + content: str + """The content of the message.""" + + role: str + """The role of the message (e.g. "system", "assistant", "user").""" + + +class DataSourceCompletionsInputMessagesTemplateTemplateEvalItemContentOutputText(BaseModel): + text: str + """The text output from the model.""" + + type: Literal["output_text"] + """The type of the output text. Always `output_text`.""" + + +DataSourceCompletionsInputMessagesTemplateTemplateEvalItemContent: TypeAlias = Union[ + str, ResponseInputText, DataSourceCompletionsInputMessagesTemplateTemplateEvalItemContentOutputText +] + + +class DataSourceCompletionsInputMessagesTemplateTemplateEvalItem(BaseModel): + content: DataSourceCompletionsInputMessagesTemplateTemplateEvalItemContent + """Text inputs to the model - can contain template strings.""" + + role: Literal["user", "assistant", "system", "developer"] + """The role of the message input. + + One of `user`, `assistant`, `system`, or `developer`. + """ + + type: Optional[Literal["message"]] = None + """The type of the message input. Always `message`.""" + + +DataSourceCompletionsInputMessagesTemplateTemplate: TypeAlias = Union[ + DataSourceCompletionsInputMessagesTemplateTemplateChatMessage, + DataSourceCompletionsInputMessagesTemplateTemplateEvalItem, +] + + +class DataSourceCompletionsInputMessagesTemplate(BaseModel): + template: List[DataSourceCompletionsInputMessagesTemplateTemplate] + """A list of chat messages forming the prompt or context. + + May include variable references to the "item" namespace, ie {{item.name}}. + """ + + type: Literal["template"] + """The type of input messages. Always `template`.""" + + +class DataSourceCompletionsInputMessagesItemReference(BaseModel): + item_reference: str + """A reference to a variable in the "item" namespace. Ie, "item.name" """ + + type: Literal["item_reference"] + """The type of input messages. Always `item_reference`.""" + + +DataSourceCompletionsInputMessages: TypeAlias = Annotated[ + Union[DataSourceCompletionsInputMessagesTemplate, DataSourceCompletionsInputMessagesItemReference], + PropertyInfo(discriminator="type"), +] + + +class DataSourceCompletionsSamplingParams(BaseModel): + max_completion_tokens: Optional[int] = None + """The maximum number of tokens in the generated output.""" + + seed: Optional[int] = None + """A seed value to initialize the randomness, during sampling.""" + + temperature: Optional[float] = None + """A higher temperature increases randomness in the outputs.""" + + top_p: Optional[float] = None + """An alternative to temperature for nucleus sampling; 1.0 includes all tokens.""" + + +class DataSourceCompletions(BaseModel): + source: DataSourceCompletionsSource + """A EvalResponsesSource object describing a run data source configuration.""" + + type: Literal["completions"] + """The type of run data source. Always `completions`.""" + + input_messages: Optional[DataSourceCompletionsInputMessages] = None + + model: Optional[str] = None + """The name of the model to use for generating completions (e.g. "o3-mini").""" + + sampling_params: Optional[DataSourceCompletionsSamplingParams] = None + DataSource: TypeAlias = Annotated[ - Union[CreateEvalJSONLRunDataSource, CreateEvalCompletionsRunDataSource], PropertyInfo(discriminator="type") + Union[CreateEvalJSONLRunDataSource, CreateEvalCompletionsRunDataSource, DataSourceCompletions], + PropertyInfo(discriminator="type"), ] diff --git a/src/openai/types/evals/run_list_params.py b/src/openai/types/evals/run_list_params.py index 6060eafb97..383b89d85c 100644 --- a/src/openai/types/evals/run_list_params.py +++ b/src/openai/types/evals/run_list_params.py @@ -23,5 +23,5 @@ class RunListParams(TypedDict, total=False): status: Literal["queued", "in_progress", "completed", "canceled", "failed"] """Filter runs by status. - Use "queued" | "in_progress" | "failed" | "completed" | "canceled". + One of `queued` | `in_progress` | `failed` | `completed` | `canceled`. """ diff --git a/src/openai/types/evals/run_list_response.py b/src/openai/types/evals/run_list_response.py index a1022f542f..278ceeabed 100644 --- a/src/openai/types/evals/run_list_response.py +++ b/src/openai/types/evals/run_list_response.py @@ -1,6 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing import List, Union, Optional +from typing import Dict, List, Union, Optional from typing_extensions import Literal, Annotated, TypeAlias from pydantic import Field as FieldInfo @@ -9,13 +9,225 @@ from ..._models import BaseModel from .eval_api_error import EvalAPIError from ..shared.metadata import Metadata +from ..shared.reasoning_effort import ReasoningEffort +from ..responses.response_input_text import ResponseInputText from .create_eval_jsonl_run_data_source import CreateEvalJSONLRunDataSource from .create_eval_completions_run_data_source import CreateEvalCompletionsRunDataSource -__all__ = ["RunListResponse", "DataSource", "PerModelUsage", "PerTestingCriteriaResult", "ResultCounts"] +__all__ = [ + "RunListResponse", + "DataSource", + "DataSourceCompletions", + "DataSourceCompletionsSource", + "DataSourceCompletionsSourceFileContent", + "DataSourceCompletionsSourceFileContentContent", + "DataSourceCompletionsSourceFileID", + "DataSourceCompletionsSourceResponses", + "DataSourceCompletionsInputMessages", + "DataSourceCompletionsInputMessagesTemplate", + "DataSourceCompletionsInputMessagesTemplateTemplate", + "DataSourceCompletionsInputMessagesTemplateTemplateChatMessage", + "DataSourceCompletionsInputMessagesTemplateTemplateEvalItem", + "DataSourceCompletionsInputMessagesTemplateTemplateEvalItemContent", + "DataSourceCompletionsInputMessagesTemplateTemplateEvalItemContentOutputText", + "DataSourceCompletionsInputMessagesItemReference", + "DataSourceCompletionsSamplingParams", + "PerModelUsage", + "PerTestingCriteriaResult", + "ResultCounts", +] + + +class DataSourceCompletionsSourceFileContentContent(BaseModel): + item: Dict[str, object] + + sample: Optional[Dict[str, object]] = None + + +class DataSourceCompletionsSourceFileContent(BaseModel): + content: List[DataSourceCompletionsSourceFileContentContent] + """The content of the jsonl file.""" + + type: Literal["file_content"] + """The type of jsonl source. Always `file_content`.""" + + +class DataSourceCompletionsSourceFileID(BaseModel): + id: str + """The identifier of the file.""" + + type: Literal["file_id"] + """The type of jsonl source. Always `file_id`.""" + + +class DataSourceCompletionsSourceResponses(BaseModel): + type: Literal["responses"] + """The type of run data source. Always `responses`.""" + + allow_parallel_tool_calls: Optional[bool] = None + """Whether to allow parallel tool calls. + + This is a query parameter used to select responses. + """ + + created_after: Optional[int] = None + """Only include items created after this timestamp (inclusive). + + This is a query parameter used to select responses. + """ + + created_before: Optional[int] = None + """Only include items created before this timestamp (inclusive). + + This is a query parameter used to select responses. + """ + + has_tool_calls: Optional[bool] = None + """Whether the response has tool calls. + + This is a query parameter used to select responses. + """ + + instructions_search: Optional[str] = None + """Optional search string for instructions. + + This is a query parameter used to select responses. + """ + + metadata: Optional[object] = None + """Metadata filter for the responses. + + This is a query parameter used to select responses. + """ + + model: Optional[str] = None + """The name of the model to find responses for. + + This is a query parameter used to select responses. + """ + + reasoning_effort: Optional[ReasoningEffort] = None + """Optional reasoning effort parameter. + + This is a query parameter used to select responses. + """ + + temperature: Optional[float] = None + """Sampling temperature. This is a query parameter used to select responses.""" + + top_p: Optional[float] = None + """Nucleus sampling parameter. This is a query parameter used to select responses.""" + + users: Optional[List[str]] = None + """List of user identifiers. This is a query parameter used to select responses.""" + + +DataSourceCompletionsSource: TypeAlias = Annotated[ + Union[ + DataSourceCompletionsSourceFileContent, DataSourceCompletionsSourceFileID, DataSourceCompletionsSourceResponses + ], + PropertyInfo(discriminator="type"), +] + + +class DataSourceCompletionsInputMessagesTemplateTemplateChatMessage(BaseModel): + content: str + """The content of the message.""" + + role: str + """The role of the message (e.g. "system", "assistant", "user").""" + + +class DataSourceCompletionsInputMessagesTemplateTemplateEvalItemContentOutputText(BaseModel): + text: str + """The text output from the model.""" + + type: Literal["output_text"] + """The type of the output text. Always `output_text`.""" + + +DataSourceCompletionsInputMessagesTemplateTemplateEvalItemContent: TypeAlias = Union[ + str, ResponseInputText, DataSourceCompletionsInputMessagesTemplateTemplateEvalItemContentOutputText +] + + +class DataSourceCompletionsInputMessagesTemplateTemplateEvalItem(BaseModel): + content: DataSourceCompletionsInputMessagesTemplateTemplateEvalItemContent + """Text inputs to the model - can contain template strings.""" + + role: Literal["user", "assistant", "system", "developer"] + """The role of the message input. + + One of `user`, `assistant`, `system`, or `developer`. + """ + + type: Optional[Literal["message"]] = None + """The type of the message input. Always `message`.""" + + +DataSourceCompletionsInputMessagesTemplateTemplate: TypeAlias = Union[ + DataSourceCompletionsInputMessagesTemplateTemplateChatMessage, + DataSourceCompletionsInputMessagesTemplateTemplateEvalItem, +] + + +class DataSourceCompletionsInputMessagesTemplate(BaseModel): + template: List[DataSourceCompletionsInputMessagesTemplateTemplate] + """A list of chat messages forming the prompt or context. + + May include variable references to the "item" namespace, ie {{item.name}}. + """ + + type: Literal["template"] + """The type of input messages. Always `template`.""" + + +class DataSourceCompletionsInputMessagesItemReference(BaseModel): + item_reference: str + """A reference to a variable in the "item" namespace. Ie, "item.name" """ + + type: Literal["item_reference"] + """The type of input messages. Always `item_reference`.""" + + +DataSourceCompletionsInputMessages: TypeAlias = Annotated[ + Union[DataSourceCompletionsInputMessagesTemplate, DataSourceCompletionsInputMessagesItemReference], + PropertyInfo(discriminator="type"), +] + + +class DataSourceCompletionsSamplingParams(BaseModel): + max_completion_tokens: Optional[int] = None + """The maximum number of tokens in the generated output.""" + + seed: Optional[int] = None + """A seed value to initialize the randomness, during sampling.""" + + temperature: Optional[float] = None + """A higher temperature increases randomness in the outputs.""" + + top_p: Optional[float] = None + """An alternative to temperature for nucleus sampling; 1.0 includes all tokens.""" + + +class DataSourceCompletions(BaseModel): + source: DataSourceCompletionsSource + """A EvalResponsesSource object describing a run data source configuration.""" + + type: Literal["completions"] + """The type of run data source. Always `completions`.""" + + input_messages: Optional[DataSourceCompletionsInputMessages] = None + + model: Optional[str] = None + """The name of the model to use for generating completions (e.g. "o3-mini").""" + + sampling_params: Optional[DataSourceCompletionsSamplingParams] = None + DataSource: TypeAlias = Annotated[ - Union[CreateEvalJSONLRunDataSource, CreateEvalCompletionsRunDataSource], PropertyInfo(discriminator="type") + Union[CreateEvalJSONLRunDataSource, CreateEvalCompletionsRunDataSource, DataSourceCompletions], + PropertyInfo(discriminator="type"), ] diff --git a/src/openai/types/evals/run_retrieve_response.py b/src/openai/types/evals/run_retrieve_response.py index 461ed43dda..e142f31b14 100644 --- a/src/openai/types/evals/run_retrieve_response.py +++ b/src/openai/types/evals/run_retrieve_response.py @@ -1,6 +1,6 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing import List, Union, Optional +from typing import Dict, List, Union, Optional from typing_extensions import Literal, Annotated, TypeAlias from pydantic import Field as FieldInfo @@ -9,13 +9,225 @@ from ..._models import BaseModel from .eval_api_error import EvalAPIError from ..shared.metadata import Metadata +from ..shared.reasoning_effort import ReasoningEffort +from ..responses.response_input_text import ResponseInputText from .create_eval_jsonl_run_data_source import CreateEvalJSONLRunDataSource from .create_eval_completions_run_data_source import CreateEvalCompletionsRunDataSource -__all__ = ["RunRetrieveResponse", "DataSource", "PerModelUsage", "PerTestingCriteriaResult", "ResultCounts"] +__all__ = [ + "RunRetrieveResponse", + "DataSource", + "DataSourceCompletions", + "DataSourceCompletionsSource", + "DataSourceCompletionsSourceFileContent", + "DataSourceCompletionsSourceFileContentContent", + "DataSourceCompletionsSourceFileID", + "DataSourceCompletionsSourceResponses", + "DataSourceCompletionsInputMessages", + "DataSourceCompletionsInputMessagesTemplate", + "DataSourceCompletionsInputMessagesTemplateTemplate", + "DataSourceCompletionsInputMessagesTemplateTemplateChatMessage", + "DataSourceCompletionsInputMessagesTemplateTemplateEvalItem", + "DataSourceCompletionsInputMessagesTemplateTemplateEvalItemContent", + "DataSourceCompletionsInputMessagesTemplateTemplateEvalItemContentOutputText", + "DataSourceCompletionsInputMessagesItemReference", + "DataSourceCompletionsSamplingParams", + "PerModelUsage", + "PerTestingCriteriaResult", + "ResultCounts", +] + + +class DataSourceCompletionsSourceFileContentContent(BaseModel): + item: Dict[str, object] + + sample: Optional[Dict[str, object]] = None + + +class DataSourceCompletionsSourceFileContent(BaseModel): + content: List[DataSourceCompletionsSourceFileContentContent] + """The content of the jsonl file.""" + + type: Literal["file_content"] + """The type of jsonl source. Always `file_content`.""" + + +class DataSourceCompletionsSourceFileID(BaseModel): + id: str + """The identifier of the file.""" + + type: Literal["file_id"] + """The type of jsonl source. Always `file_id`.""" + + +class DataSourceCompletionsSourceResponses(BaseModel): + type: Literal["responses"] + """The type of run data source. Always `responses`.""" + + allow_parallel_tool_calls: Optional[bool] = None + """Whether to allow parallel tool calls. + + This is a query parameter used to select responses. + """ + + created_after: Optional[int] = None + """Only include items created after this timestamp (inclusive). + + This is a query parameter used to select responses. + """ + + created_before: Optional[int] = None + """Only include items created before this timestamp (inclusive). + + This is a query parameter used to select responses. + """ + + has_tool_calls: Optional[bool] = None + """Whether the response has tool calls. + + This is a query parameter used to select responses. + """ + + instructions_search: Optional[str] = None + """Optional search string for instructions. + + This is a query parameter used to select responses. + """ + + metadata: Optional[object] = None + """Metadata filter for the responses. + + This is a query parameter used to select responses. + """ + + model: Optional[str] = None + """The name of the model to find responses for. + + This is a query parameter used to select responses. + """ + + reasoning_effort: Optional[ReasoningEffort] = None + """Optional reasoning effort parameter. + + This is a query parameter used to select responses. + """ + + temperature: Optional[float] = None + """Sampling temperature. This is a query parameter used to select responses.""" + + top_p: Optional[float] = None + """Nucleus sampling parameter. This is a query parameter used to select responses.""" + + users: Optional[List[str]] = None + """List of user identifiers. This is a query parameter used to select responses.""" + + +DataSourceCompletionsSource: TypeAlias = Annotated[ + Union[ + DataSourceCompletionsSourceFileContent, DataSourceCompletionsSourceFileID, DataSourceCompletionsSourceResponses + ], + PropertyInfo(discriminator="type"), +] + + +class DataSourceCompletionsInputMessagesTemplateTemplateChatMessage(BaseModel): + content: str + """The content of the message.""" + + role: str + """The role of the message (e.g. "system", "assistant", "user").""" + + +class DataSourceCompletionsInputMessagesTemplateTemplateEvalItemContentOutputText(BaseModel): + text: str + """The text output from the model.""" + + type: Literal["output_text"] + """The type of the output text. Always `output_text`.""" + + +DataSourceCompletionsInputMessagesTemplateTemplateEvalItemContent: TypeAlias = Union[ + str, ResponseInputText, DataSourceCompletionsInputMessagesTemplateTemplateEvalItemContentOutputText +] + + +class DataSourceCompletionsInputMessagesTemplateTemplateEvalItem(BaseModel): + content: DataSourceCompletionsInputMessagesTemplateTemplateEvalItemContent + """Text inputs to the model - can contain template strings.""" + + role: Literal["user", "assistant", "system", "developer"] + """The role of the message input. + + One of `user`, `assistant`, `system`, or `developer`. + """ + + type: Optional[Literal["message"]] = None + """The type of the message input. Always `message`.""" + + +DataSourceCompletionsInputMessagesTemplateTemplate: TypeAlias = Union[ + DataSourceCompletionsInputMessagesTemplateTemplateChatMessage, + DataSourceCompletionsInputMessagesTemplateTemplateEvalItem, +] + + +class DataSourceCompletionsInputMessagesTemplate(BaseModel): + template: List[DataSourceCompletionsInputMessagesTemplateTemplate] + """A list of chat messages forming the prompt or context. + + May include variable references to the "item" namespace, ie {{item.name}}. + """ + + type: Literal["template"] + """The type of input messages. Always `template`.""" + + +class DataSourceCompletionsInputMessagesItemReference(BaseModel): + item_reference: str + """A reference to a variable in the "item" namespace. Ie, "item.name" """ + + type: Literal["item_reference"] + """The type of input messages. Always `item_reference`.""" + + +DataSourceCompletionsInputMessages: TypeAlias = Annotated[ + Union[DataSourceCompletionsInputMessagesTemplate, DataSourceCompletionsInputMessagesItemReference], + PropertyInfo(discriminator="type"), +] + + +class DataSourceCompletionsSamplingParams(BaseModel): + max_completion_tokens: Optional[int] = None + """The maximum number of tokens in the generated output.""" + + seed: Optional[int] = None + """A seed value to initialize the randomness, during sampling.""" + + temperature: Optional[float] = None + """A higher temperature increases randomness in the outputs.""" + + top_p: Optional[float] = None + """An alternative to temperature for nucleus sampling; 1.0 includes all tokens.""" + + +class DataSourceCompletions(BaseModel): + source: DataSourceCompletionsSource + """A EvalResponsesSource object describing a run data source configuration.""" + + type: Literal["completions"] + """The type of run data source. Always `completions`.""" + + input_messages: Optional[DataSourceCompletionsInputMessages] = None + + model: Optional[str] = None + """The name of the model to use for generating completions (e.g. "o3-mini").""" + + sampling_params: Optional[DataSourceCompletionsSamplingParams] = None + DataSource: TypeAlias = Annotated[ - Union[CreateEvalJSONLRunDataSource, CreateEvalCompletionsRunDataSource], PropertyInfo(discriminator="type") + Union[CreateEvalJSONLRunDataSource, CreateEvalCompletionsRunDataSource, DataSourceCompletions], + PropertyInfo(discriminator="type"), ] diff --git a/src/openai/types/image.py b/src/openai/types/image.py index f48aa2c702..ecaef3fd58 100644 --- a/src/openai/types/image.py +++ b/src/openai/types/image.py @@ -9,16 +9,18 @@ class Image(BaseModel): b64_json: Optional[str] = None - """ - The base64-encoded JSON of the generated image, if `response_format` is - `b64_json`. + """The base64-encoded JSON of the generated image. + + Default value for `gpt-image-1`, and only present if `response_format` is set to + `b64_json` for `dall-e-2` and `dall-e-3`. """ revised_prompt: Optional[str] = None - """ - The prompt that was used to generate the image, if there was any revision to the - prompt. - """ + """For `dall-e-3` only, the revised prompt that was used to generate the image.""" url: Optional[str] = None - """The URL of the generated image, if `response_format` is `url` (default).""" + """ + When using `dall-e-2` or `dall-e-3`, the URL of the generated image if + `response_format` is set to `url` (default value). Unsupported for + `gpt-image-1`. + """ diff --git a/src/openai/types/image_create_variation_params.py b/src/openai/types/image_create_variation_params.py index d20f672912..d10b74b2c2 100644 --- a/src/openai/types/image_create_variation_params.py +++ b/src/openai/types/image_create_variation_params.py @@ -25,10 +25,7 @@ class ImageCreateVariationParams(TypedDict, total=False): """ n: Optional[int] - """The number of images to generate. - - Must be between 1 and 10. For `dall-e-3`, only `n=1` is supported. - """ + """The number of images to generate. Must be between 1 and 10.""" response_format: Optional[Literal["url", "b64_json"]] """The format in which the generated images are returned. diff --git a/src/openai/types/image_edit_params.py b/src/openai/types/image_edit_params.py index 1cb10611f3..f01a12c1b0 100644 --- a/src/openai/types/image_edit_params.py +++ b/src/openai/types/image_edit_params.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Union, Optional +from typing import List, Union, Optional from typing_extensions import Literal, Required, TypedDict from .._types import FileTypes @@ -12,46 +12,61 @@ class ImageEditParams(TypedDict, total=False): - image: Required[FileTypes] - """The image to edit. + image: Required[Union[FileTypes, List[FileTypes]]] + """The image(s) to edit. - Must be a valid PNG file, less than 4MB, and square. If mask is not provided, - image must have transparency, which will be used as the mask. + Must be a supported image file or an array of images. For `gpt-image-1`, each + image should be a `png`, `webp`, or `jpg` file less than 25MB. For `dall-e-2`, + you can only provide one image, and it should be a square `png` file less than + 4MB. """ prompt: Required[str] """A text description of the desired image(s). - The maximum length is 1000 characters. + The maximum length is 1000 characters for `dall-e-2`, and 32000 characters for + `gpt-image-1`. """ mask: FileTypes """An additional image whose fully transparent areas (e.g. - where alpha is zero) indicate where `image` should be edited. Must be a valid - PNG file, less than 4MB, and have the same dimensions as `image`. + where alpha is zero) indicate where `image` should be edited. If there are + multiple images provided, the mask will be applied on the first image. Must be a + valid PNG file, less than 4MB, and have the same dimensions as `image`. """ model: Union[str, ImageModel, None] """The model to use for image generation. - Only `dall-e-2` is supported at this time. + Only `dall-e-2` and `gpt-image-1` are supported. Defaults to `dall-e-2` unless a + parameter specific to `gpt-image-1` is used. """ n: Optional[int] """The number of images to generate. Must be between 1 and 10.""" + quality: Optional[Literal["standard", "low", "medium", "high", "auto"]] + """The quality of the image that will be generated. + + `high`, `medium` and `low` are only supported for `gpt-image-1`. `dall-e-2` only + supports `standard` quality. Defaults to `auto`. + """ + response_format: Optional[Literal["url", "b64_json"]] """The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the - image has been generated. + image has been generated. This parameter is only supported for `dall-e-2`, as + `gpt-image-1` will always return base64-encoded images. """ size: Optional[Literal["256x256", "512x512", "1024x1024"]] """The size of the generated images. - Must be one of `256x256`, `512x512`, or `1024x1024`. + Must be one of `1024x1024`, `1536x1024` (landscape), `1024x1536` (portrait), or + `auto` (default value) for `gpt-image-1`, and one of `256x256`, `512x512`, or + `1024x1024` for `dall-e-2`. """ user: str diff --git a/src/openai/types/image_generate_params.py b/src/openai/types/image_generate_params.py index c88c45f518..8fc10220dc 100644 --- a/src/openai/types/image_generate_params.py +++ b/src/openai/types/image_generate_params.py @@ -14,12 +14,33 @@ class ImageGenerateParams(TypedDict, total=False): prompt: Required[str] """A text description of the desired image(s). - The maximum length is 1000 characters for `dall-e-2` and 4000 characters for - `dall-e-3`. + The maximum length is 32000 characters for `gpt-image-1`, 1000 characters for + `dall-e-2` and 4000 characters for `dall-e-3`. + """ + + background: Optional[Literal["transparent", "opaque", "auto"]] + """Allows to set transparency for the background of the generated image(s). + + This parameter is only supported for `gpt-image-1`. Must be one of + `transparent`, `opaque` or `auto` (default value). When `auto` is used, the + model will automatically determine the best background for the image. + + If `transparent`, the output format needs to support transparency, so it should + be set to either `png` (default value) or `webp`. """ model: Union[str, ImageModel, None] - """The model to use for image generation.""" + """The model to use for image generation. + + One of `dall-e-2`, `dall-e-3`, or `gpt-image-1`. Defaults to `dall-e-2` unless a + parameter specific to `gpt-image-1` is used. + """ + + moderation: Optional[Literal["low", "auto"]] + """Control the content-moderation level for images generated by `gpt-image-1`. + + Must be either `low` for less restrictive filtering or `auto` (default value). + """ n: Optional[int] """The number of images to generate. @@ -27,34 +48,57 @@ class ImageGenerateParams(TypedDict, total=False): Must be between 1 and 10. For `dall-e-3`, only `n=1` is supported. """ - quality: Literal["standard", "hd"] + output_compression: Optional[int] + """The compression level (0-100%) for the generated images. + + This parameter is only supported for `gpt-image-1` with the `webp` or `jpeg` + output formats, and defaults to 100. + """ + + output_format: Optional[Literal["png", "jpeg", "webp"]] + """The format in which the generated images are returned. + + This parameter is only supported for `gpt-image-1`. Must be one of `png`, + `jpeg`, or `webp`. + """ + + quality: Optional[Literal["standard", "hd", "low", "medium", "high", "auto"]] """The quality of the image that will be generated. - `hd` creates images with finer details and greater consistency across the image. - This param is only supported for `dall-e-3`. + - `auto` (default value) will automatically select the best quality for the + given model. + - `high`, `medium` and `low` are supported for `gpt-image-1`. + - `hd` and `standard` are supported for `dall-e-3`. + - `standard` is the only option for `dall-e-2`. """ response_format: Optional[Literal["url", "b64_json"]] - """The format in which the generated images are returned. + """The format in which generated images with `dall-e-2` and `dall-e-3` are + returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the - image has been generated. + image has been generated. This parameter isn't supported for `gpt-image-1` which + will always return base64-encoded images. """ - size: Optional[Literal["256x256", "512x512", "1024x1024", "1792x1024", "1024x1792"]] + size: Optional[ + Literal["auto", "1024x1024", "1536x1024", "1024x1536", "256x256", "512x512", "1792x1024", "1024x1792"] + ] """The size of the generated images. - Must be one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`. Must be one - of `1024x1024`, `1792x1024`, or `1024x1792` for `dall-e-3` models. + Must be one of `1024x1024`, `1536x1024` (landscape), `1024x1536` (portrait), or + `auto` (default value) for `gpt-image-1`, one of `256x256`, `512x512`, or + `1024x1024` for `dall-e-2`, and one of `1024x1024`, `1792x1024`, or `1024x1792` + for `dall-e-3`. """ style: Optional[Literal["vivid", "natural"]] """The style of the generated images. - Must be one of `vivid` or `natural`. Vivid causes the model to lean towards - generating hyper-real and dramatic images. Natural causes the model to produce - more natural, less hyper-real looking images. This param is only supported for - `dall-e-3`. + This parameter is only supported for `dall-e-3`. Must be one of `vivid` or + `natural`. Vivid causes the model to lean towards generating hyper-real and + dramatic images. Natural causes the model to produce more natural, less + hyper-real looking images. """ user: str diff --git a/src/openai/types/image_model.py b/src/openai/types/image_model.py index 1672369bea..7fed69ed82 100644 --- a/src/openai/types/image_model.py +++ b/src/openai/types/image_model.py @@ -4,4 +4,4 @@ __all__ = ["ImageModel"] -ImageModel: TypeAlias = Literal["dall-e-2", "dall-e-3"] +ImageModel: TypeAlias = Literal["dall-e-2", "dall-e-3", "gpt-image-1"] diff --git a/src/openai/types/images_response.py b/src/openai/types/images_response.py index 7cee813184..df454afa4d 100644 --- a/src/openai/types/images_response.py +++ b/src/openai/types/images_response.py @@ -1,14 +1,41 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing import List +from typing import List, Optional from .image import Image from .._models import BaseModel -__all__ = ["ImagesResponse"] +__all__ = ["ImagesResponse", "Usage", "UsageInputTokensDetails"] + + +class UsageInputTokensDetails(BaseModel): + image_tokens: int + """The number of image tokens in the input prompt.""" + + text_tokens: int + """The number of text tokens in the input prompt.""" + + +class Usage(BaseModel): + input_tokens: int + """The number of tokens (images and text) in the input prompt.""" + + input_tokens_details: UsageInputTokensDetails + """The input tokens detailed information for the image generation.""" + + output_tokens: int + """The number of image tokens in the output image.""" + + total_tokens: int + """The total number of tokens (images and text) used for the image generation.""" class ImagesResponse(BaseModel): created: int + """The Unix timestamp (in seconds) of when the image was created.""" + + data: Optional[List[Image]] = None + """The list of generated images.""" - data: List[Image] + usage: Optional[Usage] = None + """For `gpt-image-1` only, the token usage information for the image generation.""" diff --git a/src/openai/types/responses/__init__.py b/src/openai/types/responses/__init__.py index 4f07a3d097..22fd2a0802 100644 --- a/src/openai/types/responses/__init__.py +++ b/src/openai/types/responses/__init__.py @@ -22,6 +22,7 @@ from .web_search_tool import WebSearchTool as WebSearchTool from .file_search_tool import FileSearchTool as FileSearchTool from .tool_choice_types import ToolChoiceTypes as ToolChoiceTypes +from .easy_input_message import EasyInputMessage as EasyInputMessage from .response_item_list import ResponseItemList as ResponseItemList from .computer_tool_param import ComputerToolParam as ComputerToolParam from .function_tool_param import FunctionToolParam as FunctionToolParam @@ -117,6 +118,12 @@ from .response_input_message_content_list_param import ( ResponseInputMessageContentListParam as ResponseInputMessageContentListParam, ) +from .response_reasoning_summary_part_done_event import ( + ResponseReasoningSummaryPartDoneEvent as ResponseReasoningSummaryPartDoneEvent, +) +from .response_reasoning_summary_text_done_event import ( + ResponseReasoningSummaryTextDoneEvent as ResponseReasoningSummaryTextDoneEvent, +) from .response_web_search_call_in_progress_event import ( ResponseWebSearchCallInProgressEvent as ResponseWebSearchCallInProgressEvent, ) @@ -126,6 +133,12 @@ from .response_function_call_arguments_done_event import ( ResponseFunctionCallArgumentsDoneEvent as ResponseFunctionCallArgumentsDoneEvent, ) +from .response_reasoning_summary_part_added_event import ( + ResponseReasoningSummaryPartAddedEvent as ResponseReasoningSummaryPartAddedEvent, +) +from .response_reasoning_summary_text_delta_event import ( + ResponseReasoningSummaryTextDeltaEvent as ResponseReasoningSummaryTextDeltaEvent, +) from .response_function_call_arguments_delta_event import ( ResponseFunctionCallArgumentsDeltaEvent as ResponseFunctionCallArgumentsDeltaEvent, ) diff --git a/src/openai/types/responses/easy_input_message.py b/src/openai/types/responses/easy_input_message.py new file mode 100644 index 0000000000..4ed0194f9f --- /dev/null +++ b/src/openai/types/responses/easy_input_message.py @@ -0,0 +1,26 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union, Optional +from typing_extensions import Literal + +from ..._models import BaseModel +from .response_input_message_content_list import ResponseInputMessageContentList + +__all__ = ["EasyInputMessage"] + + +class EasyInputMessage(BaseModel): + content: Union[str, ResponseInputMessageContentList] + """ + Text, image, or audio input to the model, used to generate a response. Can also + contain previous assistant responses. + """ + + role: Literal["user", "assistant", "system", "developer"] + """The role of the message input. + + One of `user`, `assistant`, `system`, or `developer`. + """ + + type: Optional[Literal["message"]] = None + """The type of the message input. Always `message`.""" diff --git a/src/openai/types/responses/response_reasoning_summary_part_added_event.py b/src/openai/types/responses/response_reasoning_summary_part_added_event.py new file mode 100644 index 0000000000..fd11520170 --- /dev/null +++ b/src/openai/types/responses/response_reasoning_summary_part_added_event.py @@ -0,0 +1,32 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseReasoningSummaryPartAddedEvent", "Part"] + + +class Part(BaseModel): + text: str + """The text of the summary part.""" + + type: Literal["summary_text"] + """The type of the summary part. Always `summary_text`.""" + + +class ResponseReasoningSummaryPartAddedEvent(BaseModel): + item_id: str + """The ID of the item this summary part is associated with.""" + + output_index: int + """The index of the output item this summary part is associated with.""" + + part: Part + """The summary part that was added.""" + + summary_index: int + """The index of the summary part within the reasoning summary.""" + + type: Literal["response.reasoning_summary_part.added"] + """The type of the event. Always `response.reasoning_summary_part.added`.""" diff --git a/src/openai/types/responses/response_reasoning_summary_part_done_event.py b/src/openai/types/responses/response_reasoning_summary_part_done_event.py new file mode 100644 index 0000000000..7f30189a49 --- /dev/null +++ b/src/openai/types/responses/response_reasoning_summary_part_done_event.py @@ -0,0 +1,32 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseReasoningSummaryPartDoneEvent", "Part"] + + +class Part(BaseModel): + text: str + """The text of the summary part.""" + + type: Literal["summary_text"] + """The type of the summary part. Always `summary_text`.""" + + +class ResponseReasoningSummaryPartDoneEvent(BaseModel): + item_id: str + """The ID of the item this summary part is associated with.""" + + output_index: int + """The index of the output item this summary part is associated with.""" + + part: Part + """The completed summary part.""" + + summary_index: int + """The index of the summary part within the reasoning summary.""" + + type: Literal["response.reasoning_summary_part.done"] + """The type of the event. Always `response.reasoning_summary_part.done`.""" diff --git a/src/openai/types/responses/response_reasoning_summary_text_delta_event.py b/src/openai/types/responses/response_reasoning_summary_text_delta_event.py new file mode 100644 index 0000000000..6d0cbd8265 --- /dev/null +++ b/src/openai/types/responses/response_reasoning_summary_text_delta_event.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseReasoningSummaryTextDeltaEvent"] + + +class ResponseReasoningSummaryTextDeltaEvent(BaseModel): + delta: str + """The text delta that was added to the summary.""" + + item_id: str + """The ID of the item this summary text delta is associated with.""" + + output_index: int + """The index of the output item this summary text delta is associated with.""" + + summary_index: int + """The index of the summary part within the reasoning summary.""" + + type: Literal["response.reasoning_summary_text.delta"] + """The type of the event. Always `response.reasoning_summary_text.delta`.""" diff --git a/src/openai/types/responses/response_reasoning_summary_text_done_event.py b/src/openai/types/responses/response_reasoning_summary_text_done_event.py new file mode 100644 index 0000000000..15b894c75b --- /dev/null +++ b/src/openai/types/responses/response_reasoning_summary_text_done_event.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ResponseReasoningSummaryTextDoneEvent"] + + +class ResponseReasoningSummaryTextDoneEvent(BaseModel): + item_id: str + """The ID of the item this summary text is associated with.""" + + output_index: int + """The index of the output item this summary text is associated with.""" + + summary_index: int + """The index of the summary part within the reasoning summary.""" + + text: str + """The full text of the completed reasoning summary.""" + + type: Literal["response.reasoning_summary_text.done"] + """The type of the event. Always `response.reasoning_summary_text.done`.""" diff --git a/src/openai/types/responses/response_stream_event.py b/src/openai/types/responses/response_stream_event.py index 446863b175..07c18bd217 100644 --- a/src/openai/types/responses/response_stream_event.py +++ b/src/openai/types/responses/response_stream_event.py @@ -27,9 +27,13 @@ from .response_web_search_call_searching_event import ResponseWebSearchCallSearchingEvent from .response_file_search_call_completed_event import ResponseFileSearchCallCompletedEvent from .response_file_search_call_searching_event import ResponseFileSearchCallSearchingEvent +from .response_reasoning_summary_part_done_event import ResponseReasoningSummaryPartDoneEvent +from .response_reasoning_summary_text_done_event import ResponseReasoningSummaryTextDoneEvent from .response_web_search_call_in_progress_event import ResponseWebSearchCallInProgressEvent from .response_file_search_call_in_progress_event import ResponseFileSearchCallInProgressEvent from .response_function_call_arguments_done_event import ResponseFunctionCallArgumentsDoneEvent +from .response_reasoning_summary_part_added_event import ResponseReasoningSummaryPartAddedEvent +from .response_reasoning_summary_text_delta_event import ResponseReasoningSummaryTextDeltaEvent from .response_function_call_arguments_delta_event import ResponseFunctionCallArgumentsDeltaEvent from .response_code_interpreter_call_code_done_event import ResponseCodeInterpreterCallCodeDoneEvent from .response_code_interpreter_call_completed_event import ResponseCodeInterpreterCallCompletedEvent @@ -65,6 +69,10 @@ ResponseIncompleteEvent, ResponseOutputItemAddedEvent, ResponseOutputItemDoneEvent, + ResponseReasoningSummaryPartAddedEvent, + ResponseReasoningSummaryPartDoneEvent, + ResponseReasoningSummaryTextDeltaEvent, + ResponseReasoningSummaryTextDoneEvent, ResponseRefusalDeltaEvent, ResponseRefusalDoneEvent, ResponseTextAnnotationDeltaEvent, diff --git a/tests/api_resources/fine_tuning/checkpoints/test_permissions.py b/tests/api_resources/fine_tuning/checkpoints/test_permissions.py index d40466919a..6aa0b867d9 100644 --- a/tests/api_resources/fine_tuning/checkpoints/test_permissions.py +++ b/tests/api_resources/fine_tuning/checkpoints/test_permissions.py @@ -117,19 +117,19 @@ def test_path_params_retrieve(self, client: OpenAI) -> None: fine_tuned_model_checkpoint="", ) - @pytest.mark.skip(reason="OpenAPI spec is slightly incorrect") @parametrize def test_method_delete(self, client: OpenAI) -> None: permission = client.fine_tuning.checkpoints.permissions.delete( - "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", + permission_id="cp_zc4Q7MP6XxulcVzj4MZdwsAB", + fine_tuned_model_checkpoint="ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", ) assert_matches_type(PermissionDeleteResponse, permission, path=["response"]) - @pytest.mark.skip(reason="OpenAPI spec is slightly incorrect") @parametrize def test_raw_response_delete(self, client: OpenAI) -> None: response = client.fine_tuning.checkpoints.permissions.with_raw_response.delete( - "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", + permission_id="cp_zc4Q7MP6XxulcVzj4MZdwsAB", + fine_tuned_model_checkpoint="ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", ) assert response.is_closed is True @@ -137,11 +137,11 @@ def test_raw_response_delete(self, client: OpenAI) -> None: permission = response.parse() assert_matches_type(PermissionDeleteResponse, permission, path=["response"]) - @pytest.mark.skip(reason="OpenAPI spec is slightly incorrect") @parametrize def test_streaming_response_delete(self, client: OpenAI) -> None: with client.fine_tuning.checkpoints.permissions.with_streaming_response.delete( - "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", + permission_id="cp_zc4Q7MP6XxulcVzj4MZdwsAB", + fine_tuned_model_checkpoint="ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -151,14 +151,20 @@ def test_streaming_response_delete(self, client: OpenAI) -> None: assert cast(Any, response.is_closed) is True - @pytest.mark.skip(reason="OpenAPI spec is slightly incorrect") @parametrize def test_path_params_delete(self, client: OpenAI) -> None: with pytest.raises( ValueError, match=r"Expected a non-empty value for `fine_tuned_model_checkpoint` but received ''" ): client.fine_tuning.checkpoints.permissions.with_raw_response.delete( - "", + permission_id="cp_zc4Q7MP6XxulcVzj4MZdwsAB", + fine_tuned_model_checkpoint="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `permission_id` but received ''"): + client.fine_tuning.checkpoints.permissions.with_raw_response.delete( + permission_id="", + fine_tuned_model_checkpoint="ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", ) @@ -260,19 +266,19 @@ async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None: fine_tuned_model_checkpoint="", ) - @pytest.mark.skip(reason="OpenAPI spec is slightly incorrect") @parametrize async def test_method_delete(self, async_client: AsyncOpenAI) -> None: permission = await async_client.fine_tuning.checkpoints.permissions.delete( - "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", + permission_id="cp_zc4Q7MP6XxulcVzj4MZdwsAB", + fine_tuned_model_checkpoint="ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", ) assert_matches_type(PermissionDeleteResponse, permission, path=["response"]) - @pytest.mark.skip(reason="OpenAPI spec is slightly incorrect") @parametrize async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None: response = await async_client.fine_tuning.checkpoints.permissions.with_raw_response.delete( - "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", + permission_id="cp_zc4Q7MP6XxulcVzj4MZdwsAB", + fine_tuned_model_checkpoint="ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", ) assert response.is_closed is True @@ -280,11 +286,11 @@ async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None: permission = response.parse() assert_matches_type(PermissionDeleteResponse, permission, path=["response"]) - @pytest.mark.skip(reason="OpenAPI spec is slightly incorrect") @parametrize async def test_streaming_response_delete(self, async_client: AsyncOpenAI) -> None: async with async_client.fine_tuning.checkpoints.permissions.with_streaming_response.delete( - "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", + permission_id="cp_zc4Q7MP6XxulcVzj4MZdwsAB", + fine_tuned_model_checkpoint="ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" @@ -294,12 +300,18 @@ async def test_streaming_response_delete(self, async_client: AsyncOpenAI) -> Non assert cast(Any, response.is_closed) is True - @pytest.mark.skip(reason="OpenAPI spec is slightly incorrect") @parametrize async def test_path_params_delete(self, async_client: AsyncOpenAI) -> None: with pytest.raises( ValueError, match=r"Expected a non-empty value for `fine_tuned_model_checkpoint` but received ''" ): await async_client.fine_tuning.checkpoints.permissions.with_raw_response.delete( - "", + permission_id="cp_zc4Q7MP6XxulcVzj4MZdwsAB", + fine_tuned_model_checkpoint="", + ) + + with pytest.raises(ValueError, match=r"Expected a non-empty value for `permission_id` but received ''"): + await async_client.fine_tuning.checkpoints.permissions.with_raw_response.delete( + permission_id="", + fine_tuned_model_checkpoint="ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", ) diff --git a/tests/api_resources/test_evals.py b/tests/api_resources/test_evals.py index 8d03513b32..4ae2c597dd 100644 --- a/tests/api_resources/test_evals.py +++ b/tests/api_resources/test_evals.py @@ -74,7 +74,6 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: ], metadata={"foo": "string"}, name="name", - share_with_openai=True, ) assert_matches_type(EvalCreateResponse, eval, path=["response"]) @@ -350,7 +349,6 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> ], metadata={"foo": "string"}, name="name", - share_with_openai=True, ) assert_matches_type(EvalCreateResponse, eval, path=["response"]) diff --git a/tests/api_resources/test_images.py b/tests/api_resources/test_images.py index 0a88f2ebcf..7997e9f5a1 100644 --- a/tests/api_resources/test_images.py +++ b/tests/api_resources/test_images.py @@ -76,6 +76,7 @@ def test_method_edit_with_all_params(self, client: OpenAI) -> None: mask=b"raw file contents", model="string", n=1, + quality="high", response_format="url", size="1024x1024", user="user-1234", @@ -119,9 +120,13 @@ def test_method_generate(self, client: OpenAI) -> None: def test_method_generate_with_all_params(self, client: OpenAI) -> None: image = client.images.generate( prompt="A cute baby sea otter", + background="transparent", model="string", + moderation="low", n=1, - quality="standard", + output_compression=100, + output_format="png", + quality="medium", response_format="url", size="1024x1024", style="vivid", @@ -216,6 +221,7 @@ async def test_method_edit_with_all_params(self, async_client: AsyncOpenAI) -> N mask=b"raw file contents", model="string", n=1, + quality="high", response_format="url", size="1024x1024", user="user-1234", @@ -259,9 +265,13 @@ async def test_method_generate(self, async_client: AsyncOpenAI) -> None: async def test_method_generate_with_all_params(self, async_client: AsyncOpenAI) -> None: image = await async_client.images.generate( prompt="A cute baby sea otter", + background="transparent", model="string", + moderation="low", n=1, - quality="standard", + output_compression=100, + output_format="png", + quality="medium", response_format="url", size="1024x1024", style="vivid", From 8e1a1cd60d990361b934f922fd7d176f2ae0a63c Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 23 Apr 2025 16:31:09 +0000 Subject: [PATCH 797/816] release: 1.76.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 25 +++++++++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 28 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index cb464946f0..df3aaa16a7 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.75.0" + ".": "1.76.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index fb077b91c3..73d8f2bf6e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,30 @@ # Changelog +## 1.76.0 (2025-04-23) + +Full Changelog: [v1.75.0...v1.76.0](https://github.com/openai/openai-python/compare/v1.75.0...v1.76.0) + +### Features + +* **api:** adding new image model support ([74d7692](https://github.com/openai/openai-python/commit/74d7692e94c9dca96db8793809d75631c22dbb87)) + + +### Bug Fixes + +* **pydantic v1:** more robust `ModelField.annotation` check ([#2163](https://github.com/openai/openai-python/issues/2163)) ([7351b12](https://github.com/openai/openai-python/commit/7351b12bc981f56632b92342d9ef26f6fb28d540)) +* **pydantic v1:** more robust ModelField.annotation check ([eba7856](https://github.com/openai/openai-python/commit/eba7856db55afb8cb44376a0248587549f7bc65f)) + + +### Chores + +* **ci:** add timeout thresholds for CI jobs ([0997211](https://github.com/openai/openai-python/commit/09972119df5dd4c7c8db137c721364787e22d4c6)) +* **internal:** fix list file params ([da2113c](https://github.com/openai/openai-python/commit/da2113c60b50b4438459325fcd38d55df3f63d8e)) +* **internal:** import reformatting ([b425fb9](https://github.com/openai/openai-python/commit/b425fb906f62550c3669b09b9d8575f3d4d8496b)) +* **internal:** minor formatting changes ([aed1d76](https://github.com/openai/openai-python/commit/aed1d767898324cf90328db329e04e89a77579c3)) +* **internal:** refactor retries to not use recursion ([8cb8cfa](https://github.com/openai/openai-python/commit/8cb8cfab48a4fed70a756ce50036e7e56e1f9f87)) +* **internal:** update models test ([870ad4e](https://github.com/openai/openai-python/commit/870ad4ed3a284d75f44b825503750129284c7906)) +* update completion parse signature ([a44016c](https://github.com/openai/openai-python/commit/a44016c64cdefe404e97592808ed3c25411ab27b)) + ## 1.75.0 (2025-04-16) Full Changelog: [v1.74.1...v1.75.0](https://github.com/openai/openai-python/compare/v1.74.1...v1.75.0) diff --git a/pyproject.toml b/pyproject.toml index b5648e9e51..947e082f78 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.75.0" +version = "1.76.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 8eab2d7416..ea6b974272 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.75.0" # x-release-please-version +__version__ = "1.76.0" # x-release-please-version From c1ceebbd62400d66291173763f546a8a98f201ad Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 23 Apr 2025 19:07:40 +0000 Subject: [PATCH 798/816] chore(ci): run on more branches and use depot runners --- .github/workflows/ci.yml | 18 +++++++++--------- .github/workflows/publish-pypi.yml | 2 +- .github/workflows/release-doctor.yml | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d148b34a9e..bbf8a2c65a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,18 +1,18 @@ name: CI on: push: - branches: - - main - pull_request: - branches: - - main - - next + branches-ignore: + - 'generated' + - 'codegen/**' + - 'integrated/**' + - 'stl-preview-head/**' + - 'stl-preview-base/**' jobs: lint: timeout-minutes: 10 name: lint - runs-on: ubuntu-latest + runs-on: depot-ubuntu-24.04 steps: - uses: actions/checkout@v4 @@ -33,7 +33,7 @@ jobs: test: timeout-minutes: 10 name: test - runs-on: ubuntu-latest + runs-on: depot-ubuntu-24.04 steps: - uses: actions/checkout@v4 @@ -54,7 +54,7 @@ jobs: examples: timeout-minutes: 10 name: examples - runs-on: ubuntu-latest + runs-on: depot-ubuntu-24.04 if: github.repository == 'openai/openai-python' steps: diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml index 32bd6929e2..d669229973 100644 --- a/.github/workflows/publish-pypi.yml +++ b/.github/workflows/publish-pypi.yml @@ -7,7 +7,7 @@ on: jobs: publish: name: publish - runs-on: ubuntu-latest + runs-on: depot-ubuntu-24.04 environment: publish steps: diff --git a/.github/workflows/release-doctor.yml b/.github/workflows/release-doctor.yml index e078964a6f..be17b9c07f 100644 --- a/.github/workflows/release-doctor.yml +++ b/.github/workflows/release-doctor.yml @@ -8,7 +8,7 @@ on: jobs: release_doctor: name: release doctor - runs-on: ubuntu-latest + runs-on: depot-ubuntu-24.04 environment: publish if: github.repository == 'openai/openai-python' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch' || startsWith(github.head_ref, 'release-please') || github.head_ref == 'next') From c9cedd8a47290ff2c95c54c1528fbc7202f6b523 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 23 Apr 2025 20:00:18 +0000 Subject: [PATCH 799/816] chore(ci): only use depot for staging repos --- .github/workflows/ci.yml | 6 +++--- .github/workflows/publish-pypi.yml | 2 +- .github/workflows/release-doctor.yml | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bbf8a2c65a..e1e21f3fae 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,7 +12,7 @@ jobs: lint: timeout-minutes: 10 name: lint - runs-on: depot-ubuntu-24.04 + runs-on: ${{ github.repository == 'stainless-sdks/openai-python' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} steps: - uses: actions/checkout@v4 @@ -33,7 +33,7 @@ jobs: test: timeout-minutes: 10 name: test - runs-on: depot-ubuntu-24.04 + runs-on: ${{ github.repository == 'stainless-sdks/openai-python' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} steps: - uses: actions/checkout@v4 @@ -54,7 +54,7 @@ jobs: examples: timeout-minutes: 10 name: examples - runs-on: depot-ubuntu-24.04 + runs-on: ${{ github.repository == 'stainless-sdks/openai-python' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }} if: github.repository == 'openai/openai-python' steps: diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml index d669229973..32bd6929e2 100644 --- a/.github/workflows/publish-pypi.yml +++ b/.github/workflows/publish-pypi.yml @@ -7,7 +7,7 @@ on: jobs: publish: name: publish - runs-on: depot-ubuntu-24.04 + runs-on: ubuntu-latest environment: publish steps: diff --git a/.github/workflows/release-doctor.yml b/.github/workflows/release-doctor.yml index be17b9c07f..e078964a6f 100644 --- a/.github/workflows/release-doctor.yml +++ b/.github/workflows/release-doctor.yml @@ -8,7 +8,7 @@ on: jobs: release_doctor: name: release doctor - runs-on: depot-ubuntu-24.04 + runs-on: ubuntu-latest environment: publish if: github.repository == 'openai/openai-python' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch' || startsWith(github.head_ref, 'release-please') || github.head_ref == 'next') From 761be76cb7512de232b1892f8915cd022bee040a Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Wed, 23 Apr 2025 22:08:18 +0000 Subject: [PATCH 800/816] chore: broadly detect json family of content-type headers --- src/openai/_legacy_response.py | 2 +- src/openai/_response.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/openai/_legacy_response.py b/src/openai/_legacy_response.py index 8880e5f104..cfabaa2fc2 100644 --- a/src/openai/_legacy_response.py +++ b/src/openai/_legacy_response.py @@ -304,7 +304,7 @@ def _parse(self, *, to: type[_T] | None = None) -> R | _T: # split is required to handle cases where additional information is included # in the response, e.g. application/json; charset=utf-8 content_type, *_ = response.headers.get("content-type", "*").split(";") - if content_type != "application/json": + if not content_type.endswith("json"): if is_basemodel(cast_to): try: data = response.json() diff --git a/src/openai/_response.py b/src/openai/_response.py index 95e94e6537..350da38dd4 100644 --- a/src/openai/_response.py +++ b/src/openai/_response.py @@ -237,7 +237,7 @@ def _parse(self, *, to: type[_T] | None = None) -> R | _T: # split is required to handle cases where additional information is included # in the response, e.g. application/json; charset=utf-8 content_type, *_ = response.headers.get("content-type", "*").split(";") - if content_type != "application/json": + if not content_type.endswith("json"): if is_basemodel(cast_to): try: data = response.json() From b75f4093026265d7a3f0c38998a3360f03bf44f4 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 29 Apr 2025 05:03:55 +0000 Subject: [PATCH 801/816] release: 1.76.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 10 ++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 13 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index df3aaa16a7..0c3ec30cf9 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.76.0" + ".": "1.76.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 73d8f2bf6e..1c5b507e43 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## 1.76.1 (2025-04-29) + +Full Changelog: [v1.76.0...v1.76.1](https://github.com/openai/openai-python/compare/v1.76.0...v1.76.1) + +### Chores + +* broadly detect json family of content-type headers ([b4b1b08](https://github.com/openai/openai-python/commit/b4b1b086b512eecc0ada7fc1efa45eb506982f13)) +* **ci:** only use depot for staging repos ([35312d8](https://github.com/openai/openai-python/commit/35312d80e6bbc1a61d06ad253af9a713b5ef040c)) +* **ci:** run on more branches and use depot runners ([a6a45d4](https://github.com/openai/openai-python/commit/a6a45d4af8a4d904b37573a9b223d56106b4887d)) + ## 1.76.0 (2025-04-23) Full Changelog: [v1.75.0...v1.76.0](https://github.com/openai/openai-python/compare/v1.75.0...v1.76.0) diff --git a/pyproject.toml b/pyproject.toml index 947e082f78..570e59ec67 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.76.0" +version = "1.76.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index ea6b974272..77a1b26c42 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.76.0" # x-release-please-version +__version__ = "1.76.1" # x-release-please-version From a6460677e956762d1b9cdb59cdc5e161cd5ea370 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 29 Apr 2025 19:58:55 +0000 Subject: [PATCH 802/816] chore(api): API spec cleanup --- src/openai/lib/streaming/responses/_events.py | 8 ++++++++ src/openai/resources/beta/threads/threads.py | 16 ++++++++-------- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/src/openai/lib/streaming/responses/_events.py b/src/openai/lib/streaming/responses/_events.py index fe17edf649..0cdc5992ee 100644 --- a/src/openai/lib/streaming/responses/_events.py +++ b/src/openai/lib/streaming/responses/_events.py @@ -32,7 +32,11 @@ ResponseFileSearchCallSearchingEvent, ResponseWebSearchCallInProgressEvent, ResponseFileSearchCallInProgressEvent, + ResponseReasoningSummaryPartDoneEvent, + ResponseReasoningSummaryTextDoneEvent, ResponseFunctionCallArgumentsDoneEvent, + ResponseReasoningSummaryPartAddedEvent, + ResponseReasoningSummaryTextDeltaEvent, ResponseFunctionCallArgumentsDeltaEvent as RawResponseFunctionCallArgumentsDeltaEvent, ResponseCodeInterpreterCallCodeDoneEvent, ResponseCodeInterpreterCallCodeDeltaEvent, @@ -101,6 +105,10 @@ class ResponseCompletedEvent(RawResponseCompletedEvent, GenericModel, Generic[Te ResponseWebSearchCallCompletedEvent, ResponseWebSearchCallInProgressEvent, ResponseWebSearchCallSearchingEvent, + ResponseReasoningSummaryPartAddedEvent, + ResponseReasoningSummaryPartDoneEvent, + ResponseReasoningSummaryTextDeltaEvent, + ResponseReasoningSummaryTextDoneEvent, ], PropertyInfo(discriminator="type"), ] diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 22dc5fe0ea..13d8cb6411 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -741,7 +741,7 @@ def create_and_run_poll( thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, - tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, poll_interval_ms: int | NotGiven = NOT_GIVEN, @@ -797,7 +797,7 @@ def create_and_run_stream( thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, - tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -826,7 +826,7 @@ def create_and_run_stream( thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, - tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, event_handler: AssistantEventHandlerT, @@ -855,7 +855,7 @@ def create_and_run_stream( thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, - tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, event_handler: AssistantEventHandlerT | None = None, @@ -1590,7 +1590,7 @@ async def create_and_run_poll( thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, - tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, poll_interval_ms: int | NotGiven = NOT_GIVEN, @@ -1648,7 +1648,7 @@ def create_and_run_stream( thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, - tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. @@ -1677,7 +1677,7 @@ def create_and_run_stream( thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, - tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, event_handler: AsyncAssistantEventHandlerT, @@ -1706,7 +1706,7 @@ def create_and_run_stream( thread: thread_create_and_run_params.Thread | NotGiven = NOT_GIVEN, tool_choice: Optional[AssistantToolChoiceOptionParam] | NotGiven = NOT_GIVEN, tool_resources: Optional[thread_create_and_run_params.ToolResources] | NotGiven = NOT_GIVEN, - tools: Optional[Iterable[thread_create_and_run_params.Tool]] | NotGiven = NOT_GIVEN, + tools: Optional[Iterable[AssistantToolParam]] | NotGiven = NOT_GIVEN, top_p: Optional[float] | NotGiven = NOT_GIVEN, truncation_strategy: Optional[thread_create_and_run_params.TruncationStrategy] | NotGiven = NOT_GIVEN, event_handler: AsyncAssistantEventHandlerT | None = None, From fad098ffad7982a5150306a3d17f51ffef574f2e Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 29 Apr 2025 19:59:25 +0000 Subject: [PATCH 803/816] release: 1.76.2 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 8 ++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 0c3ec30cf9..8bcd8a5b4f 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.76.1" + ".": "1.76.2" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c5b507e43..bc85128f6a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 1.76.2 (2025-04-29) + +Full Changelog: [v1.76.1...v1.76.2](https://github.com/openai/openai-python/compare/v1.76.1...v1.76.2) + +### Chores + +* **api:** API spec cleanup ([0a4d3e2](https://github.com/openai/openai-python/commit/0a4d3e2b495d22dd42ce1773b870554c64f9b3b2)) + ## 1.76.1 (2025-04-29) Full Changelog: [v1.76.0...v1.76.1](https://github.com/openai/openai-python/compare/v1.76.0...v1.76.1) diff --git a/pyproject.toml b/pyproject.toml index 570e59ec67..2c3c3eaf3b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.76.1" +version = "1.76.2" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 77a1b26c42..ef1e3fe526 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.76.1" # x-release-please-version +__version__ = "1.76.2" # x-release-please-version From b3f0daf3dbc344998b09762615a59d80621d7921 Mon Sep 17 00:00:00 2001 From: Pon Pongwachirin <138108569+maesta7@users.noreply.github.com> Date: Wed, 30 Apr 2025 22:46:30 +0700 Subject: [PATCH 804/816] fix(parsing): handle whitespace only strings (#2007) * fix: add a check to handle empty or newline-only strings before calling `from_json` * style: adjust comment format for better readability Co-authored-by: Robert Craigie --------- Co-authored-by: SenorSpes <138108569+senorNox@users.noreply.github.com> Co-authored-by: Robert Craigie --- src/openai/lib/streaming/chat/_completions.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/openai/lib/streaming/chat/_completions.py b/src/openai/lib/streaming/chat/_completions.py index f147696cca..6177ffbed2 100644 --- a/src/openai/lib/streaming/chat/_completions.py +++ b/src/openai/lib/streaming/chat/_completions.py @@ -438,6 +438,8 @@ def _accumulate_chunk(self, chunk: ChatCompletionChunk) -> ParsedChatCompletionS choice_snapshot.message.content and not choice_snapshot.message.refusal and is_given(self._rich_response_format) + # partial parsing fails on white-space + and choice_snapshot.message.content.strip() ): choice_snapshot.message.parsed = from_json( bytes(choice_snapshot.message.content, "utf-8"), From 4fc52529439c05ace100e05bf07f5e3d23abbc5b Mon Sep 17 00:00:00 2001 From: Robert Craigie Date: Wed, 30 Apr 2025 11:47:27 -0400 Subject: [PATCH 805/816] chore: only strip leading whitespace --- src/openai/lib/streaming/chat/_completions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/openai/lib/streaming/chat/_completions.py b/src/openai/lib/streaming/chat/_completions.py index 6177ffbed2..a7b70c32d3 100644 --- a/src/openai/lib/streaming/chat/_completions.py +++ b/src/openai/lib/streaming/chat/_completions.py @@ -439,7 +439,7 @@ def _accumulate_chunk(self, chunk: ChatCompletionChunk) -> ParsedChatCompletionS and not choice_snapshot.message.refusal and is_given(self._rich_response_format) # partial parsing fails on white-space - and choice_snapshot.message.content.strip() + and choice_snapshot.message.content.lstrip() ): choice_snapshot.message.parsed = from_json( bytes(choice_snapshot.message.content, "utf-8"), From b8a3720ed6157dff5100c9a36f8d51fe47a2994c Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 2 May 2025 19:09:24 +0000 Subject: [PATCH 806/816] feat(api): add image sizes, reasoning encryption --- .stats.yml | 6 +-- src/openai/resources/audio/speech.py | 4 +- src/openai/resources/images.py | 48 +++++++++++++++---- src/openai/resources/responses/responses.py | 30 ++++++++++++ .../types/audio/speech_create_params.py | 3 +- src/openai/types/image_edit_params.py | 24 +++++++--- src/openai/types/responses/computer_tool.py | 6 +-- .../types/responses/computer_tool_param.py | 6 +-- .../types/responses/file_search_tool.py | 12 ++--- .../types/responses/file_search_tool_param.py | 14 +++--- src/openai/types/responses/function_tool.py | 4 +- .../types/responses/function_tool_param.py | 4 +- .../types/responses/response_create_params.py | 5 ++ .../types/responses/response_includable.py | 5 +- .../responses/response_input_file_param.py | 3 +- .../types/responses/response_input_image.py | 2 +- .../responses/response_input_image_param.py | 2 +- .../responses/response_input_item_param.py | 18 +++---- .../types/responses/response_input_param.py | 18 +++---- .../responses/response_reasoning_item.py | 6 +++ .../response_reasoning_item_param.py | 8 +++- src/openai/types/responses/tool.py | 2 +- src/openai/types/responses/tool_param.py | 2 +- src/openai/types/responses/web_search_tool.py | 13 ++--- .../types/responses/web_search_tool_param.py | 21 ++++---- tests/api_resources/test_images.py | 2 + 26 files changed, 182 insertions(+), 86 deletions(-) diff --git a/.stats.yml b/.stats.yml index d92408173b..0c8278866d 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 97 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-8b68ae6b807dca92e914da1dd9e835a20f69b075e79102a264367fd7fddddb33.yml -openapi_spec_hash: b6ade5b1a6327339e6669e1134de2d03 -config_hash: b597cd9a31e9e5ec709e2eefb4c54122 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-0ee6b36cf3cc278cef4199a6aec5f7d530a6c1f17a74830037e96d50ca1edc50.yml +openapi_spec_hash: e8ec5f46bc0655b34f292422d58a60f6 +config_hash: d9b6b6e6bc85744663e300eebc482067 diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index fad18dcdf5..a195d7135e 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -85,7 +85,7 @@ def create( `wav`, and `pcm`. speed: The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is - the default. + the default. Does not work with `gpt-4o-mini-tts`. extra_headers: Send extra headers @@ -176,7 +176,7 @@ async def create( `wav`, and `pcm`. speed: The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is - the default. + the default. Does not work with `gpt-4o-mini-tts`. extra_headers: Send extra headers diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py index e59d0ce35c..524bebacae 100644 --- a/src/openai/resources/images.py +++ b/src/openai/resources/images.py @@ -119,12 +119,14 @@ def edit( *, image: Union[FileTypes, List[FileTypes]], prompt: str, + background: Optional[Literal["transparent", "opaque", "auto"]] | NotGiven = NOT_GIVEN, mask: FileTypes | NotGiven = NOT_GIVEN, model: Union[str, ImageModel, None] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, quality: Optional[Literal["standard", "low", "medium", "high", "auto"]] | NotGiven = NOT_GIVEN, response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN, - size: Optional[Literal["256x256", "512x512", "1024x1024"]] | NotGiven = NOT_GIVEN, + size: Optional[Literal["256x256", "512x512", "1024x1024", "1536x1024", "1024x1536", "auto"]] + | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -139,14 +141,25 @@ def edit( This endpoint only supports `gpt-image-1` and `dall-e-2`. Args: - image: The image(s) to edit. Must be a supported image file or an array of images. For - `gpt-image-1`, each image should be a `png`, `webp`, or `jpg` file less than - 25MB. For `dall-e-2`, you can only provide one image, and it should be a square - `png` file less than 4MB. + image: The image(s) to edit. Must be a supported image file or an array of images. + + For `gpt-image-1`, each image should be a `png`, `webp`, or `jpg` file less than + 25MB. You can provide up to 16 images. + + For `dall-e-2`, you can only provide one image, and it should be a square `png` + file less than 4MB. prompt: A text description of the desired image(s). The maximum length is 1000 characters for `dall-e-2`, and 32000 characters for `gpt-image-1`. + background: Allows to set transparency for the background of the generated image(s). This + parameter is only supported for `gpt-image-1`. Must be one of `transparent`, + `opaque` or `auto` (default value). When `auto` is used, the model will + automatically determine the best background for the image. + + If `transparent`, the output format needs to support transparency, so it should + be set to either `png` (default value) or `webp`. + mask: An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where `image` should be edited. If there are multiple images provided, the mask will be applied on the first image. Must be a valid PNG file, less than @@ -187,6 +200,7 @@ def edit( { "image": image, "prompt": prompt, + "background": background, "mask": mask, "model": model, "n": n, @@ -429,12 +443,14 @@ async def edit( *, image: Union[FileTypes, List[FileTypes]], prompt: str, + background: Optional[Literal["transparent", "opaque", "auto"]] | NotGiven = NOT_GIVEN, mask: FileTypes | NotGiven = NOT_GIVEN, model: Union[str, ImageModel, None] | NotGiven = NOT_GIVEN, n: Optional[int] | NotGiven = NOT_GIVEN, quality: Optional[Literal["standard", "low", "medium", "high", "auto"]] | NotGiven = NOT_GIVEN, response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN, - size: Optional[Literal["256x256", "512x512", "1024x1024"]] | NotGiven = NOT_GIVEN, + size: Optional[Literal["256x256", "512x512", "1024x1024", "1536x1024", "1024x1536", "auto"]] + | NotGiven = NOT_GIVEN, user: str | NotGiven = NOT_GIVEN, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. @@ -449,14 +465,25 @@ async def edit( This endpoint only supports `gpt-image-1` and `dall-e-2`. Args: - image: The image(s) to edit. Must be a supported image file or an array of images. For - `gpt-image-1`, each image should be a `png`, `webp`, or `jpg` file less than - 25MB. For `dall-e-2`, you can only provide one image, and it should be a square - `png` file less than 4MB. + image: The image(s) to edit. Must be a supported image file or an array of images. + + For `gpt-image-1`, each image should be a `png`, `webp`, or `jpg` file less than + 25MB. You can provide up to 16 images. + + For `dall-e-2`, you can only provide one image, and it should be a square `png` + file less than 4MB. prompt: A text description of the desired image(s). The maximum length is 1000 characters for `dall-e-2`, and 32000 characters for `gpt-image-1`. + background: Allows to set transparency for the background of the generated image(s). This + parameter is only supported for `gpt-image-1`. Must be one of `transparent`, + `opaque` or `auto` (default value). When `auto` is used, the model will + automatically determine the best background for the image. + + If `transparent`, the output format needs to support transparency, so it should + be set to either `png` (default value) or `webp`. + mask: An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where `image` should be edited. If there are multiple images provided, the mask will be applied on the first image. Must be a valid PNG file, less than @@ -497,6 +524,7 @@ async def edit( { "image": image, "prompt": prompt, + "background": background, "mask": mask, "model": model, "n": n, diff --git a/src/openai/resources/responses/responses.py b/src/openai/resources/responses/responses.py index 4a0687f9f3..a905bc34b1 100644 --- a/src/openai/resources/responses/responses.py +++ b/src/openai/resources/responses/responses.py @@ -140,6 +140,11 @@ def create( - `message.input_image.image_url`: Include image urls from the input message. - `computer_call_output.output.image_url`: Include image urls from the computer call output. + - `reasoning.encrypted_content`: Includes an encrypted version of reasoning + tokens in reasoning item outputs. This enables reasoning items to be used in + multi-turn conversations when using the Responses API statelessly (like when + the `store` parameter is set to `false`, or when an organization is enrolled + in the zero data retention program). instructions: Inserts a system (or developer) message as the first item in the model's context. @@ -331,6 +336,11 @@ def create( - `message.input_image.image_url`: Include image urls from the input message. - `computer_call_output.output.image_url`: Include image urls from the computer call output. + - `reasoning.encrypted_content`: Includes an encrypted version of reasoning + tokens in reasoning item outputs. This enables reasoning items to be used in + multi-turn conversations when using the Responses API statelessly (like when + the `store` parameter is set to `false`, or when an organization is enrolled + in the zero data retention program). instructions: Inserts a system (or developer) message as the first item in the model's context. @@ -515,6 +525,11 @@ def create( - `message.input_image.image_url`: Include image urls from the input message. - `computer_call_output.output.image_url`: Include image urls from the computer call output. + - `reasoning.encrypted_content`: Includes an encrypted version of reasoning + tokens in reasoning item outputs. This enables reasoning items to be used in + multi-turn conversations when using the Responses API statelessly (like when + the `store` parameter is set to `false`, or when an organization is enrolled + in the zero data retention program). instructions: Inserts a system (or developer) message as the first item in the model's context. @@ -1013,6 +1028,11 @@ async def create( - `message.input_image.image_url`: Include image urls from the input message. - `computer_call_output.output.image_url`: Include image urls from the computer call output. + - `reasoning.encrypted_content`: Includes an encrypted version of reasoning + tokens in reasoning item outputs. This enables reasoning items to be used in + multi-turn conversations when using the Responses API statelessly (like when + the `store` parameter is set to `false`, or when an organization is enrolled + in the zero data retention program). instructions: Inserts a system (or developer) message as the first item in the model's context. @@ -1204,6 +1224,11 @@ async def create( - `message.input_image.image_url`: Include image urls from the input message. - `computer_call_output.output.image_url`: Include image urls from the computer call output. + - `reasoning.encrypted_content`: Includes an encrypted version of reasoning + tokens in reasoning item outputs. This enables reasoning items to be used in + multi-turn conversations when using the Responses API statelessly (like when + the `store` parameter is set to `false`, or when an organization is enrolled + in the zero data retention program). instructions: Inserts a system (or developer) message as the first item in the model's context. @@ -1388,6 +1413,11 @@ async def create( - `message.input_image.image_url`: Include image urls from the input message. - `computer_call_output.output.image_url`: Include image urls from the computer call output. + - `reasoning.encrypted_content`: Includes an encrypted version of reasoning + tokens in reasoning item outputs. This enables reasoning items to be used in + multi-turn conversations when using the Responses API statelessly (like when + the `store` parameter is set to `false`, or when an organization is enrolled + in the zero data retention program). instructions: Inserts a system (or developer) message as the first item in the model's context. diff --git a/src/openai/types/audio/speech_create_params.py b/src/openai/types/audio/speech_create_params.py index a4fc020532..905ca5c3a8 100644 --- a/src/openai/types/audio/speech_create_params.py +++ b/src/openai/types/audio/speech_create_params.py @@ -48,5 +48,6 @@ class SpeechCreateParams(TypedDict, total=False): speed: float """The speed of the generated audio. - Select a value from `0.25` to `4.0`. `1.0` is the default. + Select a value from `0.25` to `4.0`. `1.0` is the default. Does not work with + `gpt-4o-mini-tts`. """ diff --git a/src/openai/types/image_edit_params.py b/src/openai/types/image_edit_params.py index f01a12c1b0..6294e8ac19 100644 --- a/src/openai/types/image_edit_params.py +++ b/src/openai/types/image_edit_params.py @@ -13,12 +13,13 @@ class ImageEditParams(TypedDict, total=False): image: Required[Union[FileTypes, List[FileTypes]]] - """The image(s) to edit. + """The image(s) to edit. Must be a supported image file or an array of images. - Must be a supported image file or an array of images. For `gpt-image-1`, each - image should be a `png`, `webp`, or `jpg` file less than 25MB. For `dall-e-2`, - you can only provide one image, and it should be a square `png` file less than - 4MB. + For `gpt-image-1`, each image should be a `png`, `webp`, or `jpg` file less than + 25MB. You can provide up to 16 images. + + For `dall-e-2`, you can only provide one image, and it should be a square `png` + file less than 4MB. """ prompt: Required[str] @@ -28,6 +29,17 @@ class ImageEditParams(TypedDict, total=False): `gpt-image-1`. """ + background: Optional[Literal["transparent", "opaque", "auto"]] + """Allows to set transparency for the background of the generated image(s). + + This parameter is only supported for `gpt-image-1`. Must be one of + `transparent`, `opaque` or `auto` (default value). When `auto` is used, the + model will automatically determine the best background for the image. + + If `transparent`, the output format needs to support transparency, so it should + be set to either `png` (default value) or `webp`. + """ + mask: FileTypes """An additional image whose fully transparent areas (e.g. @@ -61,7 +73,7 @@ class ImageEditParams(TypedDict, total=False): `gpt-image-1` will always return base64-encoded images. """ - size: Optional[Literal["256x256", "512x512", "1024x1024"]] + size: Optional[Literal["256x256", "512x512", "1024x1024", "1536x1024", "1024x1536", "auto"]] """The size of the generated images. Must be one of `1024x1024`, `1536x1024` (landscape), `1024x1536` (portrait), or diff --git a/src/openai/types/responses/computer_tool.py b/src/openai/types/responses/computer_tool.py index dffb7af7b7..5b844f5bf4 100644 --- a/src/openai/types/responses/computer_tool.py +++ b/src/openai/types/responses/computer_tool.py @@ -8,13 +8,13 @@ class ComputerTool(BaseModel): - display_height: float + display_height: int """The height of the computer display.""" - display_width: float + display_width: int """The width of the computer display.""" - environment: Literal["mac", "windows", "ubuntu", "browser"] + environment: Literal["windows", "mac", "linux", "ubuntu", "browser"] """The type of computer environment to control.""" type: Literal["computer_use_preview"] diff --git a/src/openai/types/responses/computer_tool_param.py b/src/openai/types/responses/computer_tool_param.py index 6b1072ffd2..06a5c132ec 100644 --- a/src/openai/types/responses/computer_tool_param.py +++ b/src/openai/types/responses/computer_tool_param.py @@ -8,13 +8,13 @@ class ComputerToolParam(TypedDict, total=False): - display_height: Required[float] + display_height: Required[int] """The height of the computer display.""" - display_width: Required[float] + display_width: Required[int] """The width of the computer display.""" - environment: Required[Literal["mac", "windows", "ubuntu", "browser"]] + environment: Required[Literal["windows", "mac", "linux", "ubuntu", "browser"]] """The type of computer environment to control.""" type: Required[Literal["computer_use_preview"]] diff --git a/src/openai/types/responses/file_search_tool.py b/src/openai/types/responses/file_search_tool.py index 683fc533fe..dbdd8cffab 100644 --- a/src/openai/types/responses/file_search_tool.py +++ b/src/openai/types/responses/file_search_tool.py @@ -9,7 +9,7 @@ __all__ = ["FileSearchTool", "Filters", "RankingOptions"] -Filters: TypeAlias = Union[ComparisonFilter, CompoundFilter] +Filters: TypeAlias = Union[ComparisonFilter, CompoundFilter, None] class RankingOptions(BaseModel): @@ -17,10 +17,10 @@ class RankingOptions(BaseModel): """The ranker to use for the file search.""" score_threshold: Optional[float] = None - """ - The score threshold for the file search, a number between 0 and 1. Numbers - closer to 1 will attempt to return only the most relevant results, but may - return fewer results. + """The score threshold for the file search, a number between 0 and 1. + + Numbers closer to 1 will attempt to return only the most relevant results, but + may return fewer results. """ @@ -32,7 +32,7 @@ class FileSearchTool(BaseModel): """The IDs of the vector stores to search.""" filters: Optional[Filters] = None - """A filter to apply based on file attributes.""" + """A filter to apply.""" max_num_results: Optional[int] = None """The maximum number of results to return. diff --git a/src/openai/types/responses/file_search_tool_param.py b/src/openai/types/responses/file_search_tool_param.py index 2d6af8536b..2851fae460 100644 --- a/src/openai/types/responses/file_search_tool_param.py +++ b/src/openai/types/responses/file_search_tool_param.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import List, Union +from typing import List, Union, Optional from typing_extensions import Literal, Required, TypeAlias, TypedDict from ..shared_params.compound_filter import CompoundFilter @@ -18,10 +18,10 @@ class RankingOptions(TypedDict, total=False): """The ranker to use for the file search.""" score_threshold: float - """ - The score threshold for the file search, a number between 0 and 1. Numbers - closer to 1 will attempt to return only the most relevant results, but may - return fewer results. + """The score threshold for the file search, a number between 0 and 1. + + Numbers closer to 1 will attempt to return only the most relevant results, but + may return fewer results. """ @@ -32,8 +32,8 @@ class FileSearchToolParam(TypedDict, total=False): vector_store_ids: Required[List[str]] """The IDs of the vector stores to search.""" - filters: Filters - """A filter to apply based on file attributes.""" + filters: Optional[Filters] + """A filter to apply.""" max_num_results: int """The maximum number of results to return. diff --git a/src/openai/types/responses/function_tool.py b/src/openai/types/responses/function_tool.py index 236a2c7c63..d881565356 100644 --- a/src/openai/types/responses/function_tool.py +++ b/src/openai/types/responses/function_tool.py @@ -12,10 +12,10 @@ class FunctionTool(BaseModel): name: str """The name of the function to call.""" - parameters: Dict[str, object] + parameters: Optional[Dict[str, object]] = None """A JSON schema object describing the parameters of the function.""" - strict: bool + strict: Optional[bool] = None """Whether to enforce strict parameter validation. Default `true`.""" type: Literal["function"] diff --git a/src/openai/types/responses/function_tool_param.py b/src/openai/types/responses/function_tool_param.py index 774a22e336..56bab36f47 100644 --- a/src/openai/types/responses/function_tool_param.py +++ b/src/openai/types/responses/function_tool_param.py @@ -12,10 +12,10 @@ class FunctionToolParam(TypedDict, total=False): name: Required[str] """The name of the function to call.""" - parameters: Required[Dict[str, object]] + parameters: Required[Optional[Dict[str, object]]] """A JSON schema object describing the parameters of the function.""" - strict: Required[bool] + strict: Required[Optional[bool]] """Whether to enforce strict parameter validation. Default `true`.""" type: Required[Literal["function"]] diff --git a/src/openai/types/responses/response_create_params.py b/src/openai/types/responses/response_create_params.py index 3c0a9d7b8a..972d413926 100644 --- a/src/openai/types/responses/response_create_params.py +++ b/src/openai/types/responses/response_create_params.py @@ -56,6 +56,11 @@ class ResponseCreateParamsBase(TypedDict, total=False): - `message.input_image.image_url`: Include image urls from the input message. - `computer_call_output.output.image_url`: Include image urls from the computer call output. + - `reasoning.encrypted_content`: Includes an encrypted version of reasoning + tokens in reasoning item outputs. This enables reasoning items to be used in + multi-turn conversations when using the Responses API statelessly (like when + the `store` parameter is set to `false`, or when an organization is enrolled + in the zero data retention program). """ instructions: Optional[str] diff --git a/src/openai/types/responses/response_includable.py b/src/openai/types/responses/response_includable.py index 83489fa7f1..a01dddd71d 100644 --- a/src/openai/types/responses/response_includable.py +++ b/src/openai/types/responses/response_includable.py @@ -5,5 +5,8 @@ __all__ = ["ResponseIncludable"] ResponseIncludable: TypeAlias = Literal[ - "file_search_call.results", "message.input_image.image_url", "computer_call_output.output.image_url" + "file_search_call.results", + "message.input_image.image_url", + "computer_call_output.output.image_url", + "reasoning.encrypted_content", ] diff --git a/src/openai/types/responses/response_input_file_param.py b/src/openai/types/responses/response_input_file_param.py index dc06a4ea2d..61ae46f0cb 100644 --- a/src/openai/types/responses/response_input_file_param.py +++ b/src/openai/types/responses/response_input_file_param.py @@ -2,6 +2,7 @@ from __future__ import annotations +from typing import Optional from typing_extensions import Literal, Required, TypedDict __all__ = ["ResponseInputFileParam"] @@ -14,7 +15,7 @@ class ResponseInputFileParam(TypedDict, total=False): file_data: str """The content of the file to be sent to the model.""" - file_id: str + file_id: Optional[str] """The ID of the file to be sent to the model.""" filename: str diff --git a/src/openai/types/responses/response_input_image.py b/src/openai/types/responses/response_input_image.py index d719f44e9b..f2d760b25e 100644 --- a/src/openai/types/responses/response_input_image.py +++ b/src/openai/types/responses/response_input_image.py @@ -9,7 +9,7 @@ class ResponseInputImage(BaseModel): - detail: Literal["high", "low", "auto"] + detail: Literal["low", "high", "auto"] """The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. Defaults to `auto`. diff --git a/src/openai/types/responses/response_input_image_param.py b/src/openai/types/responses/response_input_image_param.py index 5dd4db2b5d..bc17e4f1c2 100644 --- a/src/openai/types/responses/response_input_image_param.py +++ b/src/openai/types/responses/response_input_image_param.py @@ -9,7 +9,7 @@ class ResponseInputImageParam(TypedDict, total=False): - detail: Required[Literal["high", "low", "auto"]] + detail: Required[Literal["low", "high", "auto"]] """The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. Defaults to `auto`. diff --git a/src/openai/types/responses/response_input_item_param.py b/src/openai/types/responses/response_input_item_param.py index 2505f7c0b5..290953a0ef 100644 --- a/src/openai/types/responses/response_input_item_param.py +++ b/src/openai/types/responses/response_input_item_param.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Union, Iterable +from typing import Union, Iterable, Optional from typing_extensions import Literal, Required, TypeAlias, TypedDict from .easy_input_message_param import EasyInputMessageParam @@ -50,10 +50,10 @@ class ComputerCallOutputAcknowledgedSafetyCheck(TypedDict, total=False): id: Required[str] """The ID of the pending safety check.""" - code: Required[str] + code: Optional[str] """The type of the pending safety check.""" - message: Required[str] + message: Optional[str] """Details about the pending safety check.""" @@ -67,16 +67,16 @@ class ComputerCallOutput(TypedDict, total=False): type: Required[Literal["computer_call_output"]] """The type of the computer tool call output. Always `computer_call_output`.""" - id: str + id: Optional[str] """The ID of the computer tool call output.""" - acknowledged_safety_checks: Iterable[ComputerCallOutputAcknowledgedSafetyCheck] + acknowledged_safety_checks: Optional[Iterable[ComputerCallOutputAcknowledgedSafetyCheck]] """ The safety checks reported by the API that have been acknowledged by the developer. """ - status: Literal["in_progress", "completed", "incomplete"] + status: Optional[Literal["in_progress", "completed", "incomplete"]] """The status of the message input. One of `in_progress`, `completed`, or `incomplete`. Populated when input items @@ -94,13 +94,13 @@ class FunctionCallOutput(TypedDict, total=False): type: Required[Literal["function_call_output"]] """The type of the function tool call output. Always `function_call_output`.""" - id: str + id: Optional[str] """The unique ID of the function tool call output. Populated when this item is returned via API. """ - status: Literal["in_progress", "completed", "incomplete"] + status: Optional[Literal["in_progress", "completed", "incomplete"]] """The status of the item. One of `in_progress`, `completed`, or `incomplete`. Populated when items are @@ -112,7 +112,7 @@ class ItemReference(TypedDict, total=False): id: Required[str] """The ID of the item to reference.""" - type: Required[Literal["item_reference"]] + type: Optional[Literal["item_reference"]] """The type of item to reference. Always `item_reference`.""" diff --git a/src/openai/types/responses/response_input_param.py b/src/openai/types/responses/response_input_param.py index 84a80eb7c2..b24182697a 100644 --- a/src/openai/types/responses/response_input_param.py +++ b/src/openai/types/responses/response_input_param.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import List, Union, Iterable +from typing import List, Union, Iterable, Optional from typing_extensions import Literal, Required, TypeAlias, TypedDict from .easy_input_message_param import EasyInputMessageParam @@ -51,10 +51,10 @@ class ComputerCallOutputAcknowledgedSafetyCheck(TypedDict, total=False): id: Required[str] """The ID of the pending safety check.""" - code: Required[str] + code: Optional[str] """The type of the pending safety check.""" - message: Required[str] + message: Optional[str] """Details about the pending safety check.""" @@ -68,16 +68,16 @@ class ComputerCallOutput(TypedDict, total=False): type: Required[Literal["computer_call_output"]] """The type of the computer tool call output. Always `computer_call_output`.""" - id: str + id: Optional[str] """The ID of the computer tool call output.""" - acknowledged_safety_checks: Iterable[ComputerCallOutputAcknowledgedSafetyCheck] + acknowledged_safety_checks: Optional[Iterable[ComputerCallOutputAcknowledgedSafetyCheck]] """ The safety checks reported by the API that have been acknowledged by the developer. """ - status: Literal["in_progress", "completed", "incomplete"] + status: Optional[Literal["in_progress", "completed", "incomplete"]] """The status of the message input. One of `in_progress`, `completed`, or `incomplete`. Populated when input items @@ -95,13 +95,13 @@ class FunctionCallOutput(TypedDict, total=False): type: Required[Literal["function_call_output"]] """The type of the function tool call output. Always `function_call_output`.""" - id: str + id: Optional[str] """The unique ID of the function tool call output. Populated when this item is returned via API. """ - status: Literal["in_progress", "completed", "incomplete"] + status: Optional[Literal["in_progress", "completed", "incomplete"]] """The status of the item. One of `in_progress`, `completed`, or `incomplete`. Populated when items are @@ -113,7 +113,7 @@ class ItemReference(TypedDict, total=False): id: Required[str] """The ID of the item to reference.""" - type: Required[Literal["item_reference"]] + type: Optional[Literal["item_reference"]] """The type of item to reference. Always `item_reference`.""" diff --git a/src/openai/types/responses/response_reasoning_item.py b/src/openai/types/responses/response_reasoning_item.py index 57e5fbfe6d..f5da7802f8 100644 --- a/src/openai/types/responses/response_reasoning_item.py +++ b/src/openai/types/responses/response_reasoning_item.py @@ -28,6 +28,12 @@ class ResponseReasoningItem(BaseModel): type: Literal["reasoning"] """The type of the object. Always `reasoning`.""" + encrypted_content: Optional[str] = None + """ + The encrypted content of the reasoning item - populated when a response is + generated with `reasoning.encrypted_content` in the `include` parameter. + """ + status: Optional[Literal["in_progress", "completed", "incomplete"]] = None """The status of the item. diff --git a/src/openai/types/responses/response_reasoning_item_param.py b/src/openai/types/responses/response_reasoning_item_param.py index adb49d6402..2cfa5312ed 100644 --- a/src/openai/types/responses/response_reasoning_item_param.py +++ b/src/openai/types/responses/response_reasoning_item_param.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import Iterable +from typing import Iterable, Optional from typing_extensions import Literal, Required, TypedDict __all__ = ["ResponseReasoningItemParam", "Summary"] @@ -28,6 +28,12 @@ class ResponseReasoningItemParam(TypedDict, total=False): type: Required[Literal["reasoning"]] """The type of the object. Always `reasoning`.""" + encrypted_content: Optional[str] + """ + The encrypted content of the reasoning item - populated when a response is + generated with `reasoning.encrypted_content` in the `include` parameter. + """ + status: Literal["in_progress", "completed", "incomplete"] """The status of the item. diff --git a/src/openai/types/responses/tool.py b/src/openai/types/responses/tool.py index de5d5524d4..d96abdbe5a 100644 --- a/src/openai/types/responses/tool.py +++ b/src/openai/types/responses/tool.py @@ -12,5 +12,5 @@ __all__ = ["Tool"] Tool: TypeAlias = Annotated[ - Union[FileSearchTool, FunctionTool, ComputerTool, WebSearchTool], PropertyInfo(discriminator="type") + Union[FileSearchTool, FunctionTool, WebSearchTool, ComputerTool], PropertyInfo(discriminator="type") ] diff --git a/src/openai/types/responses/tool_param.py b/src/openai/types/responses/tool_param.py index be1cf82452..200c347005 100644 --- a/src/openai/types/responses/tool_param.py +++ b/src/openai/types/responses/tool_param.py @@ -13,6 +13,6 @@ __all__ = ["ToolParam"] -ToolParam: TypeAlias = Union[FileSearchToolParam, FunctionToolParam, ComputerToolParam, WebSearchToolParam] +ToolParam: TypeAlias = Union[FileSearchToolParam, FunctionToolParam, WebSearchToolParam, ComputerToolParam] ParseableToolParam: TypeAlias = Union[ToolParam, ChatCompletionToolParam] diff --git a/src/openai/types/responses/web_search_tool.py b/src/openai/types/responses/web_search_tool.py index bee270bf85..a6bf951145 100644 --- a/src/openai/types/responses/web_search_tool.py +++ b/src/openai/types/responses/web_search_tool.py @@ -33,16 +33,17 @@ class UserLocation(BaseModel): class WebSearchTool(BaseModel): type: Literal["web_search_preview", "web_search_preview_2025_03_11"] - """The type of the web search tool. One of: + """The type of the web search tool. - - `web_search_preview` - - `web_search_preview_2025_03_11` + One of `web_search_preview` or `web_search_preview_2025_03_11`. """ search_context_size: Optional[Literal["low", "medium", "high"]] = None - """ - High level guidance for the amount of context window space to use for the - search. One of `low`, `medium`, or `high`. `medium` is the default. + """High level guidance for the amount of context window space to use for the + search. + + One of `low`, `medium`, or `high`. `medium` is the default. """ user_location: Optional[UserLocation] = None + """The user's location.""" diff --git a/src/openai/types/responses/web_search_tool_param.py b/src/openai/types/responses/web_search_tool_param.py index 8ee36ffb47..d0335c01a3 100644 --- a/src/openai/types/responses/web_search_tool_param.py +++ b/src/openai/types/responses/web_search_tool_param.py @@ -12,19 +12,19 @@ class UserLocation(TypedDict, total=False): type: Required[Literal["approximate"]] """The type of location approximation. Always `approximate`.""" - city: str + city: Optional[str] """Free text input for the city of the user, e.g. `San Francisco`.""" - country: str + country: Optional[str] """ The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user, e.g. `US`. """ - region: str + region: Optional[str] """Free text input for the region of the user, e.g. `California`.""" - timezone: str + timezone: Optional[str] """ The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the user, e.g. `America/Los_Angeles`. @@ -33,16 +33,17 @@ class UserLocation(TypedDict, total=False): class WebSearchToolParam(TypedDict, total=False): type: Required[Literal["web_search_preview", "web_search_preview_2025_03_11"]] - """The type of the web search tool. One of: + """The type of the web search tool. - - `web_search_preview` - - `web_search_preview_2025_03_11` + One of `web_search_preview` or `web_search_preview_2025_03_11`. """ search_context_size: Literal["low", "medium", "high"] - """ - High level guidance for the amount of context window space to use for the - search. One of `low`, `medium`, or `high`. `medium` is the default. + """High level guidance for the amount of context window space to use for the + search. + + One of `low`, `medium`, or `high`. `medium` is the default. """ user_location: Optional[UserLocation] + """The user's location.""" diff --git a/tests/api_resources/test_images.py b/tests/api_resources/test_images.py index 7997e9f5a1..7c61453bc1 100644 --- a/tests/api_resources/test_images.py +++ b/tests/api_resources/test_images.py @@ -73,6 +73,7 @@ def test_method_edit_with_all_params(self, client: OpenAI) -> None: image = client.images.edit( image=b"raw file contents", prompt="A cute baby sea otter wearing a beret", + background="transparent", mask=b"raw file contents", model="string", n=1, @@ -218,6 +219,7 @@ async def test_method_edit_with_all_params(self, async_client: AsyncOpenAI) -> N image = await async_client.images.edit( image=b"raw file contents", prompt="A cute baby sea otter wearing a beret", + background="transparent", mask=b"raw file contents", model="string", n=1, From 67997a4ec1ebcdf8e740afb0d0b2e37897657bde Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 2 May 2025 19:10:28 +0000 Subject: [PATCH 807/816] release: 1.77.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 18 ++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 21 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 8bcd8a5b4f..33a65d75c4 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.76.2" + ".": "1.77.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index bc85128f6a..9097cdc65a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,23 @@ # Changelog +## 1.77.0 (2025-05-02) + +Full Changelog: [v1.76.2...v1.77.0](https://github.com/openai/openai-python/compare/v1.76.2...v1.77.0) + +### Features + +* **api:** add image sizes, reasoning encryption ([473469a](https://github.com/openai/openai-python/commit/473469afa1a5f0a03f727bdcdadb9fd57872f9c5)) + + +### Bug Fixes + +* **parsing:** handle whitespace only strings ([#2007](https://github.com/openai/openai-python/issues/2007)) ([246bc5b](https://github.com/openai/openai-python/commit/246bc5b7559887840717667a0dad465caef66c3b)) + + +### Chores + +* only strip leading whitespace ([8467d66](https://github.com/openai/openai-python/commit/8467d666e0ddf1a9f81b8769a5c8a2fef1de20c1)) + ## 1.76.2 (2025-04-29) Full Changelog: [v1.76.1...v1.76.2](https://github.com/openai/openai-python/compare/v1.76.1...v1.76.2) diff --git a/pyproject.toml b/pyproject.toml index 2c3c3eaf3b..4b854b05e5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.76.2" +version = "1.77.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index ef1e3fe526..9d8ba015e1 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.76.2" # x-release-please-version +__version__ = "1.77.0" # x-release-please-version From 1356c89a1302a1f6c1f6d6d7e8398a741d4e7423 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 5 May 2025 08:26:41 +0000 Subject: [PATCH 808/816] chore: use lazy imports for module level client --- src/openai/_module_client.py | 112 +++++++++++++++++++++-------------- 1 file changed, 66 insertions(+), 46 deletions(-) diff --git a/src/openai/_module_client.py b/src/openai/_module_client.py index cf12f7a31e..dd601f9be9 100644 --- a/src/openai/_module_client.py +++ b/src/openai/_module_client.py @@ -1,113 +1,133 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +from __future__ import annotations + +from typing import TYPE_CHECKING from typing_extensions import override -from . import resources, _load_client +if TYPE_CHECKING: + from .resources.files import Files + from .resources.images import Images + from .resources.models import Models + from .resources.batches import Batches + from .resources.beta.beta import Beta + from .resources.chat.chat import Chat + from .resources.embeddings import Embeddings + from .resources.audio.audio import Audio + from .resources.completions import Completions + from .resources.evals.evals import Evals + from .resources.moderations import Moderations + from .resources.uploads.uploads import Uploads + from .resources.responses.responses import Responses + from .resources.fine_tuning.fine_tuning import FineTuning + from .resources.vector_stores.vector_stores import VectorStores + +from . import _load_client from ._utils import LazyProxy -class ChatProxy(LazyProxy[resources.Chat]): +class ChatProxy(LazyProxy["Chat"]): @override - def __load__(self) -> resources.Chat: + def __load__(self) -> Chat: return _load_client().chat -class BetaProxy(LazyProxy[resources.Beta]): +class BetaProxy(LazyProxy["Beta"]): @override - def __load__(self) -> resources.Beta: + def __load__(self) -> Beta: return _load_client().beta -class FilesProxy(LazyProxy[resources.Files]): +class FilesProxy(LazyProxy["Files"]): @override - def __load__(self) -> resources.Files: + def __load__(self) -> Files: return _load_client().files -class AudioProxy(LazyProxy[resources.Audio]): +class AudioProxy(LazyProxy["Audio"]): @override - def __load__(self) -> resources.Audio: + def __load__(self) -> Audio: return _load_client().audio -class EvalsProxy(LazyProxy[resources.Evals]): +class EvalsProxy(LazyProxy["Evals"]): @override - def __load__(self) -> resources.Evals: + def __load__(self) -> Evals: return _load_client().evals -class ImagesProxy(LazyProxy[resources.Images]): +class ImagesProxy(LazyProxy["Images"]): @override - def __load__(self) -> resources.Images: + def __load__(self) -> Images: return _load_client().images -class ModelsProxy(LazyProxy[resources.Models]): +class ModelsProxy(LazyProxy["Models"]): @override - def __load__(self) -> resources.Models: + def __load__(self) -> Models: return _load_client().models -class BatchesProxy(LazyProxy[resources.Batches]): +class BatchesProxy(LazyProxy["Batches"]): @override - def __load__(self) -> resources.Batches: + def __load__(self) -> Batches: return _load_client().batches -class UploadsProxy(LazyProxy[resources.Uploads]): +class UploadsProxy(LazyProxy["Uploads"]): @override - def __load__(self) -> resources.Uploads: + def __load__(self) -> Uploads: return _load_client().uploads -class ResponsesProxy(LazyProxy[resources.Responses]): +class ResponsesProxy(LazyProxy["Responses"]): @override - def __load__(self) -> resources.Responses: + def __load__(self) -> Responses: return _load_client().responses -class EmbeddingsProxy(LazyProxy[resources.Embeddings]): +class EmbeddingsProxy(LazyProxy["Embeddings"]): @override - def __load__(self) -> resources.Embeddings: + def __load__(self) -> Embeddings: return _load_client().embeddings -class CompletionsProxy(LazyProxy[resources.Completions]): +class CompletionsProxy(LazyProxy["Completions"]): @override - def __load__(self) -> resources.Completions: + def __load__(self) -> Completions: return _load_client().completions -class ModerationsProxy(LazyProxy[resources.Moderations]): +class ModerationsProxy(LazyProxy["Moderations"]): @override - def __load__(self) -> resources.Moderations: + def __load__(self) -> Moderations: return _load_client().moderations -class FineTuningProxy(LazyProxy[resources.FineTuning]): +class FineTuningProxy(LazyProxy["FineTuning"]): @override - def __load__(self) -> resources.FineTuning: + def __load__(self) -> FineTuning: return _load_client().fine_tuning -class VectorStoresProxy(LazyProxy[resources.VectorStores]): +class VectorStoresProxy(LazyProxy["VectorStores"]): @override - def __load__(self) -> resources.VectorStores: + def __load__(self) -> VectorStores: return _load_client().vector_stores -chat: resources.Chat = ChatProxy().__as_proxied__() -beta: resources.Beta = BetaProxy().__as_proxied__() -files: resources.Files = FilesProxy().__as_proxied__() -audio: resources.Audio = AudioProxy().__as_proxied__() -evals: resources.Evals = EvalsProxy().__as_proxied__() -images: resources.Images = ImagesProxy().__as_proxied__() -models: resources.Models = ModelsProxy().__as_proxied__() -batches: resources.Batches = BatchesProxy().__as_proxied__() -uploads: resources.Uploads = UploadsProxy().__as_proxied__() -responses: resources.Responses = ResponsesProxy().__as_proxied__() -embeddings: resources.Embeddings = EmbeddingsProxy().__as_proxied__() -completions: resources.Completions = CompletionsProxy().__as_proxied__() -moderations: resources.Moderations = ModerationsProxy().__as_proxied__() -fine_tuning: resources.FineTuning = FineTuningProxy().__as_proxied__() -vector_stores: resources.VectorStores = VectorStoresProxy().__as_proxied__() +chat: Chat = ChatProxy().__as_proxied__() +beta: Beta = BetaProxy().__as_proxied__() +files: Files = FilesProxy().__as_proxied__() +audio: Audio = AudioProxy().__as_proxied__() +evals: Evals = EvalsProxy().__as_proxied__() +images: Images = ImagesProxy().__as_proxied__() +models: Models = ModelsProxy().__as_proxied__() +batches: Batches = BatchesProxy().__as_proxied__() +uploads: Uploads = UploadsProxy().__as_proxied__() +responses: Responses = ResponsesProxy().__as_proxied__() +embeddings: Embeddings = EmbeddingsProxy().__as_proxied__() +completions: Completions = CompletionsProxy().__as_proxied__() +moderations: Moderations = ModerationsProxy().__as_proxied__() +fine_tuning: FineTuning = FineTuningProxy().__as_proxied__() +vector_stores: VectorStores = VectorStoresProxy().__as_proxied__() From 917dade87f0243caf24d890a1ee3307ee89d145c Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 5 May 2025 13:15:15 +0000 Subject: [PATCH 809/816] chore: use lazy imports for resources --- src/openai/_client.py | 742 +++++++++++++++++++++++++------ src/openai/resources/__init__.py | 14 - 2 files changed, 602 insertions(+), 154 deletions(-) diff --git a/src/openai/_client.py b/src/openai/_client.py index 3aca6cb124..b251ab0917 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -3,7 +3,7 @@ from __future__ import annotations import os -from typing import Any, Union, Mapping +from typing import TYPE_CHECKING, Any, Union, Mapping from typing_extensions import Self, override import httpx @@ -24,8 +24,8 @@ is_mapping, get_async_library, ) +from ._compat import cached_property from ._version import __version__ -from .resources import files, images, models, batches, embeddings, completions, moderations from ._streaming import Stream as Stream, AsyncStream as AsyncStream from ._exceptions import OpenAIError, APIStatusError from ._base_client import ( @@ -33,37 +33,45 @@ SyncAPIClient, AsyncAPIClient, ) -from .resources.beta import beta -from .resources.chat import chat -from .resources.audio import audio -from .resources.evals import evals -from .resources.uploads import uploads -from .resources.responses import responses -from .resources.fine_tuning import fine_tuning -from .resources.vector_stores import vector_stores + +if TYPE_CHECKING: + from .resources import ( + beta, + chat, + audio, + evals, + files, + images, + models, + batches, + uploads, + responses, + embeddings, + completions, + fine_tuning, + moderations, + vector_stores, + ) + from .resources.files import Files, AsyncFiles + from .resources.images import Images, AsyncImages + from .resources.models import Models, AsyncModels + from .resources.batches import Batches, AsyncBatches + from .resources.beta.beta import Beta, AsyncBeta + from .resources.chat.chat import Chat, AsyncChat + from .resources.embeddings import Embeddings, AsyncEmbeddings + from .resources.audio.audio import Audio, AsyncAudio + from .resources.completions import Completions, AsyncCompletions + from .resources.evals.evals import Evals, AsyncEvals + from .resources.moderations import Moderations, AsyncModerations + from .resources.uploads.uploads import Uploads, AsyncUploads + from .resources.responses.responses import Responses, AsyncResponses + from .resources.fine_tuning.fine_tuning import FineTuning, AsyncFineTuning + from .resources.vector_stores.vector_stores import VectorStores, AsyncVectorStores __all__ = ["Timeout", "Transport", "ProxiesTypes", "RequestOptions", "OpenAI", "AsyncOpenAI", "Client", "AsyncClient"] class OpenAI(SyncAPIClient): - completions: completions.Completions - chat: chat.Chat - embeddings: embeddings.Embeddings - files: files.Files - images: images.Images - audio: audio.Audio - moderations: moderations.Moderations - models: models.Models - fine_tuning: fine_tuning.FineTuning - vector_stores: vector_stores.VectorStores - beta: beta.Beta - batches: batches.Batches - uploads: uploads.Uploads - responses: responses.Responses - evals: evals.Evals - with_raw_response: OpenAIWithRawResponse - with_streaming_response: OpenAIWithStreamedResponse - # client options api_key: str organization: str | None @@ -146,23 +154,103 @@ def __init__( self._default_stream_cls = Stream - self.completions = completions.Completions(self) - self.chat = chat.Chat(self) - self.embeddings = embeddings.Embeddings(self) - self.files = files.Files(self) - self.images = images.Images(self) - self.audio = audio.Audio(self) - self.moderations = moderations.Moderations(self) - self.models = models.Models(self) - self.fine_tuning = fine_tuning.FineTuning(self) - self.vector_stores = vector_stores.VectorStores(self) - self.beta = beta.Beta(self) - self.batches = batches.Batches(self) - self.uploads = uploads.Uploads(self) - self.responses = responses.Responses(self) - self.evals = evals.Evals(self) - self.with_raw_response = OpenAIWithRawResponse(self) - self.with_streaming_response = OpenAIWithStreamedResponse(self) + @cached_property + def completions(self) -> Completions: + from .resources.completions import Completions + + return Completions(self) + + @cached_property + def chat(self) -> Chat: + from .resources.chat import Chat + + return Chat(self) + + @cached_property + def embeddings(self) -> Embeddings: + from .resources.embeddings import Embeddings + + return Embeddings(self) + + @cached_property + def files(self) -> Files: + from .resources.files import Files + + return Files(self) + + @cached_property + def images(self) -> Images: + from .resources.images import Images + + return Images(self) + + @cached_property + def audio(self) -> Audio: + from .resources.audio import Audio + + return Audio(self) + + @cached_property + def moderations(self) -> Moderations: + from .resources.moderations import Moderations + + return Moderations(self) + + @cached_property + def models(self) -> Models: + from .resources.models import Models + + return Models(self) + + @cached_property + def fine_tuning(self) -> FineTuning: + from .resources.fine_tuning import FineTuning + + return FineTuning(self) + + @cached_property + def vector_stores(self) -> VectorStores: + from .resources.vector_stores import VectorStores + + return VectorStores(self) + + @cached_property + def beta(self) -> Beta: + from .resources.beta import Beta + + return Beta(self) + + @cached_property + def batches(self) -> Batches: + from .resources.batches import Batches + + return Batches(self) + + @cached_property + def uploads(self) -> Uploads: + from .resources.uploads import Uploads + + return Uploads(self) + + @cached_property + def responses(self) -> Responses: + from .resources.responses import Responses + + return Responses(self) + + @cached_property + def evals(self) -> Evals: + from .resources.evals import Evals + + return Evals(self) + + @cached_property + def with_raw_response(self) -> OpenAIWithRawResponse: + return OpenAIWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> OpenAIWithStreamedResponse: + return OpenAIWithStreamedResponse(self) @property @override @@ -279,24 +367,6 @@ def _make_status_error( class AsyncOpenAI(AsyncAPIClient): - completions: completions.AsyncCompletions - chat: chat.AsyncChat - embeddings: embeddings.AsyncEmbeddings - files: files.AsyncFiles - images: images.AsyncImages - audio: audio.AsyncAudio - moderations: moderations.AsyncModerations - models: models.AsyncModels - fine_tuning: fine_tuning.AsyncFineTuning - vector_stores: vector_stores.AsyncVectorStores - beta: beta.AsyncBeta - batches: batches.AsyncBatches - uploads: uploads.AsyncUploads - responses: responses.AsyncResponses - evals: evals.AsyncEvals - with_raw_response: AsyncOpenAIWithRawResponse - with_streaming_response: AsyncOpenAIWithStreamedResponse - # client options api_key: str organization: str | None @@ -379,23 +449,103 @@ def __init__( self._default_stream_cls = AsyncStream - self.completions = completions.AsyncCompletions(self) - self.chat = chat.AsyncChat(self) - self.embeddings = embeddings.AsyncEmbeddings(self) - self.files = files.AsyncFiles(self) - self.images = images.AsyncImages(self) - self.audio = audio.AsyncAudio(self) - self.moderations = moderations.AsyncModerations(self) - self.models = models.AsyncModels(self) - self.fine_tuning = fine_tuning.AsyncFineTuning(self) - self.vector_stores = vector_stores.AsyncVectorStores(self) - self.beta = beta.AsyncBeta(self) - self.batches = batches.AsyncBatches(self) - self.uploads = uploads.AsyncUploads(self) - self.responses = responses.AsyncResponses(self) - self.evals = evals.AsyncEvals(self) - self.with_raw_response = AsyncOpenAIWithRawResponse(self) - self.with_streaming_response = AsyncOpenAIWithStreamedResponse(self) + @cached_property + def completions(self) -> AsyncCompletions: + from .resources.completions import AsyncCompletions + + return AsyncCompletions(self) + + @cached_property + def chat(self) -> AsyncChat: + from .resources.chat import AsyncChat + + return AsyncChat(self) + + @cached_property + def embeddings(self) -> AsyncEmbeddings: + from .resources.embeddings import AsyncEmbeddings + + return AsyncEmbeddings(self) + + @cached_property + def files(self) -> AsyncFiles: + from .resources.files import AsyncFiles + + return AsyncFiles(self) + + @cached_property + def images(self) -> AsyncImages: + from .resources.images import AsyncImages + + return AsyncImages(self) + + @cached_property + def audio(self) -> AsyncAudio: + from .resources.audio import AsyncAudio + + return AsyncAudio(self) + + @cached_property + def moderations(self) -> AsyncModerations: + from .resources.moderations import AsyncModerations + + return AsyncModerations(self) + + @cached_property + def models(self) -> AsyncModels: + from .resources.models import AsyncModels + + return AsyncModels(self) + + @cached_property + def fine_tuning(self) -> AsyncFineTuning: + from .resources.fine_tuning import AsyncFineTuning + + return AsyncFineTuning(self) + + @cached_property + def vector_stores(self) -> AsyncVectorStores: + from .resources.vector_stores import AsyncVectorStores + + return AsyncVectorStores(self) + + @cached_property + def beta(self) -> AsyncBeta: + from .resources.beta import AsyncBeta + + return AsyncBeta(self) + + @cached_property + def batches(self) -> AsyncBatches: + from .resources.batches import AsyncBatches + + return AsyncBatches(self) + + @cached_property + def uploads(self) -> AsyncUploads: + from .resources.uploads import AsyncUploads + + return AsyncUploads(self) + + @cached_property + def responses(self) -> AsyncResponses: + from .resources.responses import AsyncResponses + + return AsyncResponses(self) + + @cached_property + def evals(self) -> AsyncEvals: + from .resources.evals import AsyncEvals + + return AsyncEvals(self) + + @cached_property + def with_raw_response(self) -> AsyncOpenAIWithRawResponse: + return AsyncOpenAIWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncOpenAIWithStreamedResponse: + return AsyncOpenAIWithStreamedResponse(self) @property @override @@ -512,79 +662,391 @@ def _make_status_error( class OpenAIWithRawResponse: + _client: OpenAI + def __init__(self, client: OpenAI) -> None: - self.completions = completions.CompletionsWithRawResponse(client.completions) - self.chat = chat.ChatWithRawResponse(client.chat) - self.embeddings = embeddings.EmbeddingsWithRawResponse(client.embeddings) - self.files = files.FilesWithRawResponse(client.files) - self.images = images.ImagesWithRawResponse(client.images) - self.audio = audio.AudioWithRawResponse(client.audio) - self.moderations = moderations.ModerationsWithRawResponse(client.moderations) - self.models = models.ModelsWithRawResponse(client.models) - self.fine_tuning = fine_tuning.FineTuningWithRawResponse(client.fine_tuning) - self.vector_stores = vector_stores.VectorStoresWithRawResponse(client.vector_stores) - self.beta = beta.BetaWithRawResponse(client.beta) - self.batches = batches.BatchesWithRawResponse(client.batches) - self.uploads = uploads.UploadsWithRawResponse(client.uploads) - self.responses = responses.ResponsesWithRawResponse(client.responses) - self.evals = evals.EvalsWithRawResponse(client.evals) + self._client = client + + @cached_property + def completions(self) -> completions.CompletionsWithRawResponse: + from .resources.completions import CompletionsWithRawResponse + + return CompletionsWithRawResponse(self._client.completions) + + @cached_property + def chat(self) -> chat.ChatWithRawResponse: + from .resources.chat import ChatWithRawResponse + + return ChatWithRawResponse(self._client.chat) + + @cached_property + def embeddings(self) -> embeddings.EmbeddingsWithRawResponse: + from .resources.embeddings import EmbeddingsWithRawResponse + + return EmbeddingsWithRawResponse(self._client.embeddings) + + @cached_property + def files(self) -> files.FilesWithRawResponse: + from .resources.files import FilesWithRawResponse + + return FilesWithRawResponse(self._client.files) + + @cached_property + def images(self) -> images.ImagesWithRawResponse: + from .resources.images import ImagesWithRawResponse + + return ImagesWithRawResponse(self._client.images) + + @cached_property + def audio(self) -> audio.AudioWithRawResponse: + from .resources.audio import AudioWithRawResponse + + return AudioWithRawResponse(self._client.audio) + + @cached_property + def moderations(self) -> moderations.ModerationsWithRawResponse: + from .resources.moderations import ModerationsWithRawResponse + + return ModerationsWithRawResponse(self._client.moderations) + + @cached_property + def models(self) -> models.ModelsWithRawResponse: + from .resources.models import ModelsWithRawResponse + + return ModelsWithRawResponse(self._client.models) + + @cached_property + def fine_tuning(self) -> fine_tuning.FineTuningWithRawResponse: + from .resources.fine_tuning import FineTuningWithRawResponse + + return FineTuningWithRawResponse(self._client.fine_tuning) + + @cached_property + def vector_stores(self) -> vector_stores.VectorStoresWithRawResponse: + from .resources.vector_stores import VectorStoresWithRawResponse + + return VectorStoresWithRawResponse(self._client.vector_stores) + + @cached_property + def beta(self) -> beta.BetaWithRawResponse: + from .resources.beta import BetaWithRawResponse + + return BetaWithRawResponse(self._client.beta) + + @cached_property + def batches(self) -> batches.BatchesWithRawResponse: + from .resources.batches import BatchesWithRawResponse + + return BatchesWithRawResponse(self._client.batches) + + @cached_property + def uploads(self) -> uploads.UploadsWithRawResponse: + from .resources.uploads import UploadsWithRawResponse + + return UploadsWithRawResponse(self._client.uploads) + + @cached_property + def responses(self) -> responses.ResponsesWithRawResponse: + from .resources.responses import ResponsesWithRawResponse + + return ResponsesWithRawResponse(self._client.responses) + + @cached_property + def evals(self) -> evals.EvalsWithRawResponse: + from .resources.evals import EvalsWithRawResponse + + return EvalsWithRawResponse(self._client.evals) class AsyncOpenAIWithRawResponse: + _client: AsyncOpenAI + def __init__(self, client: AsyncOpenAI) -> None: - self.completions = completions.AsyncCompletionsWithRawResponse(client.completions) - self.chat = chat.AsyncChatWithRawResponse(client.chat) - self.embeddings = embeddings.AsyncEmbeddingsWithRawResponse(client.embeddings) - self.files = files.AsyncFilesWithRawResponse(client.files) - self.images = images.AsyncImagesWithRawResponse(client.images) - self.audio = audio.AsyncAudioWithRawResponse(client.audio) - self.moderations = moderations.AsyncModerationsWithRawResponse(client.moderations) - self.models = models.AsyncModelsWithRawResponse(client.models) - self.fine_tuning = fine_tuning.AsyncFineTuningWithRawResponse(client.fine_tuning) - self.vector_stores = vector_stores.AsyncVectorStoresWithRawResponse(client.vector_stores) - self.beta = beta.AsyncBetaWithRawResponse(client.beta) - self.batches = batches.AsyncBatchesWithRawResponse(client.batches) - self.uploads = uploads.AsyncUploadsWithRawResponse(client.uploads) - self.responses = responses.AsyncResponsesWithRawResponse(client.responses) - self.evals = evals.AsyncEvalsWithRawResponse(client.evals) + self._client = client + + @cached_property + def completions(self) -> completions.AsyncCompletionsWithRawResponse: + from .resources.completions import AsyncCompletionsWithRawResponse + + return AsyncCompletionsWithRawResponse(self._client.completions) + + @cached_property + def chat(self) -> chat.AsyncChatWithRawResponse: + from .resources.chat import AsyncChatWithRawResponse + + return AsyncChatWithRawResponse(self._client.chat) + + @cached_property + def embeddings(self) -> embeddings.AsyncEmbeddingsWithRawResponse: + from .resources.embeddings import AsyncEmbeddingsWithRawResponse + + return AsyncEmbeddingsWithRawResponse(self._client.embeddings) + + @cached_property + def files(self) -> files.AsyncFilesWithRawResponse: + from .resources.files import AsyncFilesWithRawResponse + + return AsyncFilesWithRawResponse(self._client.files) + + @cached_property + def images(self) -> images.AsyncImagesWithRawResponse: + from .resources.images import AsyncImagesWithRawResponse + + return AsyncImagesWithRawResponse(self._client.images) + + @cached_property + def audio(self) -> audio.AsyncAudioWithRawResponse: + from .resources.audio import AsyncAudioWithRawResponse + + return AsyncAudioWithRawResponse(self._client.audio) + + @cached_property + def moderations(self) -> moderations.AsyncModerationsWithRawResponse: + from .resources.moderations import AsyncModerationsWithRawResponse + + return AsyncModerationsWithRawResponse(self._client.moderations) + + @cached_property + def models(self) -> models.AsyncModelsWithRawResponse: + from .resources.models import AsyncModelsWithRawResponse + + return AsyncModelsWithRawResponse(self._client.models) + + @cached_property + def fine_tuning(self) -> fine_tuning.AsyncFineTuningWithRawResponse: + from .resources.fine_tuning import AsyncFineTuningWithRawResponse + + return AsyncFineTuningWithRawResponse(self._client.fine_tuning) + + @cached_property + def vector_stores(self) -> vector_stores.AsyncVectorStoresWithRawResponse: + from .resources.vector_stores import AsyncVectorStoresWithRawResponse + + return AsyncVectorStoresWithRawResponse(self._client.vector_stores) + + @cached_property + def beta(self) -> beta.AsyncBetaWithRawResponse: + from .resources.beta import AsyncBetaWithRawResponse + + return AsyncBetaWithRawResponse(self._client.beta) + + @cached_property + def batches(self) -> batches.AsyncBatchesWithRawResponse: + from .resources.batches import AsyncBatchesWithRawResponse + + return AsyncBatchesWithRawResponse(self._client.batches) + + @cached_property + def uploads(self) -> uploads.AsyncUploadsWithRawResponse: + from .resources.uploads import AsyncUploadsWithRawResponse + + return AsyncUploadsWithRawResponse(self._client.uploads) + + @cached_property + def responses(self) -> responses.AsyncResponsesWithRawResponse: + from .resources.responses import AsyncResponsesWithRawResponse + + return AsyncResponsesWithRawResponse(self._client.responses) + + @cached_property + def evals(self) -> evals.AsyncEvalsWithRawResponse: + from .resources.evals import AsyncEvalsWithRawResponse + + return AsyncEvalsWithRawResponse(self._client.evals) class OpenAIWithStreamedResponse: + _client: OpenAI + def __init__(self, client: OpenAI) -> None: - self.completions = completions.CompletionsWithStreamingResponse(client.completions) - self.chat = chat.ChatWithStreamingResponse(client.chat) - self.embeddings = embeddings.EmbeddingsWithStreamingResponse(client.embeddings) - self.files = files.FilesWithStreamingResponse(client.files) - self.images = images.ImagesWithStreamingResponse(client.images) - self.audio = audio.AudioWithStreamingResponse(client.audio) - self.moderations = moderations.ModerationsWithStreamingResponse(client.moderations) - self.models = models.ModelsWithStreamingResponse(client.models) - self.fine_tuning = fine_tuning.FineTuningWithStreamingResponse(client.fine_tuning) - self.vector_stores = vector_stores.VectorStoresWithStreamingResponse(client.vector_stores) - self.beta = beta.BetaWithStreamingResponse(client.beta) - self.batches = batches.BatchesWithStreamingResponse(client.batches) - self.uploads = uploads.UploadsWithStreamingResponse(client.uploads) - self.responses = responses.ResponsesWithStreamingResponse(client.responses) - self.evals = evals.EvalsWithStreamingResponse(client.evals) + self._client = client + + @cached_property + def completions(self) -> completions.CompletionsWithStreamingResponse: + from .resources.completions import CompletionsWithStreamingResponse + + return CompletionsWithStreamingResponse(self._client.completions) + + @cached_property + def chat(self) -> chat.ChatWithStreamingResponse: + from .resources.chat import ChatWithStreamingResponse + + return ChatWithStreamingResponse(self._client.chat) + + @cached_property + def embeddings(self) -> embeddings.EmbeddingsWithStreamingResponse: + from .resources.embeddings import EmbeddingsWithStreamingResponse + + return EmbeddingsWithStreamingResponse(self._client.embeddings) + + @cached_property + def files(self) -> files.FilesWithStreamingResponse: + from .resources.files import FilesWithStreamingResponse + + return FilesWithStreamingResponse(self._client.files) + + @cached_property + def images(self) -> images.ImagesWithStreamingResponse: + from .resources.images import ImagesWithStreamingResponse + + return ImagesWithStreamingResponse(self._client.images) + + @cached_property + def audio(self) -> audio.AudioWithStreamingResponse: + from .resources.audio import AudioWithStreamingResponse + + return AudioWithStreamingResponse(self._client.audio) + + @cached_property + def moderations(self) -> moderations.ModerationsWithStreamingResponse: + from .resources.moderations import ModerationsWithStreamingResponse + + return ModerationsWithStreamingResponse(self._client.moderations) + + @cached_property + def models(self) -> models.ModelsWithStreamingResponse: + from .resources.models import ModelsWithStreamingResponse + + return ModelsWithStreamingResponse(self._client.models) + + @cached_property + def fine_tuning(self) -> fine_tuning.FineTuningWithStreamingResponse: + from .resources.fine_tuning import FineTuningWithStreamingResponse + + return FineTuningWithStreamingResponse(self._client.fine_tuning) + + @cached_property + def vector_stores(self) -> vector_stores.VectorStoresWithStreamingResponse: + from .resources.vector_stores import VectorStoresWithStreamingResponse + + return VectorStoresWithStreamingResponse(self._client.vector_stores) + + @cached_property + def beta(self) -> beta.BetaWithStreamingResponse: + from .resources.beta import BetaWithStreamingResponse + + return BetaWithStreamingResponse(self._client.beta) + + @cached_property + def batches(self) -> batches.BatchesWithStreamingResponse: + from .resources.batches import BatchesWithStreamingResponse + + return BatchesWithStreamingResponse(self._client.batches) + + @cached_property + def uploads(self) -> uploads.UploadsWithStreamingResponse: + from .resources.uploads import UploadsWithStreamingResponse + + return UploadsWithStreamingResponse(self._client.uploads) + + @cached_property + def responses(self) -> responses.ResponsesWithStreamingResponse: + from .resources.responses import ResponsesWithStreamingResponse + + return ResponsesWithStreamingResponse(self._client.responses) + + @cached_property + def evals(self) -> evals.EvalsWithStreamingResponse: + from .resources.evals import EvalsWithStreamingResponse + + return EvalsWithStreamingResponse(self._client.evals) class AsyncOpenAIWithStreamedResponse: + _client: AsyncOpenAI + def __init__(self, client: AsyncOpenAI) -> None: - self.completions = completions.AsyncCompletionsWithStreamingResponse(client.completions) - self.chat = chat.AsyncChatWithStreamingResponse(client.chat) - self.embeddings = embeddings.AsyncEmbeddingsWithStreamingResponse(client.embeddings) - self.files = files.AsyncFilesWithStreamingResponse(client.files) - self.images = images.AsyncImagesWithStreamingResponse(client.images) - self.audio = audio.AsyncAudioWithStreamingResponse(client.audio) - self.moderations = moderations.AsyncModerationsWithStreamingResponse(client.moderations) - self.models = models.AsyncModelsWithStreamingResponse(client.models) - self.fine_tuning = fine_tuning.AsyncFineTuningWithStreamingResponse(client.fine_tuning) - self.vector_stores = vector_stores.AsyncVectorStoresWithStreamingResponse(client.vector_stores) - self.beta = beta.AsyncBetaWithStreamingResponse(client.beta) - self.batches = batches.AsyncBatchesWithStreamingResponse(client.batches) - self.uploads = uploads.AsyncUploadsWithStreamingResponse(client.uploads) - self.responses = responses.AsyncResponsesWithStreamingResponse(client.responses) - self.evals = evals.AsyncEvalsWithStreamingResponse(client.evals) + self._client = client + + @cached_property + def completions(self) -> completions.AsyncCompletionsWithStreamingResponse: + from .resources.completions import AsyncCompletionsWithStreamingResponse + + return AsyncCompletionsWithStreamingResponse(self._client.completions) + + @cached_property + def chat(self) -> chat.AsyncChatWithStreamingResponse: + from .resources.chat import AsyncChatWithStreamingResponse + + return AsyncChatWithStreamingResponse(self._client.chat) + + @cached_property + def embeddings(self) -> embeddings.AsyncEmbeddingsWithStreamingResponse: + from .resources.embeddings import AsyncEmbeddingsWithStreamingResponse + + return AsyncEmbeddingsWithStreamingResponse(self._client.embeddings) + + @cached_property + def files(self) -> files.AsyncFilesWithStreamingResponse: + from .resources.files import AsyncFilesWithStreamingResponse + + return AsyncFilesWithStreamingResponse(self._client.files) + + @cached_property + def images(self) -> images.AsyncImagesWithStreamingResponse: + from .resources.images import AsyncImagesWithStreamingResponse + + return AsyncImagesWithStreamingResponse(self._client.images) + + @cached_property + def audio(self) -> audio.AsyncAudioWithStreamingResponse: + from .resources.audio import AsyncAudioWithStreamingResponse + + return AsyncAudioWithStreamingResponse(self._client.audio) + + @cached_property + def moderations(self) -> moderations.AsyncModerationsWithStreamingResponse: + from .resources.moderations import AsyncModerationsWithStreamingResponse + + return AsyncModerationsWithStreamingResponse(self._client.moderations) + + @cached_property + def models(self) -> models.AsyncModelsWithStreamingResponse: + from .resources.models import AsyncModelsWithStreamingResponse + + return AsyncModelsWithStreamingResponse(self._client.models) + + @cached_property + def fine_tuning(self) -> fine_tuning.AsyncFineTuningWithStreamingResponse: + from .resources.fine_tuning import AsyncFineTuningWithStreamingResponse + + return AsyncFineTuningWithStreamingResponse(self._client.fine_tuning) + + @cached_property + def vector_stores(self) -> vector_stores.AsyncVectorStoresWithStreamingResponse: + from .resources.vector_stores import AsyncVectorStoresWithStreamingResponse + + return AsyncVectorStoresWithStreamingResponse(self._client.vector_stores) + + @cached_property + def beta(self) -> beta.AsyncBetaWithStreamingResponse: + from .resources.beta import AsyncBetaWithStreamingResponse + + return AsyncBetaWithStreamingResponse(self._client.beta) + + @cached_property + def batches(self) -> batches.AsyncBatchesWithStreamingResponse: + from .resources.batches import AsyncBatchesWithStreamingResponse + + return AsyncBatchesWithStreamingResponse(self._client.batches) + + @cached_property + def uploads(self) -> uploads.AsyncUploadsWithStreamingResponse: + from .resources.uploads import AsyncUploadsWithStreamingResponse + + return AsyncUploadsWithStreamingResponse(self._client.uploads) + + @cached_property + def responses(self) -> responses.AsyncResponsesWithStreamingResponse: + from .resources.responses import AsyncResponsesWithStreamingResponse + + return AsyncResponsesWithStreamingResponse(self._client.responses) + + @cached_property + def evals(self) -> evals.AsyncEvalsWithStreamingResponse: + from .resources.evals import AsyncEvalsWithStreamingResponse + + return AsyncEvalsWithStreamingResponse(self._client.evals) Client = OpenAI diff --git a/src/openai/resources/__init__.py b/src/openai/resources/__init__.py index ab9cd73e81..8612dec797 100644 --- a/src/openai/resources/__init__.py +++ b/src/openai/resources/__init__.py @@ -72,14 +72,6 @@ UploadsWithStreamingResponse, AsyncUploadsWithStreamingResponse, ) -from .responses import ( - Responses, - AsyncResponses, - ResponsesWithRawResponse, - AsyncResponsesWithRawResponse, - ResponsesWithStreamingResponse, - AsyncResponsesWithStreamingResponse, -) from .embeddings import ( Embeddings, AsyncEmbeddings, @@ -200,12 +192,6 @@ "AsyncUploadsWithRawResponse", "UploadsWithStreamingResponse", "AsyncUploadsWithStreamingResponse", - "Responses", - "AsyncResponses", - "ResponsesWithRawResponse", - "AsyncResponsesWithRawResponse", - "ResponsesWithStreamingResponse", - "AsyncResponsesWithStreamingResponse", "Evals", "AsyncEvals", "EvalsWithRawResponse", From 08d67adfffad61802e1ac1b3f35795040182a12d Mon Sep 17 00:00:00 2001 From: Bruno Alla Date: Wed, 7 May 2025 18:50:47 +0100 Subject: [PATCH 810/816] fix: ignore errors in isinstance() calls on LazyProxy subclasses (#2343) Fix #2056 --- src/openai/_utils/_proxy.py | 5 ++++- tests/test_utils/test_proxy.py | 12 ++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/openai/_utils/_proxy.py b/src/openai/_utils/_proxy.py index ffd883e9dd..0f239a33c6 100644 --- a/src/openai/_utils/_proxy.py +++ b/src/openai/_utils/_proxy.py @@ -46,7 +46,10 @@ def __dir__(self) -> Iterable[str]: @property # type: ignore @override def __class__(self) -> type: # pyright: ignore - proxied = self.__get_proxied__() + try: + proxied = self.__get_proxied__() + except Exception: + return type(self) if issubclass(type(proxied), LazyProxy): return type(proxied) return proxied.__class__ diff --git a/tests/test_utils/test_proxy.py b/tests/test_utils/test_proxy.py index aedd3731ee..19bedc7780 100644 --- a/tests/test_utils/test_proxy.py +++ b/tests/test_utils/test_proxy.py @@ -3,6 +3,7 @@ from typing_extensions import override from openai._utils import LazyProxy +from openai._extras._common import MissingDependencyError class RecursiveLazyProxy(LazyProxy[Any]): @@ -21,3 +22,14 @@ def test_recursive_proxy() -> None: assert dir(proxy) == [] assert type(proxy).__name__ == "RecursiveLazyProxy" assert type(operator.attrgetter("name.foo.bar.baz")(proxy)).__name__ == "RecursiveLazyProxy" + + +def test_is_instance_with_missing_dependency_error() -> None: + class MissingDepsProxy(LazyProxy[Any]): + @override + def __load__(self) -> Any: + raise MissingDependencyError("Mocking missing dependency") + + proxy = MissingDepsProxy() + assert not isinstance(proxy, dict) + assert isinstance(proxy, LazyProxy) From e241775593ce683a9888606645f0ecfa02fe6efc Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 8 May 2025 12:40:47 +0000 Subject: [PATCH 811/816] chore(internal): update proxy tests --- tests/test_utils/test_proxy.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_utils/test_proxy.py b/tests/test_utils/test_proxy.py index 19bedc7780..2b5ff19dab 100644 --- a/tests/test_utils/test_proxy.py +++ b/tests/test_utils/test_proxy.py @@ -24,7 +24,7 @@ def test_recursive_proxy() -> None: assert type(operator.attrgetter("name.foo.bar.baz")(proxy)).__name__ == "RecursiveLazyProxy" -def test_is_instance_with_missing_dependency_error() -> None: +def test_isinstance_does_not_error() -> None: class MissingDepsProxy(LazyProxy[Any]): @override def __load__(self) -> Any: From a3b8e7724f505cb3f8dd9efff0f23301b6804bb6 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 8 May 2025 17:23:49 +0000 Subject: [PATCH 812/816] feat(api): Add reinforcement fine-tuning api support --- .stats.yml | 8 +- api.md | 52 +++- src/openai/resources/fine_tuning/__init__.py | 14 + .../resources/fine_tuning/alpha/__init__.py | 33 ++ .../resources/fine_tuning/alpha/alpha.py | 102 +++++++ .../resources/fine_tuning/alpha/graders.py | 272 +++++++++++++++++ .../resources/fine_tuning/fine_tuning.py | 32 ++ src/openai/resources/fine_tuning/jobs/jobs.py | 156 ++++++++++ src/openai/types/__init__.py | 5 - src/openai/types/eval_create_params.py | 91 ++---- src/openai/types/eval_create_response.py | 97 ++---- src/openai/types/eval_list_response.py | 97 ++---- src/openai/types/eval_retrieve_response.py | 97 ++---- src/openai/types/eval_update_response.py | 97 ++---- src/openai/types/fine_tuning/__init__.py | 12 + .../types/fine_tuning/alpha/__init__.py | 8 + .../fine_tuning/alpha/grader_run_params.py | 30 ++ .../fine_tuning/alpha/grader_run_response.py | 67 ++++ .../alpha/grader_validate_params.py | 24 ++ .../alpha/grader_validate_response.py | 20 ++ .../types/fine_tuning/dpo_hyperparameters.py | 36 +++ .../fine_tuning/dpo_hyperparameters_param.py | 36 +++ src/openai/types/fine_tuning/dpo_method.py | 13 + .../types/fine_tuning/dpo_method_param.py | 14 + .../types/fine_tuning/fine_tuning_job.py | 86 +----- .../types/fine_tuning/job_create_params.py | 87 +----- .../reinforcement_hyperparameters.py | 43 +++ .../reinforcement_hyperparameters_param.py | 43 +++ .../types/fine_tuning/reinforcement_method.py | 24 ++ .../fine_tuning/reinforcement_method_param.py | 27 ++ .../fine_tuning/supervised_hyperparameters.py | 29 ++ .../supervised_hyperparameters_param.py | 29 ++ .../types/fine_tuning/supervised_method.py | 13 + .../fine_tuning/supervised_method_param.py | 14 + src/openai/types/graders/__init__.py | 16 + .../label_model_grader.py} | 8 +- .../types/graders/label_model_grader_param.py | 54 ++++ src/openai/types/graders/multi_grader.py | 28 ++ .../types/graders/multi_grader_param.py | 31 ++ src/openai/types/graders/python_grader.py | 22 ++ .../types/graders/python_grader_param.py | 21 ++ .../types/graders/score_model_grader.py | 54 ++++ .../types/graders/score_model_grader_param.py | 55 ++++ .../string_check_grader.py} | 6 +- .../string_check_grader_param.py} | 4 +- .../text_similarity_grader.py} | 14 +- .../text_similarity_grader_param.py} | 11 +- .../fine_tuning/alpha/__init__.py | 1 + .../fine_tuning/alpha/test_graders.py | 289 ++++++++++++++++++ tests/api_resources/fine_tuning/test_jobs.py | 192 +++++++++++- 50 files changed, 2048 insertions(+), 566 deletions(-) create mode 100644 src/openai/resources/fine_tuning/alpha/__init__.py create mode 100644 src/openai/resources/fine_tuning/alpha/alpha.py create mode 100644 src/openai/resources/fine_tuning/alpha/graders.py create mode 100644 src/openai/types/fine_tuning/alpha/__init__.py create mode 100644 src/openai/types/fine_tuning/alpha/grader_run_params.py create mode 100644 src/openai/types/fine_tuning/alpha/grader_run_response.py create mode 100644 src/openai/types/fine_tuning/alpha/grader_validate_params.py create mode 100644 src/openai/types/fine_tuning/alpha/grader_validate_response.py create mode 100644 src/openai/types/fine_tuning/dpo_hyperparameters.py create mode 100644 src/openai/types/fine_tuning/dpo_hyperparameters_param.py create mode 100644 src/openai/types/fine_tuning/dpo_method.py create mode 100644 src/openai/types/fine_tuning/dpo_method_param.py create mode 100644 src/openai/types/fine_tuning/reinforcement_hyperparameters.py create mode 100644 src/openai/types/fine_tuning/reinforcement_hyperparameters_param.py create mode 100644 src/openai/types/fine_tuning/reinforcement_method.py create mode 100644 src/openai/types/fine_tuning/reinforcement_method_param.py create mode 100644 src/openai/types/fine_tuning/supervised_hyperparameters.py create mode 100644 src/openai/types/fine_tuning/supervised_hyperparameters_param.py create mode 100644 src/openai/types/fine_tuning/supervised_method.py create mode 100644 src/openai/types/fine_tuning/supervised_method_param.py create mode 100644 src/openai/types/graders/__init__.py rename src/openai/types/{eval_label_model_grader.py => graders/label_model_grader.py} (85%) create mode 100644 src/openai/types/graders/label_model_grader_param.py create mode 100644 src/openai/types/graders/multi_grader.py create mode 100644 src/openai/types/graders/multi_grader_param.py create mode 100644 src/openai/types/graders/python_grader.py create mode 100644 src/openai/types/graders/python_grader_param.py create mode 100644 src/openai/types/graders/score_model_grader.py create mode 100644 src/openai/types/graders/score_model_grader_param.py rename src/openai/types/{eval_string_check_grader.py => graders/string_check_grader.py} (84%) rename src/openai/types/{eval_string_check_grader_param.py => graders/string_check_grader_param.py} (87%) rename src/openai/types/{eval_text_similarity_grader.py => graders/text_similarity_grader.py} (69%) rename src/openai/types/{eval_text_similarity_grader_param.py => graders/text_similarity_grader_param.py} (76%) create mode 100644 tests/api_resources/fine_tuning/alpha/__init__.py create mode 100644 tests/api_resources/fine_tuning/alpha/test_graders.py diff --git a/.stats.yml b/.stats.yml index 0c8278866d..5f1bee851b 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ -configured_endpoints: 97 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-0ee6b36cf3cc278cef4199a6aec5f7d530a6c1f17a74830037e96d50ca1edc50.yml -openapi_spec_hash: e8ec5f46bc0655b34f292422d58a60f6 -config_hash: d9b6b6e6bc85744663e300eebc482067 +configured_endpoints: 101 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-794a6ed3c3d3d77887564755168056af8a426b17cf1ec721e3a300503dc22a41.yml +openapi_spec_hash: 25a81c220713cd5b0bafc221d1dfa79a +config_hash: 0b768ed1b56c6d82816f0fa40dc4aaf5 diff --git a/api.md b/api.md index d04c76960e..496e5548b3 100644 --- a/api.md +++ b/api.md @@ -225,6 +225,21 @@ Methods: # FineTuning +## Methods + +Types: + +```python +from openai.types.fine_tuning import ( + DpoHyperparameters, + DpoMethod, + ReinforcementHyperparameters, + ReinforcementMethod, + SupervisedHyperparameters, + SupervisedMethod, +) +``` + ## Jobs Types: @@ -246,6 +261,8 @@ Methods: - client.fine_tuning.jobs.list(\*\*params) -> SyncCursorPage[FineTuningJob] - client.fine_tuning.jobs.cancel(fine_tuning_job_id) -> FineTuningJob - client.fine_tuning.jobs.list_events(fine_tuning_job_id, \*\*params) -> SyncCursorPage[FineTuningJobEvent] +- client.fine_tuning.jobs.pause(fine_tuning_job_id) -> FineTuningJob +- client.fine_tuning.jobs.resume(fine_tuning_job_id) -> FineTuningJob ### Checkpoints @@ -279,6 +296,38 @@ Methods: - client.fine_tuning.checkpoints.permissions.retrieve(fine_tuned_model_checkpoint, \*\*params) -> PermissionRetrieveResponse - client.fine_tuning.checkpoints.permissions.delete(permission_id, \*, fine_tuned_model_checkpoint) -> PermissionDeleteResponse +## Alpha + +### Graders + +Types: + +```python +from openai.types.fine_tuning.alpha import GraderRunResponse, GraderValidateResponse +``` + +Methods: + +- client.fine_tuning.alpha.graders.run(\*\*params) -> GraderRunResponse +- client.fine_tuning.alpha.graders.validate(\*\*params) -> GraderValidateResponse + +# Graders + +## GraderModels + +Types: + +```python +from openai.types.graders import ( + LabelModelGrader, + MultiGrader, + PythonGrader, + ScoreModelGrader, + StringCheckGrader, + TextSimilarityGrader, +) +``` + # VectorStores Types: @@ -738,10 +787,7 @@ Types: ```python from openai.types import ( EvalCustomDataSourceConfig, - EvalLabelModelGrader, EvalStoredCompletionsDataSourceConfig, - EvalStringCheckGrader, - EvalTextSimilarityGrader, EvalCreateResponse, EvalRetrieveResponse, EvalUpdateResponse, diff --git a/src/openai/resources/fine_tuning/__init__.py b/src/openai/resources/fine_tuning/__init__.py index ed7db4f4e0..c76af83deb 100644 --- a/src/openai/resources/fine_tuning/__init__.py +++ b/src/openai/resources/fine_tuning/__init__.py @@ -8,6 +8,14 @@ JobsWithStreamingResponse, AsyncJobsWithStreamingResponse, ) +from .alpha import ( + Alpha, + AsyncAlpha, + AlphaWithRawResponse, + AsyncAlphaWithRawResponse, + AlphaWithStreamingResponse, + AsyncAlphaWithStreamingResponse, +) from .checkpoints import ( Checkpoints, AsyncCheckpoints, @@ -38,6 +46,12 @@ "AsyncCheckpointsWithRawResponse", "CheckpointsWithStreamingResponse", "AsyncCheckpointsWithStreamingResponse", + "Alpha", + "AsyncAlpha", + "AlphaWithRawResponse", + "AsyncAlphaWithRawResponse", + "AlphaWithStreamingResponse", + "AsyncAlphaWithStreamingResponse", "FineTuning", "AsyncFineTuning", "FineTuningWithRawResponse", diff --git a/src/openai/resources/fine_tuning/alpha/__init__.py b/src/openai/resources/fine_tuning/alpha/__init__.py new file mode 100644 index 0000000000..8bed8af4fd --- /dev/null +++ b/src/openai/resources/fine_tuning/alpha/__init__.py @@ -0,0 +1,33 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from .alpha import ( + Alpha, + AsyncAlpha, + AlphaWithRawResponse, + AsyncAlphaWithRawResponse, + AlphaWithStreamingResponse, + AsyncAlphaWithStreamingResponse, +) +from .graders import ( + Graders, + AsyncGraders, + GradersWithRawResponse, + AsyncGradersWithRawResponse, + GradersWithStreamingResponse, + AsyncGradersWithStreamingResponse, +) + +__all__ = [ + "Graders", + "AsyncGraders", + "GradersWithRawResponse", + "AsyncGradersWithRawResponse", + "GradersWithStreamingResponse", + "AsyncGradersWithStreamingResponse", + "Alpha", + "AsyncAlpha", + "AlphaWithRawResponse", + "AsyncAlphaWithRawResponse", + "AlphaWithStreamingResponse", + "AsyncAlphaWithStreamingResponse", +] diff --git a/src/openai/resources/fine_tuning/alpha/alpha.py b/src/openai/resources/fine_tuning/alpha/alpha.py new file mode 100644 index 0000000000..54c05fab69 --- /dev/null +++ b/src/openai/resources/fine_tuning/alpha/alpha.py @@ -0,0 +1,102 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .graders import ( + Graders, + AsyncGraders, + GradersWithRawResponse, + AsyncGradersWithRawResponse, + GradersWithStreamingResponse, + AsyncGradersWithStreamingResponse, +) +from ...._compat import cached_property +from ...._resource import SyncAPIResource, AsyncAPIResource + +__all__ = ["Alpha", "AsyncAlpha"] + + +class Alpha(SyncAPIResource): + @cached_property + def graders(self) -> Graders: + return Graders(self._client) + + @cached_property + def with_raw_response(self) -> AlphaWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return AlphaWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AlphaWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return AlphaWithStreamingResponse(self) + + +class AsyncAlpha(AsyncAPIResource): + @cached_property + def graders(self) -> AsyncGraders: + return AsyncGraders(self._client) + + @cached_property + def with_raw_response(self) -> AsyncAlphaWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return AsyncAlphaWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncAlphaWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return AsyncAlphaWithStreamingResponse(self) + + +class AlphaWithRawResponse: + def __init__(self, alpha: Alpha) -> None: + self._alpha = alpha + + @cached_property + def graders(self) -> GradersWithRawResponse: + return GradersWithRawResponse(self._alpha.graders) + + +class AsyncAlphaWithRawResponse: + def __init__(self, alpha: AsyncAlpha) -> None: + self._alpha = alpha + + @cached_property + def graders(self) -> AsyncGradersWithRawResponse: + return AsyncGradersWithRawResponse(self._alpha.graders) + + +class AlphaWithStreamingResponse: + def __init__(self, alpha: Alpha) -> None: + self._alpha = alpha + + @cached_property + def graders(self) -> GradersWithStreamingResponse: + return GradersWithStreamingResponse(self._alpha.graders) + + +class AsyncAlphaWithStreamingResponse: + def __init__(self, alpha: AsyncAlpha) -> None: + self._alpha = alpha + + @cached_property + def graders(self) -> AsyncGradersWithStreamingResponse: + return AsyncGradersWithStreamingResponse(self._alpha.graders) diff --git a/src/openai/resources/fine_tuning/alpha/graders.py b/src/openai/resources/fine_tuning/alpha/graders.py new file mode 100644 index 0000000000..f27acdfd9c --- /dev/null +++ b/src/openai/resources/fine_tuning/alpha/graders.py @@ -0,0 +1,272 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable + +import httpx + +from .... import _legacy_response +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ...._utils import maybe_transform, async_maybe_transform +from ...._compat import cached_property +from ...._resource import SyncAPIResource, AsyncAPIResource +from ...._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper +from ...._base_client import make_request_options +from ....types.fine_tuning.alpha import grader_run_params, grader_validate_params +from ....types.fine_tuning.alpha.grader_run_response import GraderRunResponse +from ....types.fine_tuning.alpha.grader_validate_response import GraderValidateResponse + +__all__ = ["Graders", "AsyncGraders"] + + +class Graders(SyncAPIResource): + @cached_property + def with_raw_response(self) -> GradersWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return GradersWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> GradersWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return GradersWithStreamingResponse(self) + + def run( + self, + *, + grader: grader_run_params.Grader, + model_sample: str, + reference_answer: Union[str, Iterable[object], float, object], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> GraderRunResponse: + """ + Run a grader. + + Args: + grader: The grader used for the fine-tuning job. + + model_sample: The model sample to be evaluated. + + reference_answer: The reference answer for the evaluation. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._post( + "/fine_tuning/alpha/graders/run", + body=maybe_transform( + { + "grader": grader, + "model_sample": model_sample, + "reference_answer": reference_answer, + }, + grader_run_params.GraderRunParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=GraderRunResponse, + ) + + def validate( + self, + *, + grader: grader_validate_params.Grader, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> GraderValidateResponse: + """ + Validate a grader. + + Args: + grader: The grader used for the fine-tuning job. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return self._post( + "/fine_tuning/alpha/graders/validate", + body=maybe_transform({"grader": grader}, grader_validate_params.GraderValidateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=GraderValidateResponse, + ) + + +class AsyncGraders(AsyncAPIResource): + @cached_property + def with_raw_response(self) -> AsyncGradersWithRawResponse: + """ + This property can be used as a prefix for any HTTP method call to return + the raw response object instead of the parsed content. + + For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers + """ + return AsyncGradersWithRawResponse(self) + + @cached_property + def with_streaming_response(self) -> AsyncGradersWithStreamingResponse: + """ + An alternative to `.with_raw_response` that doesn't eagerly read the response body. + + For more information, see https://www.github.com/openai/openai-python#with_streaming_response + """ + return AsyncGradersWithStreamingResponse(self) + + async def run( + self, + *, + grader: grader_run_params.Grader, + model_sample: str, + reference_answer: Union[str, Iterable[object], float, object], + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> GraderRunResponse: + """ + Run a grader. + + Args: + grader: The grader used for the fine-tuning job. + + model_sample: The model sample to be evaluated. + + reference_answer: The reference answer for the evaluation. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._post( + "/fine_tuning/alpha/graders/run", + body=await async_maybe_transform( + { + "grader": grader, + "model_sample": model_sample, + "reference_answer": reference_answer, + }, + grader_run_params.GraderRunParams, + ), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=GraderRunResponse, + ) + + async def validate( + self, + *, + grader: grader_validate_params.Grader, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> GraderValidateResponse: + """ + Validate a grader. + + Args: + grader: The grader used for the fine-tuning job. + + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + return await self._post( + "/fine_tuning/alpha/graders/validate", + body=await async_maybe_transform({"grader": grader}, grader_validate_params.GraderValidateParams), + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=GraderValidateResponse, + ) + + +class GradersWithRawResponse: + def __init__(self, graders: Graders) -> None: + self._graders = graders + + self.run = _legacy_response.to_raw_response_wrapper( + graders.run, + ) + self.validate = _legacy_response.to_raw_response_wrapper( + graders.validate, + ) + + +class AsyncGradersWithRawResponse: + def __init__(self, graders: AsyncGraders) -> None: + self._graders = graders + + self.run = _legacy_response.async_to_raw_response_wrapper( + graders.run, + ) + self.validate = _legacy_response.async_to_raw_response_wrapper( + graders.validate, + ) + + +class GradersWithStreamingResponse: + def __init__(self, graders: Graders) -> None: + self._graders = graders + + self.run = to_streamed_response_wrapper( + graders.run, + ) + self.validate = to_streamed_response_wrapper( + graders.validate, + ) + + +class AsyncGradersWithStreamingResponse: + def __init__(self, graders: AsyncGraders) -> None: + self._graders = graders + + self.run = async_to_streamed_response_wrapper( + graders.run, + ) + self.validate = async_to_streamed_response_wrapper( + graders.validate, + ) diff --git a/src/openai/resources/fine_tuning/fine_tuning.py b/src/openai/resources/fine_tuning/fine_tuning.py index 1388c8230c..25ae3e8cf4 100644 --- a/src/openai/resources/fine_tuning/fine_tuning.py +++ b/src/openai/resources/fine_tuning/fine_tuning.py @@ -12,6 +12,14 @@ AsyncJobsWithStreamingResponse, ) from ..._resource import SyncAPIResource, AsyncAPIResource +from .alpha.alpha import ( + Alpha, + AsyncAlpha, + AlphaWithRawResponse, + AsyncAlphaWithRawResponse, + AlphaWithStreamingResponse, + AsyncAlphaWithStreamingResponse, +) from .checkpoints.checkpoints import ( Checkpoints, AsyncCheckpoints, @@ -33,6 +41,10 @@ def jobs(self) -> Jobs: def checkpoints(self) -> Checkpoints: return Checkpoints(self._client) + @cached_property + def alpha(self) -> Alpha: + return Alpha(self._client) + @cached_property def with_raw_response(self) -> FineTuningWithRawResponse: """ @@ -62,6 +74,10 @@ def jobs(self) -> AsyncJobs: def checkpoints(self) -> AsyncCheckpoints: return AsyncCheckpoints(self._client) + @cached_property + def alpha(self) -> AsyncAlpha: + return AsyncAlpha(self._client) + @cached_property def with_raw_response(self) -> AsyncFineTuningWithRawResponse: """ @@ -94,6 +110,10 @@ def jobs(self) -> JobsWithRawResponse: def checkpoints(self) -> CheckpointsWithRawResponse: return CheckpointsWithRawResponse(self._fine_tuning.checkpoints) + @cached_property + def alpha(self) -> AlphaWithRawResponse: + return AlphaWithRawResponse(self._fine_tuning.alpha) + class AsyncFineTuningWithRawResponse: def __init__(self, fine_tuning: AsyncFineTuning) -> None: @@ -107,6 +127,10 @@ def jobs(self) -> AsyncJobsWithRawResponse: def checkpoints(self) -> AsyncCheckpointsWithRawResponse: return AsyncCheckpointsWithRawResponse(self._fine_tuning.checkpoints) + @cached_property + def alpha(self) -> AsyncAlphaWithRawResponse: + return AsyncAlphaWithRawResponse(self._fine_tuning.alpha) + class FineTuningWithStreamingResponse: def __init__(self, fine_tuning: FineTuning) -> None: @@ -120,6 +144,10 @@ def jobs(self) -> JobsWithStreamingResponse: def checkpoints(self) -> CheckpointsWithStreamingResponse: return CheckpointsWithStreamingResponse(self._fine_tuning.checkpoints) + @cached_property + def alpha(self) -> AlphaWithStreamingResponse: + return AlphaWithStreamingResponse(self._fine_tuning.alpha) + class AsyncFineTuningWithStreamingResponse: def __init__(self, fine_tuning: AsyncFineTuning) -> None: @@ -132,3 +160,7 @@ def jobs(self) -> AsyncJobsWithStreamingResponse: @cached_property def checkpoints(self) -> AsyncCheckpointsWithStreamingResponse: return AsyncCheckpointsWithStreamingResponse(self._fine_tuning.checkpoints) + + @cached_property + def alpha(self) -> AsyncAlphaWithStreamingResponse: + return AsyncAlphaWithStreamingResponse(self._fine_tuning.alpha) diff --git a/src/openai/resources/fine_tuning/jobs/jobs.py b/src/openai/resources/fine_tuning/jobs/jobs.py index 90619c8609..5cca219172 100644 --- a/src/openai/resources/fine_tuning/jobs/jobs.py +++ b/src/openai/resources/fine_tuning/jobs/jobs.py @@ -345,6 +345,72 @@ def list_events( model=FineTuningJobEvent, ) + def pause( + self, + fine_tuning_job_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> FineTuningJob: + """ + Pause a fine-tune job. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not fine_tuning_job_id: + raise ValueError(f"Expected a non-empty value for `fine_tuning_job_id` but received {fine_tuning_job_id!r}") + return self._post( + f"/fine_tuning/jobs/{fine_tuning_job_id}/pause", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=FineTuningJob, + ) + + def resume( + self, + fine_tuning_job_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> FineTuningJob: + """ + Resume a fine-tune job. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not fine_tuning_job_id: + raise ValueError(f"Expected a non-empty value for `fine_tuning_job_id` but received {fine_tuning_job_id!r}") + return self._post( + f"/fine_tuning/jobs/{fine_tuning_job_id}/resume", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=FineTuningJob, + ) + class AsyncJobs(AsyncAPIResource): @cached_property @@ -657,6 +723,72 @@ def list_events( model=FineTuningJobEvent, ) + async def pause( + self, + fine_tuning_job_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> FineTuningJob: + """ + Pause a fine-tune job. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not fine_tuning_job_id: + raise ValueError(f"Expected a non-empty value for `fine_tuning_job_id` but received {fine_tuning_job_id!r}") + return await self._post( + f"/fine_tuning/jobs/{fine_tuning_job_id}/pause", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=FineTuningJob, + ) + + async def resume( + self, + fine_tuning_job_id: str, + *, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Headers | None = None, + extra_query: Query | None = None, + extra_body: Body | None = None, + timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, + ) -> FineTuningJob: + """ + Resume a fine-tune job. + + Args: + extra_headers: Send extra headers + + extra_query: Add additional query parameters to the request + + extra_body: Add additional JSON properties to the request + + timeout: Override the client-level default timeout for this request, in seconds + """ + if not fine_tuning_job_id: + raise ValueError(f"Expected a non-empty value for `fine_tuning_job_id` but received {fine_tuning_job_id!r}") + return await self._post( + f"/fine_tuning/jobs/{fine_tuning_job_id}/resume", + options=make_request_options( + extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout + ), + cast_to=FineTuningJob, + ) + class JobsWithRawResponse: def __init__(self, jobs: Jobs) -> None: @@ -677,6 +809,12 @@ def __init__(self, jobs: Jobs) -> None: self.list_events = _legacy_response.to_raw_response_wrapper( jobs.list_events, ) + self.pause = _legacy_response.to_raw_response_wrapper( + jobs.pause, + ) + self.resume = _legacy_response.to_raw_response_wrapper( + jobs.resume, + ) @cached_property def checkpoints(self) -> CheckpointsWithRawResponse: @@ -702,6 +840,12 @@ def __init__(self, jobs: AsyncJobs) -> None: self.list_events = _legacy_response.async_to_raw_response_wrapper( jobs.list_events, ) + self.pause = _legacy_response.async_to_raw_response_wrapper( + jobs.pause, + ) + self.resume = _legacy_response.async_to_raw_response_wrapper( + jobs.resume, + ) @cached_property def checkpoints(self) -> AsyncCheckpointsWithRawResponse: @@ -727,6 +871,12 @@ def __init__(self, jobs: Jobs) -> None: self.list_events = to_streamed_response_wrapper( jobs.list_events, ) + self.pause = to_streamed_response_wrapper( + jobs.pause, + ) + self.resume = to_streamed_response_wrapper( + jobs.resume, + ) @cached_property def checkpoints(self) -> CheckpointsWithStreamingResponse: @@ -752,6 +902,12 @@ def __init__(self, jobs: AsyncJobs) -> None: self.list_events = async_to_streamed_response_wrapper( jobs.list_events, ) + self.pause = async_to_streamed_response_wrapper( + jobs.pause, + ) + self.resume = async_to_streamed_response_wrapper( + jobs.resume, + ) @cached_property def checkpoints(self) -> AsyncCheckpointsWithStreamingResponse: diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index 57c91811b9..bf5493fd62 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -61,9 +61,7 @@ from .file_chunking_strategy import FileChunkingStrategy as FileChunkingStrategy from .upload_complete_params import UploadCompleteParams as UploadCompleteParams from .embedding_create_params import EmbeddingCreateParams as EmbeddingCreateParams -from .eval_label_model_grader import EvalLabelModelGrader as EvalLabelModelGrader from .completion_create_params import CompletionCreateParams as CompletionCreateParams -from .eval_string_check_grader import EvalStringCheckGrader as EvalStringCheckGrader from .moderation_create_params import ModerationCreateParams as ModerationCreateParams from .vector_store_list_params import VectorStoreListParams as VectorStoreListParams from .create_embedding_response import CreateEmbeddingResponse as CreateEmbeddingResponse @@ -71,7 +69,6 @@ from .vector_store_create_params import VectorStoreCreateParams as VectorStoreCreateParams from .vector_store_search_params import VectorStoreSearchParams as VectorStoreSearchParams from .vector_store_update_params import VectorStoreUpdateParams as VectorStoreUpdateParams -from .eval_text_similarity_grader import EvalTextSimilarityGrader as EvalTextSimilarityGrader from .moderation_text_input_param import ModerationTextInputParam as ModerationTextInputParam from .file_chunking_strategy_param import FileChunkingStrategyParam as FileChunkingStrategyParam from .vector_store_search_response import VectorStoreSearchResponse as VectorStoreSearchResponse @@ -79,10 +76,8 @@ from .image_create_variation_params import ImageCreateVariationParams as ImageCreateVariationParams from .static_file_chunking_strategy import StaticFileChunkingStrategy as StaticFileChunkingStrategy from .eval_custom_data_source_config import EvalCustomDataSourceConfig as EvalCustomDataSourceConfig -from .eval_string_check_grader_param import EvalStringCheckGraderParam as EvalStringCheckGraderParam from .moderation_image_url_input_param import ModerationImageURLInputParam as ModerationImageURLInputParam from .auto_file_chunking_strategy_param import AutoFileChunkingStrategyParam as AutoFileChunkingStrategyParam -from .eval_text_similarity_grader_param import EvalTextSimilarityGraderParam as EvalTextSimilarityGraderParam from .moderation_multi_modal_input_param import ModerationMultiModalInputParam as ModerationMultiModalInputParam from .other_file_chunking_strategy_object import OtherFileChunkingStrategyObject as OtherFileChunkingStrategyObject from .static_file_chunking_strategy_param import StaticFileChunkingStrategyParam as StaticFileChunkingStrategyParam diff --git a/src/openai/types/eval_create_params.py b/src/openai/types/eval_create_params.py index 03f44f2c8c..66178287e4 100644 --- a/src/openai/types/eval_create_params.py +++ b/src/openai/types/eval_create_params.py @@ -6,15 +6,17 @@ from typing_extensions import Literal, Required, TypeAlias, TypedDict from .shared_params.metadata import Metadata -from .eval_string_check_grader_param import EvalStringCheckGraderParam -from .eval_text_similarity_grader_param import EvalTextSimilarityGraderParam +from .graders.python_grader_param import PythonGraderParam +from .graders.score_model_grader_param import ScoreModelGraderParam +from .graders.string_check_grader_param import StringCheckGraderParam from .responses.response_input_text_param import ResponseInputTextParam +from .graders.text_similarity_grader_param import TextSimilarityGraderParam __all__ = [ "EvalCreateParams", "DataSourceConfig", "DataSourceConfigCustom", - "DataSourceConfigLogs", + "DataSourceConfigStoredCompletions", "TestingCriterion", "TestingCriterionLabelModel", "TestingCriterionLabelModelInput", @@ -22,11 +24,9 @@ "TestingCriterionLabelModelInputEvalItem", "TestingCriterionLabelModelInputEvalItemContent", "TestingCriterionLabelModelInputEvalItemContentOutputText", + "TestingCriterionTextSimilarity", "TestingCriterionPython", "TestingCriterionScoreModel", - "TestingCriterionScoreModelInput", - "TestingCriterionScoreModelInputContent", - "TestingCriterionScoreModelInputContentOutputText", ] @@ -65,15 +65,15 @@ class DataSourceConfigCustom(TypedDict, total=False): """ -class DataSourceConfigLogs(TypedDict, total=False): - type: Required[Literal["logs"]] - """The type of data source. Always `logs`.""" +class DataSourceConfigStoredCompletions(TypedDict, total=False): + type: Required[Literal["stored_completions"]] + """The type of data source. Always `stored_completions`.""" metadata: Dict[str, object] - """Metadata filters for the logs data source.""" + """Metadata filters for the stored completions data source.""" -DataSourceConfig: TypeAlias = Union[DataSourceConfigCustom, DataSourceConfigLogs] +DataSourceConfig: TypeAlias = Union[DataSourceConfigCustom, DataSourceConfigStoredCompletions] class TestingCriterionLabelModelInputSimpleInputMessage(TypedDict, total=False): @@ -139,77 +139,28 @@ class TestingCriterionLabelModel(TypedDict, total=False): """The object type, which is always `label_model`.""" -class TestingCriterionPython(TypedDict, total=False): - name: Required[str] - """The name of the grader.""" - - source: Required[str] - """The source code of the python script.""" - - type: Required[Literal["python"]] - """The object type, which is always `python`.""" +class TestingCriterionTextSimilarity(TextSimilarityGraderParam, total=False): + __test__ = False + pass_threshold: Required[float] + """The threshold for the score.""" - image_tag: str - """The image tag to use for the python script.""" +class TestingCriterionPython(PythonGraderParam, total=False): + __test__ = False pass_threshold: float """The threshold for the score.""" -class TestingCriterionScoreModelInputContentOutputText(TypedDict, total=False): - text: Required[str] - """The text output from the model.""" - - type: Required[Literal["output_text"]] - """The type of the output text. Always `output_text`.""" - - -TestingCriterionScoreModelInputContent: TypeAlias = Union[ - str, ResponseInputTextParam, TestingCriterionScoreModelInputContentOutputText -] - - -class TestingCriterionScoreModelInput(TypedDict, total=False): - content: Required[TestingCriterionScoreModelInputContent] - """Text inputs to the model - can contain template strings.""" - - role: Required[Literal["user", "assistant", "system", "developer"]] - """The role of the message input. - - One of `user`, `assistant`, `system`, or `developer`. - """ - - type: Literal["message"] - """The type of the message input. Always `message`.""" - - -class TestingCriterionScoreModel(TypedDict, total=False): - input: Required[Iterable[TestingCriterionScoreModelInput]] - """The input text. This may include template strings.""" - - model: Required[str] - """The model to use for the evaluation.""" - - name: Required[str] - """The name of the grader.""" - - type: Required[Literal["score_model"]] - """The object type, which is always `score_model`.""" - +class TestingCriterionScoreModel(ScoreModelGraderParam, total=False): + __test__ = False pass_threshold: float """The threshold for the score.""" - range: Iterable[float] - """The range of the score. Defaults to `[0, 1]`.""" - - sampling_params: object - """The sampling parameters for the model.""" - TestingCriterion: TypeAlias = Union[ TestingCriterionLabelModel, - EvalStringCheckGraderParam, - EvalTextSimilarityGraderParam, + StringCheckGraderParam, + TestingCriterionTextSimilarity, TestingCriterionPython, TestingCriterionScoreModel, ] diff --git a/src/openai/types/eval_create_response.py b/src/openai/types/eval_create_response.py index 6d77a81870..d5f158ad29 100644 --- a/src/openai/types/eval_create_response.py +++ b/src/openai/types/eval_create_response.py @@ -6,22 +6,21 @@ from .._utils import PropertyInfo from .._models import BaseModel from .shared.metadata import Metadata -from .eval_label_model_grader import EvalLabelModelGrader -from .eval_string_check_grader import EvalStringCheckGrader -from .eval_text_similarity_grader import EvalTextSimilarityGrader -from .responses.response_input_text import ResponseInputText +from .graders.python_grader import PythonGrader +from .graders.label_model_grader import LabelModelGrader +from .graders.score_model_grader import ScoreModelGrader +from .graders.string_check_grader import StringCheckGrader from .eval_custom_data_source_config import EvalCustomDataSourceConfig +from .graders.text_similarity_grader import TextSimilarityGrader from .eval_stored_completions_data_source_config import EvalStoredCompletionsDataSourceConfig __all__ = [ "EvalCreateResponse", "DataSourceConfig", "TestingCriterion", - "TestingCriterionPython", - "TestingCriterionScoreModel", - "TestingCriterionScoreModelInput", - "TestingCriterionScoreModelInputContent", - "TestingCriterionScoreModelInputContentOutputText", + "TestingCriterionEvalGraderTextSimilarity", + "TestingCriterionEvalGraderPython", + "TestingCriterionEvalGraderScoreModel", ] DataSourceConfig: TypeAlias = Annotated[ @@ -29,86 +28,30 @@ ] -class TestingCriterionPython(BaseModel): +class TestingCriterionEvalGraderTextSimilarity(TextSimilarityGrader): __test__ = False - name: str - """The name of the grader.""" - - source: str - """The source code of the python script.""" - - type: Literal["python"] - """The object type, which is always `python`.""" - - image_tag: Optional[str] = None - """The image tag to use for the python script.""" - - pass_threshold: Optional[float] = None + pass_threshold: float """The threshold for the score.""" -class TestingCriterionScoreModelInputContentOutputText(BaseModel): - __test__ = False - text: str - """The text output from the model.""" - - type: Literal["output_text"] - """The type of the output text. Always `output_text`.""" - - -TestingCriterionScoreModelInputContent: TypeAlias = Union[ - str, ResponseInputText, TestingCriterionScoreModelInputContentOutputText -] - - -class TestingCriterionScoreModelInput(BaseModel): +class TestingCriterionEvalGraderPython(PythonGrader): __test__ = False - content: TestingCriterionScoreModelInputContent - """Text inputs to the model - can contain template strings.""" - - role: Literal["user", "assistant", "system", "developer"] - """The role of the message input. - - One of `user`, `assistant`, `system`, or `developer`. - """ - - type: Optional[Literal["message"]] = None - """The type of the message input. Always `message`.""" + pass_threshold: Optional[float] = None + """The threshold for the score.""" -class TestingCriterionScoreModel(BaseModel): +class TestingCriterionEvalGraderScoreModel(ScoreModelGrader): __test__ = False - input: List[TestingCriterionScoreModelInput] - """The input text. This may include template strings.""" - - model: str - """The model to use for the evaluation.""" - - name: str - """The name of the grader.""" - - type: Literal["score_model"] - """The object type, which is always `score_model`.""" - pass_threshold: Optional[float] = None """The threshold for the score.""" - range: Optional[List[float]] = None - """The range of the score. Defaults to `[0, 1]`.""" - - sampling_params: Optional[object] = None - """The sampling parameters for the model.""" - -TestingCriterion: TypeAlias = Annotated[ - Union[ - EvalLabelModelGrader, - EvalStringCheckGrader, - EvalTextSimilarityGrader, - TestingCriterionPython, - TestingCriterionScoreModel, - ], - PropertyInfo(discriminator="type"), +TestingCriterion: TypeAlias = Union[ + LabelModelGrader, + StringCheckGrader, + TestingCriterionEvalGraderTextSimilarity, + TestingCriterionEvalGraderPython, + TestingCriterionEvalGraderScoreModel, ] diff --git a/src/openai/types/eval_list_response.py b/src/openai/types/eval_list_response.py index 8c7e9c5588..b743f57f6a 100644 --- a/src/openai/types/eval_list_response.py +++ b/src/openai/types/eval_list_response.py @@ -6,22 +6,21 @@ from .._utils import PropertyInfo from .._models import BaseModel from .shared.metadata import Metadata -from .eval_label_model_grader import EvalLabelModelGrader -from .eval_string_check_grader import EvalStringCheckGrader -from .eval_text_similarity_grader import EvalTextSimilarityGrader -from .responses.response_input_text import ResponseInputText +from .graders.python_grader import PythonGrader +from .graders.label_model_grader import LabelModelGrader +from .graders.score_model_grader import ScoreModelGrader +from .graders.string_check_grader import StringCheckGrader from .eval_custom_data_source_config import EvalCustomDataSourceConfig +from .graders.text_similarity_grader import TextSimilarityGrader from .eval_stored_completions_data_source_config import EvalStoredCompletionsDataSourceConfig __all__ = [ "EvalListResponse", "DataSourceConfig", "TestingCriterion", - "TestingCriterionPython", - "TestingCriterionScoreModel", - "TestingCriterionScoreModelInput", - "TestingCriterionScoreModelInputContent", - "TestingCriterionScoreModelInputContentOutputText", + "TestingCriterionEvalGraderTextSimilarity", + "TestingCriterionEvalGraderPython", + "TestingCriterionEvalGraderScoreModel", ] DataSourceConfig: TypeAlias = Annotated[ @@ -29,86 +28,30 @@ ] -class TestingCriterionPython(BaseModel): +class TestingCriterionEvalGraderTextSimilarity(TextSimilarityGrader): __test__ = False - name: str - """The name of the grader.""" - - source: str - """The source code of the python script.""" - - type: Literal["python"] - """The object type, which is always `python`.""" - - image_tag: Optional[str] = None - """The image tag to use for the python script.""" - - pass_threshold: Optional[float] = None + pass_threshold: float """The threshold for the score.""" -class TestingCriterionScoreModelInputContentOutputText(BaseModel): - __test__ = False - text: str - """The text output from the model.""" - - type: Literal["output_text"] - """The type of the output text. Always `output_text`.""" - - -TestingCriterionScoreModelInputContent: TypeAlias = Union[ - str, ResponseInputText, TestingCriterionScoreModelInputContentOutputText -] - - -class TestingCriterionScoreModelInput(BaseModel): +class TestingCriterionEvalGraderPython(PythonGrader): __test__ = False - content: TestingCriterionScoreModelInputContent - """Text inputs to the model - can contain template strings.""" - - role: Literal["user", "assistant", "system", "developer"] - """The role of the message input. - - One of `user`, `assistant`, `system`, or `developer`. - """ - - type: Optional[Literal["message"]] = None - """The type of the message input. Always `message`.""" + pass_threshold: Optional[float] = None + """The threshold for the score.""" -class TestingCriterionScoreModel(BaseModel): +class TestingCriterionEvalGraderScoreModel(ScoreModelGrader): __test__ = False - input: List[TestingCriterionScoreModelInput] - """The input text. This may include template strings.""" - - model: str - """The model to use for the evaluation.""" - - name: str - """The name of the grader.""" - - type: Literal["score_model"] - """The object type, which is always `score_model`.""" - pass_threshold: Optional[float] = None """The threshold for the score.""" - range: Optional[List[float]] = None - """The range of the score. Defaults to `[0, 1]`.""" - - sampling_params: Optional[object] = None - """The sampling parameters for the model.""" - -TestingCriterion: TypeAlias = Annotated[ - Union[ - EvalLabelModelGrader, - EvalStringCheckGrader, - EvalTextSimilarityGrader, - TestingCriterionPython, - TestingCriterionScoreModel, - ], - PropertyInfo(discriminator="type"), +TestingCriterion: TypeAlias = Union[ + LabelModelGrader, + StringCheckGrader, + TestingCriterionEvalGraderTextSimilarity, + TestingCriterionEvalGraderPython, + TestingCriterionEvalGraderScoreModel, ] diff --git a/src/openai/types/eval_retrieve_response.py b/src/openai/types/eval_retrieve_response.py index 625bae80f4..dabb20674e 100644 --- a/src/openai/types/eval_retrieve_response.py +++ b/src/openai/types/eval_retrieve_response.py @@ -6,22 +6,21 @@ from .._utils import PropertyInfo from .._models import BaseModel from .shared.metadata import Metadata -from .eval_label_model_grader import EvalLabelModelGrader -from .eval_string_check_grader import EvalStringCheckGrader -from .eval_text_similarity_grader import EvalTextSimilarityGrader -from .responses.response_input_text import ResponseInputText +from .graders.python_grader import PythonGrader +from .graders.label_model_grader import LabelModelGrader +from .graders.score_model_grader import ScoreModelGrader +from .graders.string_check_grader import StringCheckGrader from .eval_custom_data_source_config import EvalCustomDataSourceConfig +from .graders.text_similarity_grader import TextSimilarityGrader from .eval_stored_completions_data_source_config import EvalStoredCompletionsDataSourceConfig __all__ = [ "EvalRetrieveResponse", "DataSourceConfig", "TestingCriterion", - "TestingCriterionPython", - "TestingCriterionScoreModel", - "TestingCriterionScoreModelInput", - "TestingCriterionScoreModelInputContent", - "TestingCriterionScoreModelInputContentOutputText", + "TestingCriterionEvalGraderTextSimilarity", + "TestingCriterionEvalGraderPython", + "TestingCriterionEvalGraderScoreModel", ] DataSourceConfig: TypeAlias = Annotated[ @@ -29,86 +28,30 @@ ] -class TestingCriterionPython(BaseModel): +class TestingCriterionEvalGraderTextSimilarity(TextSimilarityGrader): __test__ = False - name: str - """The name of the grader.""" - - source: str - """The source code of the python script.""" - - type: Literal["python"] - """The object type, which is always `python`.""" - - image_tag: Optional[str] = None - """The image tag to use for the python script.""" - - pass_threshold: Optional[float] = None + pass_threshold: float """The threshold for the score.""" -class TestingCriterionScoreModelInputContentOutputText(BaseModel): - __test__ = False - text: str - """The text output from the model.""" - - type: Literal["output_text"] - """The type of the output text. Always `output_text`.""" - - -TestingCriterionScoreModelInputContent: TypeAlias = Union[ - str, ResponseInputText, TestingCriterionScoreModelInputContentOutputText -] - - -class TestingCriterionScoreModelInput(BaseModel): +class TestingCriterionEvalGraderPython(PythonGrader): __test__ = False - content: TestingCriterionScoreModelInputContent - """Text inputs to the model - can contain template strings.""" - - role: Literal["user", "assistant", "system", "developer"] - """The role of the message input. - - One of `user`, `assistant`, `system`, or `developer`. - """ - - type: Optional[Literal["message"]] = None - """The type of the message input. Always `message`.""" + pass_threshold: Optional[float] = None + """The threshold for the score.""" -class TestingCriterionScoreModel(BaseModel): +class TestingCriterionEvalGraderScoreModel(ScoreModelGrader): __test__ = False - input: List[TestingCriterionScoreModelInput] - """The input text. This may include template strings.""" - - model: str - """The model to use for the evaluation.""" - - name: str - """The name of the grader.""" - - type: Literal["score_model"] - """The object type, which is always `score_model`.""" - pass_threshold: Optional[float] = None """The threshold for the score.""" - range: Optional[List[float]] = None - """The range of the score. Defaults to `[0, 1]`.""" - - sampling_params: Optional[object] = None - """The sampling parameters for the model.""" - -TestingCriterion: TypeAlias = Annotated[ - Union[ - EvalLabelModelGrader, - EvalStringCheckGrader, - EvalTextSimilarityGrader, - TestingCriterionPython, - TestingCriterionScoreModel, - ], - PropertyInfo(discriminator="type"), +TestingCriterion: TypeAlias = Union[ + LabelModelGrader, + StringCheckGrader, + TestingCriterionEvalGraderTextSimilarity, + TestingCriterionEvalGraderPython, + TestingCriterionEvalGraderScoreModel, ] diff --git a/src/openai/types/eval_update_response.py b/src/openai/types/eval_update_response.py index 2c280977a1..c5cb2622ea 100644 --- a/src/openai/types/eval_update_response.py +++ b/src/openai/types/eval_update_response.py @@ -6,22 +6,21 @@ from .._utils import PropertyInfo from .._models import BaseModel from .shared.metadata import Metadata -from .eval_label_model_grader import EvalLabelModelGrader -from .eval_string_check_grader import EvalStringCheckGrader -from .eval_text_similarity_grader import EvalTextSimilarityGrader -from .responses.response_input_text import ResponseInputText +from .graders.python_grader import PythonGrader +from .graders.label_model_grader import LabelModelGrader +from .graders.score_model_grader import ScoreModelGrader +from .graders.string_check_grader import StringCheckGrader from .eval_custom_data_source_config import EvalCustomDataSourceConfig +from .graders.text_similarity_grader import TextSimilarityGrader from .eval_stored_completions_data_source_config import EvalStoredCompletionsDataSourceConfig __all__ = [ "EvalUpdateResponse", "DataSourceConfig", "TestingCriterion", - "TestingCriterionPython", - "TestingCriterionScoreModel", - "TestingCriterionScoreModelInput", - "TestingCriterionScoreModelInputContent", - "TestingCriterionScoreModelInputContentOutputText", + "TestingCriterionEvalGraderTextSimilarity", + "TestingCriterionEvalGraderPython", + "TestingCriterionEvalGraderScoreModel", ] DataSourceConfig: TypeAlias = Annotated[ @@ -29,86 +28,30 @@ ] -class TestingCriterionPython(BaseModel): +class TestingCriterionEvalGraderTextSimilarity(TextSimilarityGrader): __test__ = False - name: str - """The name of the grader.""" - - source: str - """The source code of the python script.""" - - type: Literal["python"] - """The object type, which is always `python`.""" - - image_tag: Optional[str] = None - """The image tag to use for the python script.""" - - pass_threshold: Optional[float] = None + pass_threshold: float """The threshold for the score.""" -class TestingCriterionScoreModelInputContentOutputText(BaseModel): - __test__ = False - text: str - """The text output from the model.""" - - type: Literal["output_text"] - """The type of the output text. Always `output_text`.""" - - -TestingCriterionScoreModelInputContent: TypeAlias = Union[ - str, ResponseInputText, TestingCriterionScoreModelInputContentOutputText -] - - -class TestingCriterionScoreModelInput(BaseModel): +class TestingCriterionEvalGraderPython(PythonGrader): __test__ = False - content: TestingCriterionScoreModelInputContent - """Text inputs to the model - can contain template strings.""" - - role: Literal["user", "assistant", "system", "developer"] - """The role of the message input. - - One of `user`, `assistant`, `system`, or `developer`. - """ - - type: Optional[Literal["message"]] = None - """The type of the message input. Always `message`.""" + pass_threshold: Optional[float] = None + """The threshold for the score.""" -class TestingCriterionScoreModel(BaseModel): +class TestingCriterionEvalGraderScoreModel(ScoreModelGrader): __test__ = False - input: List[TestingCriterionScoreModelInput] - """The input text. This may include template strings.""" - - model: str - """The model to use for the evaluation.""" - - name: str - """The name of the grader.""" - - type: Literal["score_model"] - """The object type, which is always `score_model`.""" - pass_threshold: Optional[float] = None """The threshold for the score.""" - range: Optional[List[float]] = None - """The range of the score. Defaults to `[0, 1]`.""" - - sampling_params: Optional[object] = None - """The sampling parameters for the model.""" - -TestingCriterion: TypeAlias = Annotated[ - Union[ - EvalLabelModelGrader, - EvalStringCheckGrader, - EvalTextSimilarityGrader, - TestingCriterionPython, - TestingCriterionScoreModel, - ], - PropertyInfo(discriminator="type"), +TestingCriterion: TypeAlias = Union[ + LabelModelGrader, + StringCheckGrader, + TestingCriterionEvalGraderTextSimilarity, + TestingCriterionEvalGraderPython, + TestingCriterionEvalGraderScoreModel, ] diff --git a/src/openai/types/fine_tuning/__init__.py b/src/openai/types/fine_tuning/__init__.py index 92b81329b1..cc664eacea 100644 --- a/src/openai/types/fine_tuning/__init__.py +++ b/src/openai/types/fine_tuning/__init__.py @@ -2,13 +2,25 @@ from __future__ import annotations +from .dpo_method import DpoMethod as DpoMethod from .fine_tuning_job import FineTuningJob as FineTuningJob from .job_list_params import JobListParams as JobListParams +from .dpo_method_param import DpoMethodParam as DpoMethodParam from .job_create_params import JobCreateParams as JobCreateParams +from .supervised_method import SupervisedMethod as SupervisedMethod +from .dpo_hyperparameters import DpoHyperparameters as DpoHyperparameters +from .reinforcement_method import ReinforcementMethod as ReinforcementMethod from .fine_tuning_job_event import FineTuningJobEvent as FineTuningJobEvent from .job_list_events_params import JobListEventsParams as JobListEventsParams +from .supervised_method_param import SupervisedMethodParam as SupervisedMethodParam +from .dpo_hyperparameters_param import DpoHyperparametersParam as DpoHyperparametersParam +from .reinforcement_method_param import ReinforcementMethodParam as ReinforcementMethodParam +from .supervised_hyperparameters import SupervisedHyperparameters as SupervisedHyperparameters from .fine_tuning_job_integration import FineTuningJobIntegration as FineTuningJobIntegration +from .reinforcement_hyperparameters import ReinforcementHyperparameters as ReinforcementHyperparameters +from .supervised_hyperparameters_param import SupervisedHyperparametersParam as SupervisedHyperparametersParam from .fine_tuning_job_wandb_integration import FineTuningJobWandbIntegration as FineTuningJobWandbIntegration +from .reinforcement_hyperparameters_param import ReinforcementHyperparametersParam as ReinforcementHyperparametersParam from .fine_tuning_job_wandb_integration_object import ( FineTuningJobWandbIntegrationObject as FineTuningJobWandbIntegrationObject, ) diff --git a/src/openai/types/fine_tuning/alpha/__init__.py b/src/openai/types/fine_tuning/alpha/__init__.py new file mode 100644 index 0000000000..6394961b0b --- /dev/null +++ b/src/openai/types/fine_tuning/alpha/__init__.py @@ -0,0 +1,8 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .grader_run_params import GraderRunParams as GraderRunParams +from .grader_run_response import GraderRunResponse as GraderRunResponse +from .grader_validate_params import GraderValidateParams as GraderValidateParams +from .grader_validate_response import GraderValidateResponse as GraderValidateResponse diff --git a/src/openai/types/fine_tuning/alpha/grader_run_params.py b/src/openai/types/fine_tuning/alpha/grader_run_params.py new file mode 100644 index 0000000000..fa729f55ba --- /dev/null +++ b/src/openai/types/fine_tuning/alpha/grader_run_params.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import Required, TypeAlias, TypedDict + +from ...graders.multi_grader_param import MultiGraderParam +from ...graders.python_grader_param import PythonGraderParam +from ...graders.score_model_grader_param import ScoreModelGraderParam +from ...graders.string_check_grader_param import StringCheckGraderParam +from ...graders.text_similarity_grader_param import TextSimilarityGraderParam + +__all__ = ["GraderRunParams", "Grader"] + + +class GraderRunParams(TypedDict, total=False): + grader: Required[Grader] + """The grader used for the fine-tuning job.""" + + model_sample: Required[str] + """The model sample to be evaluated.""" + + reference_answer: Required[Union[str, Iterable[object], float, object]] + """The reference answer for the evaluation.""" + + +Grader: TypeAlias = Union[ + StringCheckGraderParam, TextSimilarityGraderParam, PythonGraderParam, ScoreModelGraderParam, MultiGraderParam +] diff --git a/src/openai/types/fine_tuning/alpha/grader_run_response.py b/src/openai/types/fine_tuning/alpha/grader_run_response.py new file mode 100644 index 0000000000..8ef046d133 --- /dev/null +++ b/src/openai/types/fine_tuning/alpha/grader_run_response.py @@ -0,0 +1,67 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional + +from pydantic import Field as FieldInfo + +from ...._models import BaseModel + +__all__ = ["GraderRunResponse", "Metadata", "MetadataErrors"] + + +class MetadataErrors(BaseModel): + formula_parse_error: bool + + invalid_variable_error: bool + + api_model_grader_parse_error: bool = FieldInfo(alias="model_grader_parse_error") + + api_model_grader_refusal_error: bool = FieldInfo(alias="model_grader_refusal_error") + + api_model_grader_server_error: bool = FieldInfo(alias="model_grader_server_error") + + api_model_grader_server_error_details: Optional[str] = FieldInfo( + alias="model_grader_server_error_details", default=None + ) + + other_error: bool + + python_grader_runtime_error: bool + + python_grader_runtime_error_details: Optional[str] = None + + python_grader_server_error: bool + + python_grader_server_error_type: Optional[str] = None + + sample_parse_error: bool + + truncated_observation_error: bool + + unresponsive_reward_error: bool + + +class Metadata(BaseModel): + errors: MetadataErrors + + execution_time: float + + name: str + + sampled_model_name: Optional[str] = None + + scores: Dict[str, object] + + token_usage: Optional[int] = None + + type: str + + +class GraderRunResponse(BaseModel): + metadata: Metadata + + api_model_grader_token_usage_per_model: Dict[str, object] = FieldInfo(alias="model_grader_token_usage_per_model") + + reward: float + + sub_rewards: Dict[str, object] diff --git a/src/openai/types/fine_tuning/alpha/grader_validate_params.py b/src/openai/types/fine_tuning/alpha/grader_validate_params.py new file mode 100644 index 0000000000..fe9eb44e32 --- /dev/null +++ b/src/openai/types/fine_tuning/alpha/grader_validate_params.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Required, TypeAlias, TypedDict + +from ...graders.multi_grader_param import MultiGraderParam +from ...graders.python_grader_param import PythonGraderParam +from ...graders.score_model_grader_param import ScoreModelGraderParam +from ...graders.string_check_grader_param import StringCheckGraderParam +from ...graders.text_similarity_grader_param import TextSimilarityGraderParam + +__all__ = ["GraderValidateParams", "Grader"] + + +class GraderValidateParams(TypedDict, total=False): + grader: Required[Grader] + """The grader used for the fine-tuning job.""" + + +Grader: TypeAlias = Union[ + StringCheckGraderParam, TextSimilarityGraderParam, PythonGraderParam, ScoreModelGraderParam, MultiGraderParam +] diff --git a/src/openai/types/fine_tuning/alpha/grader_validate_response.py b/src/openai/types/fine_tuning/alpha/grader_validate_response.py new file mode 100644 index 0000000000..b373292d80 --- /dev/null +++ b/src/openai/types/fine_tuning/alpha/grader_validate_response.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union, Optional +from typing_extensions import TypeAlias + +from ...._models import BaseModel +from ...graders.multi_grader import MultiGrader +from ...graders.python_grader import PythonGrader +from ...graders.score_model_grader import ScoreModelGrader +from ...graders.string_check_grader import StringCheckGrader +from ...graders.text_similarity_grader import TextSimilarityGrader + +__all__ = ["GraderValidateResponse", "Grader"] + +Grader: TypeAlias = Union[StringCheckGrader, TextSimilarityGrader, PythonGrader, ScoreModelGrader, MultiGrader] + + +class GraderValidateResponse(BaseModel): + grader: Optional[Grader] = None + """The grader used for the fine-tuning job.""" diff --git a/src/openai/types/fine_tuning/dpo_hyperparameters.py b/src/openai/types/fine_tuning/dpo_hyperparameters.py new file mode 100644 index 0000000000..b0b3f0581b --- /dev/null +++ b/src/openai/types/fine_tuning/dpo_hyperparameters.py @@ -0,0 +1,36 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["DpoHyperparameters"] + + +class DpoHyperparameters(BaseModel): + batch_size: Union[Literal["auto"], int, None] = None + """Number of examples in each batch. + + A larger batch size means that model parameters are updated less frequently, but + with lower variance. + """ + + beta: Union[Literal["auto"], float, None] = None + """The beta value for the DPO method. + + A higher beta value will increase the weight of the penalty between the policy + and reference model. + """ + + learning_rate_multiplier: Union[Literal["auto"], float, None] = None + """Scaling factor for the learning rate. + + A smaller learning rate may be useful to avoid overfitting. + """ + + n_epochs: Union[Literal["auto"], int, None] = None + """The number of epochs to train the model for. + + An epoch refers to one full cycle through the training dataset. + """ diff --git a/src/openai/types/fine_tuning/dpo_hyperparameters_param.py b/src/openai/types/fine_tuning/dpo_hyperparameters_param.py new file mode 100644 index 0000000000..87c6ee80a5 --- /dev/null +++ b/src/openai/types/fine_tuning/dpo_hyperparameters_param.py @@ -0,0 +1,36 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, TypedDict + +__all__ = ["DpoHyperparametersParam"] + + +class DpoHyperparametersParam(TypedDict, total=False): + batch_size: Union[Literal["auto"], int] + """Number of examples in each batch. + + A larger batch size means that model parameters are updated less frequently, but + with lower variance. + """ + + beta: Union[Literal["auto"], float] + """The beta value for the DPO method. + + A higher beta value will increase the weight of the penalty between the policy + and reference model. + """ + + learning_rate_multiplier: Union[Literal["auto"], float] + """Scaling factor for the learning rate. + + A smaller learning rate may be useful to avoid overfitting. + """ + + n_epochs: Union[Literal["auto"], int] + """The number of epochs to train the model for. + + An epoch refers to one full cycle through the training dataset. + """ diff --git a/src/openai/types/fine_tuning/dpo_method.py b/src/openai/types/fine_tuning/dpo_method.py new file mode 100644 index 0000000000..3e20f360dd --- /dev/null +++ b/src/openai/types/fine_tuning/dpo_method.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from ..._models import BaseModel +from .dpo_hyperparameters import DpoHyperparameters + +__all__ = ["DpoMethod"] + + +class DpoMethod(BaseModel): + hyperparameters: Optional[DpoHyperparameters] = None + """The hyperparameters used for the DPO fine-tuning job.""" diff --git a/src/openai/types/fine_tuning/dpo_method_param.py b/src/openai/types/fine_tuning/dpo_method_param.py new file mode 100644 index 0000000000..ce6b6510f6 --- /dev/null +++ b/src/openai/types/fine_tuning/dpo_method_param.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +from .dpo_hyperparameters_param import DpoHyperparametersParam + +__all__ = ["DpoMethodParam"] + + +class DpoMethodParam(TypedDict, total=False): + hyperparameters: DpoHyperparametersParam + """The hyperparameters used for the DPO fine-tuning job.""" diff --git a/src/openai/types/fine_tuning/fine_tuning_job.py b/src/openai/types/fine_tuning/fine_tuning_job.py index c7fff2b7b1..f626fbba64 100644 --- a/src/openai/types/fine_tuning/fine_tuning_job.py +++ b/src/openai/types/fine_tuning/fine_tuning_job.py @@ -4,19 +4,13 @@ from typing_extensions import Literal from ..._models import BaseModel +from .dpo_method import DpoMethod from ..shared.metadata import Metadata +from .supervised_method import SupervisedMethod +from .reinforcement_method import ReinforcementMethod from .fine_tuning_job_wandb_integration_object import FineTuningJobWandbIntegrationObject -__all__ = [ - "FineTuningJob", - "Error", - "Hyperparameters", - "Method", - "MethodDpo", - "MethodDpoHyperparameters", - "MethodSupervised", - "MethodSupervisedHyperparameters", -] +__all__ = ["FineTuningJob", "Error", "Hyperparameters", "Method"] class Error(BaseModel): @@ -54,74 +48,18 @@ class Hyperparameters(BaseModel): """ -class MethodDpoHyperparameters(BaseModel): - batch_size: Union[Literal["auto"], int, None] = None - """Number of examples in each batch. - - A larger batch size means that model parameters are updated less frequently, but - with lower variance. - """ - - beta: Union[Literal["auto"], float, None] = None - """The beta value for the DPO method. - - A higher beta value will increase the weight of the penalty between the policy - and reference model. - """ - - learning_rate_multiplier: Union[Literal["auto"], float, None] = None - """Scaling factor for the learning rate. - - A smaller learning rate may be useful to avoid overfitting. - """ - - n_epochs: Union[Literal["auto"], int, None] = None - """The number of epochs to train the model for. - - An epoch refers to one full cycle through the training dataset. - """ - - -class MethodDpo(BaseModel): - hyperparameters: Optional[MethodDpoHyperparameters] = None - """The hyperparameters used for the fine-tuning job.""" - - -class MethodSupervisedHyperparameters(BaseModel): - batch_size: Union[Literal["auto"], int, None] = None - """Number of examples in each batch. - - A larger batch size means that model parameters are updated less frequently, but - with lower variance. - """ - - learning_rate_multiplier: Union[Literal["auto"], float, None] = None - """Scaling factor for the learning rate. - - A smaller learning rate may be useful to avoid overfitting. - """ - - n_epochs: Union[Literal["auto"], int, None] = None - """The number of epochs to train the model for. - - An epoch refers to one full cycle through the training dataset. - """ - - -class MethodSupervised(BaseModel): - hyperparameters: Optional[MethodSupervisedHyperparameters] = None - """The hyperparameters used for the fine-tuning job.""" - - class Method(BaseModel): - dpo: Optional[MethodDpo] = None + type: Literal["supervised", "dpo", "reinforcement"] + """The type of method. Is either `supervised`, `dpo`, or `reinforcement`.""" + + dpo: Optional[DpoMethod] = None """Configuration for the DPO fine-tuning method.""" - supervised: Optional[MethodSupervised] = None - """Configuration for the supervised fine-tuning method.""" + reinforcement: Optional[ReinforcementMethod] = None + """Configuration for the reinforcement fine-tuning method.""" - type: Optional[Literal["supervised", "dpo"]] = None - """The type of method. Is either `supervised` or `dpo`.""" + supervised: Optional[SupervisedMethod] = None + """Configuration for the supervised fine-tuning method.""" class FineTuningJob(BaseModel): diff --git a/src/openai/types/fine_tuning/job_create_params.py b/src/openai/types/fine_tuning/job_create_params.py index f4cf980b08..6b2f41cb71 100644 --- a/src/openai/types/fine_tuning/job_create_params.py +++ b/src/openai/types/fine_tuning/job_create_params.py @@ -5,19 +5,12 @@ from typing import List, Union, Iterable, Optional from typing_extensions import Literal, Required, TypedDict +from .dpo_method_param import DpoMethodParam from ..shared_params.metadata import Metadata +from .supervised_method_param import SupervisedMethodParam +from .reinforcement_method_param import ReinforcementMethodParam -__all__ = [ - "JobCreateParams", - "Hyperparameters", - "Integration", - "IntegrationWandb", - "Method", - "MethodDpo", - "MethodDpoHyperparameters", - "MethodSupervised", - "MethodSupervisedHyperparameters", -] +__all__ = ["JobCreateParams", "Hyperparameters", "Integration", "IntegrationWandb", "Method"] class JobCreateParams(TypedDict, total=False): @@ -166,71 +159,15 @@ class Integration(TypedDict, total=False): """ -class MethodDpoHyperparameters(TypedDict, total=False): - batch_size: Union[Literal["auto"], int] - """Number of examples in each batch. - - A larger batch size means that model parameters are updated less frequently, but - with lower variance. - """ - - beta: Union[Literal["auto"], float] - """The beta value for the DPO method. - - A higher beta value will increase the weight of the penalty between the policy - and reference model. - """ - - learning_rate_multiplier: Union[Literal["auto"], float] - """Scaling factor for the learning rate. - - A smaller learning rate may be useful to avoid overfitting. - """ - - n_epochs: Union[Literal["auto"], int] - """The number of epochs to train the model for. - - An epoch refers to one full cycle through the training dataset. - """ - - -class MethodDpo(TypedDict, total=False): - hyperparameters: MethodDpoHyperparameters - """The hyperparameters used for the fine-tuning job.""" - - -class MethodSupervisedHyperparameters(TypedDict, total=False): - batch_size: Union[Literal["auto"], int] - """Number of examples in each batch. - - A larger batch size means that model parameters are updated less frequently, but - with lower variance. - """ - - learning_rate_multiplier: Union[Literal["auto"], float] - """Scaling factor for the learning rate. - - A smaller learning rate may be useful to avoid overfitting. - """ - - n_epochs: Union[Literal["auto"], int] - """The number of epochs to train the model for. - - An epoch refers to one full cycle through the training dataset. - """ - - -class MethodSupervised(TypedDict, total=False): - hyperparameters: MethodSupervisedHyperparameters - """The hyperparameters used for the fine-tuning job.""" - - class Method(TypedDict, total=False): - dpo: MethodDpo + type: Required[Literal["supervised", "dpo", "reinforcement"]] + """The type of method. Is either `supervised`, `dpo`, or `reinforcement`.""" + + dpo: DpoMethodParam """Configuration for the DPO fine-tuning method.""" - supervised: MethodSupervised - """Configuration for the supervised fine-tuning method.""" + reinforcement: ReinforcementMethodParam + """Configuration for the reinforcement fine-tuning method.""" - type: Literal["supervised", "dpo"] - """The type of method. Is either `supervised` or `dpo`.""" + supervised: SupervisedMethodParam + """Configuration for the supervised fine-tuning method.""" diff --git a/src/openai/types/fine_tuning/reinforcement_hyperparameters.py b/src/openai/types/fine_tuning/reinforcement_hyperparameters.py new file mode 100644 index 0000000000..7c1762d38c --- /dev/null +++ b/src/openai/types/fine_tuning/reinforcement_hyperparameters.py @@ -0,0 +1,43 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union, Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["ReinforcementHyperparameters"] + + +class ReinforcementHyperparameters(BaseModel): + batch_size: Union[Literal["auto"], int, None] = None + """Number of examples in each batch. + + A larger batch size means that model parameters are updated less frequently, but + with lower variance. + """ + + compute_multiplier: Union[Literal["auto"], float, None] = None + """ + Multiplier on amount of compute used for exploring search space during training. + """ + + eval_interval: Union[Literal["auto"], int, None] = None + """The number of training steps between evaluation runs.""" + + eval_samples: Union[Literal["auto"], int, None] = None + """Number of evaluation samples to generate per training step.""" + + learning_rate_multiplier: Union[Literal["auto"], float, None] = None + """Scaling factor for the learning rate. + + A smaller learning rate may be useful to avoid overfitting. + """ + + n_epochs: Union[Literal["auto"], int, None] = None + """The number of epochs to train the model for. + + An epoch refers to one full cycle through the training dataset. + """ + + reasoning_effort: Optional[Literal["default", "low", "medium", "high"]] = None + """Level of reasoning effort.""" diff --git a/src/openai/types/fine_tuning/reinforcement_hyperparameters_param.py b/src/openai/types/fine_tuning/reinforcement_hyperparameters_param.py new file mode 100644 index 0000000000..0cc12fcb17 --- /dev/null +++ b/src/openai/types/fine_tuning/reinforcement_hyperparameters_param.py @@ -0,0 +1,43 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, TypedDict + +__all__ = ["ReinforcementHyperparametersParam"] + + +class ReinforcementHyperparametersParam(TypedDict, total=False): + batch_size: Union[Literal["auto"], int] + """Number of examples in each batch. + + A larger batch size means that model parameters are updated less frequently, but + with lower variance. + """ + + compute_multiplier: Union[Literal["auto"], float] + """ + Multiplier on amount of compute used for exploring search space during training. + """ + + eval_interval: Union[Literal["auto"], int] + """The number of training steps between evaluation runs.""" + + eval_samples: Union[Literal["auto"], int] + """Number of evaluation samples to generate per training step.""" + + learning_rate_multiplier: Union[Literal["auto"], float] + """Scaling factor for the learning rate. + + A smaller learning rate may be useful to avoid overfitting. + """ + + n_epochs: Union[Literal["auto"], int] + """The number of epochs to train the model for. + + An epoch refers to one full cycle through the training dataset. + """ + + reasoning_effort: Literal["default", "low", "medium", "high"] + """Level of reasoning effort.""" diff --git a/src/openai/types/fine_tuning/reinforcement_method.py b/src/openai/types/fine_tuning/reinforcement_method.py new file mode 100644 index 0000000000..9b65c41033 --- /dev/null +++ b/src/openai/types/fine_tuning/reinforcement_method.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union, Optional +from typing_extensions import TypeAlias + +from ..._models import BaseModel +from ..graders.multi_grader import MultiGrader +from ..graders.python_grader import PythonGrader +from ..graders.score_model_grader import ScoreModelGrader +from ..graders.string_check_grader import StringCheckGrader +from .reinforcement_hyperparameters import ReinforcementHyperparameters +from ..graders.text_similarity_grader import TextSimilarityGrader + +__all__ = ["ReinforcementMethod", "Grader"] + +Grader: TypeAlias = Union[StringCheckGrader, TextSimilarityGrader, PythonGrader, ScoreModelGrader, MultiGrader] + + +class ReinforcementMethod(BaseModel): + grader: Grader + """The grader used for the fine-tuning job.""" + + hyperparameters: Optional[ReinforcementHyperparameters] = None + """The hyperparameters used for the reinforcement fine-tuning job.""" diff --git a/src/openai/types/fine_tuning/reinforcement_method_param.py b/src/openai/types/fine_tuning/reinforcement_method_param.py new file mode 100644 index 0000000000..00d5060536 --- /dev/null +++ b/src/openai/types/fine_tuning/reinforcement_method_param.py @@ -0,0 +1,27 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Required, TypeAlias, TypedDict + +from ..graders.multi_grader_param import MultiGraderParam +from ..graders.python_grader_param import PythonGraderParam +from ..graders.score_model_grader_param import ScoreModelGraderParam +from ..graders.string_check_grader_param import StringCheckGraderParam +from .reinforcement_hyperparameters_param import ReinforcementHyperparametersParam +from ..graders.text_similarity_grader_param import TextSimilarityGraderParam + +__all__ = ["ReinforcementMethodParam", "Grader"] + +Grader: TypeAlias = Union[ + StringCheckGraderParam, TextSimilarityGraderParam, PythonGraderParam, ScoreModelGraderParam, MultiGraderParam +] + + +class ReinforcementMethodParam(TypedDict, total=False): + grader: Required[Grader] + """The grader used for the fine-tuning job.""" + + hyperparameters: ReinforcementHyperparametersParam + """The hyperparameters used for the reinforcement fine-tuning job.""" diff --git a/src/openai/types/fine_tuning/supervised_hyperparameters.py b/src/openai/types/fine_tuning/supervised_hyperparameters.py new file mode 100644 index 0000000000..3955ecf437 --- /dev/null +++ b/src/openai/types/fine_tuning/supervised_hyperparameters.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["SupervisedHyperparameters"] + + +class SupervisedHyperparameters(BaseModel): + batch_size: Union[Literal["auto"], int, None] = None + """Number of examples in each batch. + + A larger batch size means that model parameters are updated less frequently, but + with lower variance. + """ + + learning_rate_multiplier: Union[Literal["auto"], float, None] = None + """Scaling factor for the learning rate. + + A smaller learning rate may be useful to avoid overfitting. + """ + + n_epochs: Union[Literal["auto"], int, None] = None + """The number of epochs to train the model for. + + An epoch refers to one full cycle through the training dataset. + """ diff --git a/src/openai/types/fine_tuning/supervised_hyperparameters_param.py b/src/openai/types/fine_tuning/supervised_hyperparameters_param.py new file mode 100644 index 0000000000..bd37d9b239 --- /dev/null +++ b/src/openai/types/fine_tuning/supervised_hyperparameters_param.py @@ -0,0 +1,29 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Literal, TypedDict + +__all__ = ["SupervisedHyperparametersParam"] + + +class SupervisedHyperparametersParam(TypedDict, total=False): + batch_size: Union[Literal["auto"], int] + """Number of examples in each batch. + + A larger batch size means that model parameters are updated less frequently, but + with lower variance. + """ + + learning_rate_multiplier: Union[Literal["auto"], float] + """Scaling factor for the learning rate. + + A smaller learning rate may be useful to avoid overfitting. + """ + + n_epochs: Union[Literal["auto"], int] + """The number of epochs to train the model for. + + An epoch refers to one full cycle through the training dataset. + """ diff --git a/src/openai/types/fine_tuning/supervised_method.py b/src/openai/types/fine_tuning/supervised_method.py new file mode 100644 index 0000000000..3a32bf27a0 --- /dev/null +++ b/src/openai/types/fine_tuning/supervised_method.py @@ -0,0 +1,13 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional + +from ..._models import BaseModel +from .supervised_hyperparameters import SupervisedHyperparameters + +__all__ = ["SupervisedMethod"] + + +class SupervisedMethod(BaseModel): + hyperparameters: Optional[SupervisedHyperparameters] = None + """The hyperparameters used for the fine-tuning job.""" diff --git a/src/openai/types/fine_tuning/supervised_method_param.py b/src/openai/types/fine_tuning/supervised_method_param.py new file mode 100644 index 0000000000..ba277853d7 --- /dev/null +++ b/src/openai/types/fine_tuning/supervised_method_param.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +from .supervised_hyperparameters_param import SupervisedHyperparametersParam + +__all__ = ["SupervisedMethodParam"] + + +class SupervisedMethodParam(TypedDict, total=False): + hyperparameters: SupervisedHyperparametersParam + """The hyperparameters used for the fine-tuning job.""" diff --git a/src/openai/types/graders/__init__.py b/src/openai/types/graders/__init__.py new file mode 100644 index 0000000000..e0a909125e --- /dev/null +++ b/src/openai/types/graders/__init__.py @@ -0,0 +1,16 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .multi_grader import MultiGrader as MultiGrader +from .python_grader import PythonGrader as PythonGrader +from .label_model_grader import LabelModelGrader as LabelModelGrader +from .multi_grader_param import MultiGraderParam as MultiGraderParam +from .score_model_grader import ScoreModelGrader as ScoreModelGrader +from .python_grader_param import PythonGraderParam as PythonGraderParam +from .string_check_grader import StringCheckGrader as StringCheckGrader +from .text_similarity_grader import TextSimilarityGrader as TextSimilarityGrader +from .label_model_grader_param import LabelModelGraderParam as LabelModelGraderParam +from .score_model_grader_param import ScoreModelGraderParam as ScoreModelGraderParam +from .string_check_grader_param import StringCheckGraderParam as StringCheckGraderParam +from .text_similarity_grader_param import TextSimilarityGraderParam as TextSimilarityGraderParam diff --git a/src/openai/types/eval_label_model_grader.py b/src/openai/types/graders/label_model_grader.py similarity index 85% rename from src/openai/types/eval_label_model_grader.py rename to src/openai/types/graders/label_model_grader.py index 40e6bda140..d95ccc6df6 100644 --- a/src/openai/types/eval_label_model_grader.py +++ b/src/openai/types/graders/label_model_grader.py @@ -3,10 +3,10 @@ from typing import List, Union, Optional from typing_extensions import Literal, TypeAlias -from .._models import BaseModel -from .responses.response_input_text import ResponseInputText +from ..._models import BaseModel +from ..responses.response_input_text import ResponseInputText -__all__ = ["EvalLabelModelGrader", "Input", "InputContent", "InputContentOutputText"] +__all__ = ["LabelModelGrader", "Input", "InputContent", "InputContentOutputText"] class InputContentOutputText(BaseModel): @@ -34,7 +34,7 @@ class Input(BaseModel): """The type of the message input. Always `message`.""" -class EvalLabelModelGrader(BaseModel): +class LabelModelGrader(BaseModel): input: List[Input] labels: List[str] diff --git a/src/openai/types/graders/label_model_grader_param.py b/src/openai/types/graders/label_model_grader_param.py new file mode 100644 index 0000000000..76d01421ee --- /dev/null +++ b/src/openai/types/graders/label_model_grader_param.py @@ -0,0 +1,54 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import List, Union, Iterable +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from ..responses.response_input_text_param import ResponseInputTextParam + +__all__ = ["LabelModelGraderParam", "Input", "InputContent", "InputContentOutputText"] + + +class InputContentOutputText(TypedDict, total=False): + text: Required[str] + """The text output from the model.""" + + type: Required[Literal["output_text"]] + """The type of the output text. Always `output_text`.""" + + +InputContent: TypeAlias = Union[str, ResponseInputTextParam, InputContentOutputText] + + +class Input(TypedDict, total=False): + content: Required[InputContent] + """Text inputs to the model - can contain template strings.""" + + role: Required[Literal["user", "assistant", "system", "developer"]] + """The role of the message input. + + One of `user`, `assistant`, `system`, or `developer`. + """ + + type: Literal["message"] + """The type of the message input. Always `message`.""" + + +class LabelModelGraderParam(TypedDict, total=False): + input: Required[Iterable[Input]] + + labels: Required[List[str]] + """The labels to assign to each item in the evaluation.""" + + model: Required[str] + """The model to use for the evaluation. Must support structured outputs.""" + + name: Required[str] + """The name of the grader.""" + + passing_labels: Required[List[str]] + """The labels that indicate a passing result. Must be a subset of labels.""" + + type: Required[Literal["label_model"]] + """The object type, which is always `label_model`.""" diff --git a/src/openai/types/graders/multi_grader.py b/src/openai/types/graders/multi_grader.py new file mode 100644 index 0000000000..ee9b31d2b0 --- /dev/null +++ b/src/openai/types/graders/multi_grader.py @@ -0,0 +1,28 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Union +from typing_extensions import Literal, TypeAlias + +from ..._models import BaseModel +from .python_grader import PythonGrader +from .label_model_grader import LabelModelGrader +from .score_model_grader import ScoreModelGrader +from .string_check_grader import StringCheckGrader +from .text_similarity_grader import TextSimilarityGrader + +__all__ = ["MultiGrader", "Graders"] + +Graders: TypeAlias = Union[StringCheckGrader, TextSimilarityGrader, PythonGrader, ScoreModelGrader, LabelModelGrader] + + +class MultiGrader(BaseModel): + calculate_output: str + """A formula to calculate the output based on grader results.""" + + graders: Dict[str, Graders] + + name: str + """The name of the grader.""" + + type: Literal["multi"] + """The type of grader.""" diff --git a/src/openai/types/graders/multi_grader_param.py b/src/openai/types/graders/multi_grader_param.py new file mode 100644 index 0000000000..4dd1a48530 --- /dev/null +++ b/src/openai/types/graders/multi_grader_param.py @@ -0,0 +1,31 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Dict, Union +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from .python_grader_param import PythonGraderParam +from .label_model_grader_param import LabelModelGraderParam +from .score_model_grader_param import ScoreModelGraderParam +from .string_check_grader_param import StringCheckGraderParam +from .text_similarity_grader_param import TextSimilarityGraderParam + +__all__ = ["MultiGraderParam", "Graders"] + +Graders: TypeAlias = Union[ + StringCheckGraderParam, TextSimilarityGraderParam, PythonGraderParam, ScoreModelGraderParam, LabelModelGraderParam +] + + +class MultiGraderParam(TypedDict, total=False): + calculate_output: Required[str] + """A formula to calculate the output based on grader results.""" + + graders: Required[Dict[str, Graders]] + + name: Required[str] + """The name of the grader.""" + + type: Required[Literal["multi"]] + """The type of grader.""" diff --git a/src/openai/types/graders/python_grader.py b/src/openai/types/graders/python_grader.py new file mode 100644 index 0000000000..faa10b1ef9 --- /dev/null +++ b/src/openai/types/graders/python_grader.py @@ -0,0 +1,22 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ..._models import BaseModel + +__all__ = ["PythonGrader"] + + +class PythonGrader(BaseModel): + name: str + """The name of the grader.""" + + source: str + """The source code of the python script.""" + + type: Literal["python"] + """The object type, which is always `python`.""" + + image_tag: Optional[str] = None + """The image tag to use for the python script.""" diff --git a/src/openai/types/graders/python_grader_param.py b/src/openai/types/graders/python_grader_param.py new file mode 100644 index 0000000000..efb923751e --- /dev/null +++ b/src/openai/types/graders/python_grader_param.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["PythonGraderParam"] + + +class PythonGraderParam(TypedDict, total=False): + name: Required[str] + """The name of the grader.""" + + source: Required[str] + """The source code of the python script.""" + + type: Required[Literal["python"]] + """The object type, which is always `python`.""" + + image_tag: str + """The image tag to use for the python script.""" diff --git a/src/openai/types/graders/score_model_grader.py b/src/openai/types/graders/score_model_grader.py new file mode 100644 index 0000000000..1349f75a58 --- /dev/null +++ b/src/openai/types/graders/score_model_grader.py @@ -0,0 +1,54 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Union, Optional +from typing_extensions import Literal, TypeAlias + +from ..._models import BaseModel +from ..responses.response_input_text import ResponseInputText + +__all__ = ["ScoreModelGrader", "Input", "InputContent", "InputContentOutputText"] + + +class InputContentOutputText(BaseModel): + text: str + """The text output from the model.""" + + type: Literal["output_text"] + """The type of the output text. Always `output_text`.""" + + +InputContent: TypeAlias = Union[str, ResponseInputText, InputContentOutputText] + + +class Input(BaseModel): + content: InputContent + """Text inputs to the model - can contain template strings.""" + + role: Literal["user", "assistant", "system", "developer"] + """The role of the message input. + + One of `user`, `assistant`, `system`, or `developer`. + """ + + type: Optional[Literal["message"]] = None + """The type of the message input. Always `message`.""" + + +class ScoreModelGrader(BaseModel): + input: List[Input] + """The input text. This may include template strings.""" + + model: str + """The model to use for the evaluation.""" + + name: str + """The name of the grader.""" + + type: Literal["score_model"] + """The object type, which is always `score_model`.""" + + range: Optional[List[float]] = None + """The range of the score. Defaults to `[0, 1]`.""" + + sampling_params: Optional[object] = None + """The sampling parameters for the model.""" diff --git a/src/openai/types/graders/score_model_grader_param.py b/src/openai/types/graders/score_model_grader_param.py new file mode 100644 index 0000000000..673f14e47d --- /dev/null +++ b/src/openai/types/graders/score_model_grader_param.py @@ -0,0 +1,55 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union, Iterable +from typing_extensions import Literal, Required, TypeAlias, TypedDict + +from ..responses.response_input_text_param import ResponseInputTextParam + +__all__ = ["ScoreModelGraderParam", "Input", "InputContent", "InputContentOutputText"] + + +class InputContentOutputText(TypedDict, total=False): + text: Required[str] + """The text output from the model.""" + + type: Required[Literal["output_text"]] + """The type of the output text. Always `output_text`.""" + + +InputContent: TypeAlias = Union[str, ResponseInputTextParam, InputContentOutputText] + + +class Input(TypedDict, total=False): + content: Required[InputContent] + """Text inputs to the model - can contain template strings.""" + + role: Required[Literal["user", "assistant", "system", "developer"]] + """The role of the message input. + + One of `user`, `assistant`, `system`, or `developer`. + """ + + type: Literal["message"] + """The type of the message input. Always `message`.""" + + +class ScoreModelGraderParam(TypedDict, total=False): + input: Required[Iterable[Input]] + """The input text. This may include template strings.""" + + model: Required[str] + """The model to use for the evaluation.""" + + name: Required[str] + """The name of the grader.""" + + type: Required[Literal["score_model"]] + """The object type, which is always `score_model`.""" + + range: Iterable[float] + """The range of the score. Defaults to `[0, 1]`.""" + + sampling_params: object + """The sampling parameters for the model.""" diff --git a/src/openai/types/eval_string_check_grader.py b/src/openai/types/graders/string_check_grader.py similarity index 84% rename from src/openai/types/eval_string_check_grader.py rename to src/openai/types/graders/string_check_grader.py index 4dfc8035f9..3bf0b8c868 100644 --- a/src/openai/types/eval_string_check_grader.py +++ b/src/openai/types/graders/string_check_grader.py @@ -2,12 +2,12 @@ from typing_extensions import Literal -from .._models import BaseModel +from ..._models import BaseModel -__all__ = ["EvalStringCheckGrader"] +__all__ = ["StringCheckGrader"] -class EvalStringCheckGrader(BaseModel): +class StringCheckGrader(BaseModel): input: str """The input text. This may include template strings.""" diff --git a/src/openai/types/eval_string_check_grader_param.py b/src/openai/types/graders/string_check_grader_param.py similarity index 87% rename from src/openai/types/eval_string_check_grader_param.py rename to src/openai/types/graders/string_check_grader_param.py index 3511329f8b..27b204cec0 100644 --- a/src/openai/types/eval_string_check_grader_param.py +++ b/src/openai/types/graders/string_check_grader_param.py @@ -4,10 +4,10 @@ from typing_extensions import Literal, Required, TypedDict -__all__ = ["EvalStringCheckGraderParam"] +__all__ = ["StringCheckGraderParam"] -class EvalStringCheckGraderParam(TypedDict, total=False): +class StringCheckGraderParam(TypedDict, total=False): input: Required[str] """The input text. This may include template strings.""" diff --git a/src/openai/types/eval_text_similarity_grader.py b/src/openai/types/graders/text_similarity_grader.py similarity index 69% rename from src/openai/types/eval_text_similarity_grader.py rename to src/openai/types/graders/text_similarity_grader.py index 853c6d4fbf..738d317766 100644 --- a/src/openai/types/eval_text_similarity_grader.py +++ b/src/openai/types/graders/text_similarity_grader.py @@ -1,14 +1,13 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -from typing import Optional from typing_extensions import Literal -from .._models import BaseModel +from ..._models import BaseModel -__all__ = ["EvalTextSimilarityGrader"] +__all__ = ["TextSimilarityGrader"] -class EvalTextSimilarityGrader(BaseModel): +class TextSimilarityGrader(BaseModel): evaluation_metric: Literal[ "fuzzy_match", "bleu", "gleu", "meteor", "rouge_1", "rouge_2", "rouge_3", "rouge_4", "rouge_5", "rouge_l" ] @@ -21,14 +20,11 @@ class EvalTextSimilarityGrader(BaseModel): input: str """The text being graded.""" - pass_threshold: float - """A float score where a value greater than or equal indicates a passing grade.""" + name: str + """The name of the grader.""" reference: str """The text being graded against.""" type: Literal["text_similarity"] """The type of grader.""" - - name: Optional[str] = None - """The name of the grader.""" diff --git a/src/openai/types/eval_text_similarity_grader_param.py b/src/openai/types/graders/text_similarity_grader_param.py similarity index 76% rename from src/openai/types/eval_text_similarity_grader_param.py rename to src/openai/types/graders/text_similarity_grader_param.py index f07cc29178..db14553217 100644 --- a/src/openai/types/eval_text_similarity_grader_param.py +++ b/src/openai/types/graders/text_similarity_grader_param.py @@ -4,10 +4,10 @@ from typing_extensions import Literal, Required, TypedDict -__all__ = ["EvalTextSimilarityGraderParam"] +__all__ = ["TextSimilarityGraderParam"] -class EvalTextSimilarityGraderParam(TypedDict, total=False): +class TextSimilarityGraderParam(TypedDict, total=False): evaluation_metric: Required[ Literal[ "fuzzy_match", "bleu", "gleu", "meteor", "rouge_1", "rouge_2", "rouge_3", "rouge_4", "rouge_5", "rouge_l" @@ -22,14 +22,11 @@ class EvalTextSimilarityGraderParam(TypedDict, total=False): input: Required[str] """The text being graded.""" - pass_threshold: Required[float] - """A float score where a value greater than or equal indicates a passing grade.""" + name: Required[str] + """The name of the grader.""" reference: Required[str] """The text being graded against.""" type: Required[Literal["text_similarity"]] """The type of grader.""" - - name: str - """The name of the grader.""" diff --git a/tests/api_resources/fine_tuning/alpha/__init__.py b/tests/api_resources/fine_tuning/alpha/__init__.py new file mode 100644 index 0000000000..fd8019a9a1 --- /dev/null +++ b/tests/api_resources/fine_tuning/alpha/__init__.py @@ -0,0 +1 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. diff --git a/tests/api_resources/fine_tuning/alpha/test_graders.py b/tests/api_resources/fine_tuning/alpha/test_graders.py new file mode 100644 index 0000000000..b144c78c74 --- /dev/null +++ b/tests/api_resources/fine_tuning/alpha/test_graders.py @@ -0,0 +1,289 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +import os +from typing import Any, cast + +import pytest + +from openai import OpenAI, AsyncOpenAI +from tests.utils import assert_matches_type +from openai.types.fine_tuning.alpha import ( + GraderRunResponse, + GraderValidateResponse, +) + +base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010/") + + +class TestGraders: + parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + def test_method_run(self, client: OpenAI) -> None: + grader = client.fine_tuning.alpha.graders.run( + grader={ + "input": "input", + "name": "name", + "operation": "eq", + "reference": "reference", + "type": "string_check", + }, + model_sample="model_sample", + reference_answer="string", + ) + assert_matches_type(GraderRunResponse, grader, path=["response"]) + + @parametrize + def test_method_run_with_all_params(self, client: OpenAI) -> None: + grader = client.fine_tuning.alpha.graders.run( + grader={ + "input": "input", + "name": "name", + "operation": "eq", + "reference": "reference", + "type": "string_check", + }, + model_sample="model_sample", + reference_answer="string", + ) + assert_matches_type(GraderRunResponse, grader, path=["response"]) + + @parametrize + def test_raw_response_run(self, client: OpenAI) -> None: + response = client.fine_tuning.alpha.graders.with_raw_response.run( + grader={ + "input": "input", + "name": "name", + "operation": "eq", + "reference": "reference", + "type": "string_check", + }, + model_sample="model_sample", + reference_answer="string", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + grader = response.parse() + assert_matches_type(GraderRunResponse, grader, path=["response"]) + + @parametrize + def test_streaming_response_run(self, client: OpenAI) -> None: + with client.fine_tuning.alpha.graders.with_streaming_response.run( + grader={ + "input": "input", + "name": "name", + "operation": "eq", + "reference": "reference", + "type": "string_check", + }, + model_sample="model_sample", + reference_answer="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + grader = response.parse() + assert_matches_type(GraderRunResponse, grader, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_method_validate(self, client: OpenAI) -> None: + grader = client.fine_tuning.alpha.graders.validate( + grader={ + "input": "input", + "name": "name", + "operation": "eq", + "reference": "reference", + "type": "string_check", + }, + ) + assert_matches_type(GraderValidateResponse, grader, path=["response"]) + + @parametrize + def test_method_validate_with_all_params(self, client: OpenAI) -> None: + grader = client.fine_tuning.alpha.graders.validate( + grader={ + "input": "input", + "name": "name", + "operation": "eq", + "reference": "reference", + "type": "string_check", + }, + ) + assert_matches_type(GraderValidateResponse, grader, path=["response"]) + + @parametrize + def test_raw_response_validate(self, client: OpenAI) -> None: + response = client.fine_tuning.alpha.graders.with_raw_response.validate( + grader={ + "input": "input", + "name": "name", + "operation": "eq", + "reference": "reference", + "type": "string_check", + }, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + grader = response.parse() + assert_matches_type(GraderValidateResponse, grader, path=["response"]) + + @parametrize + def test_streaming_response_validate(self, client: OpenAI) -> None: + with client.fine_tuning.alpha.graders.with_streaming_response.validate( + grader={ + "input": "input", + "name": "name", + "operation": "eq", + "reference": "reference", + "type": "string_check", + }, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + grader = response.parse() + assert_matches_type(GraderValidateResponse, grader, path=["response"]) + + assert cast(Any, response.is_closed) is True + + +class TestAsyncGraders: + parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) + + @parametrize + async def test_method_run(self, async_client: AsyncOpenAI) -> None: + grader = await async_client.fine_tuning.alpha.graders.run( + grader={ + "input": "input", + "name": "name", + "operation": "eq", + "reference": "reference", + "type": "string_check", + }, + model_sample="model_sample", + reference_answer="string", + ) + assert_matches_type(GraderRunResponse, grader, path=["response"]) + + @parametrize + async def test_method_run_with_all_params(self, async_client: AsyncOpenAI) -> None: + grader = await async_client.fine_tuning.alpha.graders.run( + grader={ + "input": "input", + "name": "name", + "operation": "eq", + "reference": "reference", + "type": "string_check", + }, + model_sample="model_sample", + reference_answer="string", + ) + assert_matches_type(GraderRunResponse, grader, path=["response"]) + + @parametrize + async def test_raw_response_run(self, async_client: AsyncOpenAI) -> None: + response = await async_client.fine_tuning.alpha.graders.with_raw_response.run( + grader={ + "input": "input", + "name": "name", + "operation": "eq", + "reference": "reference", + "type": "string_check", + }, + model_sample="model_sample", + reference_answer="string", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + grader = response.parse() + assert_matches_type(GraderRunResponse, grader, path=["response"]) + + @parametrize + async def test_streaming_response_run(self, async_client: AsyncOpenAI) -> None: + async with async_client.fine_tuning.alpha.graders.with_streaming_response.run( + grader={ + "input": "input", + "name": "name", + "operation": "eq", + "reference": "reference", + "type": "string_check", + }, + model_sample="model_sample", + reference_answer="string", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + grader = await response.parse() + assert_matches_type(GraderRunResponse, grader, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_method_validate(self, async_client: AsyncOpenAI) -> None: + grader = await async_client.fine_tuning.alpha.graders.validate( + grader={ + "input": "input", + "name": "name", + "operation": "eq", + "reference": "reference", + "type": "string_check", + }, + ) + assert_matches_type(GraderValidateResponse, grader, path=["response"]) + + @parametrize + async def test_method_validate_with_all_params(self, async_client: AsyncOpenAI) -> None: + grader = await async_client.fine_tuning.alpha.graders.validate( + grader={ + "input": "input", + "name": "name", + "operation": "eq", + "reference": "reference", + "type": "string_check", + }, + ) + assert_matches_type(GraderValidateResponse, grader, path=["response"]) + + @parametrize + async def test_raw_response_validate(self, async_client: AsyncOpenAI) -> None: + response = await async_client.fine_tuning.alpha.graders.with_raw_response.validate( + grader={ + "input": "input", + "name": "name", + "operation": "eq", + "reference": "reference", + "type": "string_check", + }, + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + grader = response.parse() + assert_matches_type(GraderValidateResponse, grader, path=["response"]) + + @parametrize + async def test_streaming_response_validate(self, async_client: AsyncOpenAI) -> None: + async with async_client.fine_tuning.alpha.graders.with_streaming_response.validate( + grader={ + "input": "input", + "name": "name", + "operation": "eq", + "reference": "reference", + "type": "string_check", + }, + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + grader = await response.parse() + assert_matches_type(GraderValidateResponse, grader, path=["response"]) + + assert cast(Any, response.is_closed) is True diff --git a/tests/api_resources/fine_tuning/test_jobs.py b/tests/api_resources/fine_tuning/test_jobs.py index 75f72f9d09..4589f12846 100644 --- a/tests/api_resources/fine_tuning/test_jobs.py +++ b/tests/api_resources/fine_tuning/test_jobs.py @@ -52,6 +52,7 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: ], metadata={"foo": "string"}, method={ + "type": "supervised", "dpo": { "hyperparameters": { "batch_size": "auto", @@ -60,6 +61,24 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "n_epochs": "auto", } }, + "reinforcement": { + "grader": { + "input": "input", + "name": "name", + "operation": "eq", + "reference": "reference", + "type": "string_check", + }, + "hyperparameters": { + "batch_size": "auto", + "compute_multiplier": "auto", + "eval_interval": "auto", + "eval_samples": "auto", + "learning_rate_multiplier": "auto", + "n_epochs": "auto", + "reasoning_effort": "default", + }, + }, "supervised": { "hyperparameters": { "batch_size": "auto", @@ -67,7 +86,6 @@ def test_method_create_with_all_params(self, client: OpenAI) -> None: "n_epochs": "auto", } }, - "type": "supervised", }, seed=42, suffix="x", @@ -258,6 +276,82 @@ def test_path_params_list_events(self, client: OpenAI) -> None: "", ) + @parametrize + def test_method_pause(self, client: OpenAI) -> None: + job = client.fine_tuning.jobs.pause( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert_matches_type(FineTuningJob, job, path=["response"]) + + @parametrize + def test_raw_response_pause(self, client: OpenAI) -> None: + response = client.fine_tuning.jobs.with_raw_response.pause( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + job = response.parse() + assert_matches_type(FineTuningJob, job, path=["response"]) + + @parametrize + def test_streaming_response_pause(self, client: OpenAI) -> None: + with client.fine_tuning.jobs.with_streaming_response.pause( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + job = response.parse() + assert_matches_type(FineTuningJob, job, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_pause(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `fine_tuning_job_id` but received ''"): + client.fine_tuning.jobs.with_raw_response.pause( + "", + ) + + @parametrize + def test_method_resume(self, client: OpenAI) -> None: + job = client.fine_tuning.jobs.resume( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert_matches_type(FineTuningJob, job, path=["response"]) + + @parametrize + def test_raw_response_resume(self, client: OpenAI) -> None: + response = client.fine_tuning.jobs.with_raw_response.resume( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + job = response.parse() + assert_matches_type(FineTuningJob, job, path=["response"]) + + @parametrize + def test_streaming_response_resume(self, client: OpenAI) -> None: + with client.fine_tuning.jobs.with_streaming_response.resume( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + job = response.parse() + assert_matches_type(FineTuningJob, job, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + def test_path_params_resume(self, client: OpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `fine_tuning_job_id` but received ''"): + client.fine_tuning.jobs.with_raw_response.resume( + "", + ) + class TestAsyncJobs: parametrize = pytest.mark.parametrize("async_client", [False, True], indirect=True, ids=["loose", "strict"]) @@ -293,6 +387,7 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> ], metadata={"foo": "string"}, method={ + "type": "supervised", "dpo": { "hyperparameters": { "batch_size": "auto", @@ -301,6 +396,24 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "n_epochs": "auto", } }, + "reinforcement": { + "grader": { + "input": "input", + "name": "name", + "operation": "eq", + "reference": "reference", + "type": "string_check", + }, + "hyperparameters": { + "batch_size": "auto", + "compute_multiplier": "auto", + "eval_interval": "auto", + "eval_samples": "auto", + "learning_rate_multiplier": "auto", + "n_epochs": "auto", + "reasoning_effort": "default", + }, + }, "supervised": { "hyperparameters": { "batch_size": "auto", @@ -308,7 +421,6 @@ async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> "n_epochs": "auto", } }, - "type": "supervised", }, seed=42, suffix="x", @@ -498,3 +610,79 @@ async def test_path_params_list_events(self, async_client: AsyncOpenAI) -> None: await async_client.fine_tuning.jobs.with_raw_response.list_events( "", ) + + @parametrize + async def test_method_pause(self, async_client: AsyncOpenAI) -> None: + job = await async_client.fine_tuning.jobs.pause( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert_matches_type(FineTuningJob, job, path=["response"]) + + @parametrize + async def test_raw_response_pause(self, async_client: AsyncOpenAI) -> None: + response = await async_client.fine_tuning.jobs.with_raw_response.pause( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + job = response.parse() + assert_matches_type(FineTuningJob, job, path=["response"]) + + @parametrize + async def test_streaming_response_pause(self, async_client: AsyncOpenAI) -> None: + async with async_client.fine_tuning.jobs.with_streaming_response.pause( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + job = await response.parse() + assert_matches_type(FineTuningJob, job, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_pause(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `fine_tuning_job_id` but received ''"): + await async_client.fine_tuning.jobs.with_raw_response.pause( + "", + ) + + @parametrize + async def test_method_resume(self, async_client: AsyncOpenAI) -> None: + job = await async_client.fine_tuning.jobs.resume( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + assert_matches_type(FineTuningJob, job, path=["response"]) + + @parametrize + async def test_raw_response_resume(self, async_client: AsyncOpenAI) -> None: + response = await async_client.fine_tuning.jobs.with_raw_response.resume( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + + assert response.is_closed is True + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + job = response.parse() + assert_matches_type(FineTuningJob, job, path=["response"]) + + @parametrize + async def test_streaming_response_resume(self, async_client: AsyncOpenAI) -> None: + async with async_client.fine_tuning.jobs.with_streaming_response.resume( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) as response: + assert not response.is_closed + assert response.http_request.headers.get("X-Stainless-Lang") == "python" + + job = await response.parse() + assert_matches_type(FineTuningJob, job, path=["response"]) + + assert cast(Any, response.is_closed) is True + + @parametrize + async def test_path_params_resume(self, async_client: AsyncOpenAI) -> None: + with pytest.raises(ValueError, match=r"Expected a non-empty value for `fine_tuning_job_id` but received ''"): + await async_client.fine_tuning.jobs.with_raw_response.resume( + "", + ) From 01a69ab8cbed129e9edb84865893310ab52e59c7 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 8 May 2025 17:25:01 +0000 Subject: [PATCH 813/816] release: 1.78.0 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 20 ++++++++++++++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 23 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 33a65d75c4..21621582fa 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.77.0" + ".": "1.78.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 9097cdc65a..8648497457 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,25 @@ # Changelog +## 1.78.0 (2025-05-08) + +Full Changelog: [v1.77.0...v1.78.0](https://github.com/openai/openai-python/compare/v1.77.0...v1.78.0) + +### Features + +* **api:** Add reinforcement fine-tuning api support ([bebe361](https://github.com/openai/openai-python/commit/bebe36104bd3062d09ab9bbfb4bacfc99e737cb2)) + + +### Bug Fixes + +* ignore errors in isinstance() calls on LazyProxy subclasses ([#2343](https://github.com/openai/openai-python/issues/2343)) ([52cbbdf](https://github.com/openai/openai-python/commit/52cbbdf2207567741f16d18f1ea1b0d13d667375)), closes [#2056](https://github.com/openai/openai-python/issues/2056) + + +### Chores + +* **internal:** update proxy tests ([b8e848d](https://github.com/openai/openai-python/commit/b8e848d5fb58472cbfa27fb3ed01efc25a05d944)) +* use lazy imports for module level client ([4d0f409](https://github.com/openai/openai-python/commit/4d0f409e79a18cce9855fe076f5a50e52b8bafd8)) +* use lazy imports for resources ([834813c](https://github.com/openai/openai-python/commit/834813c5cb1a84effc34e5eabed760393e1de806)) + ## 1.77.0 (2025-05-02) Full Changelog: [v1.76.2...v1.77.0](https://github.com/openai/openai-python/compare/v1.76.2...v1.77.0) diff --git a/pyproject.toml b/pyproject.toml index 4b854b05e5..3d5af260cf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.77.0" +version = "1.78.0" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 9d8ba015e1..495a094581 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.77.0" # x-release-please-version +__version__ = "1.78.0" # x-release-please-version From 21209abbf29113c8eedcd5e2645db31ab2bda61a Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 9 May 2025 14:38:23 +0000 Subject: [PATCH 814/816] fix(package): support direct resource imports --- src/openai/__init__.py | 4 ++++ src/openai/_utils/_resources_proxy.py | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 src/openai/_utils/_resources_proxy.py diff --git a/src/openai/__init__.py b/src/openai/__init__.py index 9e97098bb0..6b21a9af23 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -3,6 +3,7 @@ from __future__ import annotations import os as _os +import typing as _t from typing_extensions import override from . import types @@ -78,6 +79,9 @@ "DefaultAsyncHttpxClient", ] +if not _t.TYPE_CHECKING: + from ._utils._resources_proxy import resources as resources + from .lib import azure as _azure, pydantic_function_tool as pydantic_function_tool from .version import VERSION as VERSION from .lib.azure import AzureOpenAI as AzureOpenAI, AsyncAzureOpenAI as AsyncAzureOpenAI diff --git a/src/openai/_utils/_resources_proxy.py b/src/openai/_utils/_resources_proxy.py new file mode 100644 index 0000000000..e5b9ec7a37 --- /dev/null +++ b/src/openai/_utils/_resources_proxy.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +from typing import Any +from typing_extensions import override + +from ._proxy import LazyProxy + + +class ResourcesProxy(LazyProxy[Any]): + """A proxy for the `openai.resources` module. + + This is used so that we can lazily import `openai.resources` only when + needed *and* so that users can just import `openai` and reference `openai.resources` + """ + + @override + def __load__(self) -> Any: + import importlib + + mod = importlib.import_module("openai.resources") + return mod + + +resources = ResourcesProxy().__as_proxied__() From 12a534987d0f3d238de5774749c326ee79bcfb00 Mon Sep 17 00:00:00 2001 From: David Meadows Date: Fri, 9 May 2025 11:15:26 -0400 Subject: [PATCH 815/816] fix(internal): fix linting due to broken __test__ annotation --- src/openai/types/eval_create_params.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/openai/types/eval_create_params.py b/src/openai/types/eval_create_params.py index 66178287e4..3b712580a0 100644 --- a/src/openai/types/eval_create_params.py +++ b/src/openai/types/eval_create_params.py @@ -140,19 +140,16 @@ class TestingCriterionLabelModel(TypedDict, total=False): class TestingCriterionTextSimilarity(TextSimilarityGraderParam, total=False): - __test__ = False pass_threshold: Required[float] """The threshold for the score.""" class TestingCriterionPython(PythonGraderParam, total=False): - __test__ = False pass_threshold: float """The threshold for the score.""" class TestingCriterionScoreModel(ScoreModelGraderParam, total=False): - __test__ = False pass_threshold: float """The threshold for the score.""" From c097025779fc0bdc3389c047d4c060b5d7349f16 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 12 May 2025 05:04:02 +0000 Subject: [PATCH 816/816] release: 1.78.1 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 9 +++++++++ pyproject.toml | 2 +- src/openai/_version.py | 2 +- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 21621582fa..f15af035f8 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.78.0" + ".": "1.78.1" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 8648497457..b153f3ef05 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 1.78.1 (2025-05-12) + +Full Changelog: [v1.78.0...v1.78.1](https://github.com/openai/openai-python/compare/v1.78.0...v1.78.1) + +### Bug Fixes + +* **internal:** fix linting due to broken __test__ annotation ([5a7d7a0](https://github.com/openai/openai-python/commit/5a7d7a081138c6473bff44e60d439812ecb85cdf)) +* **package:** support direct resource imports ([2293fc0](https://github.com/openai/openai-python/commit/2293fc0dd23a9c756067cdc22b39c18448f35feb)) + ## 1.78.0 (2025-05-08) Full Changelog: [v1.77.0...v1.78.0](https://github.com/openai/openai-python/compare/v1.77.0...v1.78.0) diff --git a/pyproject.toml b/pyproject.toml index 3d5af260cf..71c86c38ea 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.78.0" +version = "1.78.1" description = "The official Python library for the openai API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/openai/_version.py b/src/openai/_version.py index 495a094581..9b430dfa8b 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "openai" -__version__ = "1.78.0" # x-release-please-version +__version__ = "1.78.1" # x-release-please-version